Merge tag 'net-6.16-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net
[linux-2.6-block.git] / fs / ext4 / inode.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
ac27a0ec 2/*
617ba13b 3 * linux/fs/ext4/inode.c
ac27a0ec
DK
4 *
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
9 *
10 * from
11 *
12 * linux/fs/minix/inode.c
13 *
14 * Copyright (C) 1991, 1992 Linus Torvalds
15 *
ac27a0ec
DK
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
18 *
617ba13b 19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
ac27a0ec
DK
20 */
21
ac27a0ec 22#include <linux/fs.h>
14f3db55 23#include <linux/mount.h>
ac27a0ec 24#include <linux/time.h>
ac27a0ec
DK
25#include <linux/highuid.h>
26#include <linux/pagemap.h>
c94c2acf 27#include <linux/dax.h>
ac27a0ec
DK
28#include <linux/quotaops.h>
29#include <linux/string.h>
30#include <linux/buffer_head.h>
31#include <linux/writeback.h>
64769240 32#include <linux/pagevec.h>
ac27a0ec 33#include <linux/mpage.h>
17207d0b 34#include <linux/rmap.h>
e83c1397 35#include <linux/namei.h>
ac27a0ec
DK
36#include <linux/uio.h>
37#include <linux/bio.h>
4c0425ff 38#include <linux/workqueue.h>
744692dc 39#include <linux/kernel.h>
6db26ffc 40#include <linux/printk.h>
5a0e3ad6 41#include <linux/slab.h>
00a1a053 42#include <linux/bitops.h>
364443cb 43#include <linux/iomap.h>
ae5e165d 44#include <linux/iversion.h>
9bffad1e 45
3dcf5451 46#include "ext4_jbd2.h"
ac27a0ec
DK
47#include "xattr.h"
48#include "acl.h"
9f125d64 49#include "truncate.h"
ac27a0ec 50
9bffad1e
TT
51#include <trace/events/ext4.h>
52
cb3de5fc
SZ
53static void ext4_journalled_zero_new_buffers(handle_t *handle,
54 struct inode *inode,
55 struct folio *folio,
56 unsigned from, unsigned to);
57
814525f4
DW
58static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
59 struct ext4_inode_info *ei)
60{
814525f4 61 __u32 csum;
b47820ed
DJ
62 __u16 dummy_csum = 0;
63 int offset = offsetof(struct ext4_inode, i_checksum_lo);
64 unsigned int csum_size = sizeof(dummy_csum);
814525f4 65
6cbab5f9
EB
66 csum = ext4_chksum(ei->i_csum_seed, (__u8 *)raw, offset);
67 csum = ext4_chksum(csum, (__u8 *)&dummy_csum, csum_size);
b47820ed 68 offset += csum_size;
6cbab5f9 69 csum = ext4_chksum(csum, (__u8 *)raw + offset,
b47820ed 70 EXT4_GOOD_OLD_INODE_SIZE - offset);
814525f4 71
b47820ed
DJ
72 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
73 offset = offsetof(struct ext4_inode, i_checksum_hi);
6cbab5f9 74 csum = ext4_chksum(csum, (__u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE,
b47820ed
DJ
75 offset - EXT4_GOOD_OLD_INODE_SIZE);
76 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
6cbab5f9 77 csum = ext4_chksum(csum, (__u8 *)&dummy_csum,
b47820ed
DJ
78 csum_size);
79 offset += csum_size;
b47820ed 80 }
6cbab5f9 81 csum = ext4_chksum(csum, (__u8 *)raw + offset,
05ac5aa1 82 EXT4_INODE_SIZE(inode->i_sb) - offset);
814525f4
DW
83 }
84
814525f4
DW
85 return csum;
86}
87
88static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
89 struct ext4_inode_info *ei)
90{
91 __u32 provided, calculated;
92
93 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
94 cpu_to_le32(EXT4_OS_LINUX) ||
e224fa3b 95 !ext4_has_feature_metadata_csum(inode->i_sb))
814525f4
DW
96 return 1;
97
98 provided = le16_to_cpu(raw->i_checksum_lo);
99 calculated = ext4_inode_csum(inode, raw, ei);
100 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
101 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
102 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
103 else
104 calculated &= 0xFFFF;
105
106 return provided == calculated;
107}
108
8016e29f
HS
109void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
110 struct ext4_inode_info *ei)
814525f4
DW
111{
112 __u32 csum;
113
114 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
115 cpu_to_le32(EXT4_OS_LINUX) ||
e224fa3b 116 !ext4_has_feature_metadata_csum(inode->i_sb))
814525f4
DW
117 return;
118
119 csum = ext4_inode_csum(inode, raw, ei);
120 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
121 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
122 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
123 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
124}
125
678aaf48
JK
126static inline int ext4_begin_ordered_truncate(struct inode *inode,
127 loff_t new_size)
128{
7ff9c073 129 trace_ext4_begin_ordered_truncate(inode, new_size);
8aefcd55
TT
130 /*
131 * If jinode is zero, then we never opened the file for
132 * writing, so there's no need to call
133 * jbd2_journal_begin_ordered_truncate() since there's no
134 * outstanding writes we need to flush.
135 */
136 if (!EXT4_I(inode)->jinode)
137 return 0;
138 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
139 EXT4_I(inode)->jinode,
140 new_size);
678aaf48
JK
141}
142
ac27a0ec
DK
143/*
144 * Test whether an inode is a fast symlink.
407cd7fb 145 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
ac27a0ec 146 */
f348c252 147int ext4_inode_is_fast_symlink(struct inode *inode)
ac27a0ec 148{
fc82228a
AK
149 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
150 int ea_blocks = EXT4_I(inode)->i_file_acl ?
151 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152
153 if (ext4_has_inline_data(inode))
154 return 0;
155
156 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157 }
407cd7fb
TE
158 return S_ISLNK(inode->i_mode) && inode->i_size &&
159 (inode->i_size < EXT4_N_BLOCKS * 4);
ac27a0ec
DK
160}
161
ac27a0ec
DK
162/*
163 * Called at the last iput() if i_nlink is zero.
164 */
0930fcc1 165void ext4_evict_inode(struct inode *inode)
ac27a0ec
DK
166{
167 handle_t *handle;
bc965ab3 168 int err;
65db869c
JK
169 /*
170 * Credits for final inode cleanup and freeing:
171 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
172 * (xattr block freeing), bitmap, group descriptor (inode freeing)
173 */
174 int extra_credits = 6;
0421a189 175 struct ext4_xattr_inode_array *ea_inode_array = NULL;
46e294ef 176 bool freeze_protected = false;
ac27a0ec 177
7ff9c073 178 trace_ext4_evict_inode(inode);
2581fdc8 179
0e2f80af
AP
180 dax_break_layout_final(inode);
181
6bc0d63d
JK
182 if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
183 ext4_evict_ea_inode(inode);
0930fcc1 184 if (inode->i_nlink) {
91b0abe3 185 truncate_inode_pages_final(&inode->i_data);
5dc23bdd 186
0930fcc1
AV
187 goto no_delete;
188 }
189
e2bfb088
TT
190 if (is_bad_inode(inode))
191 goto no_delete;
192 dquot_initialize(inode);
907f4554 193
678aaf48
JK
194 if (ext4_should_order_data(inode))
195 ext4_begin_ordered_truncate(inode, 0);
91b0abe3 196 truncate_inode_pages_final(&inode->i_data);
ac27a0ec 197
ceff86fd
JK
198 /*
199 * For inodes with journalled data, transaction commit could have
bc12ac98
ZY
200 * dirtied the inode. And for inodes with dioread_nolock, unwritten
201 * extents converting worker could merge extents and also have dirtied
202 * the inode. Flush worker is ignoring it because of I_FREEING flag but
203 * we still need to remove the inode from the writeback lists.
ceff86fd 204 */
bc12ac98 205 if (!list_empty_careful(&inode->i_io_list))
ceff86fd 206 inode_io_list_del(inode);
ceff86fd 207
8e8ad8a5
JK
208 /*
209 * Protect us against freezing - iput() caller didn't have to have any
46e294ef
JK
210 * protection against it. When we are in a running transaction though,
211 * we are already protected against freezing and we cannot grab further
212 * protection due to lock ordering constraints.
8e8ad8a5 213 */
46e294ef
JK
214 if (!ext4_journal_current_handle()) {
215 sb_start_intwrite(inode->i_sb);
216 freeze_protected = true;
217 }
e50e5129 218
30a7eb97
TE
219 if (!IS_NOQUOTA(inode))
220 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
221
65db869c
JK
222 /*
223 * Block bitmap, group descriptor, and inode are accounted in both
224 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
225 */
30a7eb97 226 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
65db869c 227 ext4_blocks_for_truncate(inode) + extra_credits - 3);
ac27a0ec 228 if (IS_ERR(handle)) {
bc965ab3 229 ext4_std_error(inode->i_sb, PTR_ERR(handle));
ac27a0ec
DK
230 /*
231 * If we're going to skip the normal cleanup, we still need to
232 * make sure that the in-core orphan linked list is properly
233 * cleaned up.
234 */
617ba13b 235 ext4_orphan_del(NULL, inode);
46e294ef
JK
236 if (freeze_protected)
237 sb_end_intwrite(inode->i_sb);
ac27a0ec
DK
238 goto no_delete;
239 }
30a7eb97 240
ac27a0ec 241 if (IS_SYNC(inode))
0390131b 242 ext4_handle_sync(handle);
407cd7fb
TE
243
244 /*
245 * Set inode->i_size to 0 before calling ext4_truncate(). We need
246 * special handling of symlinks here because i_size is used to
247 * determine whether ext4_inode_info->i_data contains symlink data or
248 * block mappings. Setting i_size to 0 will remove its fast symlink
249 * status. Erase i_data so that it becomes a valid empty block map.
250 */
251 if (ext4_inode_is_fast_symlink(inode))
252 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
ac27a0ec 253 inode->i_size = 0;
bc965ab3
TT
254 err = ext4_mark_inode_dirty(handle, inode);
255 if (err) {
12062ddd 256 ext4_warning(inode->i_sb,
bc965ab3
TT
257 "couldn't mark inode dirty (err %d)", err);
258 goto stop_handle;
259 }
2c98eb5e
TT
260 if (inode->i_blocks) {
261 err = ext4_truncate(inode);
262 if (err) {
54d3adbc
TT
263 ext4_error_err(inode->i_sb, -err,
264 "couldn't truncate inode %lu (err %d)",
265 inode->i_ino, err);
2c98eb5e
TT
266 goto stop_handle;
267 }
268 }
bc965ab3 269
30a7eb97
TE
270 /* Remove xattr references. */
271 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
272 extra_credits);
273 if (err) {
274 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
275stop_handle:
276 ext4_journal_stop(handle);
277 ext4_orphan_del(NULL, inode);
46e294ef
JK
278 if (freeze_protected)
279 sb_end_intwrite(inode->i_sb);
30a7eb97
TE
280 ext4_xattr_inode_array_free(ea_inode_array);
281 goto no_delete;
bc965ab3
TT
282 }
283
ac27a0ec 284 /*
617ba13b 285 * Kill off the orphan record which ext4_truncate created.
ac27a0ec 286 * AKPM: I think this can be inside the above `if'.
617ba13b 287 * Note that ext4_orphan_del() has to be able to cope with the
ac27a0ec 288 * deletion of a non-existent orphan - this is because we don't
617ba13b 289 * know if ext4_truncate() actually created an orphan record.
ac27a0ec
DK
290 * (Well, we could do this if we need to, but heck - it works)
291 */
617ba13b 292 ext4_orphan_del(handle, inode);
5ffff834 293 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
ac27a0ec
DK
294
295 /*
296 * One subtle ordering requirement: if anything has gone wrong
297 * (transaction abort, IO errors, whatever), then we can still
298 * do these next steps (the fs will already have been marked as
299 * having errors), but we can't free the inode if the mark_dirty
300 * fails.
301 */
617ba13b 302 if (ext4_mark_inode_dirty(handle, inode))
ac27a0ec 303 /* If that failed, just do the required in-core inode clear. */
0930fcc1 304 ext4_clear_inode(inode);
ac27a0ec 305 else
617ba13b
MC
306 ext4_free_inode(handle, inode);
307 ext4_journal_stop(handle);
46e294ef
JK
308 if (freeze_protected)
309 sb_end_intwrite(inode->i_sb);
0421a189 310 ext4_xattr_inode_array_free(ea_inode_array);
ac27a0ec
DK
311 return;
312no_delete:
318cdc82
ZY
313 /*
314 * Check out some where else accidentally dirty the evicting inode,
315 * which may probably cause inode use-after-free issues later.
316 */
317 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
318
b21ebf14 319 if (!list_empty(&EXT4_I(inode)->i_fc_list))
e85c81ba 320 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
0930fcc1 321 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
ac27a0ec
DK
322}
323
a9e7f447
DM
324#ifdef CONFIG_QUOTA
325qsize_t *ext4_get_reserved_space(struct inode *inode)
60e58e0f 326{
a9e7f447 327 return &EXT4_I(inode)->i_reserved_quota;
60e58e0f 328}
a9e7f447 329#endif
9d0be502 330
0637c6f4
TT
331/*
332 * Called with i_data_sem down, which is important since we can call
333 * ext4_discard_preallocations() from here.
334 */
5f634d06
AK
335void ext4_da_update_reserve_space(struct inode *inode,
336 int used, int quota_claim)
12219aea
AK
337{
338 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 339 struct ext4_inode_info *ei = EXT4_I(inode);
0637c6f4
TT
340
341 spin_lock(&ei->i_block_reservation_lock);
d8990240 342 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
0637c6f4 343 if (unlikely(used > ei->i_reserved_data_blocks)) {
8de5c325 344 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
1084f252 345 "with only %d reserved data blocks",
0637c6f4
TT
346 __func__, inode->i_ino, used,
347 ei->i_reserved_data_blocks);
348 WARN_ON(1);
349 used = ei->i_reserved_data_blocks;
350 }
12219aea 351
0637c6f4
TT
352 /* Update per-inode reservations */
353 ei->i_reserved_data_blocks -= used;
71d4f7d0 354 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
6bc6e63f 355
f9505c72 356 spin_unlock(&ei->i_block_reservation_lock);
60e58e0f 357
72b8ab9d
ES
358 /* Update quota subsystem for data blocks */
359 if (quota_claim)
7b415bf6 360 dquot_claim_block(inode, EXT4_C2B(sbi, used));
72b8ab9d 361 else {
5f634d06
AK
362 /*
363 * We did fallocate with an offset that is already delayed
364 * allocated. So on delayed allocated writeback we should
72b8ab9d 365 * not re-claim the quota for fallocated blocks.
5f634d06 366 */
7b415bf6 367 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
5f634d06 368 }
d6014301
AK
369
370 /*
371 * If we have done all the pending block allocations and if
372 * there aren't any writers on the inode, we can discard the
373 * inode's preallocations.
374 */
0637c6f4 375 if ((ei->i_reserved_data_blocks == 0) &&
82dd124c 376 !inode_is_open_for_write(inode))
2ffd2a6a 377 ext4_discard_preallocations(inode);
12219aea
AK
378}
379
e29136f8 380static int __check_block_validity(struct inode *inode, const char *func,
c398eda0
TT
381 unsigned int line,
382 struct ext4_map_blocks *map)
6fd058f7 383{
ccad447a
OM
384 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
385
386 if (journal && inode == journal->j_inode)
345c0dbf 387 return 0;
ccad447a 388
ce9f24cc 389 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
c398eda0 390 ext4_error_inode(inode, func, line, map->m_pblk,
bdbd6ce0 391 "lblock %lu mapped to illegal pblock %llu "
c398eda0 392 "(length %d)", (unsigned long) map->m_lblk,
bdbd6ce0 393 map->m_pblk, map->m_len);
6a797d27 394 return -EFSCORRUPTED;
6fd058f7
TT
395 }
396 return 0;
397}
398
53085fac
JK
399int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
400 ext4_lblk_t len)
401{
402 int ret;
403
33b4cc25 404 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
a7550b30 405 return fscrypt_zeroout_range(inode, lblk, pblk, len);
53085fac
JK
406
407 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
408 if (ret > 0)
409 ret = 0;
410
411 return ret;
412}
413
7871da20
ZY
414/*
415 * For generic regular files, when updating the extent tree, Ext4 should
416 * hold the i_rwsem and invalidate_lock exclusively. This ensures
417 * exclusion against concurrent page faults, as well as reads and writes.
418 */
419#ifdef CONFIG_EXT4_DEBUG
420void ext4_check_map_extents_env(struct inode *inode)
421{
422 if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
423 return;
424
425 if (!S_ISREG(inode->i_mode) ||
426 IS_NOQUOTA(inode) || IS_VERITY(inode) ||
427 is_special_ino(inode->i_sb, inode->i_ino) ||
428 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) ||
429 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE) ||
430 ext4_verity_in_progress(inode))
431 return;
432
433 WARN_ON_ONCE(!inode_is_locked(inode) &&
434 !rwsem_is_locked(&inode->i_mapping->invalidate_lock));
435}
436#else
437void ext4_check_map_extents_env(struct inode *inode) {}
438#endif
439
e29136f8 440#define check_block_validity(inode, map) \
c398eda0 441 __check_block_validity((inode), __func__, __LINE__, (map))
e29136f8 442
921f266b
DM
443#ifdef ES_AGGRESSIVE_TEST
444static void ext4_map_blocks_es_recheck(handle_t *handle,
445 struct inode *inode,
446 struct ext4_map_blocks *es_map,
447 struct ext4_map_blocks *map,
448 int flags)
449{
450 int retval;
451
452 map->m_flags = 0;
453 /*
454 * There is a race window that the result is not the same.
455 * e.g. xfstests #223 when dioread_nolock enables. The reason
456 * is that we lookup a block mapping in extent status tree with
457 * out taking i_data_sem. So at the time the unwritten extent
458 * could be converted.
459 */
2dcba478 460 down_read(&EXT4_I(inode)->i_data_sem);
921f266b 461 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
9e52484c 462 retval = ext4_ext_map_blocks(handle, inode, map, 0);
921f266b 463 } else {
9e52484c 464 retval = ext4_ind_map_blocks(handle, inode, map, 0);
921f266b 465 }
2dcba478 466 up_read((&EXT4_I(inode)->i_data_sem));
921f266b
DM
467
468 /*
469 * We don't check m_len because extent will be collpased in status
470 * tree. So the m_len might not equal.
471 */
472 if (es_map->m_lblk != map->m_lblk ||
473 es_map->m_flags != map->m_flags ||
474 es_map->m_pblk != map->m_pblk) {
bdafe42a 475 printk("ES cache assertion failed for inode: %lu "
921f266b
DM
476 "es_cached ex [%d/%d/%llu/%x] != "
477 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
478 inode->i_ino, es_map->m_lblk, es_map->m_len,
479 es_map->m_pblk, es_map->m_flags, map->m_lblk,
480 map->m_len, map->m_pblk, map->m_flags,
481 retval, flags);
482 }
483}
484#endif /* ES_AGGRESSIVE_TEST */
485
5bb12b18
RHI
486static int ext4_map_query_blocks_next_in_leaf(handle_t *handle,
487 struct inode *inode, struct ext4_map_blocks *map,
488 unsigned int orig_mlen)
489{
490 struct ext4_map_blocks map2;
491 unsigned int status, status2;
492 int retval;
493
494 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
495 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
496
497 WARN_ON_ONCE(!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF));
498 WARN_ON_ONCE(orig_mlen <= map->m_len);
499
500 /* Prepare map2 for lookup in next leaf block */
501 map2.m_lblk = map->m_lblk + map->m_len;
502 map2.m_len = orig_mlen - map->m_len;
503 map2.m_flags = 0;
504 retval = ext4_ext_map_blocks(handle, inode, &map2, 0);
505
506 if (retval <= 0) {
507 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
508 map->m_pblk, status, false);
509 return map->m_len;
510 }
511
512 if (unlikely(retval != map2.m_len)) {
513 ext4_warning(inode->i_sb,
514 "ES len assertion failed for inode "
515 "%lu: retval %d != map->m_len %d",
516 inode->i_ino, retval, map2.m_len);
517 WARN_ON(1);
518 }
519
520 status2 = map2.m_flags & EXT4_MAP_UNWRITTEN ?
521 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
522
523 /*
524 * If map2 is contiguous with map, then let's insert it as a single
525 * extent in es cache and return the combined length of both the maps.
526 */
527 if (map->m_pblk + map->m_len == map2.m_pblk &&
528 status == status2) {
529 ext4_es_insert_extent(inode, map->m_lblk,
530 map->m_len + map2.m_len, map->m_pblk,
531 status, false);
532 map->m_len += map2.m_len;
533 } else {
534 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
535 map->m_pblk, status, false);
536 }
537
538 return map->m_len;
539}
540
8e4e5cdf 541static int ext4_map_query_blocks(handle_t *handle, struct inode *inode,
402e38e6 542 struct ext4_map_blocks *map, int flags)
8e4e5cdf
ZY
543{
544 unsigned int status;
545 int retval;
5bb12b18 546 unsigned int orig_mlen = map->m_len;
8e4e5cdf 547
9597376b 548 flags &= EXT4_EX_QUERY_FILTER;
8e4e5cdf 549 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
618320da 550 retval = ext4_ext_map_blocks(handle, inode, map, flags);
8e4e5cdf 551 else
402e38e6 552 retval = ext4_ind_map_blocks(handle, inode, map, flags);
8e4e5cdf
ZY
553
554 if (retval <= 0)
555 return retval;
556
557 if (unlikely(retval != map->m_len)) {
558 ext4_warning(inode->i_sb,
559 "ES len assertion failed for inode "
560 "%lu: retval %d != map->m_len %d",
561 inode->i_ino, retval, map->m_len);
562 WARN_ON(1);
563 }
564
5bb12b18
RHI
565 /*
566 * No need to query next in leaf:
567 * - if returned extent is not last in leaf or
568 * - if the last in leaf is the full requested range
569 */
570 if (!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) ||
797ac3ca 571 map->m_len == orig_mlen) {
5bb12b18
RHI
572 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
573 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
574 ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
575 map->m_pblk, status, false);
576 return retval;
577 }
578
579 return ext4_map_query_blocks_next_in_leaf(handle, inode, map,
580 orig_mlen);
8e4e5cdf
ZY
581}
582
130078d0
ZY
583static int ext4_map_create_blocks(handle_t *handle, struct inode *inode,
584 struct ext4_map_blocks *map, int flags)
585{
586 struct extent_status es;
587 unsigned int status;
588 int err, retval = 0;
589
8b825288
ZY
590 /*
591 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE
592 * indicates that the blocks and quotas has already been
593 * checked when the data was copied into the page cache.
594 */
595 if (map->m_flags & EXT4_MAP_DELAYED)
596 flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
597
130078d0
ZY
598 /*
599 * Here we clear m_flags because after allocating an new extent,
600 * it will be set again.
601 */
602 map->m_flags &= ~EXT4_MAP_FLAGS;
603
604 /*
605 * We need to check for EXT4 here because migrate could have
606 * changed the inode type in between.
607 */
608 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
609 retval = ext4_ext_map_blocks(handle, inode, map, flags);
610 } else {
611 retval = ext4_ind_map_blocks(handle, inode, map, flags);
612
613 /*
614 * We allocated new blocks which will result in i_data's
615 * format changing. Force the migrate to fail by clearing
616 * migrate flags.
617 */
618 if (retval > 0 && map->m_flags & EXT4_MAP_NEW)
619 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
620 }
621 if (retval <= 0)
622 return retval;
623
624 if (unlikely(retval != map->m_len)) {
625 ext4_warning(inode->i_sb,
626 "ES len assertion failed for inode %lu: "
627 "retval %d != map->m_len %d",
628 inode->i_ino, retval, map->m_len);
629 WARN_ON(1);
630 }
631
632 /*
633 * We have to zeroout blocks before inserting them into extent
634 * status tree. Otherwise someone could look them up there and
635 * use them before they are really zeroed. We also have to
636 * unmap metadata before zeroing as otherwise writeback can
637 * overwrite zeros with stale data from block device.
638 */
639 if (flags & EXT4_GET_BLOCKS_ZERO &&
640 map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) {
641 err = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk,
642 map->m_len);
643 if (err)
644 return err;
645 }
646
647 /*
648 * If the extent has been zeroed out, we don't need to update
649 * extent status tree.
650 */
651 if (flags & EXT4_GET_BLOCKS_PRE_IO &&
652 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
653 if (ext4_es_is_written(&es))
654 return retval;
655 }
656
657 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
658 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
a9082589
ZY
659 ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk,
660 status, flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE);
130078d0 661
8e4e5cdf
ZY
662 return retval;
663}
664
f5ab0d1f 665/*
e35fd660 666 * The ext4_map_blocks() function tries to look up the requested blocks,
2b2d6d01 667 * and returns if the blocks are already mapped.
f5ab0d1f 668 *
f5ab0d1f
MC
669 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
670 * and store the allocated blocks in the result buffer head and mark it
671 * mapped.
672 *
e35fd660
TT
673 * If file type is extents based, it will call ext4_ext_map_blocks(),
674 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
f5ab0d1f
MC
675 * based files
676 *
547e64bd
CN
677 * On success, it returns the number of blocks being mapped or allocated.
678 * If flags doesn't contain EXT4_GET_BLOCKS_CREATE the blocks are
679 * pre-allocated and unwritten, the resulting @map is marked as unwritten.
680 * If the flags contain EXT4_GET_BLOCKS_CREATE, it will mark @map as mapped.
f5ab0d1f
MC
681 *
682 * It returns 0 if plain look up failed (blocks have not been allocated), in
facab4d9
JK
683 * that case, @map is returned as unmapped but we still do fill map->m_len to
684 * indicate the length of a hole starting at map->m_lblk.
f5ab0d1f
MC
685 *
686 * It returns the error in case of allocation failure.
687 */
e35fd660
TT
688int ext4_map_blocks(handle_t *handle, struct inode *inode,
689 struct ext4_map_blocks *map, int flags)
0e855ac8 690{
d100eef2 691 struct extent_status es;
0e855ac8 692 int retval;
b8a86845 693 int ret = 0;
5bb12b18 694 unsigned int orig_mlen = map->m_len;
921f266b
DM
695#ifdef ES_AGGRESSIVE_TEST
696 struct ext4_map_blocks orig_map;
697
698 memcpy(&orig_map, map, sizeof(*map));
699#endif
f5ab0d1f 700
e35fd660 701 map->m_flags = 0;
70aa1554
RH
702 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
703 flags, map->m_len, (unsigned long) map->m_lblk);
d100eef2 704
e861b5e9
TT
705 /*
706 * ext4_map_blocks returns an int, and m_len is an unsigned int
707 */
708 if (unlikely(map->m_len > INT_MAX))
709 map->m_len = INT_MAX;
710
4adb6ab3
KM
711 /* We can handle the block number less than EXT_MAX_BLOCKS */
712 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
6a797d27 713 return -EFSCORRUPTED;
4adb6ab3 714
402e38e6 715 /*
1b4d2a0b
ZY
716 * Callers from the context of data submission are the only exceptions
717 * for regular files that do not hold the i_rwsem or invalidate_lock.
718 * However, caching unrelated ranges is not permitted.
402e38e6
ZY
719 */
720 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
721 WARN_ON_ONCE(!(flags & EXT4_EX_NOCACHE));
1b4d2a0b
ZY
722 else
723 ext4_check_map_extents_env(inode);
402e38e6 724
d100eef2 725 /* Lookup extent status tree firstly */
8016e29f
HS
726 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
727 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
d100eef2
ZL
728 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
729 map->m_pblk = ext4_es_pblock(&es) +
730 map->m_lblk - es.es_lblk;
731 map->m_flags |= ext4_es_is_written(&es) ?
732 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
733 retval = es.es_len - (map->m_lblk - es.es_lblk);
734 if (retval > map->m_len)
735 retval = map->m_len;
736 map->m_len = retval;
737 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
facab4d9 738 map->m_pblk = 0;
874eaba9
ZY
739 map->m_flags |= ext4_es_is_delayed(&es) ?
740 EXT4_MAP_DELAYED : 0;
facab4d9
JK
741 retval = es.es_len - (map->m_lblk - es.es_lblk);
742 if (retval > map->m_len)
743 retval = map->m_len;
744 map->m_len = retval;
d100eef2
ZL
745 retval = 0;
746 } else {
1e83bc81 747 BUG();
d100eef2 748 }
9558cf14
ZY
749
750 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
751 return retval;
921f266b
DM
752#ifdef ES_AGGRESSIVE_TEST
753 ext4_map_blocks_es_recheck(handle, inode, map,
754 &orig_map, flags);
755#endif
5bb12b18
RHI
756 if (!(flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF) ||
757 orig_mlen == map->m_len)
758 goto found;
759
760 if (flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF)
761 map->m_len = orig_mlen;
d100eef2 762 }
9558cf14
ZY
763 /*
764 * In the query cache no-wait mode, nothing we can do more if we
765 * cannot find extent in the cache.
766 */
767 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
768 return 0;
d100eef2 769
4df3d265 770 /*
b920c755
TT
771 * Try to see if we can get the block without requesting a new
772 * file system block.
4df3d265 773 */
2dcba478 774 down_read(&EXT4_I(inode)->i_data_sem);
402e38e6 775 retval = ext4_map_query_blocks(handle, inode, map, flags);
2dcba478 776 up_read((&EXT4_I(inode)->i_data_sem));
f5ab0d1f 777
d100eef2 778found:
e35fd660 779 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
b8a86845 780 ret = check_block_validity(inode, map);
6fd058f7
TT
781 if (ret != 0)
782 return ret;
783 }
784
f5ab0d1f 785 /* If it is only a block(s) look up */
c2177057 786 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
f5ab0d1f
MC
787 return retval;
788
789 /*
790 * Returns if the blocks have already allocated
791 *
792 * Note that if blocks have been preallocated
547e64bd 793 * ext4_ext_map_blocks() returns with buffer head unmapped
f5ab0d1f 794 */
e35fd660 795 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
b8a86845
LC
796 /*
797 * If we need to convert extent to unwritten
798 * we continue and do the actual work in
799 * ext4_ext_map_blocks()
800 */
801 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
802 return retval;
4df3d265 803
4d326646
HS
804
805 ext4_fc_track_inode(handle, inode);
4df3d265 806 /*
556615dc 807 * New blocks allocate and/or writing to unwritten extent
f5ab0d1f 808 * will possibly result in updating i_data, so we take
d91bd2c1 809 * the write lock of i_data_sem, and call get_block()
f5ab0d1f 810 * with create == 1 flag.
4df3d265 811 */
c8b459f4 812 down_write(&EXT4_I(inode)->i_data_sem);
130078d0 813 retval = ext4_map_create_blocks(handle, inode, map, flags);
4df3d265 814 up_write((&EXT4_I(inode)->i_data_sem));
e35fd660 815 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
b8a86845 816 ret = check_block_validity(inode, map);
6fd058f7
TT
817 if (ret != 0)
818 return ret;
06bd3c36
JK
819
820 /*
821 * Inodes with freshly allocated blocks where contents will be
822 * visible after transaction commit must be on transaction's
823 * ordered data list.
824 */
825 if (map->m_flags & EXT4_MAP_NEW &&
826 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
827 !(flags & EXT4_GET_BLOCKS_ZERO) &&
02749a4c 828 !ext4_is_quota_file(inode) &&
06bd3c36 829 ext4_should_order_data(inode)) {
73131fbb
RZ
830 loff_t start_byte =
831 (loff_t)map->m_lblk << inode->i_blkbits;
832 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
833
ee0876bc 834 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
73131fbb
RZ
835 ret = ext4_jbd2_inode_add_wait(handle, inode,
836 start_byte, length);
ee0876bc 837 else
73131fbb
RZ
838 ret = ext4_jbd2_inode_add_write(handle, inode,
839 start_byte, length);
06bd3c36
JK
840 if (ret)
841 return ret;
842 }
6fd058f7 843 }
5e4d0eba
XY
844 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
845 map->m_flags & EXT4_MAP_MAPPED))
846 ext4_fc_track_range(handle, inode, map->m_lblk,
847 map->m_lblk + map->m_len - 1);
ec8c60be 848 if (retval < 0)
70aa1554 849 ext_debug(inode, "failed with err %d\n", retval);
0e855ac8
AK
850 return retval;
851}
852
ed8ad838
JK
853/*
854 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
855 * we have to be careful as someone else may be manipulating b_state as well.
856 */
857static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
858{
859 unsigned long old_state;
860 unsigned long new_state;
861
862 flags &= EXT4_MAP_FLAGS;
863
864 /* Dummy buffer_head? Set non-atomically. */
08be56fe 865 if (!bh->b_folio) {
ed8ad838
JK
866 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
867 return;
868 }
869 /*
870 * Someone else may be modifying b_state. Be careful! This is ugly but
871 * once we get rid of using bh as a container for mapping information
872 * to pass to / from get_block functions, this can go away.
873 */
3ee2a3e7 874 old_state = READ_ONCE(bh->b_state);
ed8ad838 875 do {
ed8ad838 876 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
3ee2a3e7 877 } while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
ed8ad838
JK
878}
879
2ed88685
TT
880static int _ext4_get_block(struct inode *inode, sector_t iblock,
881 struct buffer_head *bh, int flags)
ac27a0ec 882{
2ed88685 883 struct ext4_map_blocks map;
efe70c29 884 int ret = 0;
ac27a0ec 885
46c7f254
TM
886 if (ext4_has_inline_data(inode))
887 return -ERANGE;
888
2ed88685
TT
889 map.m_lblk = iblock;
890 map.m_len = bh->b_size >> inode->i_blkbits;
891
efe70c29
JK
892 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
893 flags);
7fb5409d 894 if (ret > 0) {
2ed88685 895 map_bh(bh, inode->i_sb, map.m_pblk);
ed8ad838 896 ext4_update_bh_state(bh, map.m_flags);
2ed88685 897 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
7fb5409d 898 ret = 0;
547edce3
RZ
899 } else if (ret == 0) {
900 /* hole case, need to fill in bh->b_size */
901 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
ac27a0ec
DK
902 }
903 return ret;
904}
905
2ed88685
TT
906int ext4_get_block(struct inode *inode, sector_t iblock,
907 struct buffer_head *bh, int create)
908{
909 return _ext4_get_block(inode, iblock, bh,
910 create ? EXT4_GET_BLOCKS_CREATE : 0);
911}
912
705965bd
JK
913/*
914 * Get block function used when preparing for buffered write if we require
915 * creating an unwritten extent if blocks haven't been allocated. The extent
916 * will be converted to written after the IO is complete.
917 */
918int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
919 struct buffer_head *bh_result, int create)
920{
2cd8bdb5
OM
921 int ret = 0;
922
705965bd
JK
923 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
924 inode->i_ino, create);
2cd8bdb5 925 ret = _ext4_get_block(inode, iblock, bh_result,
8d5459c1 926 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
2cd8bdb5
OM
927
928 /*
929 * If the buffer is marked unwritten, mark it as new to make sure it is
930 * zeroed out correctly in case of partial writes. Otherwise, there is
931 * a chance of stale data getting exposed.
932 */
933 if (ret == 0 && buffer_unwritten(bh_result))
934 set_buffer_new(bh_result);
935
936 return ret;
705965bd
JK
937}
938
efe70c29
JK
939/* Maximum number of blocks we map for direct IO at once. */
940#define DIO_MAX_BLOCKS 4096
941
ac27a0ec
DK
942/*
943 * `handle' can be NULL if create is zero
944 */
617ba13b 945struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
c5e298ae 946 ext4_lblk_t block, int map_flags)
ac27a0ec 947{
2ed88685
TT
948 struct ext4_map_blocks map;
949 struct buffer_head *bh;
c5e298ae 950 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
9558cf14 951 bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
10560082 952 int err;
ac27a0ec 953
837c23fb
CX
954 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
955 || handle != NULL || create == 0);
9558cf14 956 ASSERT(create == 0 || !nowait);
ac27a0ec 957
2ed88685
TT
958 map.m_lblk = block;
959 map.m_len = 1;
c5e298ae 960 err = ext4_map_blocks(handle, inode, &map, map_flags);
ac27a0ec 961
10560082
TT
962 if (err == 0)
963 return create ? ERR_PTR(-ENOSPC) : NULL;
2ed88685 964 if (err < 0)
10560082 965 return ERR_PTR(err);
2ed88685 966
9558cf14
ZY
967 if (nowait)
968 return sb_find_get_block(inode->i_sb, map.m_pblk);
969
a9cdf82a
ZH
970 /*
971 * Since bh could introduce extra ref count such as referred by
972 * journal_head etc. Try to avoid using __GFP_MOVABLE here
973 * as it may fail the migration when journal_head remains.
974 */
975 bh = getblk_unmovable(inode->i_sb->s_bdev, map.m_pblk,
976 inode->i_sb->s_blocksize);
977
10560082
TT
978 if (unlikely(!bh))
979 return ERR_PTR(-ENOMEM);
2ed88685 980 if (map.m_flags & EXT4_MAP_NEW) {
837c23fb
CX
981 ASSERT(create != 0);
982 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
983 || (handle != NULL));
ac27a0ec 984
2ed88685
TT
985 /*
986 * Now that we do not always journal data, we should
987 * keep in mind whether this should always journal the
988 * new buffer as metadata. For now, regular file
989 * writes use ext4_get_block instead, so it's not a
990 * problem.
991 */
992 lock_buffer(bh);
993 BUFFER_TRACE(bh, "call get_create_access");
188c299e
JK
994 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
995 EXT4_JTR_NONE);
10560082
TT
996 if (unlikely(err)) {
997 unlock_buffer(bh);
998 goto errout;
999 }
1000 if (!buffer_uptodate(bh)) {
2ed88685
TT
1001 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1002 set_buffer_uptodate(bh);
ac27a0ec 1003 }
2ed88685
TT
1004 unlock_buffer(bh);
1005 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1006 err = ext4_handle_dirty_metadata(handle, inode, bh);
10560082
TT
1007 if (unlikely(err))
1008 goto errout;
1009 } else
2ed88685 1010 BUFFER_TRACE(bh, "not a new buffer");
2ed88685 1011 return bh;
10560082
TT
1012errout:
1013 brelse(bh);
1014 return ERR_PTR(err);
ac27a0ec
DK
1015}
1016
617ba13b 1017struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
c5e298ae 1018 ext4_lblk_t block, int map_flags)
ac27a0ec 1019{
af5bc92d 1020 struct buffer_head *bh;
2d069c08 1021 int ret;
ac27a0ec 1022
c5e298ae 1023 bh = ext4_getblk(handle, inode, block, map_flags);
1c215028 1024 if (IS_ERR(bh))
ac27a0ec 1025 return bh;
7963e5ac 1026 if (!bh || ext4_buffer_uptodate(bh))
ac27a0ec 1027 return bh;
2d069c08 1028
1029 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
1030 if (ret) {
1031 put_bh(bh);
1032 return ERR_PTR(ret);
1033 }
1034 return bh;
ac27a0ec
DK
1035}
1036
9699d4f9
TE
1037/* Read a contiguous batch of blocks. */
1038int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1039 bool wait, struct buffer_head **bhs)
1040{
1041 int i, err;
1042
1043 for (i = 0; i < bh_count; i++) {
1044 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1045 if (IS_ERR(bhs[i])) {
1046 err = PTR_ERR(bhs[i]);
1047 bh_count = i;
1048 goto out_brelse;
1049 }
1050 }
1051
1052 for (i = 0; i < bh_count; i++)
1053 /* Note that NULL bhs[i] is valid because of holes. */
2d069c08 1054 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
1055 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
9699d4f9
TE
1056
1057 if (!wait)
1058 return 0;
1059
1060 for (i = 0; i < bh_count; i++)
1061 if (bhs[i])
1062 wait_on_buffer(bhs[i]);
1063
1064 for (i = 0; i < bh_count; i++) {
1065 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1066 err = -EIO;
1067 goto out_brelse;
1068 }
1069 }
1070 return 0;
1071
1072out_brelse:
1073 for (i = 0; i < bh_count; i++) {
1074 brelse(bhs[i]);
1075 bhs[i] = NULL;
1076 }
1077 return err;
1078}
1079
188c299e 1080int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
f19d5870
TM
1081 struct buffer_head *head,
1082 unsigned from,
1083 unsigned to,
1084 int *partial,
188c299e 1085 int (*fn)(handle_t *handle, struct inode *inode,
f19d5870 1086 struct buffer_head *bh))
ac27a0ec
DK
1087{
1088 struct buffer_head *bh;
1089 unsigned block_start, block_end;
1090 unsigned blocksize = head->b_size;
1091 int err, ret = 0;
1092 struct buffer_head *next;
1093
af5bc92d
TT
1094 for (bh = head, block_start = 0;
1095 ret == 0 && (bh != head || !block_start);
de9a55b8 1096 block_start = block_end, bh = next) {
ac27a0ec
DK
1097 next = bh->b_this_page;
1098 block_end = block_start + blocksize;
1099 if (block_end <= from || block_start >= to) {
1100 if (partial && !buffer_uptodate(bh))
1101 *partial = 1;
1102 continue;
1103 }
188c299e 1104 err = (*fn)(handle, inode, bh);
ac27a0ec
DK
1105 if (!ret)
1106 ret = err;
1107 }
1108 return ret;
1109}
1110
d84c9ebd
JK
1111/*
1112 * Helper for handling dirtying of journalled data. We also mark the folio as
1113 * dirty so that writeback code knows about this page (and inode) contains
1114 * dirty data. ext4_writepages() then commits appropriate transaction to
1115 * make data stable.
1116 */
1117static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
1118{
e26268ff
BF
1119 struct folio *folio = bh->b_folio;
1120 struct inode *inode = folio->mapping->host;
1121
1122 /* only regular files have a_ops */
1123 if (S_ISREG(inode->i_mode))
1124 folio_mark_dirty(folio);
d84c9ebd
JK
1125 return ext4_handle_dirty_metadata(handle, NULL, bh);
1126}
1127
188c299e 1128int do_journal_get_write_access(handle_t *handle, struct inode *inode,
f19d5870 1129 struct buffer_head *bh)
ac27a0ec
DK
1130{
1131 if (!buffer_mapped(bh) || buffer_freed(bh))
1132 return 0;
5d601255 1133 BUFFER_TRACE(bh, "get write access");
183aa1d3 1134 return ext4_journal_get_write_access(handle, inode->i_sb, bh,
188c299e 1135 EXT4_JTR_NONE);
ac27a0ec
DK
1136}
1137
cb3de5fc
SZ
1138int ext4_block_write_begin(handle_t *handle, struct folio *folio,
1139 loff_t pos, unsigned len,
6b730a40 1140 get_block_t *get_block)
2058f83a 1141{
16705e52 1142 unsigned int from = offset_in_folio(folio, pos);
2058f83a 1143 unsigned to = from + len;
86b38c27 1144 struct inode *inode = folio->mapping->host;
2058f83a
MH
1145 unsigned block_start, block_end;
1146 sector_t block;
1147 int err = 0;
1148 unsigned blocksize = inode->i_sb->s_blocksize;
1149 unsigned bbits;
0b578f35
CR
1150 struct buffer_head *bh, *head, *wait[2];
1151 int nr_wait = 0;
1152 int i;
cb3de5fc 1153 bool should_journal_data = ext4_should_journal_data(inode);
2058f83a 1154
86b38c27 1155 BUG_ON(!folio_test_locked(folio));
16705e52 1156 BUG_ON(to > folio_size(folio));
2058f83a
MH
1157 BUG_ON(from > to);
1158
86b38c27 1159 head = folio_buffers(folio);
d4059993 1160 if (!head)
0a88810d 1161 head = create_empty_buffers(folio, blocksize, 0);
2058f83a 1162 bbits = ilog2(blocksize);
86b38c27 1163 block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
2058f83a
MH
1164
1165 for (bh = head, block_start = 0; bh != head || !block_start;
1166 block++, block_start = block_end, bh = bh->b_this_page) {
1167 block_end = block_start + blocksize;
1168 if (block_end <= from || block_start >= to) {
86b38c27 1169 if (folio_test_uptodate(folio)) {
3cd46171 1170 set_buffer_uptodate(bh);
2058f83a
MH
1171 }
1172 continue;
1173 }
1174 if (buffer_new(bh))
1175 clear_buffer_new(bh);
1176 if (!buffer_mapped(bh)) {
1177 WARN_ON(bh->b_size != blocksize);
1178 err = get_block(inode, block, bh, 1);
1179 if (err)
1180 break;
1181 if (buffer_new(bh)) {
cb3de5fc
SZ
1182 /*
1183 * We may be zeroing partial buffers or all new
1184 * buffers in case of failure. Prepare JBD2 for
1185 * that.
1186 */
1187 if (should_journal_data)
1188 do_journal_get_write_access(handle,
1189 inode, bh);
86b38c27 1190 if (folio_test_uptodate(folio)) {
cb3de5fc
SZ
1191 /*
1192 * Unlike __block_write_begin() we leave
1193 * dirtying of new uptodate buffers to
1194 * ->write_end() time or
1195 * folio_zero_new_buffers().
1196 */
2058f83a 1197 set_buffer_uptodate(bh);
2058f83a
MH
1198 continue;
1199 }
1200 if (block_end > to || block_start < from)
86b38c27
MW
1201 folio_zero_segments(folio, to,
1202 block_end,
1203 block_start, from);
2058f83a
MH
1204 continue;
1205 }
1206 }
86b38c27 1207 if (folio_test_uptodate(folio)) {
3cd46171 1208 set_buffer_uptodate(bh);
2058f83a
MH
1209 continue;
1210 }
1211 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1212 !buffer_unwritten(bh) &&
1213 (block_start < from || block_end > to)) {
2d069c08 1214 ext4_read_bh_lock(bh, 0, false);
0b578f35 1215 wait[nr_wait++] = bh;
2058f83a
MH
1216 }
1217 }
1218 /*
1219 * If we issued read requests, let them complete.
1220 */
0b578f35
CR
1221 for (i = 0; i < nr_wait; i++) {
1222 wait_on_buffer(wait[i]);
1223 if (!buffer_uptodate(wait[i]))
2058f83a
MH
1224 err = -EIO;
1225 }
7e0785fc 1226 if (unlikely(err)) {
cb3de5fc
SZ
1227 if (should_journal_data)
1228 ext4_journalled_zero_new_buffers(handle, inode, folio,
1229 from, to);
1230 else
1231 folio_zero_new_buffers(folio, from, to);
4f74d15f 1232 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
0b578f35
CR
1233 for (i = 0; i < nr_wait; i++) {
1234 int err2;
1235
86b38c27
MW
1236 err2 = fscrypt_decrypt_pagecache_blocks(folio,
1237 blocksize, bh_offset(wait[i]));
0b578f35
CR
1238 if (err2) {
1239 clear_buffer_uptodate(wait[i]);
1240 err = err2;
1241 }
1242 }
7e0785fc
CR
1243 }
1244
2058f83a
MH
1245 return err;
1246}
2058f83a 1247
9462f770
JK
1248/*
1249 * To preserve ordering, it is essential that the hole instantiation and
1250 * the data write be encapsulated in a single transaction. We cannot
1251 * close off a transaction and start a new one between the ext4_get_block()
1252 * and the ext4_write_end(). So doing the jbd2_journal_start at the start of
1253 * ext4_write_begin() is the right place.
1254 */
bfc1af65 1255static int ext4_write_begin(struct file *file, struct address_space *mapping,
9d6b0cd7 1256 loff_t pos, unsigned len,
1da86618 1257 struct folio **foliop, void **fsdata)
ac27a0ec 1258{
af5bc92d 1259 struct inode *inode = mapping->host;
1938a150 1260 int ret, needed_blocks;
ac27a0ec
DK
1261 handle_t *handle;
1262 int retries = 0;
4d934a5e 1263 struct folio *folio;
de9a55b8 1264 pgoff_t index;
af5bc92d 1265 unsigned from, to;
16705e52 1266 fgf_t fgp = FGP_WRITEBEGIN;
bfc1af65 1267
0a1b2f5e
BL
1268 ret = ext4_emergency_state(inode->i_sb);
1269 if (unlikely(ret))
1270 return ret;
0db1ff22 1271
9d6b0cd7 1272 trace_ext4_write_begin(inode, pos, len);
1938a150
AK
1273 /*
1274 * Reserve one block more for addition to orphan list in case
1275 * we allocate blocks but write fails for some reason
1276 */
1277 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
09cbfeaf 1278 index = pos >> PAGE_SHIFT;
ac27a0ec 1279
f19d5870
TM
1280 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1281 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1da86618 1282 foliop);
f19d5870 1283 if (ret < 0)
47564bfb
TT
1284 return ret;
1285 if (ret == 1)
1286 return 0;
f19d5870
TM
1287 }
1288
47564bfb 1289 /*
4d934a5e
MW
1290 * __filemap_get_folio() can take a long time if the
1291 * system is thrashing due to memory pressure, or if the folio
47564bfb
TT
1292 * is being written back. So grab it first before we start
1293 * the transaction handle. This also allows us to allocate
4d934a5e 1294 * the folio (if needed) without using GFP_NOFS.
47564bfb
TT
1295 */
1296retry_grab:
16705e52
ZY
1297 fgp |= fgf_set_order(len);
1298 folio = __filemap_get_folio(mapping, index, fgp,
1299 mapping_gfp_mask(mapping));
7fa8a8ee
LT
1300 if (IS_ERR(folio))
1301 return PTR_ERR(folio);
16705e52
ZY
1302
1303 if (pos + len > folio_pos(folio) + folio_size(folio))
1304 len = folio_pos(folio) + folio_size(folio) - pos;
1305
1306 from = offset_in_folio(folio, pos);
1307 to = from + len;
1308
d1052d23
JH
1309 /*
1310 * The same as page allocation, we prealloc buffer heads before
1311 * starting the handle.
1312 */
4d934a5e 1313 if (!folio_buffers(folio))
0a88810d 1314 create_empty_buffers(folio, inode->i_sb->s_blocksize, 0);
d1052d23 1315
4d934a5e 1316 folio_unlock(folio);
47564bfb
TT
1317
1318retry_journal:
9924a92a 1319 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
af5bc92d 1320 if (IS_ERR(handle)) {
4d934a5e 1321 folio_put(folio);
47564bfb 1322 return PTR_ERR(handle);
7479d2b9 1323 }
ac27a0ec 1324
4d934a5e
MW
1325 folio_lock(folio);
1326 if (folio->mapping != mapping) {
1327 /* The folio got truncated from under us */
1328 folio_unlock(folio);
1329 folio_put(folio);
cf108bca 1330 ext4_journal_stop(handle);
47564bfb 1331 goto retry_grab;
cf108bca 1332 }
4d934a5e
MW
1333 /* In case writeback began while the folio was unlocked */
1334 folio_wait_stable(folio);
cf108bca 1335
2058f83a 1336 if (ext4_should_dioread_nolock(inode))
cb3de5fc 1337 ret = ext4_block_write_begin(handle, folio, pos, len,
705965bd 1338 ext4_get_block_unwritten);
2058f83a 1339 else
cb3de5fc
SZ
1340 ret = ext4_block_write_begin(handle, folio, pos, len,
1341 ext4_get_block);
bfc1af65 1342 if (!ret && ext4_should_journal_data(inode)) {
188c299e 1343 ret = ext4_walk_page_buffers(handle, inode,
4d934a5e
MW
1344 folio_buffers(folio), from, to,
1345 NULL, do_journal_get_write_access);
ac27a0ec 1346 }
bfc1af65
NP
1347
1348 if (ret) {
c93d8f88
EB
1349 bool extended = (pos + len > inode->i_size) &&
1350 !ext4_verity_in_progress(inode);
1351
4d934a5e 1352 folio_unlock(folio);
ae4d5372 1353 /*
6b730a40 1354 * ext4_block_write_begin may have instantiated a few blocks
ae4d5372 1355 * outside i_size. Trim these off again. Don't need
f340b3d9 1356 * i_size_read because we hold i_rwsem.
1938a150
AK
1357 *
1358 * Add inode to orphan list in case we crash before
1359 * truncate finishes
ae4d5372 1360 */
c93d8f88 1361 if (extended && ext4_can_truncate(inode))
1938a150
AK
1362 ext4_orphan_add(handle, inode);
1363
1364 ext4_journal_stop(handle);
c93d8f88 1365 if (extended) {
b9a4207d 1366 ext4_truncate_failed_write(inode);
de9a55b8 1367 /*
ffacfa7a 1368 * If truncate failed early the inode might
1938a150
AK
1369 * still be on the orphan list; we need to
1370 * make sure the inode is removed from the
1371 * orphan list in that case.
1372 */
1373 if (inode->i_nlink)
1374 ext4_orphan_del(NULL, inode);
1375 }
bfc1af65 1376
47564bfb
TT
1377 if (ret == -ENOSPC &&
1378 ext4_should_retry_alloc(inode->i_sb, &retries))
1379 goto retry_journal;
4d934a5e 1380 folio_put(folio);
47564bfb
TT
1381 return ret;
1382 }
1da86618 1383 *foliop = folio;
ac27a0ec
DK
1384 return ret;
1385}
1386
bfc1af65 1387/* For write_end() in data=journal mode */
188c299e
JK
1388static int write_end_fn(handle_t *handle, struct inode *inode,
1389 struct buffer_head *bh)
ac27a0ec 1390{
13fca323 1391 int ret;
ac27a0ec
DK
1392 if (!buffer_mapped(bh) || buffer_freed(bh))
1393 return 0;
1394 set_buffer_uptodate(bh);
d84c9ebd 1395 ret = ext4_dirty_journalled_data(handle, bh);
13fca323
TT
1396 clear_buffer_meta(bh);
1397 clear_buffer_prio(bh);
1398 return ret;
ac27a0ec
DK
1399}
1400
eed4333f
ZL
1401/*
1402 * We need to pick up the new inode size which generic_commit_write gave us
1403 * `file' can be NULL - eg, when called from page_symlink().
1404 *
600f111e 1405 * ext4 never places buffers on inode->i_mapping->i_private_list. metadata
eed4333f
ZL
1406 * buffers are managed internally.
1407 */
1408static int ext4_write_end(struct file *file,
1409 struct address_space *mapping,
1410 loff_t pos, unsigned len, unsigned copied,
a225800f 1411 struct folio *folio, void *fsdata)
f8514083 1412{
f8514083 1413 handle_t *handle = ext4_journal_current_handle();
eed4333f 1414 struct inode *inode = mapping->host;
0572639f 1415 loff_t old_size = inode->i_size;
eed4333f
ZL
1416 int ret = 0, ret2;
1417 int i_size_changed = 0;
c93d8f88 1418 bool verity = ext4_verity_in_progress(inode);
eed4333f
ZL
1419
1420 trace_ext4_write_end(inode, pos, len, copied);
6984aef5 1421
5c099c4f
YB
1422 if (ext4_has_inline_data(inode) &&
1423 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
d19500da
RH
1424 return ext4_write_inline_data_end(inode, pos, len, copied,
1425 folio);
6984aef5 1426
97edbc02 1427 copied = block_write_end(file, mapping, pos, len, copied, folio, fsdata);
f8514083 1428 /*
64fb3136 1429 * it's important to update i_size while still holding folio lock:
f8514083 1430 * page writeout could otherwise come in and zero beyond i_size.
c93d8f88
EB
1431 *
1432 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1433 * blocks are being written past EOF, so skip the i_size update.
f8514083 1434 */
c93d8f88
EB
1435 if (!verity)
1436 i_size_changed = ext4_update_inode_size(inode, pos + copied);
64fb3136
MW
1437 folio_unlock(folio);
1438 folio_put(folio);
f8514083 1439
c7fc0366 1440 if (old_size < pos && !verity) {
0572639f 1441 pagecache_isize_extended(inode, old_size, pos);
c7fc0366
BF
1442 ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1443 }
f8514083 1444 /*
64fb3136
MW
1445 * Don't mark the inode dirty under folio lock. First, it unnecessarily
1446 * makes the holding time of folio lock longer. Second, it forces lock
1447 * ordering of folio lock and transaction start for journaling
f8514083
AK
1448 * filesystems.
1449 */
6984aef5 1450 if (i_size_changed)
4209ae12 1451 ret = ext4_mark_inode_dirty(handle, inode);
f8514083 1452
c93d8f88 1453 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
f8514083
AK
1454 /* if we have allocated more blocks and copied
1455 * less. We will have blocks allocated outside
1456 * inode->i_size. So truncate them
1457 */
1458 ext4_orphan_add(handle, inode);
55ce2f64 1459
617ba13b 1460 ret2 = ext4_journal_stop(handle);
ac27a0ec
DK
1461 if (!ret)
1462 ret = ret2;
bfc1af65 1463
c93d8f88 1464 if (pos + len > inode->i_size && !verity) {
b9a4207d 1465 ext4_truncate_failed_write(inode);
de9a55b8 1466 /*
ffacfa7a 1467 * If truncate failed early the inode might still be
f8514083
AK
1468 * on the orphan list; we need to make sure the inode
1469 * is removed from the orphan list in that case.
1470 */
1471 if (inode->i_nlink)
1472 ext4_orphan_del(NULL, inode);
1473 }
1474
bfc1af65 1475 return ret ? ret : copied;
ac27a0ec
DK
1476}
1477
b90197b6 1478/*
4a9622f2 1479 * This is a private version of folio_zero_new_buffers() which doesn't
b90197b6 1480 * set the buffer to be dirty, since in data=journalled mode we need
d84c9ebd 1481 * to call ext4_dirty_journalled_data() instead.
b90197b6 1482 */
3b136499 1483static void ext4_journalled_zero_new_buffers(handle_t *handle,
188c299e 1484 struct inode *inode,
86324a21 1485 struct folio *folio,
3b136499 1486 unsigned from, unsigned to)
b90197b6
TT
1487{
1488 unsigned int block_start = 0, block_end;
1489 struct buffer_head *head, *bh;
1490
86324a21 1491 bh = head = folio_buffers(folio);
b90197b6
TT
1492 do {
1493 block_end = block_start + bh->b_size;
1494 if (buffer_new(bh)) {
1495 if (block_end > from && block_start < to) {
86324a21 1496 if (!folio_test_uptodate(folio)) {
b90197b6
TT
1497 unsigned start, size;
1498
1499 start = max(from, block_start);
1500 size = min(to, block_end) - start;
1501
86324a21 1502 folio_zero_range(folio, start, size);
b90197b6
TT
1503 }
1504 clear_buffer_new(bh);
3910b513 1505 write_end_fn(handle, inode, bh);
b90197b6
TT
1506 }
1507 }
1508 block_start = block_end;
1509 bh = bh->b_this_page;
1510 } while (bh != head);
1511}
1512
bfc1af65 1513static int ext4_journalled_write_end(struct file *file,
de9a55b8
TT
1514 struct address_space *mapping,
1515 loff_t pos, unsigned len, unsigned copied,
a225800f 1516 struct folio *folio, void *fsdata)
ac27a0ec 1517{
617ba13b 1518 handle_t *handle = ext4_journal_current_handle();
bfc1af65 1519 struct inode *inode = mapping->host;
0572639f 1520 loff_t old_size = inode->i_size;
ac27a0ec
DK
1521 int ret = 0, ret2;
1522 int partial = 0;
bfc1af65 1523 unsigned from, to;
4631dbf6 1524 int size_changed = 0;
c93d8f88 1525 bool verity = ext4_verity_in_progress(inode);
ac27a0ec 1526
9bffad1e 1527 trace_ext4_journalled_write_end(inode, pos, len, copied);
09cbfeaf 1528 from = pos & (PAGE_SIZE - 1);
bfc1af65
NP
1529 to = from + len;
1530
441c8508
CW
1531 BUG_ON(!ext4_handle_valid(handle));
1532
6984aef5 1533 if (ext4_has_inline_data(inode))
d19500da
RH
1534 return ext4_write_inline_data_end(inode, pos, len, copied,
1535 folio);
6984aef5 1536
feb22b77 1537 if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
3b136499 1538 copied = 0;
86324a21
MW
1539 ext4_journalled_zero_new_buffers(handle, inode, folio,
1540 from, to);
3b136499
JK
1541 } else {
1542 if (unlikely(copied < len))
86324a21 1543 ext4_journalled_zero_new_buffers(handle, inode, folio,
3b136499 1544 from + copied, to);
feb22b77
MW
1545 ret = ext4_walk_page_buffers(handle, inode,
1546 folio_buffers(folio),
188c299e 1547 from, from + copied, &partial,
3b136499 1548 write_end_fn);
3fdcfb66 1549 if (!partial)
feb22b77 1550 folio_mark_uptodate(folio);
3fdcfb66 1551 }
c93d8f88
EB
1552 if (!verity)
1553 size_changed = ext4_update_inode_size(inode, pos + copied);
2d859db3 1554 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
feb22b77
MW
1555 folio_unlock(folio);
1556 folio_put(folio);
4631dbf6 1557
c7fc0366 1558 if (old_size < pos && !verity) {
0572639f 1559 pagecache_isize_extended(inode, old_size, pos);
c7fc0366
BF
1560 ext4_zero_partial_blocks(handle, inode, old_size, pos - old_size);
1561 }
0572639f 1562
6984aef5 1563 if (size_changed) {
617ba13b 1564 ret2 = ext4_mark_inode_dirty(handle, inode);
ac27a0ec
DK
1565 if (!ret)
1566 ret = ret2;
1567 }
bfc1af65 1568
c93d8f88 1569 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
f8514083
AK
1570 /* if we have allocated more blocks and copied
1571 * less. We will have blocks allocated outside
1572 * inode->i_size. So truncate them
1573 */
1574 ext4_orphan_add(handle, inode);
1575
617ba13b 1576 ret2 = ext4_journal_stop(handle);
ac27a0ec
DK
1577 if (!ret)
1578 ret = ret2;
c93d8f88 1579 if (pos + len > inode->i_size && !verity) {
b9a4207d 1580 ext4_truncate_failed_write(inode);
de9a55b8 1581 /*
ffacfa7a 1582 * If truncate failed early the inode might still be
f8514083
AK
1583 * on the orphan list; we need to make sure the inode
1584 * is removed from the orphan list in that case.
1585 */
1586 if (inode->i_nlink)
1587 ext4_orphan_del(NULL, inode);
1588 }
bfc1af65
NP
1589
1590 return ret ? ret : copied;
ac27a0ec 1591}
d2a17637 1592
9d0be502 1593/*
0d66b23d 1594 * Reserve space for 'nr_resv' clusters
9d0be502 1595 */
0d66b23d 1596static int ext4_da_reserve_space(struct inode *inode, int nr_resv)
d2a17637 1597{
60e58e0f 1598 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 1599 struct ext4_inode_info *ei = EXT4_I(inode);
5dd4056d 1600 int ret;
03179fe9
TT
1601
1602 /*
1603 * We will charge metadata quota at writeout time; this saves
1604 * us from metadata over-estimation, though we may go over by
1605 * a small amount in the end. Here we just reserve for data.
1606 */
0d66b23d 1607 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, nr_resv));
03179fe9
TT
1608 if (ret)
1609 return ret;
d2a17637 1610
0637c6f4 1611 spin_lock(&ei->i_block_reservation_lock);
0d66b23d 1612 if (ext4_claim_free_clusters(sbi, nr_resv, 0)) {
03179fe9 1613 spin_unlock(&ei->i_block_reservation_lock);
0d66b23d 1614 dquot_release_reservation_block(inode, EXT4_C2B(sbi, nr_resv));
d2a17637
MC
1615 return -ENOSPC;
1616 }
0d66b23d
ZY
1617 ei->i_reserved_data_blocks += nr_resv;
1618 trace_ext4_da_reserve_space(inode, nr_resv);
0637c6f4 1619 spin_unlock(&ei->i_block_reservation_lock);
39bc680a 1620
d2a17637
MC
1621 return 0; /* success */
1622}
1623
f456767d 1624void ext4_da_release_space(struct inode *inode, int to_free)
d2a17637
MC
1625{
1626 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 1627 struct ext4_inode_info *ei = EXT4_I(inode);
d2a17637 1628
cd213226
MC
1629 if (!to_free)
1630 return; /* Nothing to release, exit */
1631
d2a17637 1632 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
cd213226 1633
5a58ec87 1634 trace_ext4_da_release_space(inode, to_free);
0637c6f4 1635 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
cd213226 1636 /*
0637c6f4
TT
1637 * if there aren't enough reserved blocks, then the
1638 * counter is messed up somewhere. Since this
1639 * function is called from invalidate page, it's
1640 * harmless to return without any action.
cd213226 1641 */
8de5c325 1642 ext4_warning(inode->i_sb, "ext4_da_release_space: "
0637c6f4 1643 "ino %lu, to_free %d with only %d reserved "
1084f252 1644 "data blocks", inode->i_ino, to_free,
0637c6f4
TT
1645 ei->i_reserved_data_blocks);
1646 WARN_ON(1);
1647 to_free = ei->i_reserved_data_blocks;
cd213226 1648 }
0637c6f4 1649 ei->i_reserved_data_blocks -= to_free;
cd213226 1650
72b8ab9d 1651 /* update fs dirty data blocks counter */
57042651 1652 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
d2a17637 1653
d2a17637 1654 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
60e58e0f 1655
7b415bf6 1656 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
d2a17637
MC
1657}
1658
64769240
AT
1659/*
1660 * Delayed allocation stuff
1661 */
1662
4e7ea81d 1663struct mpage_da_data {
15648d59 1664 /* These are input fields for ext4_do_writepages() */
4e7ea81d
JK
1665 struct inode *inode;
1666 struct writeback_control *wbc;
15648d59 1667 unsigned int can_map:1; /* Can writepages call map blocks? */
6b523df4 1668
15648d59 1669 /* These are internal state of ext4_do_writepages() */
4e7ea81d
JK
1670 pgoff_t first_page; /* The first page to write */
1671 pgoff_t next_page; /* Current page to examine */
1672 pgoff_t last_page; /* Last page to examine */
791b7f08 1673 /*
4e7ea81d
JK
1674 * Extent to map - this can be after first_page because that can be
1675 * fully mapped. We somewhat abuse m_flags to store whether the extent
1676 * is delalloc or unwritten.
791b7f08 1677 */
4e7ea81d
JK
1678 struct ext4_map_blocks map;
1679 struct ext4_io_submit io_submit; /* IO submission data */
dddbd6ac 1680 unsigned int do_map:1;
6b8ed620 1681 unsigned int scanned_until_end:1;
1f1a55f0 1682 unsigned int journalled_more_data:1;
4e7ea81d 1683};
64769240 1684
4e7ea81d
JK
1685static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1686 bool invalidate)
c4a0c46e 1687{
fb5a5be0 1688 unsigned nr, i;
c4a0c46e 1689 pgoff_t index, end;
fb5a5be0 1690 struct folio_batch fbatch;
c4a0c46e
AK
1691 struct inode *inode = mpd->inode;
1692 struct address_space *mapping = inode->i_mapping;
4e7ea81d
JK
1693
1694 /* This is necessary when next_page == 0. */
1695 if (mpd->first_page >= mpd->next_page)
1696 return;
c4a0c46e 1697
6b8ed620 1698 mpd->scanned_until_end = 0;
c7f5938a
CW
1699 index = mpd->first_page;
1700 end = mpd->next_page - 1;
4e7ea81d
JK
1701 if (invalidate) {
1702 ext4_lblk_t start, last;
09cbfeaf
KS
1703 start = index << (PAGE_SHIFT - inode->i_blkbits);
1704 last = end << (PAGE_SHIFT - inode->i_blkbits);
7f0d8e1d
EW
1705
1706 /*
1707 * avoid racing with extent status tree scans made by
1708 * ext4_insert_delayed_block()
1709 */
1710 down_write(&EXT4_I(inode)->i_data_sem);
4e7ea81d 1711 ext4_es_remove_extent(inode, start, last - start + 1);
7f0d8e1d 1712 up_write(&EXT4_I(inode)->i_data_sem);
4e7ea81d 1713 }
51865fda 1714
fb5a5be0 1715 folio_batch_init(&fbatch);
c4a0c46e 1716 while (index <= end) {
fb5a5be0
MWO
1717 nr = filemap_get_folios(mapping, &index, end, &fbatch);
1718 if (nr == 0)
c4a0c46e 1719 break;
fb5a5be0
MWO
1720 for (i = 0; i < nr; i++) {
1721 struct folio *folio = fbatch.folios[i];
2b85a617 1722
fb5a5be0
MWO
1723 if (folio->index < mpd->first_page)
1724 continue;
87b11f86 1725 if (folio_next_index(folio) - 1 > end)
fb5a5be0 1726 continue;
7ba13abb
MWO
1727 BUG_ON(!folio_test_locked(folio));
1728 BUG_ON(folio_test_writeback(folio));
4e7ea81d 1729 if (invalidate) {
7ba13abb
MWO
1730 if (folio_mapped(folio))
1731 folio_clear_dirty_for_io(folio);
1732 block_invalidate_folio(folio, 0,
1733 folio_size(folio));
1734 folio_clear_uptodate(folio);
4e7ea81d 1735 }
7ba13abb 1736 folio_unlock(folio);
c4a0c46e 1737 }
fb5a5be0 1738 folio_batch_release(&fbatch);
c4a0c46e 1739 }
c4a0c46e
AK
1740}
1741
df22291f
AK
1742static void ext4_print_free_blocks(struct inode *inode)
1743{
1744 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
92b97816 1745 struct super_block *sb = inode->i_sb;
f78ee70d 1746 struct ext4_inode_info *ei = EXT4_I(inode);
92b97816
TT
1747
1748 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
5dee5437 1749 EXT4_C2B(EXT4_SB(inode->i_sb),
f78ee70d 1750 ext4_count_free_clusters(sb)));
92b97816
TT
1751 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1752 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
f78ee70d 1753 (long long) EXT4_C2B(EXT4_SB(sb),
57042651 1754 percpu_counter_sum(&sbi->s_freeclusters_counter)));
92b97816 1755 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
f78ee70d 1756 (long long) EXT4_C2B(EXT4_SB(sb),
7b415bf6 1757 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
92b97816
TT
1758 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1759 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
f78ee70d 1760 ei->i_reserved_data_blocks);
df22291f
AK
1761 return;
1762}
1763
49bf6ab4
ZY
1764/*
1765 * Check whether the cluster containing lblk has been allocated or has
1766 * delalloc reservation.
1767 *
1768 * Returns 0 if the cluster doesn't have either, 1 if it has delalloc
1769 * reservation, 2 if it's already been allocated, negative error code on
1770 * failure.
1771 */
1772static int ext4_clu_alloc_state(struct inode *inode, ext4_lblk_t lblk)
1773{
1774 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1775 int ret;
1776
1777 /* Has delalloc reservation? */
b224b184 1778 if (ext4_es_scan_clu(inode, &ext4_es_is_delayed, lblk))
49bf6ab4
ZY
1779 return 1;
1780
1781 /* Already been allocated? */
1782 if (ext4_es_scan_clu(inode, &ext4_es_is_mapped, lblk))
1783 return 2;
1784 ret = ext4_clu_mapped(inode, EXT4_B2C(sbi, lblk));
1785 if (ret < 0)
1786 return ret;
1787 if (ret > 0)
1788 return 2;
1789
1790 return 0;
1791}
1792
0b02f4c0 1793/*
1850d76c
ZY
1794 * ext4_insert_delayed_blocks - adds a multiple delayed blocks to the extents
1795 * status tree, incrementing the reserved
1796 * cluster/block count or making pending
1797 * reservations where needed
0b02f4c0
EW
1798 *
1799 * @inode - file containing the newly added block
1850d76c
ZY
1800 * @lblk - start logical block to be added
1801 * @len - length of blocks to be added
0b02f4c0
EW
1802 *
1803 * Returns 0 on success, negative error code on failure.
1804 */
1850d76c
ZY
1805static int ext4_insert_delayed_blocks(struct inode *inode, ext4_lblk_t lblk,
1806 ext4_lblk_t len)
0b02f4c0
EW
1807{
1808 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1809 int ret;
1850d76c
ZY
1810 bool lclu_allocated = false;
1811 bool end_allocated = false;
1812 ext4_lblk_t resv_clu;
1813 ext4_lblk_t end = lblk + len - 1;
0b02f4c0
EW
1814
1815 /*
1850d76c 1816 * If the cluster containing lblk or end is shared with a delayed,
0b02f4c0
EW
1817 * written, or unwritten extent in a bigalloc file system, it's
1818 * already been accounted for and does not need to be reserved.
1819 * A pending reservation must be made for the cluster if it's
1820 * shared with a written or unwritten extent and doesn't already
1821 * have one. Written and unwritten extents can be purged from the
1822 * extents status tree if the system is under memory pressure, so
1823 * it's necessary to examine the extent tree if a search of the
1824 * extents status tree doesn't get a match.
1825 */
1826 if (sbi->s_cluster_ratio == 1) {
1850d76c 1827 ret = ext4_da_reserve_space(inode, len);
0b02f4c0 1828 if (ret != 0) /* ENOSPC */
8782b020 1829 return ret;
0b02f4c0 1830 } else { /* bigalloc */
1850d76c
ZY
1831 resv_clu = EXT4_B2C(sbi, end) - EXT4_B2C(sbi, lblk) + 1;
1832
49bf6ab4
ZY
1833 ret = ext4_clu_alloc_state(inode, lblk);
1834 if (ret < 0)
1835 return ret;
1850d76c
ZY
1836 if (ret > 0) {
1837 resv_clu--;
1838 lclu_allocated = (ret == 2);
1839 }
1840
1841 if (EXT4_B2C(sbi, lblk) != EXT4_B2C(sbi, end)) {
1842 ret = ext4_clu_alloc_state(inode, end);
1843 if (ret < 0)
1844 return ret;
1845 if (ret > 0) {
1846 resv_clu--;
1847 end_allocated = (ret == 2);
1848 }
1849 }
1850
1851 if (resv_clu) {
1852 ret = ext4_da_reserve_space(inode, resv_clu);
49bf6ab4
ZY
1853 if (ret != 0) /* ENOSPC */
1854 return ret;
0b02f4c0
EW
1855 }
1856 }
1857
1850d76c
ZY
1858 ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated,
1859 end_allocated);
8782b020 1860 return 0;
0b02f4c0
EW
1861}
1862
5356f261 1863/*
8262fe9a
ZY
1864 * Looks up the requested blocks and sets the delalloc extent map.
1865 * First try to look up for the extent entry that contains the requested
1866 * blocks in the extent status tree without i_data_sem, then try to look
1867 * up for the ondisk extent mapping with i_data_sem in read mode,
1868 * finally hold i_data_sem in write mode, looks up again and add a
1869 * delalloc extent entry if it still couldn't find any extent. Pass out
1870 * the mapped extent through @map and return 0 on success.
5356f261 1871 */
8262fe9a 1872static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map)
5356f261 1873{
d100eef2 1874 struct extent_status es;
5356f261 1875 int retval;
921f266b
DM
1876#ifdef ES_AGGRESSIVE_TEST
1877 struct ext4_map_blocks orig_map;
1878
1879 memcpy(&orig_map, map, sizeof(*map));
1880#endif
5356f261 1881
5356f261 1882 map->m_flags = 0;
70aa1554 1883 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
5356f261 1884 (unsigned long) map->m_lblk);
d100eef2 1885
1b4d2a0b
ZY
1886 ext4_check_map_extents_env(inode);
1887
d100eef2 1888 /* Lookup extent status tree firstly */
bb6b1805 1889 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
8262fe9a
ZY
1890 map->m_len = min_t(unsigned int, map->m_len,
1891 es.es_len - (map->m_lblk - es.es_lblk));
14a210c1 1892
acf795dc 1893 if (ext4_es_is_hole(&es))
d100eef2 1894 goto add_delayed;
d100eef2 1895
0ea6560a 1896found:
d100eef2 1897 /*
3eda41df
EW
1898 * Delayed extent could be allocated by fallocate.
1899 * So we need to check it.
d100eef2 1900 */
b224b184 1901 if (ext4_es_is_delayed(&es)) {
8262fe9a 1902 map->m_flags |= EXT4_MAP_DELAYED;
d100eef2
ZL
1903 return 0;
1904 }
1905
bb6b1805 1906 map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk;
d100eef2
ZL
1907 if (ext4_es_is_written(&es))
1908 map->m_flags |= EXT4_MAP_MAPPED;
1909 else if (ext4_es_is_unwritten(&es))
1910 map->m_flags |= EXT4_MAP_UNWRITTEN;
1911 else
1e83bc81 1912 BUG();
d100eef2 1913
921f266b
DM
1914#ifdef ES_AGGRESSIVE_TEST
1915 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1916#endif
8262fe9a 1917 return 0;
d100eef2
ZL
1918 }
1919
5356f261
AK
1920 /*
1921 * Try to see if we can get the block without requesting a new
1922 * file system block.
1923 */
c8b459f4 1924 down_read(&EXT4_I(inode)->i_data_sem);
cbd7584e 1925 if (ext4_has_inline_data(inode))
9c3569b5 1926 retval = 0;
5356f261 1927 else
402e38e6 1928 retval = ext4_map_query_blocks(NULL, inode, map, 0);
acf795dc 1929 up_read(&EXT4_I(inode)->i_data_sem);
8e4e5cdf 1930 if (retval)
8262fe9a 1931 return retval < 0 ? retval : 0;
5356f261 1932
3fcc2b88 1933add_delayed:
acf795dc 1934 down_write(&EXT4_I(inode)->i_data_sem);
0ea6560a
ZY
1935 /*
1936 * Page fault path (ext4_page_mkwrite does not take i_rwsem)
1937 * and fallocate path (no folio lock) can race. Make sure we
1938 * lookup the extent status tree here again while i_data_sem
1939 * is held in write mode, before inserting a new da entry in
1940 * the extent status tree.
1941 */
bb6b1805 1942 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
8262fe9a
ZY
1943 map->m_len = min_t(unsigned int, map->m_len,
1944 es.es_len - (map->m_lblk - es.es_lblk));
14a210c1 1945
0ea6560a
ZY
1946 if (!ext4_es_is_hole(&es)) {
1947 up_write(&EXT4_I(inode)->i_data_sem);
1948 goto found;
1949 }
1950 } else if (!ext4_has_inline_data(inode)) {
402e38e6 1951 retval = ext4_map_query_blocks(NULL, inode, map, 0);
0ea6560a
ZY
1952 if (retval) {
1953 up_write(&EXT4_I(inode)->i_data_sem);
8262fe9a 1954 return retval < 0 ? retval : 0;
0ea6560a
ZY
1955 }
1956 }
1957
8262fe9a 1958 map->m_flags |= EXT4_MAP_DELAYED;
1850d76c 1959 retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len);
acf795dc 1960 up_write(&EXT4_I(inode)->i_data_sem);
3fcc2b88 1961
5356f261
AK
1962 return retval;
1963}
1964
64769240 1965/*
d91bd2c1 1966 * This is a special get_block_t callback which is used by
b920c755
TT
1967 * ext4_da_write_begin(). It will either return mapped block or
1968 * reserve space for a single block.
29fa89d0
AK
1969 *
1970 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1971 * We also have b_blocknr = -1 and b_bdev initialized properly
1972 *
1973 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1974 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1975 * initialized properly.
64769240 1976 */
9c3569b5
TM
1977int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1978 struct buffer_head *bh, int create)
64769240 1979{
2ed88685 1980 struct ext4_map_blocks map;
8262fe9a 1981 sector_t invalid_block = ~((sector_t) 0xffff);
64769240
AT
1982 int ret = 0;
1983
1984 BUG_ON(create == 0);
2ed88685
TT
1985 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1986
8262fe9a
ZY
1987 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1988 invalid_block = ~0;
1989
2ed88685
TT
1990 map.m_lblk = iblock;
1991 map.m_len = 1;
64769240
AT
1992
1993 /*
1994 * first, we need to know whether the block is allocated already
1995 * preallocated blocks are unmapped but should treated
1996 * the same as allocated blocks.
1997 */
8262fe9a
ZY
1998 ret = ext4_da_map_blocks(inode, &map);
1999 if (ret < 0)
2ed88685 2000 return ret;
64769240 2001
8262fe9a
ZY
2002 if (map.m_flags & EXT4_MAP_DELAYED) {
2003 map_bh(bh, inode->i_sb, invalid_block);
2004 set_buffer_new(bh);
2005 set_buffer_delay(bh);
2006 return 0;
2007 }
2008
2ed88685 2009 map_bh(bh, inode->i_sb, map.m_pblk);
ed8ad838 2010 ext4_update_bh_state(bh, map.m_flags);
2ed88685
TT
2011
2012 if (buffer_unwritten(bh)) {
2013 /* A delayed write to unwritten bh should be marked
2014 * new and mapped. Mapped ensures that we don't do
2015 * get_block multiple times when we write to the same
2016 * offset and new ensures that we do proper zero out
2017 * for partial write.
2018 */
2019 set_buffer_new(bh);
c8205636 2020 set_buffer_mapped(bh);
2ed88685
TT
2021 }
2022 return 0;
64769240 2023}
61628a3f 2024
33483b3b 2025static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
eaf2ca10 2026{
33483b3b
MW
2027 mpd->first_page += folio_nr_pages(folio);
2028 folio_unlock(folio);
eaf2ca10
JK
2029}
2030
81a0d3e1 2031static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
5f1132b2 2032{
81a0d3e1 2033 size_t len;
a056bdaa 2034 loff_t size;
5f1132b2
JK
2035 int err;
2036
81a0d3e1
MW
2037 BUG_ON(folio->index != mpd->first_page);
2038 folio_clear_dirty_for_io(folio);
a056bdaa
JK
2039 /*
2040 * We have to be very careful here! Nothing protects writeback path
2041 * against i_size changes and the page can be writeably mapped into
2042 * page tables. So an application can be growing i_size and writing
81a0d3e1 2043 * data through mmap while writeback runs. folio_clear_dirty_for_io()
a056bdaa 2044 * write-protects our page in page tables and the page cannot get
81a0d3e1
MW
2045 * written to again until we release folio lock. So only after
2046 * folio_clear_dirty_for_io() we are safe to sample i_size for
e8d6062c
MW
2047 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
2048 * on the barrier provided by folio_test_clear_dirty() in
81a0d3e1 2049 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
a056bdaa
JK
2050 * after page tables are updated.
2051 */
2052 size = i_size_read(mpd->inode);
81a0d3e1
MW
2053 len = folio_size(folio);
2054 if (folio_pos(folio) + len > size &&
c93d8f88 2055 !ext4_verity_in_progress(mpd->inode))
53c17fe5 2056 len = size & (len - 1);
e8d6062c 2057 err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
5f1132b2 2058 if (!err)
cd9f76de 2059 mpd->wbc->nr_to_write -= folio_nr_pages(folio);
5f1132b2
JK
2060
2061 return err;
2062}
2063
6db07461 2064#define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
4e7ea81d 2065
61628a3f 2066/*
fffb2739
JK
2067 * mballoc gives us at most this number of blocks...
2068 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
70261f56 2069 * The rest of mballoc seems to handle chunks up to full group size.
61628a3f 2070 */
fffb2739 2071#define MAX_WRITEPAGES_EXTENT_LEN 2048
525f4ed8 2072
4e7ea81d
JK
2073/*
2074 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2075 *
2076 * @mpd - extent of blocks
2077 * @lblk - logical number of the block in the file
09930042 2078 * @bh - buffer head we want to add to the extent
4e7ea81d 2079 *
09930042
JK
2080 * The function is used to collect contig. blocks in the same state. If the
2081 * buffer doesn't require mapping for writeback and we haven't started the
2082 * extent of buffers to map yet, the function returns 'true' immediately - the
2083 * caller can write the buffer right away. Otherwise the function returns true
2084 * if the block has been added to the extent, false if the block couldn't be
2085 * added.
4e7ea81d 2086 */
09930042
JK
2087static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2088 struct buffer_head *bh)
4e7ea81d
JK
2089{
2090 struct ext4_map_blocks *map = &mpd->map;
2091
09930042
JK
2092 /* Buffer that doesn't need mapping for writeback? */
2093 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2094 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2095 /* So far no extent to map => we write the buffer right away */
2096 if (map->m_len == 0)
2097 return true;
2098 return false;
2099 }
4e7ea81d
JK
2100
2101 /* First block in the extent? */
2102 if (map->m_len == 0) {
dddbd6ac
JK
2103 /* We cannot map unless handle is started... */
2104 if (!mpd->do_map)
2105 return false;
4e7ea81d
JK
2106 map->m_lblk = lblk;
2107 map->m_len = 1;
09930042
JK
2108 map->m_flags = bh->b_state & BH_FLAGS;
2109 return true;
4e7ea81d
JK
2110 }
2111
09930042
JK
2112 /* Don't go larger than mballoc is willing to allocate */
2113 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2114 return false;
2115
4e7ea81d
JK
2116 /* Can we merge the block to our big extent? */
2117 if (lblk == map->m_lblk + map->m_len &&
09930042 2118 (bh->b_state & BH_FLAGS) == map->m_flags) {
4e7ea81d 2119 map->m_len++;
09930042 2120 return true;
4e7ea81d 2121 }
09930042 2122 return false;
4e7ea81d
JK
2123}
2124
5f1132b2
JK
2125/*
2126 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2127 *
2128 * @mpd - extent of blocks for mapping
2129 * @head - the first buffer in the page
2130 * @bh - buffer we should start processing from
2131 * @lblk - logical number of the block in the file corresponding to @bh
2132 *
2133 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2134 * the page for IO if all buffers in this page were mapped and there's no
2135 * accumulated extent of buffers to map or add buffers in the page to the
2136 * extent of buffers to map. The function returns 1 if the caller can continue
2137 * by processing the next page, 0 if it should stop adding buffers to the
2138 * extent to map because we cannot extend it anymore. It can also return value
2139 * < 0 in case of error during IO submission.
2140 */
2141static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2142 struct buffer_head *head,
2143 struct buffer_head *bh,
2144 ext4_lblk_t lblk)
4e7ea81d
JK
2145{
2146 struct inode *inode = mpd->inode;
5f1132b2 2147 int err;
93407472 2148 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
4e7ea81d
JK
2149 >> inode->i_blkbits;
2150
c93d8f88
EB
2151 if (ext4_verity_in_progress(inode))
2152 blocks = EXT_MAX_BLOCKS;
2153
4e7ea81d
JK
2154 do {
2155 BUG_ON(buffer_locked(bh));
2156
09930042 2157 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
4e7ea81d
JK
2158 /* Found extent to map? */
2159 if (mpd->map.m_len)
5f1132b2 2160 return 0;
dddbd6ac
JK
2161 /* Buffer needs mapping and handle is not started? */
2162 if (!mpd->do_map)
2163 return 0;
09930042 2164 /* Everything mapped so far and we hit EOF */
5f1132b2 2165 break;
4e7ea81d 2166 }
4e7ea81d 2167 } while (lblk++, (bh = bh->b_this_page) != head);
5f1132b2
JK
2168 /* So far everything mapped? Submit the page for IO. */
2169 if (mpd->map.m_len == 0) {
81a0d3e1 2170 err = mpage_submit_folio(mpd, head->b_folio);
5f1132b2
JK
2171 if (err < 0)
2172 return err;
33483b3b 2173 mpage_folio_done(mpd, head->b_folio);
5f1132b2 2174 }
6b8ed620
JK
2175 if (lblk >= blocks) {
2176 mpd->scanned_until_end = 1;
2177 return 0;
2178 }
2179 return 1;
4e7ea81d
JK
2180}
2181
2943fdbc 2182/*
4da2f6e3
MW
2183 * mpage_process_folio - update folio buffers corresponding to changed extent
2184 * and may submit fully mapped page for IO
2185 * @mpd: description of extent to map, on return next extent to map
2186 * @folio: Contains these buffers.
2187 * @m_lblk: logical block mapping.
2188 * @m_pblk: corresponding physical mapping.
2189 * @map_bh: determines on return whether this page requires any further
2943fdbc 2190 * mapping or not.
4da2f6e3
MW
2191 *
2192 * Scan given folio buffers corresponding to changed extent and update buffer
2943fdbc
RH
2193 * state according to new extent state.
2194 * We map delalloc buffers to their physical location, clear unwritten bits.
4da2f6e3
MW
2195 * If the given folio is not fully mapped, we update @mpd to the next extent in
2196 * the given folio that needs mapping & return @map_bh as true.
2943fdbc 2197 */
4da2f6e3 2198static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2943fdbc
RH
2199 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2200 bool *map_bh)
2201{
2202 struct buffer_head *head, *bh;
2203 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2204 ext4_lblk_t lblk = *m_lblk;
2205 ext4_fsblk_t pblock = *m_pblk;
2206 int err = 0;
c8cc8816
RH
2207 int blkbits = mpd->inode->i_blkbits;
2208 ssize_t io_end_size = 0;
2209 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2943fdbc 2210
4da2f6e3 2211 bh = head = folio_buffers(folio);
2943fdbc
RH
2212 do {
2213 if (lblk < mpd->map.m_lblk)
2214 continue;
2215 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2216 /*
2217 * Buffer after end of mapped extent.
4da2f6e3 2218 * Find next buffer in the folio to map.
2943fdbc
RH
2219 */
2220 mpd->map.m_len = 0;
2221 mpd->map.m_flags = 0;
c8cc8816 2222 io_end_vec->size += io_end_size;
2943fdbc 2223
2943fdbc
RH
2224 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2225 if (err > 0)
2226 err = 0;
c8cc8816
RH
2227 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2228 io_end_vec = ext4_alloc_io_end_vec(io_end);
4d06bfb9
RH
2229 if (IS_ERR(io_end_vec)) {
2230 err = PTR_ERR(io_end_vec);
2231 goto out;
2232 }
d1e18b88 2233 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
c8cc8816 2234 }
2943fdbc
RH
2235 *map_bh = true;
2236 goto out;
2237 }
2238 if (buffer_delay(bh)) {
2239 clear_buffer_delay(bh);
2240 bh->b_blocknr = pblock++;
2241 }
2242 clear_buffer_unwritten(bh);
c8cc8816 2243 io_end_size += (1 << blkbits);
2943fdbc 2244 } while (lblk++, (bh = bh->b_this_page) != head);
c8cc8816
RH
2245
2246 io_end_vec->size += io_end_size;
2943fdbc
RH
2247 *map_bh = false;
2248out:
2249 *m_lblk = lblk;
2250 *m_pblk = pblock;
2251 return err;
2252}
2253
4e7ea81d
JK
2254/*
2255 * mpage_map_buffers - update buffers corresponding to changed extent and
2256 * submit fully mapped pages for IO
2257 *
2258 * @mpd - description of extent to map, on return next extent to map
2259 *
2260 * Scan buffers corresponding to changed extent (we expect corresponding pages
2261 * to be already locked) and update buffer state according to new extent state.
2262 * We map delalloc buffers to their physical location, clear unwritten bits,
556615dc 2263 * and mark buffers as uninit when we perform writes to unwritten extents
4e7ea81d
JK
2264 * and do extent conversion after IO is finished. If the last page is not fully
2265 * mapped, we update @map to the next extent in the last page that needs
2266 * mapping. Otherwise we submit the page for IO.
2267 */
2268static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2269{
7530d093
MWO
2270 struct folio_batch fbatch;
2271 unsigned nr, i;
4e7ea81d 2272 struct inode *inode = mpd->inode;
09cbfeaf 2273 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
4e7ea81d
JK
2274 pgoff_t start, end;
2275 ext4_lblk_t lblk;
2943fdbc 2276 ext4_fsblk_t pblock;
4e7ea81d 2277 int err;
2943fdbc 2278 bool map_bh = false;
4e7ea81d
JK
2279
2280 start = mpd->map.m_lblk >> bpp_bits;
2281 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
4e7ea81d
JK
2282 pblock = mpd->map.m_pblk;
2283
7530d093 2284 folio_batch_init(&fbatch);
4e7ea81d 2285 while (start <= end) {
7530d093
MWO
2286 nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2287 if (nr == 0)
4e7ea81d 2288 break;
7530d093 2289 for (i = 0; i < nr; i++) {
4da2f6e3 2290 struct folio *folio = fbatch.folios[i];
4e7ea81d 2291
cd9f76de 2292 lblk = folio->index << bpp_bits;
4da2f6e3 2293 err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2943fdbc 2294 &map_bh);
4e7ea81d 2295 /*
2943fdbc
RH
2296 * If map_bh is true, means page may require further bh
2297 * mapping, or maybe the page was submitted for IO.
2298 * So we return to call further extent mapping.
4e7ea81d 2299 */
39c0ae16 2300 if (err < 0 || map_bh)
2943fdbc 2301 goto out;
4e7ea81d 2302 /* Page fully mapped - let IO run! */
81a0d3e1 2303 err = mpage_submit_folio(mpd, folio);
2943fdbc
RH
2304 if (err < 0)
2305 goto out;
33483b3b 2306 mpage_folio_done(mpd, folio);
4e7ea81d 2307 }
7530d093 2308 folio_batch_release(&fbatch);
4e7ea81d
JK
2309 }
2310 /* Extent fully mapped and matches with page boundary. We are done. */
2311 mpd->map.m_len = 0;
2312 mpd->map.m_flags = 0;
2313 return 0;
2943fdbc 2314out:
7530d093 2315 folio_batch_release(&fbatch);
2943fdbc 2316 return err;
4e7ea81d
JK
2317}
2318
2319static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2320{
2321 struct inode *inode = mpd->inode;
2322 struct ext4_map_blocks *map = &mpd->map;
2323 int get_blocks_flags;
090f32ee 2324 int err, dioread_nolock;
4e7ea81d
JK
2325
2326 trace_ext4_da_write_pages_extent(inode, map);
2327 /*
2328 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
556615dc 2329 * to convert an unwritten extent to be initialized (in the case
4e7ea81d
JK
2330 * where we have written into one or more preallocated blocks). It is
2331 * possible that we're going to need more metadata blocks than
2332 * previously reserved. However we must not fail because we're in
2333 * writeback and there is nothing we can do about it so it might result
2334 * in data loss. So use reserved blocks to allocate metadata if
402e38e6
ZY
2335 * possible. In addition, do not cache any unrelated extents, as it
2336 * only holds the folio lock but does not hold the i_rwsem or
2337 * invalidate_lock, which could corrupt the extent status tree.
4e7ea81d
JK
2338 */
2339 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
ee0876bc 2340 EXT4_GET_BLOCKS_METADATA_NOFAIL |
402e38e6
ZY
2341 EXT4_GET_BLOCKS_IO_SUBMIT |
2342 EXT4_EX_NOCACHE;
2343
090f32ee
LC
2344 dioread_nolock = ext4_should_dioread_nolock(inode);
2345 if (dioread_nolock)
4e7ea81d 2346 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
4e7ea81d
JK
2347
2348 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2349 if (err < 0)
2350 return err;
090f32ee 2351 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
6b523df4
JK
2352 if (!mpd->io_submit.io_end->handle &&
2353 ext4_handle_valid(handle)) {
2354 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2355 handle->h_rsv_handle = NULL;
2356 }
5a1cd0e9 2357 ext4_set_io_unwritten_flag(mpd->io_submit.io_end);
6b523df4 2358 }
4e7ea81d
JK
2359
2360 BUG_ON(map->m_len == 0);
4e7ea81d
JK
2361 return 0;
2362}
2363
2364/*
2365 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2366 * mpd->len and submit pages underlying it for IO
2367 *
2368 * @handle - handle for journal operations
2369 * @mpd - extent to map
7534e854
JK
2370 * @give_up_on_write - we set this to true iff there is a fatal error and there
2371 * is no hope of writing the data. The caller should discard
2372 * dirty pages to avoid infinite loops.
4e7ea81d
JK
2373 *
2374 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2375 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2376 * them to initialized or split the described range from larger unwritten
2377 * extent. Note that we need not map all the described range since allocation
2378 * can return less blocks or the range is covered by more unwritten extents. We
2379 * cannot map more because we are limited by reserved transaction credits. On
2380 * the other hand we always make sure that the last touched page is fully
2381 * mapped so that it can be written out (and thus forward progress is
2382 * guaranteed). After mapping we submit all mapped pages for IO.
2383 */
2384static int mpage_map_and_submit_extent(handle_t *handle,
cb530541
TT
2385 struct mpage_da_data *mpd,
2386 bool *give_up_on_write)
4e7ea81d
JK
2387{
2388 struct inode *inode = mpd->inode;
2389 struct ext4_map_blocks *map = &mpd->map;
2390 int err;
2391 loff_t disksize;
6603120e 2392 int progress = 0;
c8cc8816 2393 ext4_io_end_t *io_end = mpd->io_submit.io_end;
4d06bfb9 2394 struct ext4_io_end_vec *io_end_vec;
4e7ea81d 2395
4d06bfb9
RH
2396 io_end_vec = ext4_alloc_io_end_vec(io_end);
2397 if (IS_ERR(io_end_vec))
2398 return PTR_ERR(io_end_vec);
c8cc8816 2399 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
27d7c4ed 2400 do {
4e7ea81d
JK
2401 err = mpage_map_one_extent(handle, mpd);
2402 if (err < 0) {
2403 struct super_block *sb = inode->i_sb;
2404
0a1b2f5e 2405 if (ext4_emergency_state(sb))
cb530541 2406 goto invalidate_dirty_pages;
4e7ea81d 2407 /*
cb530541
TT
2408 * Let the uper layers retry transient errors.
2409 * In the case of ENOSPC, if ext4_count_free_blocks()
2410 * is non-zero, a commit should free up blocks.
4e7ea81d 2411 */
cb530541 2412 if ((err == -ENOMEM) ||
6603120e
DM
2413 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2414 if (progress)
2415 goto update_disksize;
cb530541 2416 return err;
6603120e 2417 }
cb530541
TT
2418 ext4_msg(sb, KERN_CRIT,
2419 "Delayed block allocation failed for "
2420 "inode %lu at logical offset %llu with"
2421 " max blocks %u with error %d",
2422 inode->i_ino,
2423 (unsigned long long)map->m_lblk,
2424 (unsigned)map->m_len, -err);
2425 ext4_msg(sb, KERN_CRIT,
2426 "This should not happen!! Data will "
2427 "be lost\n");
2428 if (err == -ENOSPC)
2429 ext4_print_free_blocks(inode);
2430 invalidate_dirty_pages:
2431 *give_up_on_write = true;
4e7ea81d
JK
2432 return err;
2433 }
6603120e 2434 progress = 1;
4e7ea81d
JK
2435 /*
2436 * Update buffer state, submit mapped pages, and get us new
2437 * extent to map
2438 */
2439 err = mpage_map_and_submit_buffers(mpd);
2440 if (err < 0)
6603120e 2441 goto update_disksize;
27d7c4ed 2442 } while (map->m_len);
4e7ea81d 2443
6603120e 2444update_disksize:
622cad13
TT
2445 /*
2446 * Update on-disk size after IO is submitted. Races with
2447 * truncate are avoided by checking i_size under i_data_sem.
2448 */
09cbfeaf 2449 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
35df4299 2450 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
4e7ea81d 2451 int err2;
622cad13
TT
2452 loff_t i_size;
2453
2454 down_write(&EXT4_I(inode)->i_data_sem);
2455 i_size = i_size_read(inode);
2456 if (disksize > i_size)
2457 disksize = i_size;
2458 if (disksize > EXT4_I(inode)->i_disksize)
2459 EXT4_I(inode)->i_disksize = disksize;
622cad13 2460 up_write(&EXT4_I(inode)->i_data_sem);
b907f2d5 2461 err2 = ext4_mark_inode_dirty(handle, inode);
878520ac 2462 if (err2) {
54d3adbc
TT
2463 ext4_error_err(inode->i_sb, -err2,
2464 "Failed to mark inode %lu dirty",
2465 inode->i_ino);
878520ac 2466 }
4e7ea81d
JK
2467 if (!err)
2468 err = err2;
2469 }
2470 return err;
2471}
2472
fffb2739
JK
2473/*
2474 * Calculate the total number of credits to reserve for one writepages
20970ba6 2475 * iteration. This is called from ext4_writepages(). We map an extent of
70261f56 2476 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
fffb2739
JK
2477 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2478 * bpp - 1 blocks in bpp different extents.
2479 */
525f4ed8
MC
2480static int ext4_da_writepages_trans_blocks(struct inode *inode)
2481{
d6bf2947 2482 int bpp = ext4_journal_blocks_per_folio(inode);
525f4ed8 2483
fffb2739
JK
2484 return ext4_meta_trans_blocks(inode,
2485 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
525f4ed8 2486}
61628a3f 2487
80be8c5c
RH
2488static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
2489 size_t len)
3f079114 2490{
80be8c5c
RH
2491 struct buffer_head *page_bufs = folio_buffers(folio);
2492 struct inode *inode = folio->mapping->host;
3f079114
JK
2493 int ret, err;
2494
2495 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2496 NULL, do_journal_get_write_access);
2497 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
2498 NULL, write_end_fn);
2499 if (ret == 0)
2500 ret = err;
80be8c5c 2501 err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
3f079114
JK
2502 if (ret == 0)
2503 ret = err;
2504 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2505
3f079114
JK
2506 return ret;
2507}
2508
2509static int mpage_journal_page_buffers(handle_t *handle,
2510 struct mpage_da_data *mpd,
80be8c5c 2511 struct folio *folio)
3f079114
JK
2512{
2513 struct inode *inode = mpd->inode;
2514 loff_t size = i_size_read(inode);
80be8c5c 2515 size_t len = folio_size(folio);
3f079114 2516
80be8c5c 2517 folio_clear_checked(folio);
cd9f76de 2518 mpd->wbc->nr_to_write -= folio_nr_pages(folio);
3f079114 2519
80be8c5c 2520 if (folio_pos(folio) + len > size &&
3f079114 2521 !ext4_verity_in_progress(inode))
c2a09f3d 2522 len = size & (len - 1);
3f079114 2523
80be8c5c 2524 return ext4_journal_folio_buffers(handle, folio, len);
3f079114
JK
2525}
2526
8e48dcfb 2527/*
4e7ea81d 2528 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
de0039f6 2529 * needing mapping, submit mapped pages
4e7ea81d
JK
2530 *
2531 * @mpd - where to look for pages
2532 *
2533 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
de0039f6
JK
2534 * IO immediately. If we cannot map blocks, we submit just already mapped
2535 * buffers in the page for IO and keep page dirty. When we can map blocks and
2536 * we find a page which isn't mapped we start accumulating extent of buffers
2537 * underlying these pages that needs mapping (formed by either delayed or
2538 * unwritten buffers). We also lock the pages containing these buffers. The
2539 * extent found is returned in @mpd structure (starting at mpd->lblk with
2540 * length mpd->len blocks).
4e7ea81d
JK
2541 *
2542 * Note that this function can attach bios to one io_end structure which are
2543 * neither logically nor physically contiguous. Although it may seem as an
2544 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2545 * case as we need to track IO to all buffers underlying a page in one io_end.
8e48dcfb 2546 */
4e7ea81d 2547static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
8e48dcfb 2548{
4e7ea81d 2549 struct address_space *mapping = mpd->inode->i_mapping;
50ead253
VMO
2550 struct folio_batch fbatch;
2551 unsigned int nr_folios;
4e7ea81d
JK
2552 pgoff_t index = mpd->first_page;
2553 pgoff_t end = mpd->last_page;
10bbd235 2554 xa_mark_t tag;
4e7ea81d
JK
2555 int i, err = 0;
2556 int blkbits = mpd->inode->i_blkbits;
2557 ext4_lblk_t lblk;
2558 struct buffer_head *head;
3f079114 2559 handle_t *handle = NULL;
d6bf2947 2560 int bpp = ext4_journal_blocks_per_folio(mpd->inode);
8e48dcfb 2561
4e7ea81d 2562 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
5b41d924
ES
2563 tag = PAGECACHE_TAG_TOWRITE;
2564 else
2565 tag = PAGECACHE_TAG_DIRTY;
3f079114 2566
e6c28a26
JK
2567 mpd->map.m_len = 0;
2568 mpd->next_page = index;
d0ab8368 2569 if (ext4_should_journal_data(mpd->inode)) {
3f079114
JK
2570 handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
2571 bpp);
2572 if (IS_ERR(handle))
2573 return PTR_ERR(handle);
2574 }
50ead253 2575 folio_batch_init(&fbatch);
4f01b02c 2576 while (index <= end) {
50ead253
VMO
2577 nr_folios = filemap_get_folios_tag(mapping, &index, end,
2578 tag, &fbatch);
2579 if (nr_folios == 0)
6b8ed620 2580 break;
8e48dcfb 2581
50ead253
VMO
2582 for (i = 0; i < nr_folios; i++) {
2583 struct folio *folio = fbatch.folios[i];
8e48dcfb 2584
aeac589a
ML
2585 /*
2586 * Accumulated enough dirty pages? This doesn't apply
2587 * to WB_SYNC_ALL mode. For integrity sync we have to
2588 * keep going because someone may be concurrently
2589 * dirtying pages, and we might have synced a lot of
2590 * newly appeared dirty pages, but have not synced all
2591 * of the old dirty pages.
2592 */
c8e8e16d
JK
2593 if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
2594 mpd->wbc->nr_to_write <=
2595 mpd->map.m_len >> (PAGE_SHIFT - blkbits))
aeac589a
ML
2596 goto out;
2597
4e7ea81d 2598 /* If we can't merge this page, we are done. */
50ead253 2599 if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
4e7ea81d 2600 goto out;
78aaced3 2601
3f079114
JK
2602 if (handle) {
2603 err = ext4_journal_ensure_credits(handle, bpp,
2604 0);
2605 if (err < 0)
2606 goto out;
2607 }
2608
50ead253 2609 folio_lock(folio);
8e48dcfb 2610 /*
4e7ea81d
JK
2611 * If the page is no longer dirty, or its mapping no
2612 * longer corresponds to inode we are writing (which
2613 * means it has been truncated or invalidated), or the
2614 * page is already under writeback and we are not doing
2615 * a data integrity writeback, skip the page
8e48dcfb 2616 */
50ead253
VMO
2617 if (!folio_test_dirty(folio) ||
2618 (folio_test_writeback(folio) &&
4e7ea81d 2619 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
50ead253
VMO
2620 unlikely(folio->mapping != mapping)) {
2621 folio_unlock(folio);
8e48dcfb
TT
2622 continue;
2623 }
2624
50ead253
VMO
2625 folio_wait_writeback(folio);
2626 BUG_ON(folio_test_writeback(folio));
8e48dcfb 2627
cc509574
TT
2628 /*
2629 * Should never happen but for buggy code in
2630 * other subsystems that call
2631 * set_page_dirty() without properly warning
2632 * the file system first. See [1] for more
2633 * information.
2634 *
2635 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2636 */
50ead253
VMO
2637 if (!folio_buffers(folio)) {
2638 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
2639 folio_clear_dirty(folio);
2640 folio_unlock(folio);
cc509574
TT
2641 continue;
2642 }
2643
4e7ea81d 2644 if (mpd->map.m_len == 0)
50ead253 2645 mpd->first_page = folio->index;
87b11f86 2646 mpd->next_page = folio_next_index(folio);
de0039f6 2647 /*
3f079114
JK
2648 * Writeout when we cannot modify metadata is simple.
2649 * Just submit the page. For data=journal mode we
2650 * first handle writeout of the page for checkpoint and
2651 * only after that handle delayed page dirtying. This
ab382539
JK
2652 * makes sure current data is checkpointed to the final
2653 * location before possibly journalling it again which
2654 * is desirable when the page is frequently dirtied
2655 * through a pin.
de0039f6
JK
2656 */
2657 if (!mpd->can_map) {
5e1bdea6
JK
2658 err = mpage_submit_folio(mpd, folio);
2659 if (err < 0)
2660 goto out;
3f079114 2661 /* Pending dirtying of journalled data? */
81a0d3e1 2662 if (folio_test_checked(folio)) {
3f079114 2663 err = mpage_journal_page_buffers(handle,
80be8c5c 2664 mpd, folio);
3f079114
JK
2665 if (err < 0)
2666 goto out;
1f1a55f0 2667 mpd->journalled_more_data = 1;
3f079114 2668 }
33483b3b 2669 mpage_folio_done(mpd, folio);
de0039f6
JK
2670 } else {
2671 /* Add all dirty buffers to mpd */
50ead253 2672 lblk = ((ext4_lblk_t)folio->index) <<
de0039f6 2673 (PAGE_SHIFT - blkbits);
50ead253 2674 head = folio_buffers(folio);
de0039f6 2675 err = mpage_process_page_bufs(mpd, head, head,
50ead253 2676 lblk);
de0039f6
JK
2677 if (err <= 0)
2678 goto out;
2679 err = 0;
2680 }
8e48dcfb 2681 }
50ead253 2682 folio_batch_release(&fbatch);
8e48dcfb
TT
2683 cond_resched();
2684 }
6b8ed620 2685 mpd->scanned_until_end = 1;
3f079114
JK
2686 if (handle)
2687 ext4_journal_stop(handle);
4f01b02c 2688 return 0;
8eb9e5ce 2689out:
50ead253 2690 folio_batch_release(&fbatch);
3f079114
JK
2691 if (handle)
2692 ext4_journal_stop(handle);
4e7ea81d 2693 return err;
8e48dcfb
TT
2694}
2695
15648d59 2696static int ext4_do_writepages(struct mpage_da_data *mpd)
64769240 2697{
15648d59 2698 struct writeback_control *wbc = mpd->wbc;
4e7ea81d
JK
2699 pgoff_t writeback_index = 0;
2700 long nr_to_write = wbc->nr_to_write;
22208ded 2701 int range_whole = 0;
4e7ea81d 2702 int cycled = 1;
61628a3f 2703 handle_t *handle = NULL;
15648d59
JK
2704 struct inode *inode = mpd->inode;
2705 struct address_space *mapping = inode->i_mapping;
6b523df4 2706 int needed_blocks, rsv_blocks = 0, ret = 0;
5e745b04 2707 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
1bce63d1 2708 struct blk_plug plug;
cb530541 2709 bool give_up_on_write = false;
61628a3f 2710
20970ba6 2711 trace_ext4_writepages(inode, wbc);
ba80b101 2712
61628a3f
MC
2713 /*
2714 * No pages to write? This is mainly a kludge to avoid starting
2715 * a transaction for special inodes like journal inode on last iput()
2716 * because that could violate lock ordering on umount
2717 */
a1d6cc56 2718 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
bbf023c7 2719 goto out_writepages;
2a21e37e
TT
2720
2721 /*
2722 * If the filesystem has aborted, it is read-only, so return
2723 * right away instead of dumping stack traces later on that
2724 * will obscure the real source of the problem. We test
95257987 2725 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2a21e37e 2726 * the latter could be true if the filesystem is mounted
20970ba6 2727 * read-only, and in that case, ext4_writepages should
2a21e37e
TT
2728 * *never* be called, so if that ever happens, we would want
2729 * the stack trace.
2730 */
0a1b2f5e
BL
2731 ret = ext4_emergency_state(mapping->host->i_sb);
2732 if (unlikely(ret))
bbf023c7 2733 goto out_writepages;
2a21e37e 2734
4e7ea81d
JK
2735 /*
2736 * If we have inline data and arrive here, it means that
2737 * we will soon create the block for the 1st page, so
2738 * we'd better clear the inline data here.
2739 */
2740 if (ext4_has_inline_data(inode)) {
2741 /* Just inode will be modified... */
2742 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2743 if (IS_ERR(handle)) {
2744 ret = PTR_ERR(handle);
2745 goto out_writepages;
2746 }
2747 BUG_ON(ext4_test_inode_state(inode,
2748 EXT4_STATE_MAY_INLINE_DATA));
2749 ext4_destroy_inline_data(handle, inode);
2750 ext4_journal_stop(handle);
2751 }
2752
3f079114
JK
2753 /*
2754 * data=journal mode does not do delalloc so we just need to writeout /
1f1a55f0
JK
2755 * journal already mapped buffers. On the other hand we need to commit
2756 * transaction to make data stable. We expect all the data to be
2757 * already in the journal (the only exception are DMA pinned pages
2758 * dirtied behind our back) so we commit transaction here and run the
2759 * writeback loop to checkpoint them. The checkpointing is not actually
2760 * necessary to make data persistent *but* quite a few places (extent
2761 * shifting operations, fsverity, ...) depend on being able to drop
2762 * pagecache pages after calling filemap_write_and_wait() and for that
2763 * checkpointing needs to happen.
3f079114 2764 */
1f1a55f0 2765 if (ext4_should_journal_data(inode)) {
3f079114 2766 mpd->can_map = 0;
1f1a55f0
JK
2767 if (wbc->sync_mode == WB_SYNC_ALL)
2768 ext4_fc_commit(sbi->s_journal,
2769 EXT4_I(inode)->i_datasync_tid);
2770 }
2771 mpd->journalled_more_data = 0;
3f079114 2772
4e343231 2773 if (ext4_should_dioread_nolock(inode)) {
2774 /*
2775 * We may need to convert up to one extent per block in
2776 * the page and we may dirty the inode.
2777 */
2778 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2779 PAGE_SIZE >> inode->i_blkbits);
2780 }
2781
22208ded
AK
2782 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2783 range_whole = 1;
61628a3f 2784
2acf2c26 2785 if (wbc->range_cyclic) {
4e7ea81d
JK
2786 writeback_index = mapping->writeback_index;
2787 if (writeback_index)
2acf2c26 2788 cycled = 0;
15648d59
JK
2789 mpd->first_page = writeback_index;
2790 mpd->last_page = -1;
5b41d924 2791 } else {
15648d59
JK
2792 mpd->first_page = wbc->range_start >> PAGE_SHIFT;
2793 mpd->last_page = wbc->range_end >> PAGE_SHIFT;
5b41d924 2794 }
a1d6cc56 2795
15648d59 2796 ext4_io_submit_init(&mpd->io_submit, wbc);
2acf2c26 2797retry:
6e6938b6 2798 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
15648d59
JK
2799 tag_pages_for_writeback(mapping, mpd->first_page,
2800 mpd->last_page);
1bce63d1 2801 blk_start_plug(&plug);
dddbd6ac
JK
2802
2803 /*
2804 * First writeback pages that don't need mapping - we can avoid
2805 * starting a transaction unnecessarily and also avoid being blocked
2806 * in the block layer on device congestion while having transaction
2807 * started.
2808 */
15648d59
JK
2809 mpd->do_map = 0;
2810 mpd->scanned_until_end = 0;
2811 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2812 if (!mpd->io_submit.io_end) {
dddbd6ac
JK
2813 ret = -ENOMEM;
2814 goto unplug;
2815 }
15648d59 2816 ret = mpage_prepare_extent_to_map(mpd);
a297b2fc 2817 /* Unlock pages we didn't use */
15648d59 2818 mpage_release_unused_pages(mpd, false);
dddbd6ac 2819 /* Submit prepared bio */
15648d59
JK
2820 ext4_io_submit(&mpd->io_submit);
2821 ext4_put_io_end_defer(mpd->io_submit.io_end);
2822 mpd->io_submit.io_end = NULL;
dddbd6ac
JK
2823 if (ret < 0)
2824 goto unplug;
2825
15648d59 2826 while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
4e7ea81d 2827 /* For each extent of pages we use new io_end */
15648d59
JK
2828 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2829 if (!mpd->io_submit.io_end) {
4e7ea81d
JK
2830 ret = -ENOMEM;
2831 break;
2832 }
a1d6cc56 2833
de0039f6 2834 WARN_ON_ONCE(!mpd->can_map);
a1d6cc56 2835 /*
4e7ea81d
JK
2836 * We have two constraints: We find one extent to map and we
2837 * must always write out whole page (makes a difference when
2838 * blocksize < pagesize) so that we don't block on IO when we
2839 * try to write out the rest of the page. Journalled mode is
2840 * not supported by delalloc.
a1d6cc56
AK
2841 */
2842 BUG_ON(ext4_should_journal_data(inode));
525f4ed8 2843 needed_blocks = ext4_da_writepages_trans_blocks(inode);
a1d6cc56 2844
4e7ea81d 2845 /* start a new transaction */
6b523df4
JK
2846 handle = ext4_journal_start_with_reserve(inode,
2847 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
61628a3f
MC
2848 if (IS_ERR(handle)) {
2849 ret = PTR_ERR(handle);
1693918e 2850 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
fbe845dd 2851 "%ld pages, ino %lu; err %d", __func__,
a1d6cc56 2852 wbc->nr_to_write, inode->i_ino, ret);
4e7ea81d 2853 /* Release allocated io_end */
15648d59
JK
2854 ext4_put_io_end(mpd->io_submit.io_end);
2855 mpd->io_submit.io_end = NULL;
4e7ea81d 2856 break;
61628a3f 2857 }
15648d59 2858 mpd->do_map = 1;
f63e6005 2859
15648d59
JK
2860 trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
2861 ret = mpage_prepare_extent_to_map(mpd);
2862 if (!ret && mpd->map.m_len)
2863 ret = mpage_map_and_submit_extent(handle, mpd,
cb530541 2864 &give_up_on_write);
646caa9c
JK
2865 /*
2866 * Caution: If the handle is synchronous,
2867 * ext4_journal_stop() can wait for transaction commit
2868 * to finish which may depend on writeback of pages to
2869 * complete or on page lock to be released. In that
b483bb77 2870 * case, we have to wait until after we have
646caa9c
JK
2871 * submitted all the IO, released page locks we hold,
2872 * and dropped io_end reference (for extent conversion
2873 * to be able to complete) before stopping the handle.
2874 */
2875 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2876 ext4_journal_stop(handle);
2877 handle = NULL;
15648d59 2878 mpd->do_map = 0;
646caa9c 2879 }
4e7ea81d 2880 /* Unlock pages we didn't use */
15648d59 2881 mpage_release_unused_pages(mpd, give_up_on_write);
a297b2fc 2882 /* Submit prepared bio */
15648d59 2883 ext4_io_submit(&mpd->io_submit);
a297b2fc 2884
646caa9c
JK
2885 /*
2886 * Drop our io_end reference we got from init. We have
2887 * to be careful and use deferred io_end finishing if
2888 * we are still holding the transaction as we can
2889 * release the last reference to io_end which may end
2890 * up doing unwritten extent conversion.
2891 */
2892 if (handle) {
15648d59 2893 ext4_put_io_end_defer(mpd->io_submit.io_end);
646caa9c
JK
2894 ext4_journal_stop(handle);
2895 } else
15648d59
JK
2896 ext4_put_io_end(mpd->io_submit.io_end);
2897 mpd->io_submit.io_end = NULL;
4e7ea81d
JK
2898
2899 if (ret == -ENOSPC && sbi->s_journal) {
2900 /*
2901 * Commit the transaction which would
22208ded
AK
2902 * free blocks released in the transaction
2903 * and try again
2904 */
df22291f 2905 jbd2_journal_force_commit_nested(sbi->s_journal);
22208ded 2906 ret = 0;
4e7ea81d
JK
2907 continue;
2908 }
2909 /* Fatal error - ENOMEM, EIO... */
2910 if (ret)
61628a3f 2911 break;
a1d6cc56 2912 }
dddbd6ac 2913unplug:
1bce63d1 2914 blk_finish_plug(&plug);
9c12a831 2915 if (!ret && !cycled && wbc->nr_to_write > 0) {
2acf2c26 2916 cycled = 1;
15648d59
JK
2917 mpd->last_page = writeback_index - 1;
2918 mpd->first_page = 0;
2acf2c26
AK
2919 goto retry;
2920 }
22208ded
AK
2921
2922 /* Update index */
22208ded
AK
2923 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2924 /*
4e7ea81d 2925 * Set the writeback_index so that range_cyclic
22208ded
AK
2926 * mode will write it back later
2927 */
15648d59 2928 mapping->writeback_index = mpd->first_page;
a1d6cc56 2929
61628a3f 2930out_writepages:
20970ba6
TT
2931 trace_ext4_writepages_result(inode, wbc, ret,
2932 nr_to_write - wbc->nr_to_write);
61628a3f 2933 return ret;
64769240
AT
2934}
2935
15648d59
JK
2936static int ext4_writepages(struct address_space *mapping,
2937 struct writeback_control *wbc)
2938{
29bc9cea 2939 struct super_block *sb = mapping->host->i_sb;
15648d59
JK
2940 struct mpage_da_data mpd = {
2941 .inode = mapping->host,
2942 .wbc = wbc,
2943 .can_map = 1,
2944 };
29bc9cea 2945 int ret;
00d873c1 2946 int alloc_ctx;
29bc9cea 2947
0a1b2f5e
BL
2948 ret = ext4_emergency_state(sb);
2949 if (unlikely(ret))
2950 return ret;
15648d59 2951
00d873c1 2952 alloc_ctx = ext4_writepages_down_read(sb);
29bc9cea 2953 ret = ext4_do_writepages(&mpd);
1f1a55f0
JK
2954 /*
2955 * For data=journal writeback we could have come across pages marked
2956 * for delayed dirtying (PageChecked) which were just added to the
2957 * running transaction. Try once more to get them to stable storage.
2958 */
2959 if (!ret && mpd.journalled_more_data)
2960 ret = ext4_do_writepages(&mpd);
00d873c1 2961 ext4_writepages_up_read(sb, alloc_ctx);
29bc9cea
JK
2962
2963 return ret;
15648d59
JK
2964}
2965
59205c8d
JK
2966int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
2967{
2968 struct writeback_control wbc = {
2969 .sync_mode = WB_SYNC_ALL,
2970 .nr_to_write = LONG_MAX,
2971 .range_start = jinode->i_dirty_start,
2972 .range_end = jinode->i_dirty_end,
2973 };
2974 struct mpage_da_data mpd = {
2975 .inode = jinode->i_vfs_inode,
2976 .wbc = &wbc,
2977 .can_map = 0,
2978 };
2979 return ext4_do_writepages(&mpd);
2980}
2981
5f0663bb
DW
2982static int ext4_dax_writepages(struct address_space *mapping,
2983 struct writeback_control *wbc)
2984{
2985 int ret;
2986 long nr_to_write = wbc->nr_to_write;
2987 struct inode *inode = mapping->host;
00d873c1 2988 int alloc_ctx;
5f0663bb 2989
0a1b2f5e
BL
2990 ret = ext4_emergency_state(inode->i_sb);
2991 if (unlikely(ret))
2992 return ret;
5f0663bb 2993
00d873c1 2994 alloc_ctx = ext4_writepages_down_read(inode->i_sb);
5f0663bb
DW
2995 trace_ext4_writepages(inode, wbc);
2996
eb8ab444
JK
2997 ret = dax_writeback_mapping_range(mapping,
2998 EXT4_SB(inode->i_sb)->s_daxdev, wbc);
5f0663bb
DW
2999 trace_ext4_writepages_result(inode, wbc, ret,
3000 nr_to_write - wbc->nr_to_write);
00d873c1 3001 ext4_writepages_up_read(inode->i_sb, alloc_ctx);
5f0663bb
DW
3002 return ret;
3003}
3004
79f0be8d
AK
3005static int ext4_nonda_switch(struct super_block *sb)
3006{
5c1ff336 3007 s64 free_clusters, dirty_clusters;
79f0be8d
AK
3008 struct ext4_sb_info *sbi = EXT4_SB(sb);
3009
3010 /*
3011 * switch to non delalloc mode if we are running low
3012 * on free block. The free block accounting via percpu
179f7ebf 3013 * counters can get slightly wrong with percpu_counter_batch getting
79f0be8d
AK
3014 * accumulated on each CPU without updating global counters
3015 * Delalloc need an accurate free block accounting. So switch
3016 * to non delalloc when we are near to error range.
3017 */
5c1ff336
EW
3018 free_clusters =
3019 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3020 dirty_clusters =
3021 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
00d4e736
TT
3022 /*
3023 * Start pushing delalloc when 1/2 of free blocks are dirty.
3024 */
5c1ff336 3025 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
10ee27a0 3026 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
00d4e736 3027
5c1ff336
EW
3028 if (2 * free_clusters < 3 * dirty_clusters ||
3029 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
79f0be8d 3030 /*
c8afb446
ES
3031 * free block count is less than 150% of dirty blocks
3032 * or free blocks is less than watermark
79f0be8d
AK
3033 */
3034 return 1;
3035 }
3036 return 0;
3037}
3038
64769240 3039static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
9d6b0cd7 3040 loff_t pos, unsigned len,
1da86618 3041 struct folio **foliop, void **fsdata)
64769240 3042{
72b8ab9d 3043 int ret, retries = 0;
0b5a2543 3044 struct folio *folio;
64769240 3045 pgoff_t index;
64769240 3046 struct inode *inode = mapping->host;
16705e52 3047 fgf_t fgp = FGP_WRITEBEGIN;
64769240 3048
0a1b2f5e
BL
3049 ret = ext4_emergency_state(inode->i_sb);
3050 if (unlikely(ret))
3051 return ret;
0db1ff22 3052
09cbfeaf 3053 index = pos >> PAGE_SHIFT;
79f0be8d 3054
6493792d 3055 if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
79f0be8d
AK
3056 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3057 return ext4_write_begin(file, mapping, pos,
1da86618 3058 len, foliop, fsdata);
79f0be8d
AK
3059 }
3060 *fsdata = (void *)0;
9d6b0cd7 3061 trace_ext4_da_write_begin(inode, pos, len);
9c3569b5
TM
3062
3063 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
f9bdb042
JS
3064 ret = ext4_generic_write_inline_data(mapping, inode, pos, len,
3065 foliop, fsdata, true);
9c3569b5 3066 if (ret < 0)
47564bfb
TT
3067 return ret;
3068 if (ret == 1)
3069 return 0;
9c3569b5
TM
3070 }
3071
cc883236 3072retry:
16705e52
ZY
3073 fgp |= fgf_set_order(len);
3074 folio = __filemap_get_folio(mapping, index, fgp,
3075 mapping_gfp_mask(mapping));
7fa8a8ee
LT
3076 if (IS_ERR(folio))
3077 return PTR_ERR(folio);
47564bfb 3078
16705e52
ZY
3079 if (pos + len > folio_pos(folio) + folio_size(folio))
3080 len = folio_pos(folio) + folio_size(folio) - pos;
3081
cb3de5fc
SZ
3082 ret = ext4_block_write_begin(NULL, folio, pos, len,
3083 ext4_da_get_block_prep);
64769240 3084 if (ret < 0) {
0b5a2543
MW
3085 folio_unlock(folio);
3086 folio_put(folio);
ae4d5372
AK
3087 /*
3088 * block_write_begin may have instantiated a few blocks
3089 * outside i_size. Trim these off again. Don't need
cc883236 3090 * i_size_read because we hold inode lock.
ae4d5372
AK
3091 */
3092 if (pos + len > inode->i_size)
b9a4207d 3093 ext4_truncate_failed_write(inode);
47564bfb
TT
3094
3095 if (ret == -ENOSPC &&
3096 ext4_should_retry_alloc(inode->i_sb, &retries))
cc883236 3097 goto retry;
47564bfb 3098 return ret;
64769240
AT
3099 }
3100
1da86618 3101 *foliop = folio;
64769240
AT
3102 return ret;
3103}
3104
632eaeab
MC
3105/*
3106 * Check if we should update i_disksize
3107 * when write to the end of file but not require block allocation
3108 */
d19500da 3109static int ext4_da_should_update_i_disksize(struct folio *folio,
de9a55b8 3110 unsigned long offset)
632eaeab
MC
3111{
3112 struct buffer_head *bh;
d19500da 3113 struct inode *inode = folio->mapping->host;
632eaeab
MC
3114 unsigned int idx;
3115 int i;
3116
d19500da 3117 bh = folio_buffers(folio);
632eaeab
MC
3118 idx = offset >> inode->i_blkbits;
3119
af5bc92d 3120 for (i = 0; i < idx; i++)
632eaeab
MC
3121 bh = bh->b_this_page;
3122
29fa89d0 3123 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
632eaeab
MC
3124 return 0;
3125 return 1;
3126}
3127
03de20be
LS
3128static int ext4_da_do_write_end(struct address_space *mapping,
3129 loff_t pos, unsigned len, unsigned copied,
4d5cdd75 3130 struct folio *folio)
03de20be
LS
3131{
3132 struct inode *inode = mapping->host;
3133 loff_t old_size = inode->i_size;
3134 bool disksize_changed = false;
c7fc0366
BF
3135 loff_t new_i_size, zero_len = 0;
3136 handle_t *handle;
03de20be 3137
83f4414b
WG
3138 if (unlikely(!folio_buffers(folio))) {
3139 folio_unlock(folio);
3140 folio_put(folio);
3141 return -EIO;
3142 }
03de20be
LS
3143 /*
3144 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
3145 * flag, which all that's needed to trigger page writeback.
3146 */
4d5cdd75 3147 copied = block_write_end(NULL, mapping, pos, len, copied,
97edbc02 3148 folio, NULL);
03de20be
LS
3149 new_i_size = pos + copied;
3150
3151 /*
4d5cdd75
MWO
3152 * It's important to update i_size while still holding folio lock,
3153 * because folio writeout could otherwise come in and zero beyond
03de20be
LS
3154 * i_size.
3155 *
3156 * Since we are holding inode lock, we are sure i_disksize <=
3157 * i_size. We also know that if i_disksize < i_size, there are
3158 * delalloc writes pending in the range up to i_size. If the end of
3159 * the current write is <= i_size, there's no need to touch
3160 * i_disksize since writeback will push i_disksize up to i_size
3161 * eventually. If the end of the current write is > i_size and
3162 * inside an allocated block which ext4_da_should_update_i_disksize()
3163 * checked, we need to update i_disksize here as certain
3164 * ext4_writepages() paths not allocating blocks and update i_disksize.
3165 */
3166 if (new_i_size > inode->i_size) {
3167 unsigned long end;
3168
3169 i_size_write(inode, new_i_size);
16705e52 3170 end = offset_in_folio(folio, new_i_size - 1);
4d5cdd75 3171 if (copied && ext4_da_should_update_i_disksize(folio, end)) {
03de20be
LS
3172 ext4_update_i_disksize(inode, new_i_size);
3173 disksize_changed = true;
3174 }
3175 }
3176
4d5cdd75
MWO
3177 folio_unlock(folio);
3178 folio_put(folio);
03de20be 3179
c7fc0366 3180 if (pos > old_size) {
03de20be 3181 pagecache_isize_extended(inode, old_size, pos);
c7fc0366
BF
3182 zero_len = pos - old_size;
3183 }
03de20be 3184
c7fc0366
BF
3185 if (!disksize_changed && !zero_len)
3186 return copied;
03de20be 3187
c7fc0366
BF
3188 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3189 if (IS_ERR(handle))
3190 return PTR_ERR(handle);
3191 if (zero_len)
3192 ext4_zero_partial_blocks(handle, inode, old_size, zero_len);
3193 ext4_mark_inode_dirty(handle, inode);
3194 ext4_journal_stop(handle);
03de20be
LS
3195
3196 return copied;
3197}
3198
64769240 3199static int ext4_da_write_end(struct file *file,
de9a55b8
TT
3200 struct address_space *mapping,
3201 loff_t pos, unsigned len, unsigned copied,
a225800f 3202 struct folio *folio, void *fsdata)
64769240
AT
3203{
3204 struct inode *inode = mapping->host;
79f0be8d
AK
3205 int write_mode = (int)(unsigned long)fsdata;
3206
74d553aa
TT
3207 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3208 return ext4_write_end(file, mapping, pos,
a225800f 3209 len, copied, folio, fsdata);
632eaeab 3210
9bffad1e 3211 trace_ext4_da_write_end(inode, pos, len, copied);
6984aef5
ZY
3212
3213 if (write_mode != CONVERT_INLINE_DATA &&
3214 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3215 ext4_has_inline_data(inode))
d19500da
RH
3216 return ext4_write_inline_data_end(inode, pos, len, copied,
3217 folio);
6984aef5 3218
4d5cdd75 3219 if (unlikely(copied < len) && !folio_test_uptodate(folio))
1dedde69
ZC
3220 copied = 0;
3221
4d5cdd75 3222 return ext4_da_do_write_end(mapping, pos, len, copied, folio);
64769240
AT
3223}
3224
ccd2506b
TT
3225/*
3226 * Force all delayed allocation blocks to be allocated for a given inode.
3227 */
3228int ext4_alloc_da_blocks(struct inode *inode)
3229{
fb40ba0d
TT
3230 trace_ext4_alloc_da_blocks(inode);
3231
71d4f7d0 3232 if (!EXT4_I(inode)->i_reserved_data_blocks)
ccd2506b
TT
3233 return 0;
3234
3235 /*
3236 * We do something simple for now. The filemap_flush() will
3237 * also start triggering a write of the data blocks, which is
3238 * not strictly speaking necessary (and for users of
3239 * laptop_mode, not even desirable). However, to do otherwise
3240 * would require replicating code paths in:
de9a55b8 3241 *
20970ba6 3242 * ext4_writepages() ->
ccd2506b
TT
3243 * write_cache_pages() ---> (via passed in callback function)
3244 * __mpage_da_writepage() -->
3245 * mpage_add_bh_to_extent()
3246 * mpage_da_map_blocks()
3247 *
3248 * The problem is that write_cache_pages(), located in
3249 * mm/page-writeback.c, marks pages clean in preparation for
3250 * doing I/O, which is not desirable if we're not planning on
3251 * doing I/O at all.
3252 *
3253 * We could call write_cache_pages(), and then redirty all of
380cf090 3254 * the pages by calling redirty_page_for_writepage() but that
ccd2506b
TT
3255 * would be ugly in the extreme. So instead we would need to
3256 * replicate parts of the code in the above functions,
25985edc 3257 * simplifying them because we wouldn't actually intend to
ccd2506b
TT
3258 * write out the pages, but rather only collect contiguous
3259 * logical block extents, call the multi-block allocator, and
3260 * then update the buffer heads with the block allocations.
de9a55b8 3261 *
ccd2506b
TT
3262 * For now, though, we'll cheat by calling filemap_flush(),
3263 * which will map the blocks, and start the I/O, but not
3264 * actually wait for the I/O to complete.
3265 */
3266 return filemap_flush(inode->i_mapping);
3267}
64769240 3268
ac27a0ec
DK
3269/*
3270 * bmap() is special. It gets used by applications such as lilo and by
3271 * the swapper to find the on-disk block of a specific piece of data.
3272 *
3273 * Naturally, this is dangerous if the block concerned is still in the
617ba13b 3274 * journal. If somebody makes a swapfile on an ext4 data-journaling
ac27a0ec
DK
3275 * filesystem and enables swap, then they may get a nasty shock when the
3276 * data getting swapped to that swapfile suddenly gets overwritten by
3277 * the original zero's written out previously to the journal and
3278 * awaiting writeback in the kernel's buffer cache.
3279 *
3280 * So, if we see any bmap calls here on a modified, data-journaled file,
3281 * take extra steps to flush any blocks which might be in the cache.
3282 */
617ba13b 3283static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
ac27a0ec
DK
3284{
3285 struct inode *inode = mapping->host;
51ae846c 3286 sector_t ret = 0;
ac27a0ec 3287
51ae846c 3288 inode_lock_shared(inode);
46c7f254
TM
3289 /*
3290 * We can get here for an inline file via the FIBMAP ioctl
3291 */
3292 if (ext4_has_inline_data(inode))
51ae846c 3293 goto out;
46c7f254 3294
64769240 3295 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
951cafa6
JK
3296 (test_opt(inode->i_sb, DELALLOC) ||
3297 ext4_should_journal_data(inode))) {
64769240 3298 /*
951cafa6
JK
3299 * With delalloc or journalled data we want to sync the file so
3300 * that we can make sure we allocate blocks for file and data
3301 * is in place for the user to see it
64769240
AT
3302 */
3303 filemap_write_and_wait(mapping);
3304 }
3305
51ae846c
YB
3306 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3307
3308out:
3309 inode_unlock_shared(inode);
3310 return ret;
ac27a0ec
DK
3311}
3312
fe5ddf6b 3313static int ext4_read_folio(struct file *file, struct folio *folio)
ac27a0ec 3314{
46c7f254 3315 int ret = -EAGAIN;
c0be8e6f 3316 struct inode *inode = folio->mapping->host;
46c7f254 3317
36c9b450 3318 trace_ext4_read_folio(inode, folio);
46c7f254
TM
3319
3320 if (ext4_has_inline_data(inode))
3edde93e 3321 ret = ext4_readpage_inline(inode, folio);
46c7f254
TM
3322
3323 if (ret == -EAGAIN)
c0be8e6f 3324 return ext4_mpage_readpages(inode, NULL, folio);
46c7f254
TM
3325
3326 return ret;
ac27a0ec
DK
3327}
3328
6311f91f 3329static void ext4_readahead(struct readahead_control *rac)
ac27a0ec 3330{
6311f91f 3331 struct inode *inode = rac->mapping->host;
46c7f254 3332
6311f91f 3333 /* If the file has inline data, no need to do readahead. */
46c7f254 3334 if (ext4_has_inline_data(inode))
6311f91f 3335 return;
46c7f254 3336
a07f624b 3337 ext4_mpage_readpages(inode, rac, NULL);
ac27a0ec
DK
3338}
3339
7ba13abb
MWO
3340static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3341 size_t length)
ac27a0ec 3342{
ccd16945 3343 trace_ext4_invalidate_folio(folio, offset, length);
0562e0ba 3344
4520fb3c 3345 /* No journalling happens on data buffers when this function is used */
7ba13abb 3346 WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
4520fb3c 3347
7ba13abb 3348 block_invalidate_folio(folio, offset, length);
4520fb3c
JK
3349}
3350
ccd16945
MWO
3351static int __ext4_journalled_invalidate_folio(struct folio *folio,
3352 size_t offset, size_t length)
4520fb3c 3353{
ccd16945 3354 journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
4520fb3c 3355
ccd16945 3356 trace_ext4_journalled_invalidate_folio(folio, offset, length);
4520fb3c 3357
ac27a0ec
DK
3358 /*
3359 * If it's a full truncate we just forget about the pending dirtying
3360 */
ccd16945
MWO
3361 if (offset == 0 && length == folio_size(folio))
3362 folio_clear_checked(folio);
ac27a0ec 3363
ccd16945 3364 return jbd2_journal_invalidate_folio(journal, folio, offset, length);
53e87268
JK
3365}
3366
3367/* Wrapper for aops... */
ccd16945
MWO
3368static void ext4_journalled_invalidate_folio(struct folio *folio,
3369 size_t offset,
3370 size_t length)
53e87268 3371{
ccd16945 3372 WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
ac27a0ec
DK
3373}
3374
3c402f15 3375static bool ext4_release_folio(struct folio *folio, gfp_t wait)
ac27a0ec 3376{
36c9b450
RH
3377 struct inode *inode = folio->mapping->host;
3378 journal_t *journal = EXT4_JOURNAL(inode);
ac27a0ec 3379
36c9b450 3380 trace_ext4_release_folio(inode, folio);
0562e0ba 3381
e1c36595 3382 /* Page has dirty journalled data -> cannot release */
3c402f15
MWO
3383 if (folio_test_checked(folio))
3384 return false;
0390131b 3385 if (journal)
c56a6eb0 3386 return jbd2_journal_try_to_free_buffers(journal, folio);
0390131b 3387 else
68189fef 3388 return try_to_free_buffers(folio);
ac27a0ec
DK
3389}
3390
b8a6176c
JK
3391static bool ext4_inode_datasync_dirty(struct inode *inode)
3392{
3393 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3394
aa75f4d3
HS
3395 if (journal) {
3396 if (jbd2_transaction_committed(journal,
d0520df7
AR
3397 EXT4_I(inode)->i_datasync_tid))
3398 return false;
3399 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
1ceecb53 3400 return !list_empty(&EXT4_I(inode)->i_fc_list);
d0520df7 3401 return true;
aa75f4d3
HS
3402 }
3403
b8a6176c 3404 /* Any metadata buffers to write? */
600f111e 3405 if (!list_empty(&inode->i_mapping->i_private_list))
b8a6176c
JK
3406 return true;
3407 return inode->i_state & I_DIRTY_DATASYNC;
3408}
3409
c8fdfe29
MB
3410static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3411 struct ext4_map_blocks *map, loff_t offset,
de205114 3412 loff_t length, unsigned int flags)
364443cb 3413{
c8fdfe29 3414 u8 blkbits = inode->i_blkbits;
364443cb 3415
c8fdfe29
MB
3416 /*
3417 * Writes that span EOF might trigger an I/O size update on completion,
3418 * so consider them to be dirty for the purpose of O_DSYNC, even if
3419 * there is no other metadata changes being made or are pending.
3420 */
364443cb 3421 iomap->flags = 0;
c8fdfe29
MB
3422 if (ext4_inode_datasync_dirty(inode) ||
3423 offset + length > i_size_read(inode))
b8a6176c 3424 iomap->flags |= IOMAP_F_DIRTY;
c8fdfe29
MB
3425
3426 if (map->m_flags & EXT4_MAP_NEW)
3427 iomap->flags |= IOMAP_F_NEW;
3428
370a6de7
JG
3429 /* HW-offload atomics are always used */
3430 if (flags & IOMAP_ATOMIC)
3431 iomap->flags |= IOMAP_F_ATOMIC_BIO;
3432
de205114
CH
3433 if (flags & IOMAP_DAX)
3434 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3435 else
3436 iomap->bdev = inode->i_sb->s_bdev;
c8fdfe29
MB
3437 iomap->offset = (u64) map->m_lblk << blkbits;
3438 iomap->length = (u64) map->m_len << blkbits;
364443cb 3439
6386722a
RH
3440 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3441 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3442 iomap->flags |= IOMAP_F_MERGED;
3443
c8fdfe29
MB
3444 /*
3445 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3446 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3447 * set. In order for any allocated unwritten extents to be converted
3448 * into written extents correctly within the ->end_io() handler, we
3449 * need to ensure that the iomap->type is set appropriately. Hence, the
3450 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3451 * been set first.
3452 */
3453 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3454 iomap->type = IOMAP_UNWRITTEN;
3455 iomap->addr = (u64) map->m_pblk << blkbits;
de205114
CH
3456 if (flags & IOMAP_DAX)
3457 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
c8fdfe29
MB
3458 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3459 iomap->type = IOMAP_MAPPED;
3460 iomap->addr = (u64) map->m_pblk << blkbits;
de205114
CH
3461 if (flags & IOMAP_DAX)
3462 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
ec9d669e
ZY
3463 } else if (map->m_flags & EXT4_MAP_DELAYED) {
3464 iomap->type = IOMAP_DELALLOC;
3465 iomap->addr = IOMAP_NULL_ADDR;
364443cb 3466 } else {
c8fdfe29
MB
3467 iomap->type = IOMAP_HOLE;
3468 iomap->addr = IOMAP_NULL_ADDR;
364443cb 3469 }
364443cb
JK
3470}
3471
b86629c2
RHI
3472static int ext4_map_blocks_atomic_write_slow(handle_t *handle,
3473 struct inode *inode, struct ext4_map_blocks *map)
3474{
3475 ext4_lblk_t m_lblk = map->m_lblk;
3476 unsigned int m_len = map->m_len;
3477 unsigned int mapped_len = 0, m_flags = 0;
3478 ext4_fsblk_t next_pblk;
3479 bool check_next_pblk = false;
3480 int ret = 0;
3481
3482 WARN_ON_ONCE(!ext4_has_feature_bigalloc(inode->i_sb));
3483
3484 /*
3485 * This is a slow path in case of mixed mapping. We use
3486 * EXT4_GET_BLOCKS_CREATE_ZERO flag here to make sure we get a single
3487 * contiguous mapped mapping. This will ensure any unwritten or hole
3488 * regions within the requested range is zeroed out and we return
3489 * a single contiguous mapped extent.
3490 */
3491 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3492
3493 do {
3494 ret = ext4_map_blocks(handle, inode, map, m_flags);
3495 if (ret < 0 && ret != -ENOSPC)
3496 goto out_err;
3497 /*
3498 * This should never happen, but let's return an error code to
3499 * avoid an infinite loop in here.
3500 */
3501 if (ret == 0) {
3502 ret = -EFSCORRUPTED;
3503 ext4_warning_inode(inode,
3504 "ext4_map_blocks() couldn't allocate blocks m_flags: 0x%x, ret:%d",
3505 m_flags, ret);
3506 goto out_err;
3507 }
3508 /*
3509 * With bigalloc we should never get ENOSPC nor discontiguous
3510 * physical extents.
3511 */
3512 if ((check_next_pblk && next_pblk != map->m_pblk) ||
3513 ret == -ENOSPC) {
3514 ext4_warning_inode(inode,
3515 "Non-contiguous allocation detected: expected %llu, got %llu, "
3516 "or ext4_map_blocks() returned out of space ret: %d",
3517 next_pblk, map->m_pblk, ret);
3518 ret = -EFSCORRUPTED;
3519 goto out_err;
3520 }
3521 next_pblk = map->m_pblk + map->m_len;
3522 check_next_pblk = true;
3523
3524 mapped_len += map->m_len;
3525 map->m_lblk += map->m_len;
3526 map->m_len = m_len - mapped_len;
3527 } while (mapped_len < m_len);
3528
3529 /*
3530 * We might have done some work in above loop, so we need to query the
3531 * start of the physical extent, based on the origin m_lblk and m_len.
3532 * Let's also ensure we were able to allocate the required range for
3533 * mixed mapping case.
3534 */
3535 map->m_lblk = m_lblk;
3536 map->m_len = m_len;
3537 map->m_flags = 0;
3538
3539 ret = ext4_map_blocks(handle, inode, map,
3540 EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF);
3541 if (ret != m_len) {
3542 ext4_warning_inode(inode,
3543 "allocation failed for atomic write request m_lblk:%u, m_len:%u, ret:%d\n",
3544 m_lblk, m_len, ret);
3545 ret = -EINVAL;
3546 }
3547 return ret;
3548
3549out_err:
3550 /* reset map before returning an error */
3551 map->m_lblk = m_lblk;
3552 map->m_len = m_len;
3553 map->m_flags = 0;
3554 return ret;
3555}
3556
3557/*
3558 * ext4_map_blocks_atomic: Helper routine to ensure the entire requested
3559 * range in @map [lblk, lblk + len) is one single contiguous extent with no
3560 * mixed mappings.
3561 *
3562 * We first use m_flags passed to us by our caller (ext4_iomap_alloc()).
3563 * We only call EXT4_GET_BLOCKS_ZERO in the slow path, when the underlying
3564 * physical extent for the requested range does not have a single contiguous
3565 * mapping type i.e. (Hole, Mapped, or Unwritten) throughout.
3566 * In that case we will loop over the requested range to allocate and zero out
3567 * the unwritten / holes in between, to get a single mapped extent from
3568 * [m_lblk, m_lblk + m_len). Note that this is only possible because we know
3569 * this can be called only with bigalloc enabled filesystem where the underlying
3570 * cluster is already allocated. This avoids allocating discontiguous extents
3571 * in the slow path due to multiple calls to ext4_map_blocks().
3572 * The slow path is mostly non-performance critical path, so it should be ok to
3573 * loop using ext4_map_blocks() with appropriate flags to allocate & zero the
3574 * underlying short holes/unwritten extents within the requested range.
3575 */
3576static int ext4_map_blocks_atomic_write(handle_t *handle, struct inode *inode,
3577 struct ext4_map_blocks *map, int m_flags,
3578 bool *force_commit)
3579{
3580 ext4_lblk_t m_lblk = map->m_lblk;
3581 unsigned int m_len = map->m_len;
3582 int ret = 0;
3583
3584 WARN_ON_ONCE(m_len > 1 && !ext4_has_feature_bigalloc(inode->i_sb));
3585
3586 ret = ext4_map_blocks(handle, inode, map, m_flags);
3587 if (ret < 0 || ret == m_len)
3588 goto out;
3589 /*
3590 * This is a mixed mapping case where we were not able to allocate
3591 * a single contiguous extent. In that case let's reset requested
3592 * mapping and call the slow path.
3593 */
3594 map->m_lblk = m_lblk;
3595 map->m_len = m_len;
3596 map->m_flags = 0;
3597
3598 /*
3599 * slow path means we have mixed mapping, that means we will need
3600 * to force txn commit.
3601 */
3602 *force_commit = true;
3603 return ext4_map_blocks_atomic_write_slow(handle, inode, map);
3604out:
3605 return ret;
3606}
3607
f063db5e
MB
3608static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3609 unsigned int flags)
776722e8 3610{
776722e8 3611 handle_t *handle;
378f32ba
MB
3612 u8 blkbits = inode->i_blkbits;
3613 int ret, dio_credits, m_flags = 0, retries = 0;
b86629c2 3614 bool force_commit = false;
776722e8 3615
776722e8 3616 /*
f063db5e
MB
3617 * Trim the mapping request to the maximum value that we can map at
3618 * once for direct I/O.
776722e8 3619 */
f063db5e
MB
3620 if (map->m_len > DIO_MAX_BLOCKS)
3621 map->m_len = DIO_MAX_BLOCKS;
b86629c2
RHI
3622
3623 /*
3624 * journal credits estimation for atomic writes. We call
3625 * ext4_map_blocks(), to find if there could be a mixed mapping. If yes,
3626 * then let's assume the no. of pextents required can be m_len i.e.
3627 * every alternate block can be unwritten and hole.
3628 */
3629 if (flags & IOMAP_ATOMIC) {
3630 unsigned int orig_mlen = map->m_len;
3631
3632 ret = ext4_map_blocks(NULL, inode, map, 0);
3633 if (ret < 0)
3634 return ret;
3635 if (map->m_len < orig_mlen) {
3636 map->m_len = orig_mlen;
3637 dio_credits = ext4_meta_trans_blocks(inode, orig_mlen,
3638 map->m_len);
3639 } else {
3640 dio_credits = ext4_chunk_trans_blocks(inode,
3641 map->m_len);
3642 }
3643 } else {
3644 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3645 }
776722e8 3646
f063db5e 3647retry:
776722e8 3648 /*
f063db5e
MB
3649 * Either we allocate blocks and then don't get an unwritten extent, so
3650 * in that case we have reserved enough credits. Or, the blocks are
3651 * already allocated and unwritten. In that case, the extent conversion
3652 * fits into the credits as well.
776722e8 3653 */
f063db5e
MB
3654 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3655 if (IS_ERR(handle))
3656 return PTR_ERR(handle);
4c0425ff 3657
378f32ba
MB
3658 /*
3659 * DAX and direct I/O are the only two operations that are currently
3660 * supported with IOMAP_WRITE.
3661 */
952da063
CH
3662 WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3663 if (flags & IOMAP_DAX)
378f32ba
MB
3664 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3665 /*
3666 * We use i_size instead of i_disksize here because delalloc writeback
3667 * can complete at any point during the I/O and subsequently push the
3668 * i_disksize out to i_size. This could be beyond where direct I/O is
3669 * happening and thus expose allocated blocks to direct I/O reads.
3670 */
d0b040f5 3671 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
378f32ba
MB
3672 m_flags = EXT4_GET_BLOCKS_CREATE;
3673 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3674 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
4b70df18 3675
b86629c2
RHI
3676 if (flags & IOMAP_ATOMIC)
3677 ret = ext4_map_blocks_atomic_write(handle, inode, map, m_flags,
3678 &force_commit);
3679 else
3680 ret = ext4_map_blocks(handle, inode, map, m_flags);
8d5d02e6 3681
74c66bcb 3682 /*
378f32ba
MB
3683 * We cannot fill holes in indirect tree based inodes as that could
3684 * expose stale data in the case of a crash. Use the magic error code
3685 * to fallback to buffered I/O.
74c66bcb 3686 */
378f32ba
MB
3687 if (!m_flags && !ret)
3688 ret = -ENOTBLK;
187372a3 3689
f063db5e
MB
3690 ext4_journal_stop(handle);
3691 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3692 goto retry;
3693
b86629c2
RHI
3694 /*
3695 * Force commit the current transaction if the allocation spans a mixed
3696 * mapping range. This ensures any pending metadata updates (like
3697 * unwritten to written extents conversion) in this range are in
3698 * consistent state with the file data blocks, before performing the
3699 * actual write I/O. If the commit fails, the whole I/O must be aborted
3700 * to prevent any possible torn writes.
3701 */
3702 if (ret > 0 && force_commit) {
3703 int ret2;
3704
3705 ret2 = ext4_force_commit(inode->i_sb);
3706 if (ret2)
3707 return ret2;
3708 }
3709
f063db5e 3710 return ret;
4c0425ff 3711}
c7064ef1 3712
f063db5e 3713
364443cb 3714static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
c039b997 3715 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
4c0425ff 3716{
364443cb 3717 int ret;
09edf4d3
MB
3718 struct ext4_map_blocks map;
3719 u8 blkbits = inode->i_blkbits;
b86629c2 3720 unsigned int orig_mlen;
729f52c6 3721
bcd8e91f
TT
3722 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3723 return -EINVAL;
4bd809db 3724
09edf4d3
MB
3725 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3726 return -ERANGE;
4bd809db 3727
e8340395 3728 /*
09edf4d3 3729 * Calculate the first and last logical blocks respectively.
e8340395 3730 */
09edf4d3
MB
3731 map.m_lblk = offset >> blkbits;
3732 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3733 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
b86629c2 3734 orig_mlen = map.m_len;
e8340395 3735
9faac62d
RH
3736 if (flags & IOMAP_WRITE) {
3737 /*
3738 * We check here if the blocks are already allocated, then we
3739 * don't need to start a journal txn and we can directly return
3740 * the mapping information. This could boost performance
3741 * especially in multi-threaded overwrite requests.
3742 */
3743 if (offset + length <= i_size_read(inode)) {
3744 ret = ext4_map_blocks(NULL, inode, &map, 0);
b86629c2
RHI
3745 /*
3746 * For atomic writes the entire requested length should
3747 * be mapped.
3748 */
3749 if (map.m_flags & EXT4_MAP_MAPPED) {
3750 if ((!(flags & IOMAP_ATOMIC) && ret > 0) ||
3751 (flags & IOMAP_ATOMIC && ret >= orig_mlen))
3752 goto out;
3753 }
3754 map.m_len = orig_mlen;
9faac62d 3755 }
f063db5e 3756 ret = ext4_iomap_alloc(inode, &map, flags);
9faac62d 3757 } else {
9fa61216
RHI
3758 /*
3759 * This can be called for overwrites path from
3760 * ext4_iomap_overwrite_begin().
3761 */
545052e9 3762 ret = ext4_map_blocks(NULL, inode, &map, 0);
9faac62d 3763 }
4bd809db 3764
f063db5e
MB
3765 if (ret < 0)
3766 return ret;
9faac62d 3767out:
38ea50da
EB
3768 /*
3769 * When inline encryption is enabled, sometimes I/O to an encrypted file
3770 * has to be broken up to guarantee DUN contiguity. Handle this by
3771 * limiting the length of the mapping returned.
3772 */
3773 map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3774
b86629c2
RHI
3775 /*
3776 * Before returning to iomap, let's ensure the allocated mapping
3777 * covers the entire requested length for atomic writes.
3778 */
3779 if (flags & IOMAP_ATOMIC) {
3780 if (map.m_len < (length >> blkbits)) {
3781 WARN_ON_ONCE(1);
3782 return -EINVAL;
3783 }
3784 }
de205114 3785 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
4bd809db 3786
364443cb
JK
3787 return 0;
3788}
8d5d02e6 3789
8cd115bd
JK
3790static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3791 loff_t length, unsigned flags, struct iomap *iomap,
3792 struct iomap *srcmap)
3793{
3794 int ret;
3795
3796 /*
3797 * Even for writes we don't need to allocate blocks, so just pretend
3798 * we are reading to save overhead of starting a transaction.
3799 */
3800 flags &= ~IOMAP_WRITE;
3801 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
fa83c34e 3802 WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
8cd115bd
JK
3803 return ret;
3804}
3805
299537e9
RHI
3806static inline bool ext4_want_directio_fallback(unsigned flags, ssize_t written)
3807{
3808 /* must be a directio to fall back to buffered */
3809 if ((flags & (IOMAP_WRITE | IOMAP_DIRECT)) !=
3810 (IOMAP_WRITE | IOMAP_DIRECT))
3811 return false;
3812
3813 /* atomic writes are all-or-nothing */
370a6de7 3814 if (flags & IOMAP_ATOMIC)
299537e9
RHI
3815 return false;
3816
3817 /* can only try again if we wrote nothing */
3818 return written == 0;
3819}
3820
776722e8
JK
3821static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3822 ssize_t written, unsigned flags, struct iomap *iomap)
3823{
69c499d1 3824 /*
378f32ba 3825 * Check to see whether an error occurred while writing out the data to
299537e9
RHI
3826 * the allocated blocks. If so, return the magic error code for
3827 * non-atomic write so that we fallback to buffered I/O and attempt to
3828 * complete the remainder of the I/O.
3829 * For non-atomic writes, any blocks that may have been
3830 * allocated in preparation for the direct I/O will be reused during
3831 * buffered I/O. For atomic write, we never fallback to buffered-io.
69c499d1 3832 */
299537e9 3833 if (ext4_want_directio_fallback(flags, written))
378f32ba 3834 return -ENOTBLK;
69c499d1 3835
569342dc 3836 return 0;
776722e8 3837}
4bd809db 3838
8ff6daa1 3839const struct iomap_ops ext4_iomap_ops = {
364443cb 3840 .iomap_begin = ext4_iomap_begin,
776722e8 3841 .iomap_end = ext4_iomap_end,
364443cb 3842};
8d5d02e6 3843
8cd115bd
JK
3844const struct iomap_ops ext4_iomap_overwrite_ops = {
3845 .iomap_begin = ext4_iomap_overwrite_begin,
3846 .iomap_end = ext4_iomap_end,
3847};
3848
09edf4d3
MB
3849static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3850 loff_t length, unsigned int flags,
3851 struct iomap *iomap, struct iomap *srcmap)
4c0425ff 3852{
09edf4d3 3853 int ret;
09edf4d3
MB
3854 struct ext4_map_blocks map;
3855 u8 blkbits = inode->i_blkbits;
4c0425ff 3856
09edf4d3
MB
3857 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3858 return -EINVAL;
3859
3860 if (ext4_has_inline_data(inode)) {
3861 ret = ext4_inline_data_iomap(inode, iomap);
3862 if (ret != -EAGAIN) {
3863 if (ret == 0 && offset >= iomap->length)
3864 ret = -ENOENT;
3865 return ret;
3866 }
3867 }
2058f83a 3868
84ebd795 3869 /*
09edf4d3 3870 * Calculate the first and last logical block respectively.
84ebd795 3871 */
09edf4d3
MB
3872 map.m_lblk = offset >> blkbits;
3873 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3874 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
84ebd795 3875
b2c57642
RH
3876 /*
3877 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3878 * So handle it here itself instead of querying ext4_map_blocks().
3879 * Since ext4_map_blocks() will warn about it and will return
3880 * -EIO error.
3881 */
3882 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3883 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3884
3885 if (offset >= sbi->s_bitmap_maxbytes) {
3886 map.m_flags = 0;
3887 goto set_iomap;
3888 }
3889 }
3890
09edf4d3
MB
3891 ret = ext4_map_blocks(NULL, inode, &map, 0);
3892 if (ret < 0)
3893 return ret;
b2c57642 3894set_iomap:
de205114 3895 ext4_set_iomap(inode, iomap, &map, offset, length, flags);
09edf4d3
MB
3896
3897 return 0;
4c0425ff
MC
3898}
3899
09edf4d3
MB
3900const struct iomap_ops ext4_iomap_report_ops = {
3901 .iomap_begin = ext4_iomap_begin_report,
3902};
3903
ac27a0ec 3904/*
3f5d3063
JK
3905 * For data=journal mode, folio should be marked dirty only when it was
3906 * writeably mapped. When that happens, it was already attached to the
3907 * transaction and marked as jbddirty (we take care of this in
3908 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
3909 * so we should have nothing to do here, except for the case when someone
3910 * had the page pinned and dirtied the page through this pin (e.g. by doing
3911 * direct IO to it). In that case we'd need to attach buffers here to the
3912 * transaction but we cannot due to lock ordering. We cannot just dirty the
3913 * folio and leave attached buffers clean, because the buffers' dirty state is
3914 * "definitive". We cannot just set the buffers dirty or jbddirty because all
3915 * the journalling code will explode. So what we do is to mark the folio
3916 * "pending dirty" and next time ext4_writepages() is called, attach buffers
3917 * to the transaction appropriately.
ac27a0ec 3918 */
187c82cb
MWO
3919static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3920 struct folio *folio)
ac27a0ec 3921{
0f252336 3922 WARN_ON_ONCE(!folio_buffers(folio));
3f5d3063
JK
3923 if (folio_maybe_dma_pinned(folio))
3924 folio_set_checked(folio);
187c82cb 3925 return filemap_dirty_folio(mapping, folio);
ac27a0ec
DK
3926}
3927
e621900a 3928static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
6dcc693b 3929{
e621900a
MWO
3930 WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3931 WARN_ON_ONCE(!folio_buffers(folio));
3932 return block_dirty_folio(mapping, folio);
6dcc693b
JK
3933}
3934
0e6895ba
RH
3935static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3936 struct file *file, sector_t *span)
3937{
3938 return iomap_swapfile_activate(sis, file, span,
3939 &ext4_iomap_report_ops);
3940}
3941
74d553aa 3942static const struct address_space_operations ext4_aops = {
fe5ddf6b 3943 .read_folio = ext4_read_folio,
6311f91f 3944 .readahead = ext4_readahead,
20970ba6 3945 .writepages = ext4_writepages,
8ab22b9a 3946 .write_begin = ext4_write_begin,
74d553aa 3947 .write_end = ext4_write_end,
e621900a 3948 .dirty_folio = ext4_dirty_folio,
8ab22b9a 3949 .bmap = ext4_bmap,
7ba13abb 3950 .invalidate_folio = ext4_invalidate_folio,
3c402f15 3951 .release_folio = ext4_release_folio,
67235182 3952 .migrate_folio = buffer_migrate_folio,
8ab22b9a 3953 .is_partially_uptodate = block_is_partially_uptodate,
af7628d6 3954 .error_remove_folio = generic_error_remove_folio,
0e6895ba 3955 .swap_activate = ext4_iomap_swap_activate,
ac27a0ec
DK
3956};
3957
617ba13b 3958static const struct address_space_operations ext4_journalled_aops = {
fe5ddf6b 3959 .read_folio = ext4_read_folio,
6311f91f 3960 .readahead = ext4_readahead,
20970ba6 3961 .writepages = ext4_writepages,
8ab22b9a
HH
3962 .write_begin = ext4_write_begin,
3963 .write_end = ext4_journalled_write_end,
187c82cb 3964 .dirty_folio = ext4_journalled_dirty_folio,
8ab22b9a 3965 .bmap = ext4_bmap,
ccd16945 3966 .invalidate_folio = ext4_journalled_invalidate_folio,
3c402f15 3967 .release_folio = ext4_release_folio,
dae99960 3968 .migrate_folio = buffer_migrate_folio_norefs,
8ab22b9a 3969 .is_partially_uptodate = block_is_partially_uptodate,
af7628d6 3970 .error_remove_folio = generic_error_remove_folio,
0e6895ba 3971 .swap_activate = ext4_iomap_swap_activate,
ac27a0ec
DK
3972};
3973
64769240 3974static const struct address_space_operations ext4_da_aops = {
fe5ddf6b 3975 .read_folio = ext4_read_folio,
6311f91f 3976 .readahead = ext4_readahead,
20970ba6 3977 .writepages = ext4_writepages,
8ab22b9a
HH
3978 .write_begin = ext4_da_write_begin,
3979 .write_end = ext4_da_write_end,
e621900a 3980 .dirty_folio = ext4_dirty_folio,
8ab22b9a 3981 .bmap = ext4_bmap,
7ba13abb 3982 .invalidate_folio = ext4_invalidate_folio,
3c402f15 3983 .release_folio = ext4_release_folio,
67235182 3984 .migrate_folio = buffer_migrate_folio,
8ab22b9a 3985 .is_partially_uptodate = block_is_partially_uptodate,
af7628d6 3986 .error_remove_folio = generic_error_remove_folio,
0e6895ba 3987 .swap_activate = ext4_iomap_swap_activate,
64769240
AT
3988};
3989
5f0663bb
DW
3990static const struct address_space_operations ext4_dax_aops = {
3991 .writepages = ext4_dax_writepages,
46de8b97 3992 .dirty_folio = noop_dirty_folio,
94dbb631 3993 .bmap = ext4_bmap,
0e6895ba 3994 .swap_activate = ext4_iomap_swap_activate,
5f0663bb
DW
3995};
3996
617ba13b 3997void ext4_set_aops(struct inode *inode)
ac27a0ec 3998{
3d2b1582
LC
3999 switch (ext4_inode_journal_mode(inode)) {
4000 case EXT4_INODE_ORDERED_DATA_MODE:
3d2b1582 4001 case EXT4_INODE_WRITEBACK_DATA_MODE:
3d2b1582
LC
4002 break;
4003 case EXT4_INODE_JOURNAL_DATA_MODE:
617ba13b 4004 inode->i_mapping->a_ops = &ext4_journalled_aops;
74d553aa 4005 return;
3d2b1582
LC
4006 default:
4007 BUG();
4008 }
5f0663bb
DW
4009 if (IS_DAX(inode))
4010 inode->i_mapping->a_ops = &ext4_dax_aops;
4011 else if (test_opt(inode->i_sb, DELALLOC))
74d553aa
TT
4012 inode->i_mapping->a_ops = &ext4_da_aops;
4013 else
4014 inode->i_mapping->a_ops = &ext4_aops;
ac27a0ec
DK
4015}
4016
c6bfd724
OM
4017/*
4018 * Here we can't skip an unwritten buffer even though it usually reads zero
4019 * because it might have data in pagecache (eg, if called from ext4_zero_range,
4020 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a
4021 * racing writeback can come later and flush the stale pagecache to disk.
4022 */
923ae0ff 4023static int __ext4_block_zero_page_range(handle_t *handle,
d863dc36
LC
4024 struct address_space *mapping, loff_t from, loff_t length)
4025{
2e9466fc 4026 unsigned int offset, blocksize, pos;
d863dc36
LC
4027 ext4_lblk_t iblock;
4028 struct inode *inode = mapping->host;
4029 struct buffer_head *bh;
9d3973de 4030 struct folio *folio;
d863dc36
LC
4031 int err = 0;
4032
9d3973de
MW
4033 folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
4034 FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
4035 mapping_gfp_constraint(mapping, ~__GFP_FS));
7fa8a8ee
LT
4036 if (IS_ERR(folio))
4037 return PTR_ERR(folio);
d863dc36
LC
4038
4039 blocksize = inode->i_sb->s_blocksize;
d863dc36 4040
2e9466fc 4041 iblock = folio->index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
d863dc36 4042
9d3973de 4043 bh = folio_buffers(folio);
d4059993 4044 if (!bh)
0a88810d 4045 bh = create_empty_buffers(folio, blocksize, 0);
d863dc36
LC
4046
4047 /* Find the buffer that contains "offset" */
2e9466fc 4048 offset = offset_in_folio(folio, from);
d863dc36
LC
4049 pos = blocksize;
4050 while (offset >= pos) {
4051 bh = bh->b_this_page;
4052 iblock++;
4053 pos += blocksize;
4054 }
d863dc36
LC
4055 if (buffer_freed(bh)) {
4056 BUFFER_TRACE(bh, "freed: skip");
4057 goto unlock;
4058 }
d863dc36
LC
4059 if (!buffer_mapped(bh)) {
4060 BUFFER_TRACE(bh, "unmapped");
4061 ext4_get_block(inode, iblock, bh, 0);
4062 /* unmapped? It's a hole - nothing to do */
4063 if (!buffer_mapped(bh)) {
4064 BUFFER_TRACE(bh, "still unmapped");
4065 goto unlock;
4066 }
4067 }
4068
4069 /* Ok, it's mapped. Make sure it's up-to-date */
9d3973de 4070 if (folio_test_uptodate(folio))
d863dc36
LC
4071 set_buffer_uptodate(bh);
4072
4073 if (!buffer_uptodate(bh)) {
2d069c08 4074 err = ext4_read_bh_lock(bh, 0, true);
4075 if (err)
d863dc36 4076 goto unlock;
4f74d15f 4077 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
c9c7429c 4078 /* We expect the key to be set. */
a7550b30 4079 BUG_ON(!fscrypt_has_encryption_key(inode));
9d3973de 4080 err = fscrypt_decrypt_pagecache_blocks(folio,
51e4e315 4081 blocksize,
834f1565
EB
4082 bh_offset(bh));
4083 if (err) {
4084 clear_buffer_uptodate(bh);
4085 goto unlock;
4086 }
c9c7429c 4087 }
d863dc36 4088 }
d863dc36
LC
4089 if (ext4_should_journal_data(inode)) {
4090 BUFFER_TRACE(bh, "get write access");
188c299e
JK
4091 err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
4092 EXT4_JTR_NONE);
d863dc36
LC
4093 if (err)
4094 goto unlock;
4095 }
9d3973de 4096 folio_zero_range(folio, offset, length);
d863dc36
LC
4097 BUFFER_TRACE(bh, "zeroed end of block");
4098
d863dc36 4099 if (ext4_should_journal_data(inode)) {
d84c9ebd 4100 err = ext4_dirty_journalled_data(handle, bh);
0713ed0c 4101 } else {
353eefd3 4102 err = 0;
d863dc36 4103 mark_buffer_dirty(bh);
3957ef53 4104 if (ext4_should_order_data(inode))
73131fbb
RZ
4105 err = ext4_jbd2_inode_add_write(handle, inode, from,
4106 length);
0713ed0c 4107 }
d863dc36
LC
4108
4109unlock:
9d3973de
MW
4110 folio_unlock(folio);
4111 folio_put(folio);
d863dc36
LC
4112 return err;
4113}
4114
923ae0ff
RZ
4115/*
4116 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4117 * starting from file offset 'from'. The range to be zero'd must
4118 * be contained with in one block. If the specified range exceeds
4119 * the end of the block it will be shortened to end of the block
3088e5a5 4120 * that corresponds to 'from'
923ae0ff
RZ
4121 */
4122static int ext4_block_zero_page_range(handle_t *handle,
4123 struct address_space *mapping, loff_t from, loff_t length)
4124{
4125 struct inode *inode = mapping->host;
09cbfeaf 4126 unsigned offset = from & (PAGE_SIZE-1);
923ae0ff
RZ
4127 unsigned blocksize = inode->i_sb->s_blocksize;
4128 unsigned max = blocksize - (offset & (blocksize - 1));
4129
4130 /*
4131 * correct length if it does not fall between
4132 * 'from' and the end of the block
4133 */
4134 if (length > max || length < 0)
4135 length = max;
4136
47e69351 4137 if (IS_DAX(inode)) {
c6f40468
CH
4138 return dax_zero_range(inode, from, length, NULL,
4139 &ext4_iomap_ops);
47e69351 4140 }
923ae0ff
RZ
4141 return __ext4_block_zero_page_range(handle, mapping, from, length);
4142}
4143
94350ab5
MW
4144/*
4145 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4146 * up to the end of the block which corresponds to `from'.
4147 * This required during truncate. We need to physically zero the tail end
4148 * of that block so it doesn't yield old data if the file is later grown.
4149 */
c197855e 4150static int ext4_block_truncate_page(handle_t *handle,
94350ab5
MW
4151 struct address_space *mapping, loff_t from)
4152{
09cbfeaf 4153 unsigned offset = from & (PAGE_SIZE-1);
94350ab5
MW
4154 unsigned length;
4155 unsigned blocksize;
4156 struct inode *inode = mapping->host;
4157
0d06863f 4158 /* If we are processing an encrypted inode during orphan list handling */
592ddec7 4159 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
0d06863f
TT
4160 return 0;
4161
94350ab5
MW
4162 blocksize = inode->i_sb->s_blocksize;
4163 length = blocksize - (offset & (blocksize - 1));
4164
4165 return ext4_block_zero_page_range(handle, mapping, from, length);
4166}
4167
a87dd18c
LC
4168int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4169 loff_t lstart, loff_t length)
4170{
4171 struct super_block *sb = inode->i_sb;
4172 struct address_space *mapping = inode->i_mapping;
e1be3a92 4173 unsigned partial_start, partial_end;
a87dd18c
LC
4174 ext4_fsblk_t start, end;
4175 loff_t byte_end = (lstart + length - 1);
4176 int err = 0;
4177
e1be3a92
LC
4178 partial_start = lstart & (sb->s_blocksize - 1);
4179 partial_end = byte_end & (sb->s_blocksize - 1);
4180
a87dd18c
LC
4181 start = lstart >> sb->s_blocksize_bits;
4182 end = byte_end >> sb->s_blocksize_bits;
4183
4184 /* Handle partial zero within the single block */
e1be3a92
LC
4185 if (start == end &&
4186 (partial_start || (partial_end != sb->s_blocksize - 1))) {
a87dd18c
LC
4187 err = ext4_block_zero_page_range(handle, mapping,
4188 lstart, length);
4189 return err;
4190 }
4191 /* Handle partial zero out on the start of the range */
e1be3a92 4192 if (partial_start) {
a87dd18c
LC
4193 err = ext4_block_zero_page_range(handle, mapping,
4194 lstart, sb->s_blocksize);
4195 if (err)
4196 return err;
4197 }
4198 /* Handle partial zero out on the end of the range */
e1be3a92 4199 if (partial_end != sb->s_blocksize - 1)
a87dd18c 4200 err = ext4_block_zero_page_range(handle, mapping,
e1be3a92
LC
4201 byte_end - partial_end,
4202 partial_end + 1);
a87dd18c
LC
4203 return err;
4204}
4205
91ef4caf
DG
4206int ext4_can_truncate(struct inode *inode)
4207{
91ef4caf
DG
4208 if (S_ISREG(inode->i_mode))
4209 return 1;
4210 if (S_ISDIR(inode->i_mode))
4211 return 1;
4212 if (S_ISLNK(inode->i_mode))
4213 return !ext4_inode_is_fast_symlink(inode);
4214 return 0;
4215}
4216
01127848
JK
4217/*
4218 * We have to make sure i_disksize gets properly updated before we truncate
4219 * page cache due to hole punching or zero range. Otherwise i_disksize update
4220 * can get lost as it may have been postponed to submission of writeback but
4221 * that will never happen after we truncate page cache.
4222 */
4223int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4224 loff_t len)
4225{
4226 handle_t *handle;
4209ae12
HS
4227 int ret;
4228
01127848
JK
4229 loff_t size = i_size_read(inode);
4230
5955102c 4231 WARN_ON(!inode_is_locked(inode));
01127848
JK
4232 if (offset > size || offset + len < size)
4233 return 0;
4234
4235 if (EXT4_I(inode)->i_disksize >= size)
4236 return 0;
4237
4238 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4239 if (IS_ERR(handle))
4240 return PTR_ERR(handle);
4241 ext4_update_i_disksize(inode, size);
4209ae12 4242 ret = ext4_mark_inode_dirty(handle, inode);
01127848
JK
4243 ext4_journal_stop(handle);
4244
4209ae12 4245 return ret;
01127848
JK
4246}
4247
17207d0b
ZY
4248static inline void ext4_truncate_folio(struct inode *inode,
4249 loff_t start, loff_t end)
4250{
4251 unsigned long blocksize = i_blocksize(inode);
4252 struct folio *folio;
4253
4254 /* Nothing to be done if no complete block needs to be truncated. */
4255 if (round_up(start, blocksize) >= round_down(end, blocksize))
4256 return;
4257
4258 folio = filemap_lock_folio(inode->i_mapping, start >> PAGE_SHIFT);
4259 if (IS_ERR(folio))
4260 return;
4261
4262 if (folio_mkclean(folio))
4263 folio_mark_dirty(folio);
4264 folio_unlock(folio);
4265 folio_put(folio);
4266}
4267
4268int ext4_truncate_page_cache_block_range(struct inode *inode,
4269 loff_t start, loff_t end)
4270{
4271 unsigned long blocksize = i_blocksize(inode);
4272 int ret;
4273
4274 /*
4275 * For journalled data we need to write (and checkpoint) pages
4276 * before discarding page cache to avoid inconsitent data on disk
4277 * in case of crash before freeing or unwritten converting trans
4278 * is committed.
4279 */
4280 if (ext4_should_journal_data(inode)) {
4281 ret = filemap_write_and_wait_range(inode->i_mapping, start,
4282 end - 1);
4283 if (ret)
4284 return ret;
4285 goto truncate_pagecache;
4286 }
4287
4288 /*
4289 * If the block size is less than the page size, the file's mapped
4290 * blocks within one page could be freed or converted to unwritten.
4291 * So it's necessary to remove writable userspace mappings, and then
4292 * ext4_page_mkwrite() can be called during subsequent write access
4293 * to these partial folios.
4294 */
4295 if (!IS_ALIGNED(start | end, PAGE_SIZE) &&
4296 blocksize < PAGE_SIZE && start < inode->i_size) {
4297 loff_t page_boundary = round_up(start, PAGE_SIZE);
4298
4299 ext4_truncate_folio(inode, start, min(page_boundary, end));
4300 if (end > page_boundary)
4301 ext4_truncate_folio(inode,
4302 round_down(end, PAGE_SIZE), end);
4303 }
4304
4305truncate_pagecache:
4306 truncate_pagecache_range(inode, start, end - 1);
4307 return 0;
4308}
4309
d4f5258e 4310static void ext4_wait_dax_page(struct inode *inode)
430657b6 4311{
d4f5258e 4312 filemap_invalidate_unlock(inode->i_mapping);
430657b6 4313 schedule();
d4f5258e 4314 filemap_invalidate_lock(inode->i_mapping);
430657b6
RZ
4315}
4316
4317int ext4_break_layouts(struct inode *inode)
4318{
d4f5258e 4319 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
430657b6
RZ
4320 return -EINVAL;
4321
d5b3afea 4322 return dax_break_layout_inode(inode, ext4_wait_dax_page);
430657b6
RZ
4323}
4324
a4bb6b64 4325/*
cca32b7e 4326 * ext4_punch_hole: punches a hole in a file by releasing the blocks
a4bb6b64
AH
4327 * associated with the given offset and length
4328 *
4329 * @inode: File inode
4330 * @offset: The offset where the hole will begin
4331 * @len: The length of the hole
4332 *
4907cb7b 4333 * Returns: 0 on success or negative on failure
a4bb6b64
AH
4334 */
4335
ad5cd4f4 4336int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
a4bb6b64 4337{
ad5cd4f4 4338 struct inode *inode = file_inode(file);
26a4c0c6 4339 struct super_block *sb = inode->i_sb;
982bf37d 4340 ext4_lblk_t start_lblk, end_lblk;
29ec9bed 4341 loff_t max_end = sb->s_maxbytes;
982bf37d 4342 loff_t end = offset + length;
26a4c0c6
TT
4343 handle_t *handle;
4344 unsigned int credits;
ea3f17ef 4345 int ret;
26a4c0c6 4346
b8a86845 4347 trace_ext4_punch_hole(inode, offset, length, 0);
ea3f17ef 4348 WARN_ON_ONCE(!inode_is_locked(inode));
9ef06cec 4349
29ec9bed
ZY
4350 /*
4351 * For indirect-block based inodes, make sure that the hole within
4352 * one block before last range.
4353 */
4354 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4355 max_end = EXT4_SB(sb)->s_bitmap_maxbytes - sb->s_blocksize;
4356
26a4c0c6 4357 /* No need to punch hole beyond i_size */
b5e58bcd 4358 if (offset >= inode->i_size || offset >= max_end)
ea3f17ef 4359 return 0;
26a4c0c6
TT
4360
4361 /*
982bf37d 4362 * If the hole extends beyond i_size, set the hole to end after
29ec9bed 4363 * the page that contains i_size.
26a4c0c6 4364 */
982bf37d
ZY
4365 if (end > inode->i_size)
4366 end = round_up(inode->i_size, PAGE_SIZE);
4367 if (end > max_end)
4368 end = max_end;
4369 length = end - offset;
26a4c0c6 4370
2da37622 4371 /*
982bf37d
ZY
4372 * Attach jinode to inode for jbd2 if we do any zeroing of partial
4373 * block.
2da37622 4374 */
982bf37d 4375 if (!IS_ALIGNED(offset | end, sb->s_blocksize)) {
a361293f
JK
4376 ret = ext4_inode_attach_jinode(inode);
4377 if (ret < 0)
ea3f17ef 4378 return ret;
a361293f
JK
4379 }
4380
430657b6 4381
982bf37d 4382 ret = ext4_update_disksize_before_punch(inode, offset, length);
430657b6 4383 if (ret)
2890e5e0 4384 return ret;
26a4c0c6 4385
a87dd18c 4386 /* Now release the pages and zero block aligned part of pages*/
982bf37d
ZY
4387 ret = ext4_truncate_page_cache_block_range(inode, offset, end);
4388 if (ret)
2890e5e0 4389 return ret;
26a4c0c6
TT
4390
4391 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4392 credits = ext4_writepage_trans_blocks(inode);
4393 else
4394 credits = ext4_blocks_for_truncate(inode);
4395 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4396 if (IS_ERR(handle)) {
4397 ret = PTR_ERR(handle);
4398 ext4_std_error(sb, ret);
2890e5e0 4399 return ret;
26a4c0c6
TT
4400 }
4401
982bf37d 4402 ret = ext4_zero_partial_blocks(handle, inode, offset, length);
a87dd18c 4403 if (ret)
982bf37d 4404 goto out_handle;
26a4c0c6 4405
eee597ac 4406 /* If there are blocks to remove, do it */
982bf37d
ZY
4407 start_lblk = EXT4_B_TO_LBLK(inode, offset);
4408 end_lblk = end >> inode->i_blkbits;
4409
4410 if (end_lblk > start_lblk) {
4411 ext4_lblk_t hole_len = end_lblk - start_lblk;
26a4c0c6 4412
4d326646 4413 ext4_fc_track_inode(handle, inode);
1b4d2a0b 4414 ext4_check_map_extents_env(inode);
eee597ac 4415 down_write(&EXT4_I(inode)->i_data_sem);
2ffd2a6a 4416 ext4_discard_preallocations(inode);
26a4c0c6 4417
982bf37d 4418 ext4_es_remove_extent(inode, start_lblk, hole_len);
26a4c0c6 4419
eee597ac 4420 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
982bf37d
ZY
4421 ret = ext4_ext_remove_space(inode, start_lblk,
4422 end_lblk - 1);
eee597ac 4423 else
982bf37d
ZY
4424 ret = ext4_ind_remove_space(handle, inode, start_lblk,
4425 end_lblk);
4426 if (ret) {
4427 up_write(&EXT4_I(inode)->i_data_sem);
4428 goto out_handle;
4429 }
26a4c0c6 4430
982bf37d 4431 ext4_es_insert_extent(inode, start_lblk, hole_len, ~0,
f3baf33b 4432 EXTENT_STATUS_HOLE, 0);
eee597ac
LC
4433 up_write(&EXT4_I(inode)->i_data_sem);
4434 }
982bf37d
ZY
4435 ext4_fc_track_range(handle, inode, start_lblk, end_lblk);
4436
4437 ret = ext4_mark_inode_dirty(handle, inode);
4438 if (unlikely(ret))
4439 goto out_handle;
4440
4441 ext4_update_inode_fsync_trans(handle, inode, 1);
26a4c0c6
TT
4442 if (IS_SYNC(inode))
4443 ext4_handle_sync(handle);
982bf37d 4444out_handle:
26a4c0c6 4445 ext4_journal_stop(handle);
26a4c0c6 4446 return ret;
a4bb6b64
AH
4447}
4448
a361293f
JK
4449int ext4_inode_attach_jinode(struct inode *inode)
4450{
4451 struct ext4_inode_info *ei = EXT4_I(inode);
4452 struct jbd2_inode *jinode;
4453
4454 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4455 return 0;
4456
4457 jinode = jbd2_alloc_inode(GFP_KERNEL);
4458 spin_lock(&inode->i_lock);
4459 if (!ei->jinode) {
4460 if (!jinode) {
4461 spin_unlock(&inode->i_lock);
4462 return -ENOMEM;
4463 }
4464 ei->jinode = jinode;
4465 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4466 jinode = NULL;
4467 }
4468 spin_unlock(&inode->i_lock);
4469 if (unlikely(jinode != NULL))
4470 jbd2_free_inode(jinode);
4471 return 0;
4472}
4473
ac27a0ec 4474/*
617ba13b 4475 * ext4_truncate()
ac27a0ec 4476 *
617ba13b
MC
4477 * We block out ext4_get_block() block instantiations across the entire
4478 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
ac27a0ec
DK
4479 * simultaneously on behalf of the same inode.
4480 *
42b2aa86 4481 * As we work through the truncate and commit bits of it to the journal there
ac27a0ec
DK
4482 * is one core, guiding principle: the file's tree must always be consistent on
4483 * disk. We must be able to restart the truncate after a crash.
4484 *
4485 * The file's tree may be transiently inconsistent in memory (although it
4486 * probably isn't), but whenever we close off and commit a journal transaction,
4487 * the contents of (the filesystem + the journal) must be consistent and
4488 * restartable. It's pretty simple, really: bottom up, right to left (although
4489 * left-to-right works OK too).
4490 *
4491 * Note that at recovery time, journal replay occurs *before* the restart of
4492 * truncate against the orphan inode list.
4493 *
4494 * The committed inode has the new, desired i_size (which is the same as
617ba13b 4495 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
ac27a0ec 4496 * that this inode's truncate did not complete and it will again call
617ba13b
MC
4497 * ext4_truncate() to have another go. So there will be instantiated blocks
4498 * to the right of the truncation point in a crashed ext4 filesystem. But
ac27a0ec 4499 * that's fine - as long as they are linked from the inode, the post-crash
617ba13b 4500 * ext4_truncate() run will find them and release them.
ac27a0ec 4501 */
2c98eb5e 4502int ext4_truncate(struct inode *inode)
ac27a0ec 4503{
819c4920
TT
4504 struct ext4_inode_info *ei = EXT4_I(inode);
4505 unsigned int credits;
4209ae12 4506 int err = 0, err2;
819c4920
TT
4507 handle_t *handle;
4508 struct address_space *mapping = inode->i_mapping;
819c4920 4509
19b5ef61
TT
4510 /*
4511 * There is a possibility that we're either freeing the inode
e04027e8 4512 * or it's a completely new inode. In those cases we might not
f340b3d9 4513 * have i_rwsem locked because it's not necessary.
19b5ef61
TT
4514 */
4515 if (!(inode->i_state & (I_NEW|I_FREEING)))
5955102c 4516 WARN_ON(!inode_is_locked(inode));
0562e0ba
JZ
4517 trace_ext4_truncate_enter(inode);
4518
91ef4caf 4519 if (!ext4_can_truncate(inode))
9a5d265f 4520 goto out_trace;
ac27a0ec 4521
5534fb5b 4522 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
19f5fb7a 4523 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
7d8f9f7d 4524
aef1c851
TM
4525 if (ext4_has_inline_data(inode)) {
4526 int has_inline = 1;
4527
01daf945 4528 err = ext4_inline_data_truncate(inode, &has_inline);
9a5d265f 4529 if (err || has_inline)
4530 goto out_trace;
aef1c851
TM
4531 }
4532
a361293f
JK
4533 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4534 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
a71248b1
BL
4535 err = ext4_inode_attach_jinode(inode);
4536 if (err)
9a5d265f 4537 goto out_trace;
a361293f
JK
4538 }
4539
819c4920
TT
4540 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4541 credits = ext4_writepage_trans_blocks(inode);
4542 else
4543 credits = ext4_blocks_for_truncate(inode);
4544
4545 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
9a5d265f 4546 if (IS_ERR(handle)) {
4547 err = PTR_ERR(handle);
4548 goto out_trace;
4549 }
819c4920 4550
eb3544c6
LC
4551 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4552 ext4_block_truncate_page(handle, mapping, inode->i_size);
819c4920
TT
4553
4554 /*
4555 * We add the inode to the orphan list, so that if this
4556 * truncate spans multiple transactions, and we crash, we will
4557 * resume the truncate when the filesystem recovers. It also
4558 * marks the inode dirty, to catch the new size.
4559 *
4560 * Implication: the file must always be in a sane, consistent
4561 * truncatable state while each transaction commits.
4562 */
2c98eb5e
TT
4563 err = ext4_orphan_add(handle, inode);
4564 if (err)
819c4920
TT
4565 goto out_stop;
4566
4d326646 4567 ext4_fc_track_inode(handle, inode);
1b4d2a0b 4568 ext4_check_map_extents_env(inode);
819c4920 4569
1b4d2a0b 4570 down_write(&EXT4_I(inode)->i_data_sem);
2ffd2a6a 4571 ext4_discard_preallocations(inode);
819c4920 4572
ff9893dc 4573 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
d0abb36d 4574 err = ext4_ext_truncate(handle, inode);
ff9893dc 4575 else
819c4920
TT
4576 ext4_ind_truncate(handle, inode);
4577
4578 up_write(&ei->i_data_sem);
d0abb36d
TT
4579 if (err)
4580 goto out_stop;
819c4920
TT
4581
4582 if (IS_SYNC(inode))
4583 ext4_handle_sync(handle);
4584
4585out_stop:
4586 /*
4587 * If this was a simple ftruncate() and the file will remain alive,
4588 * then we need to clear up the orphan record which we created above.
4589 * However, if this was a real unlink then we were called by
58d86a50 4590 * ext4_evict_inode(), and we allow that function to clean up the
819c4920
TT
4591 * orphan info for us.
4592 */
4593 if (inode->i_nlink)
4594 ext4_orphan_del(handle, inode);
4595
b898ab23 4596 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4209ae12
HS
4597 err2 = ext4_mark_inode_dirty(handle, inode);
4598 if (unlikely(err2 && !err))
4599 err = err2;
819c4920 4600 ext4_journal_stop(handle);
ac27a0ec 4601
9a5d265f 4602out_trace:
0562e0ba 4603 trace_ext4_truncate_exit(inode);
2c98eb5e 4604 return err;
ac27a0ec
DK
4605}
4606
9a1bf32c
ZY
4607static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4608{
4609 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4610 return inode_peek_iversion_raw(inode);
4611 else
4612 return inode_peek_iversion(inode);
4613}
4614
4615static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4616 struct ext4_inode_info *ei)
4617{
4618 struct inode *inode = &(ei->vfs_inode);
4619 u64 i_blocks = READ_ONCE(inode->i_blocks);
4620 struct super_block *sb = inode->i_sb;
4621
4622 if (i_blocks <= ~0U) {
4623 /*
4624 * i_blocks can be represented in a 32 bit variable
4625 * as multiple of 512 bytes
4626 */
4627 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4628 raw_inode->i_blocks_high = 0;
4629 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4630 return 0;
4631 }
4632
4633 /*
4634 * This should never happen since sb->s_maxbytes should not have
4635 * allowed this, sb->s_maxbytes was set according to the huge_file
4636 * feature in ext4_fill_super().
4637 */
4638 if (!ext4_has_feature_huge_file(sb))
4639 return -EFSCORRUPTED;
4640
4641 if (i_blocks <= 0xffffffffffffULL) {
4642 /*
4643 * i_blocks can be represented in a 48 bit variable
4644 * as multiple of 512 bytes
4645 */
4646 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4647 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4648 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4649 } else {
4650 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4651 /* i_block is stored in file system block size */
4652 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4653 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4654 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4655 }
4656 return 0;
4657}
4658
4659static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4660{
4661 struct ext4_inode_info *ei = EXT4_I(inode);
4662 uid_t i_uid;
4663 gid_t i_gid;
4664 projid_t i_projid;
4665 int block;
4666 int err;
4667
4668 err = ext4_inode_blocks_set(raw_inode, ei);
4669
4670 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4671 i_uid = i_uid_read(inode);
4672 i_gid = i_gid_read(inode);
4673 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4674 if (!(test_opt(inode->i_sb, NO_UID32))) {
4675 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4676 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4677 /*
4678 * Fix up interoperability with old kernels. Otherwise,
4679 * old inodes get re-used with the upper 16 bits of the
4680 * uid/gid intact.
4681 */
4682 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4683 raw_inode->i_uid_high = 0;
4684 raw_inode->i_gid_high = 0;
4685 } else {
4686 raw_inode->i_uid_high =
4687 cpu_to_le16(high_16_bits(i_uid));
4688 raw_inode->i_gid_high =
4689 cpu_to_le16(high_16_bits(i_gid));
4690 }
4691 } else {
4692 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4693 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4694 raw_inode->i_uid_high = 0;
4695 raw_inode->i_gid_high = 0;
4696 }
4697 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4698
1bc33893 4699 EXT4_INODE_SET_CTIME(inode, raw_inode);
b898ab23
JL
4700 EXT4_INODE_SET_MTIME(inode, raw_inode);
4701 EXT4_INODE_SET_ATIME(inode, raw_inode);
9a1bf32c
ZY
4702 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4703
4704 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4705 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4706 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4707 raw_inode->i_file_acl_high =
4708 cpu_to_le16(ei->i_file_acl >> 32);
4709 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4710 ext4_isize_set(raw_inode, ei->i_disksize);
4711
4712 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4713 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4714 if (old_valid_dev(inode->i_rdev)) {
4715 raw_inode->i_block[0] =
4716 cpu_to_le32(old_encode_dev(inode->i_rdev));
4717 raw_inode->i_block[1] = 0;
4718 } else {
4719 raw_inode->i_block[0] = 0;
4720 raw_inode->i_block[1] =
4721 cpu_to_le32(new_encode_dev(inode->i_rdev));
4722 raw_inode->i_block[2] = 0;
4723 }
4724 } else if (!ext4_has_inline_data(inode)) {
4725 for (block = 0; block < EXT4_N_BLOCKS; block++)
4726 raw_inode->i_block[block] = ei->i_data[block];
4727 }
4728
4729 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4730 u64 ivers = ext4_inode_peek_iversion(inode);
4731
4732 raw_inode->i_disk_version = cpu_to_le32(ivers);
4733 if (ei->i_extra_isize) {
4734 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4735 raw_inode->i_version_hi =
4736 cpu_to_le32(ivers >> 32);
4737 raw_inode->i_extra_isize =
4738 cpu_to_le16(ei->i_extra_isize);
4739 }
4740 }
4741
4742 if (i_projid != EXT4_DEF_PROJID &&
4743 !ext4_has_feature_project(inode->i_sb))
4744 err = err ?: -EFSCORRUPTED;
4745
4746 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4747 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4748 raw_inode->i_projid = cpu_to_le32(i_projid);
4749
4750 ext4_inode_csum_set(inode, raw_inode, ei);
4751 return err;
4752}
4753
ac27a0ec 4754/*
617ba13b 4755 * ext4_get_inode_loc returns with an extra refcount against the inode's
de01f484
ZY
4756 * underlying buffer_head on success. If we pass 'inode' and it does not
4757 * have in-inode xattr, we have all inode data in memory that is needed
4758 * to recreate the on-disk version of this inode.
ac27a0ec 4759 */
8016e29f 4760static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
de01f484 4761 struct inode *inode, struct ext4_iloc *iloc,
8016e29f 4762 ext4_fsblk_t *ret_block)
ac27a0ec 4763{
240799cd
TT
4764 struct ext4_group_desc *gdp;
4765 struct buffer_head *bh;
240799cd 4766 ext4_fsblk_t block;
02f03c42 4767 struct blk_plug plug;
240799cd
TT
4768 int inodes_per_block, inode_offset;
4769
3a06d778 4770 iloc->bh = NULL;
8016e29f
HS
4771 if (ino < EXT4_ROOT_INO ||
4772 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
6a797d27 4773 return -EFSCORRUPTED;
ac27a0ec 4774
8016e29f 4775 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
240799cd
TT
4776 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4777 if (!gdp)
ac27a0ec
DK
4778 return -EIO;
4779
240799cd
TT
4780 /*
4781 * Figure out the offset within the block group inode table
4782 */
00d09882 4783 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
8016e29f 4784 inode_offset = ((ino - 1) %
240799cd 4785 EXT4_INODES_PER_GROUP(sb));
240799cd
TT
4786 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4787
eee22187
BL
4788 block = ext4_inode_table(sb, gdp);
4789 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4790 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4791 ext4_error(sb, "Invalid inode table block %llu in "
4792 "block_group %u", block, iloc->block_group);
4793 return -EFSCORRUPTED;
4794 }
4795 block += (inode_offset / inodes_per_block);
4796
240799cd 4797 bh = sb_getblk(sb, block);
aebf0243 4798 if (unlikely(!bh))
860d21e2 4799 return -ENOMEM;
8e33fadf
ZY
4800 if (ext4_buffer_uptodate(bh))
4801 goto has_buffer;
9c83a923 4802
8e33fadf 4803 lock_buffer(bh);
f2c77973
ZY
4804 if (ext4_buffer_uptodate(bh)) {
4805 /* Someone brought it uptodate while we waited */
4806 unlock_buffer(bh);
4807 goto has_buffer;
4808 }
4809
8e33fadf
ZY
4810 /*
4811 * If we have all information of the inode in memory and this
4812 * is the only valid inode in the block, we need not read the
4813 * block.
4814 */
de01f484 4815 if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
8e33fadf
ZY
4816 struct buffer_head *bitmap_bh;
4817 int i, start;
ac27a0ec 4818
8e33fadf 4819 start = inode_offset & ~(inodes_per_block - 1);
ac27a0ec 4820
8e33fadf
ZY
4821 /* Is the inode bitmap in cache? */
4822 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4823 if (unlikely(!bitmap_bh))
4824 goto make_io;
ac27a0ec 4825
8e33fadf
ZY
4826 /*
4827 * If the inode bitmap isn't in cache then the
4828 * optimisation may end up performing two reads instead
4829 * of one, so skip it.
4830 */
4831 if (!buffer_uptodate(bitmap_bh)) {
ac27a0ec 4832 brelse(bitmap_bh);
8e33fadf 4833 goto make_io;
ac27a0ec 4834 }
8e33fadf
ZY
4835 for (i = start; i < start + inodes_per_block; i++) {
4836 if (i == inode_offset)
4837 continue;
4838 if (ext4_test_bit(i, bitmap_bh->b_data))
4839 break;
ac27a0ec 4840 }
8e33fadf
ZY
4841 brelse(bitmap_bh);
4842 if (i == start + inodes_per_block) {
de01f484
ZY
4843 struct ext4_inode *raw_inode =
4844 (struct ext4_inode *) (bh->b_data + iloc->offset);
4845
8e33fadf
ZY
4846 /* all other inodes are free, so skip I/O */
4847 memset(bh->b_data, 0, bh->b_size);
de01f484
ZY
4848 if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4849 ext4_fill_raw_inode(inode, raw_inode);
8e33fadf
ZY
4850 set_buffer_uptodate(bh);
4851 unlock_buffer(bh);
4852 goto has_buffer;
4853 }
4854 }
ac27a0ec
DK
4855
4856make_io:
8e33fadf
ZY
4857 /*
4858 * If we need to do any I/O, try to pre-readahead extra
4859 * blocks from the inode table.
4860 */
4861 blk_start_plug(&plug);
4862 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4863 ext4_fsblk_t b, end, table;
4864 unsigned num;
4865 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4866
4867 table = ext4_inode_table(sb, gdp);
4868 /* s_inode_readahead_blks is always a power of 2 */
4869 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4870 if (table > b)
4871 b = table;
4872 end = b + ra_blks;
4873 num = EXT4_INODES_PER_GROUP(sb);
4874 if (ext4_has_group_desc_csum(sb))
4875 num -= ext4_itable_unused_count(sb, gdp);
4876 table += num / inodes_per_block;
4877 if (end > table)
4878 end = table;
4879 while (b <= end)
4880 ext4_sb_breadahead_unmovable(sb, b++);
4881 }
240799cd 4882
8e33fadf
ZY
4883 /*
4884 * There are other valid inodes in the buffer, this inode
4885 * has in-inode xattrs, or we don't have this inode in memory.
4886 * Read the block from disk.
4887 */
4888 trace_ext4_load_inode(sb, ino);
2f3d93e2
LL
4889 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL,
4890 ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO));
8e33fadf
ZY
4891 blk_finish_plug(&plug);
4892 wait_on_buffer(bh);
8e33fadf
ZY
4893 if (!buffer_uptodate(bh)) {
4894 if (ret_block)
4895 *ret_block = block;
4896 brelse(bh);
4897 return -EIO;
ac27a0ec
DK
4898 }
4899has_buffer:
4900 iloc->bh = bh;
4901 return 0;
4902}
4903
8016e29f
HS
4904static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4905 struct ext4_iloc *iloc)
4906{
c27c29c6 4907 ext4_fsblk_t err_blk = 0;
8016e29f
HS
4908 int ret;
4909
de01f484 4910 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
8016e29f
HS
4911 &err_blk);
4912
4913 if (ret == -EIO)
4914 ext4_error_inode_block(inode, err_blk, EIO,
4915 "unable to read itable block");
4916
4917 return ret;
4918}
4919
617ba13b 4920int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
ac27a0ec 4921{
c27c29c6 4922 ext4_fsblk_t err_blk = 0;
8016e29f
HS
4923 int ret;
4924
de01f484
ZY
4925 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4926 &err_blk);
8016e29f
HS
4927
4928 if (ret == -EIO)
4929 ext4_error_inode_block(inode, err_blk, EIO,
4930 "unable to read itable block");
4931
4932 return ret;
4933}
4934
4935
4936int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4937 struct ext4_iloc *iloc)
4938{
de01f484 4939 return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
ac27a0ec
DK
4940}
4941
a8ab6d38 4942static bool ext4_should_enable_dax(struct inode *inode)
6642586b 4943{
a8ab6d38
IW
4944 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4945
9cb20f94 4946 if (test_opt2(inode->i_sb, DAX_NEVER))
6642586b
RZ
4947 return false;
4948 if (!S_ISREG(inode->i_mode))
4949 return false;
4950 if (ext4_should_journal_data(inode))
4951 return false;
4952 if (ext4_has_inline_data(inode))
4953 return false;
592ddec7 4954 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
6642586b 4955 return false;
c93d8f88
EB
4956 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4957 return false;
a8ab6d38
IW
4958 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4959 return false;
4960 if (test_opt(inode->i_sb, DAX_ALWAYS))
4961 return true;
4962
b383a73f 4963 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
6642586b
RZ
4964}
4965
043546e4 4966void ext4_set_inode_flags(struct inode *inode, bool init)
ac27a0ec 4967{
617ba13b 4968 unsigned int flags = EXT4_I(inode)->i_flags;
00a1a053 4969 unsigned int new_fl = 0;
ac27a0ec 4970
043546e4
IW
4971 WARN_ON_ONCE(IS_DAX(inode) && init);
4972
617ba13b 4973 if (flags & EXT4_SYNC_FL)
00a1a053 4974 new_fl |= S_SYNC;
617ba13b 4975 if (flags & EXT4_APPEND_FL)
00a1a053 4976 new_fl |= S_APPEND;
617ba13b 4977 if (flags & EXT4_IMMUTABLE_FL)
00a1a053 4978 new_fl |= S_IMMUTABLE;
617ba13b 4979 if (flags & EXT4_NOATIME_FL)
00a1a053 4980 new_fl |= S_NOATIME;
617ba13b 4981 if (flags & EXT4_DIRSYNC_FL)
00a1a053 4982 new_fl |= S_DIRSYNC;
043546e4
IW
4983
4984 /* Because of the way inode_set_flags() works we must preserve S_DAX
4985 * here if already set. */
4986 new_fl |= (inode->i_flags & S_DAX);
4987 if (init && ext4_should_enable_dax(inode))
923ae0ff 4988 new_fl |= S_DAX;
043546e4 4989
2ee6a576
EB
4990 if (flags & EXT4_ENCRYPT_FL)
4991 new_fl |= S_ENCRYPTED;
b886ee3e
GKB
4992 if (flags & EXT4_CASEFOLD_FL)
4993 new_fl |= S_CASEFOLD;
c93d8f88
EB
4994 if (flags & EXT4_VERITY_FL)
4995 new_fl |= S_VERITY;
5f16f322 4996 inode_set_flags(inode, new_fl,
2ee6a576 4997 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
c93d8f88 4998 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
ac27a0ec
DK
4999}
5000
0fc1b451 5001static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
de9a55b8 5002 struct ext4_inode_info *ei)
0fc1b451
AK
5003{
5004 blkcnt_t i_blocks ;
8180a562
AK
5005 struct inode *inode = &(ei->vfs_inode);
5006 struct super_block *sb = inode->i_sb;
0fc1b451 5007
e2b911c5 5008 if (ext4_has_feature_huge_file(sb)) {
0fc1b451
AK
5009 /* we are using combined 48 bit field */
5010 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
5011 le32_to_cpu(raw_inode->i_blocks_lo);
07a03824 5012 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
8180a562
AK
5013 /* i_blocks represent file system block size */
5014 return i_blocks << (inode->i_blkbits - 9);
5015 } else {
5016 return i_blocks;
5017 }
0fc1b451
AK
5018 } else {
5019 return le32_to_cpu(raw_inode->i_blocks_lo);
5020 }
5021}
ff9ddf7e 5022
eb9b5f01 5023static inline int ext4_iget_extra_inode(struct inode *inode,
152a7b0a
TM
5024 struct ext4_inode *raw_inode,
5025 struct ext4_inode_info *ei)
5026{
5027 __le32 *magic = (void *)raw_inode +
5028 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
eb9b5f01 5029
fd7e672e 5030 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
290ab230 5031 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
1dcdce59
YB
5032 int err;
5033
5701875f
YB
5034 err = xattr_check_inode(inode, IHDR(inode, raw_inode),
5035 ITAIL(inode, raw_inode));
5036 if (err)
5037 return err;
5038
152a7b0a 5039 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
1dcdce59
YB
5040 err = ext4_find_inline_data_nolock(inode);
5041 if (!err && ext4_has_inline_data(inode))
5042 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
5043 return err;
f19d5870
TM
5044 } else
5045 EXT4_I(inode)->i_inline_off = 0;
eb9b5f01 5046 return 0;
152a7b0a
TM
5047}
5048
040cb378
LX
5049int ext4_get_projid(struct inode *inode, kprojid_t *projid)
5050{
0b7b7779 5051 if (!ext4_has_feature_project(inode->i_sb))
040cb378
LX
5052 return -EOPNOTSUPP;
5053 *projid = EXT4_I(inode)->i_projid;
5054 return 0;
5055}
5056
e254d1af
EG
5057/*
5058 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
5059 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
5060 * set.
5061 */
5062static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
5063{
5064 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5065 inode_set_iversion_raw(inode, val);
5066 else
5067 inode_set_iversion_queried(inode, val);
5068}
e254d1af 5069
642335f3
JH
5070static int check_igot_inode(struct inode *inode, ext4_iget_flags flags,
5071 const char *function, unsigned int line)
b3e6bcb9 5072{
642335f3
JH
5073 const char *err_str;
5074
b3e6bcb9 5075 if (flags & EXT4_IGET_EA_INODE) {
642335f3
JH
5076 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5077 err_str = "missing EA_INODE flag";
5078 goto error;
5079 }
2bc7e7c1 5080 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
642335f3
JH
5081 EXT4_I(inode)->i_file_acl) {
5082 err_str = "ea_inode with extended attributes";
5083 goto error;
5084 }
b3e6bcb9 5085 } else {
642335f3
JH
5086 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
5087 /*
5088 * open_by_handle_at() could provide an old inode number
5089 * that has since been reused for an ea_inode; this does
5090 * not indicate filesystem corruption
5091 */
5092 if (flags & EXT4_IGET_HANDLE)
5093 return -ESTALE;
5094 err_str = "unexpected EA_INODE flag";
5095 goto error;
5096 }
5097 }
5098 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
5099 err_str = "unexpected bad inode w/o EXT4_IGET_BAD";
5100 goto error;
b3e6bcb9 5101 }
642335f3
JH
5102 return 0;
5103
5104error:
d612a079 5105 ext4_error_inode(inode, function, line, 0, "%s", err_str);
642335f3 5106 return -EFSCORRUPTED;
b3e6bcb9
TT
5107}
5108
7ac67301
ZY
5109bool ext4_should_enable_large_folio(struct inode *inode)
5110{
5111 struct super_block *sb = inode->i_sb;
5112
5113 if (!S_ISREG(inode->i_mode))
5114 return false;
5115 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
5116 ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA))
5117 return false;
5118 if (ext4_has_feature_verity(sb))
5119 return false;
5120 if (ext4_has_feature_encrypt(sb))
5121 return false;
5122
5123 return true;
5124}
5125
8a363970
TT
5126struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
5127 ext4_iget_flags flags, const char *function,
5128 unsigned int line)
ac27a0ec 5129{
617ba13b
MC
5130 struct ext4_iloc iloc;
5131 struct ext4_inode *raw_inode;
1d1fe1ee 5132 struct ext4_inode_info *ei;
bd2c38cf 5133 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
1d1fe1ee 5134 struct inode *inode;
b436b9be 5135 journal_t *journal = EXT4_SB(sb)->s_journal;
1d1fe1ee 5136 long ret;
7e6e1ef4 5137 loff_t size;
ac27a0ec 5138 int block;
08cefc7a
EB
5139 uid_t i_uid;
5140 gid_t i_gid;
040cb378 5141 projid_t i_projid;
ac27a0ec 5142
0b8e0bd4 5143 if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) ||
8a363970 5144 (ino < EXT4_ROOT_INO) ||
bd2c38cf 5145 (ino > le32_to_cpu(es->s_inodes_count))) {
8a363970
TT
5146 if (flags & EXT4_IGET_HANDLE)
5147 return ERR_PTR(-ESTALE);
014c9caa 5148 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
8a363970
TT
5149 "inode #%lu: comm %s: iget: illegal inode #",
5150 ino, current->comm);
5151 return ERR_PTR(-EFSCORRUPTED);
5152 }
5153
1d1fe1ee
DH
5154 inode = iget_locked(sb, ino);
5155 if (!inode)
5156 return ERR_PTR(-ENOMEM);
b3e6bcb9 5157 if (!(inode->i_state & I_NEW)) {
642335f3
JH
5158 ret = check_igot_inode(inode, flags, function, line);
5159 if (ret) {
b3e6bcb9 5160 iput(inode);
642335f3 5161 return ERR_PTR(ret);
b3e6bcb9 5162 }
1d1fe1ee 5163 return inode;
b3e6bcb9 5164 }
1d1fe1ee
DH
5165
5166 ei = EXT4_I(inode);
7dc57615 5167 iloc.bh = NULL;
ac27a0ec 5168
8016e29f 5169 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
1d1fe1ee 5170 if (ret < 0)
ac27a0ec 5171 goto bad_inode;
617ba13b 5172 raw_inode = ext4_raw_inode(&iloc);
814525f4 5173
8a363970
TT
5174 if ((flags & EXT4_IGET_HANDLE) &&
5175 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
5176 ret = -ESTALE;
5177 goto bad_inode;
5178 }
5179
814525f4
DW
5180 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5181 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5182 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
2dc8d9e1
EB
5183 EXT4_INODE_SIZE(inode->i_sb) ||
5184 (ei->i_extra_isize & 3)) {
8a363970
TT
5185 ext4_error_inode(inode, function, line, 0,
5186 "iget: bad extra_isize %u "
5187 "(inode size %u)",
2dc8d9e1
EB
5188 ei->i_extra_isize,
5189 EXT4_INODE_SIZE(inode->i_sb));
6a797d27 5190 ret = -EFSCORRUPTED;
814525f4
DW
5191 goto bad_inode;
5192 }
5193 } else
5194 ei->i_extra_isize = 0;
5195
5196 /* Precompute checksum seed for inode metadata */
e224fa3b 5197 if (ext4_has_feature_metadata_csum(sb)) {
814525f4
DW
5198 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5199 __u32 csum;
5200 __le32 inum = cpu_to_le32(inode->i_ino);
5201 __le32 gen = raw_inode->i_generation;
6cbab5f9 5202 csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum,
814525f4 5203 sizeof(inum));
6cbab5f9 5204 ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen));
814525f4
DW
5205 }
5206
8016e29f
HS
5207 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
5208 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
5209 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
5210 ext4_error_inode_err(inode, function, line, 0,
5211 EFSBADCRC, "iget: checksum invalid");
6a797d27 5212 ret = -EFSBADCRC;
814525f4
DW
5213 goto bad_inode;
5214 }
5215
ac27a0ec 5216 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
08cefc7a
EB
5217 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
5218 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
0b7b7779 5219 if (ext4_has_feature_project(sb) &&
040cb378
LX
5220 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5221 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5222 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
5223 else
5224 i_projid = EXT4_DEF_PROJID;
5225
af5bc92d 5226 if (!(test_opt(inode->i_sb, NO_UID32))) {
08cefc7a
EB
5227 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
5228 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
ac27a0ec 5229 }
08cefc7a
EB
5230 i_uid_write(inode, i_uid);
5231 i_gid_write(inode, i_gid);
040cb378 5232 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
bfe86848 5233 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
ac27a0ec 5234
353eb83c 5235 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
67cf5b09 5236 ei->i_inline_off = 0;
ac27a0ec
DK
5237 ei->i_dir_start_lookup = 0;
5238 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
5239 /* We now have enough fields to check if the inode was active or not.
5240 * This is needed because nfsd might try to access dead inodes
5241 * the test is that same one that e2fsck uses
5242 * NeilBrown 1999oct15
5243 */
5244 if (inode->i_nlink == 0) {
5cd74028 5245 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
393d1d1d
DTB
5246 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
5247 ino != EXT4_BOOT_LOADER_INO) {
5cd74028
BL
5248 /* this inode is deleted or unallocated */
5249 if (flags & EXT4_IGET_SPECIAL) {
5250 ext4_error_inode(inode, function, line, 0,
5251 "iget: special inode unallocated");
5252 ret = -EFSCORRUPTED;
5253 } else
5254 ret = -ESTALE;
ac27a0ec
DK
5255 goto bad_inode;
5256 }
5257 /* The only unlinked inodes we let through here have
5258 * valid i_mode and are being read by the orphan
5259 * recovery code: that's fine, we're about to complete
393d1d1d
DTB
5260 * the process of deleting those.
5261 * OR it is the EXT4_BOOT_LOADER_INO which is
5262 * not initialized on a new filesystem. */
ac27a0ec 5263 }
ac27a0ec 5264 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
043546e4 5265 ext4_set_inode_flags(inode, true);
0fc1b451 5266 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
7973c0c1 5267 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
e2b911c5 5268 if (ext4_has_feature_64bit(sb))
a1ddeb7e
BP
5269 ei->i_file_acl |=
5270 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
e08ac99f 5271 inode->i_size = ext4_isize(sb, raw_inode);
1a77a028
ZY
5272 size = i_size_read(inode);
5273 if (size < 0 || size > ext4_get_maxbytes(inode)) {
8a363970
TT
5274 ext4_error_inode(inode, function, line, 0,
5275 "iget: bad i_size value: %lld", size);
7e6e1ef4
DW
5276 ret = -EFSCORRUPTED;
5277 goto bad_inode;
5278 }
48a34311
JK
5279 /*
5280 * If dir_index is not enabled but there's dir with INDEX flag set,
5281 * we'd normally treat htree data as empty space. But with metadata
5282 * checksumming that corrupts checksums so forbid that.
5283 */
e224fa3b
EB
5284 if (!ext4_has_feature_dir_index(sb) &&
5285 ext4_has_feature_metadata_csum(sb) &&
48a34311
JK
5286 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
5287 ext4_error_inode(inode, function, line, 0,
5288 "iget: Dir with htree data on filesystem without dir_index feature.");
5289 ret = -EFSCORRUPTED;
5290 goto bad_inode;
5291 }
ac27a0ec 5292 ei->i_disksize = inode->i_size;
a9e7f447
DM
5293#ifdef CONFIG_QUOTA
5294 ei->i_reserved_quota = 0;
5295#endif
ac27a0ec
DK
5296 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5297 ei->i_block_group = iloc.block_group;
a4912123 5298 ei->i_last_alloc_group = ~0;
ac27a0ec
DK
5299 /*
5300 * NOTE! The in-memory inode i_data array is in little-endian order
5301 * even on big-endian machines: we do NOT byteswap the block numbers!
5302 */
617ba13b 5303 for (block = 0; block < EXT4_N_BLOCKS; block++)
ac27a0ec
DK
5304 ei->i_data[block] = raw_inode->i_block[block];
5305 INIT_LIST_HEAD(&ei->i_orphan);
aa75f4d3 5306 ext4_fc_init_inode(&ei->vfs_inode);
ac27a0ec 5307
b436b9be
JK
5308 /*
5309 * Set transaction id's of transactions that have to be committed
5310 * to finish f[data]sync. We set them to currently running transaction
5311 * as we cannot be sure that the inode or some of its metadata isn't
5312 * part of the transaction - the inode could have been reclaimed and
5313 * now it is reread from disk.
5314 */
5315 if (journal) {
5316 transaction_t *transaction;
5317 tid_t tid;
5318
a931da6a 5319 read_lock(&journal->j_state_lock);
b436b9be
JK
5320 if (journal->j_running_transaction)
5321 transaction = journal->j_running_transaction;
5322 else
5323 transaction = journal->j_committing_transaction;
5324 if (transaction)
5325 tid = transaction->t_tid;
5326 else
5327 tid = journal->j_commit_sequence;
a931da6a 5328 read_unlock(&journal->j_state_lock);
b436b9be
JK
5329 ei->i_sync_tid = tid;
5330 ei->i_datasync_tid = tid;
5331 }
5332
0040d987 5333 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
ac27a0ec
DK
5334 if (ei->i_extra_isize == 0) {
5335 /* The extra space is currently unused. Use it. */
2dc8d9e1 5336 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
617ba13b
MC
5337 ei->i_extra_isize = sizeof(struct ext4_inode) -
5338 EXT4_GOOD_OLD_INODE_SIZE;
ac27a0ec 5339 } else {
eb9b5f01
TT
5340 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5341 if (ret)
5342 goto bad_inode;
ac27a0ec 5343 }
814525f4 5344 }
ac27a0ec 5345
1bc33893 5346 EXT4_INODE_GET_CTIME(inode, raw_inode);
b898ab23
JL
5347 EXT4_INODE_GET_ATIME(inode, raw_inode);
5348 EXT4_INODE_GET_MTIME(inode, raw_inode);
ef7f3835
KS
5349 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5350
ed3654eb 5351 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
ee73f9a5
JL
5352 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5353
c4f65706
TT
5354 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5355 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
ee73f9a5 5356 ivers |=
c4f65706
TT
5357 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5358 }
e254d1af 5359 ext4_inode_set_iversion_queried(inode, ivers);
25ec56b5
JNC
5360 }
5361
c4b5a614 5362 ret = 0;
485c26ec 5363 if (ei->i_file_acl &&
ce9f24cc 5364 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
8a363970
TT
5365 ext4_error_inode(inode, function, line, 0,
5366 "iget: bad extended attribute block %llu",
24676da4 5367 ei->i_file_acl);
6a797d27 5368 ret = -EFSCORRUPTED;
485c26ec 5369 goto bad_inode;
f19d5870 5370 } else if (!ext4_has_inline_data(inode)) {
bc716523 5371 /* validate the block references in the inode */
8016e29f
HS
5372 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
5373 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5374 (S_ISLNK(inode->i_mode) &&
5375 !ext4_inode_is_fast_symlink(inode)))) {
bc716523 5376 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
f19d5870 5377 ret = ext4_ext_check_inode(inode);
bc716523
LS
5378 else
5379 ret = ext4_ind_check_inode(inode);
f19d5870 5380 }
fe2c8191 5381 }
567f3e9a 5382 if (ret)
de9a55b8 5383 goto bad_inode;
7a262f7c 5384
ac27a0ec 5385 if (S_ISREG(inode->i_mode)) {
617ba13b 5386 inode->i_op = &ext4_file_inode_operations;
be64f884 5387 inode->i_fop = &ext4_file_operations;
617ba13b 5388 ext4_set_aops(inode);
ac27a0ec 5389 } else if (S_ISDIR(inode->i_mode)) {
617ba13b
MC
5390 inode->i_op = &ext4_dir_inode_operations;
5391 inode->i_fop = &ext4_dir_operations;
ac27a0ec 5392 } else if (S_ISLNK(inode->i_mode)) {
6390d33b
LR
5393 /* VFS does not allow setting these so must be corruption */
5394 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
8a363970
TT
5395 ext4_error_inode(inode, function, line, 0,
5396 "iget: immutable or append flags "
5397 "not allowed on symlinks");
6390d33b
LR
5398 ret = -EFSCORRUPTED;
5399 goto bad_inode;
5400 }
592ddec7 5401 if (IS_ENCRYPTED(inode)) {
a7a67e8a 5402 inode->i_op = &ext4_encrypted_symlink_inode_operations;
a7a67e8a 5403 } else if (ext4_inode_is_fast_symlink(inode)) {
617ba13b 5404 inode->i_op = &ext4_fast_symlink_inode_operations;
5f920d5d
JK
5405 if (inode->i_size == 0 ||
5406 inode->i_size >= sizeof(ei->i_data) ||
5407 strnlen((char *)ei->i_data, inode->i_size + 1) !=
5408 inode->i_size) {
5409 ext4_error_inode(inode, function, line, 0,
5410 "invalid fast symlink length %llu",
5411 (unsigned long long)inode->i_size);
5412 ret = -EFSCORRUPTED;
5413 goto bad_inode;
5414 }
bae80473
MG
5415 inode_set_cached_link(inode, (char *)ei->i_data,
5416 inode->i_size);
e83c1397 5417 } else {
617ba13b 5418 inode->i_op = &ext4_symlink_inode_operations;
ac27a0ec 5419 }
563bdd61
TT
5420 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5421 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
617ba13b 5422 inode->i_op = &ext4_special_inode_operations;
ac27a0ec
DK
5423 if (raw_inode->i_block[0])
5424 init_special_inode(inode, inode->i_mode,
5425 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5426 else
5427 init_special_inode(inode, inode->i_mode,
5428 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
393d1d1d
DTB
5429 } else if (ino == EXT4_BOOT_LOADER_INO) {
5430 make_bad_inode(inode);
563bdd61 5431 } else {
6a797d27 5432 ret = -EFSCORRUPTED;
8a363970
TT
5433 ext4_error_inode(inode, function, line, 0,
5434 "iget: bogus i_mode (%o)", inode->i_mode);
563bdd61 5435 goto bad_inode;
ac27a0ec 5436 }
8216776c 5437 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
6456ca65
TT
5438 ext4_error_inode(inode, function, line, 0,
5439 "casefold flag without casefold feature");
8216776c
EB
5440 ret = -EFSCORRUPTED;
5441 goto bad_inode;
5442 }
7ac67301
ZY
5443 if (ext4_should_enable_large_folio(inode))
5444 mapping_set_large_folios(inode->i_mapping);
5445
642335f3
JH
5446 ret = check_igot_inode(inode, flags, function, line);
5447 /*
5448 * -ESTALE here means there is nothing inherently wrong with the inode,
5449 * it's just not an inode we can return for an fhandle lookup.
5450 */
5451 if (ret == -ESTALE) {
5452 brelse(iloc.bh);
5453 unlock_new_inode(inode);
5454 iput(inode);
5455 return ERR_PTR(-ESTALE);
63b1e9bc 5456 }
642335f3
JH
5457 if (ret)
5458 goto bad_inode;
63b1e9bc 5459 brelse(iloc.bh);
642335f3 5460
1d1fe1ee
DH
5461 unlock_new_inode(inode);
5462 return inode;
ac27a0ec
DK
5463
5464bad_inode:
567f3e9a 5465 brelse(iloc.bh);
1d1fe1ee
DH
5466 iget_failed(inode);
5467 return ERR_PTR(ret);
ac27a0ec
DK
5468}
5469
3f19b2ab
DH
5470static void __ext4_update_other_inode_time(struct super_block *sb,
5471 unsigned long orig_ino,
5472 unsigned long ino,
5473 struct ext4_inode *raw_inode)
a26f4992 5474{
3f19b2ab
DH
5475 struct inode *inode;
5476
5477 inode = find_inode_by_ino_rcu(sb, ino);
5478 if (!inode)
5479 return;
a26f4992 5480
ed296c6c 5481 if (!inode_is_dirtytime_only(inode))
3f19b2ab
DH
5482 return;
5483
a26f4992 5484 spin_lock(&inode->i_lock);
ed296c6c 5485 if (inode_is_dirtytime_only(inode)) {
a26f4992
TT
5486 struct ext4_inode_info *ei = EXT4_I(inode);
5487
5fcd5750 5488 inode->i_state &= ~I_DIRTY_TIME;
a26f4992
TT
5489 spin_unlock(&inode->i_lock);
5490
5491 spin_lock(&ei->i_raw_lock);
1bc33893 5492 EXT4_INODE_SET_CTIME(inode, raw_inode);
b898ab23
JL
5493 EXT4_INODE_SET_MTIME(inode, raw_inode);
5494 EXT4_INODE_SET_ATIME(inode, raw_inode);
3f19b2ab 5495 ext4_inode_csum_set(inode, raw_inode, ei);
a26f4992 5496 spin_unlock(&ei->i_raw_lock);
3f19b2ab
DH
5497 trace_ext4_other_inode_update_time(inode, orig_ino);
5498 return;
a26f4992
TT
5499 }
5500 spin_unlock(&inode->i_lock);
a26f4992
TT
5501}
5502
5503/*
5504 * Opportunistically update the other time fields for other inodes in
5505 * the same inode table block.
5506 */
5507static void ext4_update_other_inodes_time(struct super_block *sb,
5508 unsigned long orig_ino, char *buf)
5509{
a26f4992
TT
5510 unsigned long ino;
5511 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5512 int inode_size = EXT4_INODE_SIZE(sb);
5513
0f0ff9a9
TT
5514 /*
5515 * Calculate the first inode in the inode table block. Inode
5516 * numbers are one-based. That is, the first inode in a block
5517 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5518 */
5519 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
3f19b2ab 5520 rcu_read_lock();
a26f4992
TT
5521 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5522 if (ino == orig_ino)
5523 continue;
3f19b2ab
DH
5524 __ext4_update_other_inode_time(sb, orig_ino, ino,
5525 (struct ext4_inode *)buf);
a26f4992 5526 }
3f19b2ab 5527 rcu_read_unlock();
a26f4992
TT
5528}
5529
664bd38b
ZY
5530/*
5531 * Post the struct inode info into an on-disk inode location in the
5532 * buffer-cache. This gobbles the caller's reference to the
5533 * buffer_head in the inode location struct.
5534 *
5535 * The caller must have write access to iloc->bh.
5536 */
5537static int ext4_do_update_inode(handle_t *handle,
5538 struct inode *inode,
5539 struct ext4_iloc *iloc)
5540{
5541 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5542 struct ext4_inode_info *ei = EXT4_I(inode);
5543 struct buffer_head *bh = iloc->bh;
5544 struct super_block *sb = inode->i_sb;
5545 int err;
5546 int need_datasync = 0, set_large_file = 0;
5547
5548 spin_lock(&ei->i_raw_lock);
5549
5550 /*
5551 * For fields not tracked in the in-memory inode, initialise them
5552 * to zero for new inodes.
5553 */
5554 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5555 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5556
5557 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5558 need_datasync = 1;
5559 if (ei->i_disksize > 0x7fffffffULL) {
5560 if (!ext4_has_feature_large_file(sb) ||
5561 EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5562 set_large_file = 1;
5563 }
5564
5565 err = ext4_fill_raw_inode(inode, raw_inode);
202ee5df 5566 spin_unlock(&ei->i_raw_lock);
baaae979
ZY
5567 if (err) {
5568 EXT4_ERROR_INODE(inode, "corrupted inode contents");
5569 goto out_brelse;
5570 }
5571
1751e8a6 5572 if (inode->i_sb->s_flags & SB_LAZYTIME)
a26f4992
TT
5573 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5574 bh->b_data);
202ee5df 5575
830156c7 5576 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
7d8bd3c7
SL
5577 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5578 if (err)
baaae979 5579 goto out_error;
19f5fb7a 5580 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
202ee5df 5581 if (set_large_file) {
5d601255 5582 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
188c299e
JK
5583 err = ext4_journal_get_write_access(handle, sb,
5584 EXT4_SB(sb)->s_sbh,
5585 EXT4_JTR_NONE);
202ee5df 5586 if (err)
baaae979 5587 goto out_error;
05c2c00f 5588 lock_buffer(EXT4_SB(sb)->s_sbh);
e2b911c5 5589 ext4_set_feature_large_file(sb);
05c2c00f
JK
5590 ext4_superblock_csum_set(sb);
5591 unlock_buffer(EXT4_SB(sb)->s_sbh);
202ee5df 5592 ext4_handle_sync(handle);
a3f5cf14
JK
5593 err = ext4_handle_dirty_metadata(handle, NULL,
5594 EXT4_SB(sb)->s_sbh);
202ee5df 5595 }
b71fc079 5596 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
baaae979
ZY
5597out_error:
5598 ext4_std_error(inode->i_sb, err);
ac27a0ec 5599out_brelse:
af5bc92d 5600 brelse(bh);
ac27a0ec
DK
5601 return err;
5602}
5603
5604/*
617ba13b 5605 * ext4_write_inode()
ac27a0ec
DK
5606 *
5607 * We are called from a few places:
5608 *
87f7e416 5609 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
ac27a0ec 5610 * Here, there will be no transaction running. We wait for any running
4907cb7b 5611 * transaction to commit.
ac27a0ec 5612 *
87f7e416
TT
5613 * - Within flush work (sys_sync(), kupdate and such).
5614 * We wait on commit, if told to.
ac27a0ec 5615 *
87f7e416
TT
5616 * - Within iput_final() -> write_inode_now()
5617 * We wait on commit, if told to.
ac27a0ec
DK
5618 *
5619 * In all cases it is actually safe for us to return without doing anything,
5620 * because the inode has been copied into a raw inode buffer in
87f7e416
TT
5621 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5622 * writeback.
ac27a0ec
DK
5623 *
5624 * Note that we are absolutely dependent upon all inode dirtiers doing the
5625 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5626 * which we are interested.
5627 *
5628 * It would be a bug for them to not do this. The code:
5629 *
5630 * mark_inode_dirty(inode)
5631 * stuff();
5632 * inode->i_size = expr;
5633 *
87f7e416
TT
5634 * is in error because write_inode() could occur while `stuff()' is running,
5635 * and the new i_size will be lost. Plus the inode will no longer be on the
5636 * superblock's dirty inode list.
ac27a0ec 5637 */
a9185b41 5638int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
ac27a0ec 5639{
91ac6f43
FM
5640 int err;
5641
f1128084 5642 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
ac27a0ec
DK
5643 return 0;
5644
0a1b2f5e
BL
5645 err = ext4_emergency_state(inode->i_sb);
5646 if (unlikely(err))
5647 return err;
18f2c4fc 5648
91ac6f43
FM
5649 if (EXT4_SB(inode->i_sb)->s_journal) {
5650 if (ext4_journal_current_handle()) {
4978c659 5651 ext4_debug("called recursively, non-PF_MEMALLOC!\n");
91ac6f43
FM
5652 dump_stack();
5653 return -EIO;
5654 }
ac27a0ec 5655
10542c22
JK
5656 /*
5657 * No need to force transaction in WB_SYNC_NONE mode. Also
5658 * ext4_sync_fs() will force the commit after everything is
5659 * written.
5660 */
5661 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
91ac6f43
FM
5662 return 0;
5663
aa75f4d3 5664 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
18f2c4fc 5665 EXT4_I(inode)->i_sync_tid);
91ac6f43
FM
5666 } else {
5667 struct ext4_iloc iloc;
ac27a0ec 5668
8016e29f 5669 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
91ac6f43
FM
5670 if (err)
5671 return err;
10542c22
JK
5672 /*
5673 * sync(2) will flush the whole buffer cache. No need to do
5674 * it here separately for each inode.
5675 */
5676 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
830156c7
FM
5677 sync_dirty_buffer(iloc.bh);
5678 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
54d3adbc
TT
5679 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5680 "IO error syncing inode");
830156c7
FM
5681 err = -EIO;
5682 }
fd2dd9fb 5683 brelse(iloc.bh);
91ac6f43
FM
5684 }
5685 return err;
ac27a0ec
DK
5686}
5687
53e87268 5688/*
ccd16945
MWO
5689 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5690 * buffers that are attached to a folio straddling i_size and are undergoing
53e87268
JK
5691 * commit. In that case we have to wait for commit to finish and try again.
5692 */
5693static void ext4_wait_for_tail_page_commit(struct inode *inode)
5694{
53e87268
JK
5695 unsigned offset;
5696 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
dd589b0f 5697 tid_t commit_tid;
53e87268 5698 int ret;
dd589b0f 5699 bool has_transaction;
53e87268 5700
09cbfeaf 5701 offset = inode->i_size & (PAGE_SIZE - 1);
53e87268 5702 /*
ccd16945
MWO
5703 * If the folio is fully truncated, we don't need to wait for any commit
5704 * (and we even should not as __ext4_journalled_invalidate_folio() may
5705 * strip all buffers from the folio but keep the folio dirty which can then
3f079114 5706 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
565333a1 5707 * buffers). Also we don't need to wait for any commit if all buffers in
ccd16945 5708 * the folio remain valid. This is most beneficial for the common case of
565333a1 5709 * blocksize == PAGESIZE.
53e87268 5710 */
565333a1 5711 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
53e87268
JK
5712 return;
5713 while (1) {
ccd16945 5714 struct folio *folio = filemap_lock_folio(inode->i_mapping,
09cbfeaf 5715 inode->i_size >> PAGE_SHIFT);
66dabbb6 5716 if (IS_ERR(folio))
53e87268 5717 return;
ccd16945
MWO
5718 ret = __ext4_journalled_invalidate_folio(folio, offset,
5719 folio_size(folio) - offset);
5720 folio_unlock(folio);
5721 folio_put(folio);
53e87268
JK
5722 if (ret != -EBUSY)
5723 return;
dd589b0f 5724 has_transaction = false;
53e87268 5725 read_lock(&journal->j_state_lock);
dd589b0f 5726 if (journal->j_committing_transaction) {
53e87268 5727 commit_tid = journal->j_committing_transaction->t_tid;
dd589b0f
LHS
5728 has_transaction = true;
5729 }
53e87268 5730 read_unlock(&journal->j_state_lock);
dd589b0f 5731 if (has_transaction)
53e87268
JK
5732 jbd2_log_wait_commit(journal, commit_tid);
5733 }
5734}
5735
ac27a0ec 5736/*
617ba13b 5737 * ext4_setattr()
ac27a0ec
DK
5738 *
5739 * Called from notify_change.
5740 *
5741 * We want to trap VFS attempts to truncate the file as soon as
5742 * possible. In particular, we want to make sure that when the VFS
5743 * shrinks i_size, we put the inode on the orphan list and modify
5744 * i_disksize immediately, so that during the subsequent flushing of
5745 * dirty pages and freeing of disk blocks, we can guarantee that any
5746 * commit will leave the blocks being flushed in an unused state on
5747 * disk. (On recovery, the inode will get truncated and the blocks will
5748 * be freed, so we have a strong guarantee that no future commit will
5749 * leave these blocks visible to the user.)
5750 *
678aaf48
JK
5751 * Another thing we have to assure is that if we are in ordered mode
5752 * and inode is still attached to the committing transaction, we must
5753 * we start writeout of all the dirty pages which are being truncated.
5754 * This way we are sure that all the data written in the previous
5755 * transaction are already on disk (truncate waits for pages under
5756 * writeback).
5757 *
f340b3d9 5758 * Called with inode->i_rwsem down.
ac27a0ec 5759 */
c1632a0f 5760int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
549c7297 5761 struct iattr *attr)
ac27a0ec 5762{
2b0143b5 5763 struct inode *inode = d_inode(dentry);
ac27a0ec 5764 int error, rc = 0;
3d287de3 5765 int orphan = 0;
ac27a0ec 5766 const unsigned int ia_valid = attr->ia_valid;
a642c2c0 5767 bool inc_ivers = true;
ac27a0ec 5768
0a1b2f5e
BL
5769 error = ext4_emergency_state(inode->i_sb);
5770 if (unlikely(error))
5771 return error;
0db1ff22 5772
02b016ca
TT
5773 if (unlikely(IS_IMMUTABLE(inode)))
5774 return -EPERM;
5775
5776 if (unlikely(IS_APPEND(inode) &&
5777 (ia_valid & (ATTR_MODE | ATTR_UID |
5778 ATTR_GID | ATTR_TIMES_SET))))
5779 return -EPERM;
5780
c1632a0f 5781 error = setattr_prepare(idmap, dentry, attr);
ac27a0ec
DK
5782 if (error)
5783 return error;
5784
3ce2b8dd
EB
5785 error = fscrypt_prepare_setattr(dentry, attr);
5786 if (error)
5787 return error;
5788
c93d8f88
EB
5789 error = fsverity_prepare_setattr(dentry, attr);
5790 if (error)
5791 return error;
5792
f861646a 5793 if (is_quota_modification(idmap, inode, attr)) {
a7cdadee
JK
5794 error = dquot_initialize(inode);
5795 if (error)
5796 return error;
5797 }
2729cfdc 5798
0dbe12f2
CB
5799 if (i_uid_needs_update(idmap, attr, inode) ||
5800 i_gid_needs_update(idmap, attr, inode)) {
ac27a0ec
DK
5801 handle_t *handle;
5802
5803 /* (user+group)*(old+new) structure, inode write (sb,
5804 * inode block, ? - but truncate inode update has it) */
9924a92a
TT
5805 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5806 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5807 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
ac27a0ec
DK
5808 if (IS_ERR(handle)) {
5809 error = PTR_ERR(handle);
5810 goto err_out;
5811 }
7a9ca53a
TE
5812
5813 /* dquot_transfer() calls back ext4_get_inode_usage() which
5814 * counts xattr inode references.
5815 */
5816 down_read(&EXT4_I(inode)->xattr_sem);
f861646a 5817 error = dquot_transfer(idmap, inode, attr);
7a9ca53a
TE
5818 up_read(&EXT4_I(inode)->xattr_sem);
5819
ac27a0ec 5820 if (error) {
617ba13b 5821 ext4_journal_stop(handle);
ac27a0ec
DK
5822 return error;
5823 }
5824 /* Update corresponding info in inode so that everything is in
5825 * one transaction */
0dbe12f2
CB
5826 i_uid_update(idmap, attr, inode);
5827 i_gid_update(idmap, attr, inode);
617ba13b
MC
5828 error = ext4_mark_inode_dirty(handle, inode);
5829 ext4_journal_stop(handle);
512c15ef 5830 if (unlikely(error)) {
4209ae12 5831 return error;
512c15ef 5832 }
ac27a0ec
DK
5833 }
5834
3da40c7b 5835 if (attr->ia_valid & ATTR_SIZE) {
5208386c 5836 handle_t *handle;
3da40c7b 5837 loff_t oldsize = inode->i_size;
f4534c9f 5838 loff_t old_disksize;
b9c1c267 5839 int shrink = (attr->ia_size < inode->i_size);
562c72aa 5840
12e9b892 5841 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
e2b46574
ES
5842 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5843
aa75f4d3 5844 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
0c095c7f 5845 return -EFBIG;
aa75f4d3 5846 }
e2b46574 5847 }
aa75f4d3 5848 if (!S_ISREG(inode->i_mode)) {
3da40c7b 5849 return -EINVAL;
aa75f4d3 5850 }
dff6efc3 5851
a642c2c0
JL
5852 if (attr->ia_size == inode->i_size)
5853 inc_ivers = false;
dff6efc3 5854
b9c1c267
JK
5855 if (shrink) {
5856 if (ext4_should_order_data(inode)) {
5857 error = ext4_begin_ordered_truncate(inode,
678aaf48 5858 attr->ia_size);
b9c1c267
JK
5859 if (error)
5860 goto err_out;
5861 }
5862 /*
5863 * Blocks are going to be removed from the inode. Wait
5864 * for dio in flight.
5865 */
5866 inode_dio_wait(inode);
5867 }
5868
d4f5258e 5869 filemap_invalidate_lock(inode->i_mapping);
b9c1c267
JK
5870
5871 rc = ext4_break_layouts(inode);
5872 if (rc) {
d4f5258e 5873 filemap_invalidate_unlock(inode->i_mapping);
aa75f4d3 5874 goto err_out;
3da40c7b 5875 }
b9c1c267 5876
3da40c7b 5877 if (attr->ia_size != inode->i_size) {
c7fc0366
BF
5878 /* attach jbd2 jinode for EOF folio tail zeroing */
5879 if (attr->ia_size & (inode->i_sb->s_blocksize - 1) ||
5880 oldsize & (inode->i_sb->s_blocksize - 1)) {
5881 error = ext4_inode_attach_jinode(inode);
5882 if (error)
7e91ae31 5883 goto out_mmap_sem;
c7fc0366
BF
5884 }
5885
5208386c
JK
5886 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5887 if (IS_ERR(handle)) {
5888 error = PTR_ERR(handle);
b9c1c267 5889 goto out_mmap_sem;
5208386c 5890 }
3da40c7b 5891 if (ext4_handle_valid(handle) && shrink) {
5208386c
JK
5892 error = ext4_orphan_add(handle, inode);
5893 orphan = 1;
5894 }
911af577 5895 /*
c7fc0366
BF
5896 * Update c/mtime and tail zero the EOF folio on
5897 * truncate up. ext4_truncate() handles the shrink case
5898 * below.
911af577 5899 */
c7fc0366 5900 if (!shrink) {
b898ab23
JL
5901 inode_set_mtime_to_ts(inode,
5902 inode_set_ctime_current(inode));
c7fc0366
BF
5903 if (oldsize & (inode->i_sb->s_blocksize - 1))
5904 ext4_block_truncate_page(handle,
5905 inode->i_mapping, oldsize);
5906 }
aa75f4d3
HS
5907
5908 if (shrink)
a80f7fcf 5909 ext4_fc_track_range(handle, inode,
aa75f4d3
HS
5910 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5911 inode->i_sb->s_blocksize_bits,
9725958b 5912 EXT_MAX_BLOCKS - 1);
aa75f4d3
HS
5913 else
5914 ext4_fc_track_range(
a80f7fcf 5915 handle, inode,
aa75f4d3
HS
5916 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5917 inode->i_sb->s_blocksize_bits,
5918 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5919 inode->i_sb->s_blocksize_bits);
5920
90e775b7 5921 down_write(&EXT4_I(inode)->i_data_sem);
f4534c9f 5922 old_disksize = EXT4_I(inode)->i_disksize;
5208386c 5923 EXT4_I(inode)->i_disksize = attr->ia_size;
0b64fd74 5924
90e775b7
JK
5925 /*
5926 * We have to update i_size under i_data_sem together
5927 * with i_disksize to avoid races with writeback code
5928 * running ext4_wb_update_i_disksize().
5929 */
5930 if (!error)
5931 i_size_write(inode, attr->ia_size);
f4534c9f
YB
5932 else
5933 EXT4_I(inode)->i_disksize = old_disksize;
90e775b7 5934 up_write(&EXT4_I(inode)->i_data_sem);
0b64fd74
HS
5935 rc = ext4_mark_inode_dirty(handle, inode);
5936 if (!error)
5937 error = rc;
5208386c 5938 ext4_journal_stop(handle);
b9c1c267
JK
5939 if (error)
5940 goto out_mmap_sem;
5941 if (!shrink) {
5942 pagecache_isize_extended(inode, oldsize,
5943 inode->i_size);
5944 } else if (ext4_should_journal_data(inode)) {
5945 ext4_wait_for_tail_page_commit(inode);
678aaf48 5946 }
d6320cbf 5947 }
430657b6 5948
5208386c
JK
5949 /*
5950 * Truncate pagecache after we've waited for commit
5951 * in data=journal mode to make pages freeable.
5952 */
923ae0ff 5953 truncate_pagecache(inode, inode->i_size);
b9c1c267
JK
5954 /*
5955 * Call ext4_truncate() even if i_size didn't change to
5956 * truncate possible preallocated blocks.
5957 */
5958 if (attr->ia_size <= oldsize) {
2c98eb5e
TT
5959 rc = ext4_truncate(inode);
5960 if (rc)
5961 error = rc;
5962 }
b9c1c267 5963out_mmap_sem:
d4f5258e 5964 filemap_invalidate_unlock(inode->i_mapping);
072bd7ea 5965 }
ac27a0ec 5966
2c98eb5e 5967 if (!error) {
a642c2c0
JL
5968 if (inc_ivers)
5969 inode_inc_iversion(inode);
c1632a0f 5970 setattr_copy(idmap, inode, attr);
1025774c
CH
5971 mark_inode_dirty(inode);
5972 }
5973
5974 /*
5975 * If the call to ext4_truncate failed to get a transaction handle at
5976 * all, we need to clean up the in-core orphan list manually.
5977 */
3d287de3 5978 if (orphan && inode->i_nlink)
617ba13b 5979 ext4_orphan_del(NULL, inode);
ac27a0ec 5980
2c98eb5e 5981 if (!error && (ia_valid & ATTR_MODE))
13e83a49 5982 rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
ac27a0ec
DK
5983
5984err_out:
aa75f4d3
HS
5985 if (error)
5986 ext4_std_error(inode->i_sb, error);
ac27a0ec
DK
5987 if (!error)
5988 error = rc;
5989 return error;
5990}
5991
8434ef1d
EB
5992u32 ext4_dio_alignment(struct inode *inode)
5993{
5994 if (fsverity_active(inode))
5995 return 0;
5996 if (ext4_should_journal_data(inode))
5997 return 0;
5998 if (ext4_has_inline_data(inode))
5999 return 0;
6000 if (IS_ENCRYPTED(inode)) {
6001 if (!fscrypt_dio_supported(inode))
6002 return 0;
6003 return i_blocksize(inode);
6004 }
6005 return 1; /* use the iomap defaults */
6006}
6007
b74d24f7 6008int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
549c7297 6009 struct kstat *stat, u32 request_mask, unsigned int query_flags)
3e3398a0 6010{
99652ea5
DH
6011 struct inode *inode = d_inode(path->dentry);
6012 struct ext4_inode *raw_inode;
6013 struct ext4_inode_info *ei = EXT4_I(inode);
6014 unsigned int flags;
6015
d4c5e960
TT
6016 if ((request_mask & STATX_BTIME) &&
6017 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
99652ea5
DH
6018 stat->result_mask |= STATX_BTIME;
6019 stat->btime.tv_sec = ei->i_crtime.tv_sec;
6020 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
6021 }
6022
8434ef1d
EB
6023 /*
6024 * Return the DIO alignment restrictions if requested. We only return
6025 * this information when requested, since on encrypted files it might
6026 * take a fair bit of work to get if the file wasn't opened recently.
6027 */
6028 if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
6029 u32 dio_align = ext4_dio_alignment(inode);
6030
6031 stat->result_mask |= STATX_DIOALIGN;
6032 if (dio_align == 1) {
6033 struct block_device *bdev = inode->i_sb->s_bdev;
6034
6035 /* iomap defaults */
6036 stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
6037 stat->dio_offset_align = bdev_logical_block_size(bdev);
6038 } else {
6039 stat->dio_mem_align = dio_align;
6040 stat->dio_offset_align = dio_align;
6041 }
6042 }
6043
6dfc1c1d
RHI
6044 if ((request_mask & STATX_WRITE_ATOMIC) && S_ISREG(inode->i_mode)) {
6045 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6046 unsigned int awu_min = 0, awu_max = 0;
6047
6048 if (ext4_inode_can_atomic_write(inode)) {
6049 awu_min = sbi->s_awu_min;
6050 awu_max = sbi->s_awu_max;
6051 }
6052
5d894321 6053 generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 0);
6dfc1c1d
RHI
6054 }
6055
99652ea5
DH
6056 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
6057 if (flags & EXT4_APPEND_FL)
6058 stat->attributes |= STATX_ATTR_APPEND;
6059 if (flags & EXT4_COMPR_FL)
6060 stat->attributes |= STATX_ATTR_COMPRESSED;
6061 if (flags & EXT4_ENCRYPT_FL)
6062 stat->attributes |= STATX_ATTR_ENCRYPTED;
6063 if (flags & EXT4_IMMUTABLE_FL)
6064 stat->attributes |= STATX_ATTR_IMMUTABLE;
6065 if (flags & EXT4_NODUMP_FL)
6066 stat->attributes |= STATX_ATTR_NODUMP;
1f607195
EB
6067 if (flags & EXT4_VERITY_FL)
6068 stat->attributes |= STATX_ATTR_VERITY;
3e3398a0 6069
3209f68b
DH
6070 stat->attributes_mask |= (STATX_ATTR_APPEND |
6071 STATX_ATTR_COMPRESSED |
6072 STATX_ATTR_ENCRYPTED |
6073 STATX_ATTR_IMMUTABLE |
1f607195
EB
6074 STATX_ATTR_NODUMP |
6075 STATX_ATTR_VERITY);
3209f68b 6076
0d72b928 6077 generic_fillattr(idmap, request_mask, inode, stat);
99652ea5
DH
6078 return 0;
6079}
6080
b74d24f7 6081int ext4_file_getattr(struct mnt_idmap *idmap,
549c7297 6082 const struct path *path, struct kstat *stat,
99652ea5
DH
6083 u32 request_mask, unsigned int query_flags)
6084{
6085 struct inode *inode = d_inode(path->dentry);
6086 u64 delalloc_blocks;
6087
b74d24f7 6088 ext4_getattr(idmap, path, stat, request_mask, query_flags);
3e3398a0 6089
9206c561
AD
6090 /*
6091 * If there is inline data in the inode, the inode will normally not
6092 * have data blocks allocated (it may have an external xattr block).
6093 * Report at least one sector for such files, so tools like tar, rsync,
d67d64f4 6094 * others don't incorrectly think the file is completely sparse.
9206c561
AD
6095 */
6096 if (unlikely(ext4_has_inline_data(inode)))
6097 stat->blocks += (stat->size + 511) >> 9;
6098
3e3398a0
MC
6099 /*
6100 * We can't update i_blocks if the block allocation is delayed
6101 * otherwise in the case of system crash before the real block
6102 * allocation is done, we will have i_blocks inconsistent with
6103 * on-disk file blocks.
6104 * We always keep i_blocks updated together with real
6105 * allocation. But to not confuse with user, stat
6106 * will return the blocks that include the delayed allocation
6107 * blocks for this file.
6108 */
96607551 6109 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
9206c561
AD
6110 EXT4_I(inode)->i_reserved_data_blocks);
6111 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
3e3398a0
MC
6112 return 0;
6113}
ac27a0ec 6114
fffb2739
JK
6115static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
6116 int pextents)
a02908f1 6117{
12e9b892 6118 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
fffb2739
JK
6119 return ext4_ind_trans_blocks(inode, lblocks);
6120 return ext4_ext_index_trans_blocks(inode, pextents);
a02908f1 6121}
ac51d837 6122
ac27a0ec 6123/*
a02908f1
MC
6124 * Account for index blocks, block groups bitmaps and block group
6125 * descriptor blocks if modify datablocks and index blocks
6126 * worse case, the indexs blocks spread over different block groups
ac27a0ec 6127 *
a02908f1 6128 * If datablocks are discontiguous, they are possible to spread over
4907cb7b 6129 * different block groups too. If they are contiguous, with flexbg,
a02908f1 6130 * they could still across block group boundary.
ac27a0ec 6131 *
a02908f1
MC
6132 * Also account for superblock, inode, quota and xattr blocks
6133 */
255e7bc2 6134int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents)
a02908f1 6135{
8df9675f
TT
6136 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
6137 int gdpblocks;
a02908f1 6138 int idxblocks;
7fc51f92 6139 int ret;
a02908f1
MC
6140
6141 /*
0e32d861
ZY
6142 * How many index and lead blocks need to touch to map @lblocks
6143 * logical blocks to @pextents physical extents?
a02908f1 6144 */
fffb2739 6145 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
a02908f1 6146
a02908f1
MC
6147 /*
6148 * Now let's see how many group bitmaps and group descriptors need
6149 * to account
6150 */
0e32d861 6151 groups = idxblocks;
a02908f1 6152 gdpblocks = groups;
8df9675f
TT
6153 if (groups > ngroups)
6154 groups = ngroups;
a02908f1
MC
6155 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
6156 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
6157
6158 /* bitmaps and block group descriptor blocks */
0e32d861 6159 ret = idxblocks + groups + gdpblocks;
a02908f1
MC
6160
6161 /* Blocks for super block, inode, quota and xattr blocks */
6162 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
6163
6164 return ret;
6165}
6166
6167/*
25985edc 6168 * Calculate the total number of credits to reserve to fit
f3bd1f3f
MC
6169 * the modification of a single pages into a single transaction,
6170 * which may include multiple chunks of block allocations.
ac27a0ec 6171 *
525f4ed8 6172 * This could be called via ext4_write_begin()
ac27a0ec 6173 *
525f4ed8 6174 * We need to consider the worse case, when
a02908f1 6175 * one new block per extent.
ac27a0ec 6176 */
a86c6181 6177int ext4_writepage_trans_blocks(struct inode *inode)
ac27a0ec 6178{
d6bf2947 6179 int bpp = ext4_journal_blocks_per_folio(inode);
ac27a0ec
DK
6180 int ret;
6181
fffb2739 6182 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
a86c6181 6183
a02908f1 6184 /* Account for data blocks for journalled mode */
617ba13b 6185 if (ext4_should_journal_data(inode))
a02908f1 6186 ret += bpp;
ac27a0ec
DK
6187 return ret;
6188}
f3bd1f3f
MC
6189
6190/*
6191 * Calculate the journal credits for a chunk of data modification.
6192 *
6193 * This is called from DIO, fallocate or whoever calling
79e83036 6194 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
f3bd1f3f
MC
6195 *
6196 * journal buffers for data blocks are not included here, as DIO
6197 * and fallocate do no need to journal data buffers.
6198 */
6199int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
6200{
6201 return ext4_meta_trans_blocks(inode, nrblocks, 1);
6202}
6203
ac27a0ec 6204/*
617ba13b 6205 * The caller must have previously called ext4_reserve_inode_write().
ac27a0ec
DK
6206 * Give this, we know that the caller already has write access to iloc->bh.
6207 */
617ba13b 6208int ext4_mark_iloc_dirty(handle_t *handle,
de9a55b8 6209 struct inode *inode, struct ext4_iloc *iloc)
ac27a0ec
DK
6210{
6211 int err = 0;
6212
0a1b2f5e
BL
6213 err = ext4_emergency_state(inode->i_sb);
6214 if (unlikely(err)) {
a6758309 6215 put_bh(iloc->bh);
0a1b2f5e 6216 return err;
a6758309 6217 }
a80f7fcf 6218 ext4_fc_track_inode(handle, inode);
aa75f4d3 6219
ac27a0ec
DK
6220 /* the do_update_inode consumes one bh->b_count */
6221 get_bh(iloc->bh);
6222
dab291af 6223 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
830156c7 6224 err = ext4_do_update_inode(handle, inode, iloc);
ac27a0ec
DK
6225 put_bh(iloc->bh);
6226 return err;
6227}
6228
6229/*
6230 * On success, We end up with an outstanding reference count against
6231 * iloc->bh. This _must_ be cleaned up later.
6232 */
6233
6234int
617ba13b
MC
6235ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
6236 struct ext4_iloc *iloc)
ac27a0ec 6237{
0390131b
FM
6238 int err;
6239
0a1b2f5e
BL
6240 err = ext4_emergency_state(inode->i_sb);
6241 if (unlikely(err))
6242 return err;
0db1ff22 6243
0390131b
FM
6244 err = ext4_get_inode_loc(inode, iloc);
6245 if (!err) {
6246 BUFFER_TRACE(iloc->bh, "get_write_access");
188c299e
JK
6247 err = ext4_journal_get_write_access(handle, inode->i_sb,
6248 iloc->bh, EXT4_JTR_NONE);
0390131b
FM
6249 if (err) {
6250 brelse(iloc->bh);
6251 iloc->bh = NULL;
ac27a0ec 6252 }
4d326646 6253 ext4_fc_track_inode(handle, inode);
ac27a0ec 6254 }
617ba13b 6255 ext4_std_error(inode->i_sb, err);
ac27a0ec
DK
6256 return err;
6257}
6258
c03b45b8
MX
6259static int __ext4_expand_extra_isize(struct inode *inode,
6260 unsigned int new_extra_isize,
6261 struct ext4_iloc *iloc,
6262 handle_t *handle, int *no_expand)
6263{
6264 struct ext4_inode *raw_inode;
6265 struct ext4_xattr_ibody_header *header;
4ea99936
TT
6266 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
6267 struct ext4_inode_info *ei = EXT4_I(inode);
c03b45b8
MX
6268 int error;
6269
4ea99936
TT
6270 /* this was checked at iget time, but double check for good measure */
6271 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
6272 (ei->i_extra_isize & 3)) {
6273 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
6274 ei->i_extra_isize,
6275 EXT4_INODE_SIZE(inode->i_sb));
6276 return -EFSCORRUPTED;
6277 }
6278 if ((new_extra_isize < ei->i_extra_isize) ||
6279 (new_extra_isize < 4) ||
6280 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
6281 return -EINVAL; /* Should never happen */
6282
c03b45b8
MX
6283 raw_inode = ext4_raw_inode(iloc);
6284
6285 header = IHDR(inode, raw_inode);
6286
6287 /* No extended attributes present */
6288 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
6289 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
6290 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
6291 EXT4_I(inode)->i_extra_isize, 0,
6292 new_extra_isize - EXT4_I(inode)->i_extra_isize);
6293 EXT4_I(inode)->i_extra_isize = new_extra_isize;
6294 return 0;
6295 }
6296
8994d113
JK
6297 /*
6298 * We may need to allocate external xattr block so we need quotas
6299 * initialized. Here we can be called with various locks held so we
6300 * cannot affort to initialize quotas ourselves. So just bail.
6301 */
6302 if (dquot_initialize_needed(inode))
6303 return -EAGAIN;
6304
c03b45b8
MX
6305 /* try to expand with EAs present */
6306 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
6307 raw_inode, handle);
6308 if (error) {
6309 /*
6310 * Inode size expansion failed; don't try again
6311 */
6312 *no_expand = 1;
6313 }
6314
6315 return error;
6316}
6317
6dd4ee7c
KS
6318/*
6319 * Expand an inode by new_extra_isize bytes.
6320 * Returns 0 on success or negative error number on failure.
6321 */
cf0a5e81
MX
6322static int ext4_try_to_expand_extra_isize(struct inode *inode,
6323 unsigned int new_extra_isize,
6324 struct ext4_iloc iloc,
6325 handle_t *handle)
6dd4ee7c 6326{
3b10fdc6
MX
6327 int no_expand;
6328 int error;
6dd4ee7c 6329
cf0a5e81
MX
6330 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
6331 return -EOVERFLOW;
6332
6333 /*
6334 * In nojournal mode, we can immediately attempt to expand
6335 * the inode. When journaled, we first need to obtain extra
6336 * buffer credits since we may write into the EA block
6337 * with this same handle. If journal_extend fails, then it will
6338 * only result in a minor loss of functionality for that inode.
6339 * If this is felt to be critical, then e2fsck should be run to
6340 * force a large enough s_min_extra_isize.
6341 */
6cb367c2 6342 if (ext4_journal_extend(handle,
83448bdf 6343 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
cf0a5e81 6344 return -ENOSPC;
6dd4ee7c 6345
3b10fdc6 6346 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
cf0a5e81 6347 return -EBUSY;
3b10fdc6 6348
c03b45b8
MX
6349 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
6350 handle, &no_expand);
6351 ext4_write_unlock_xattr(inode, &no_expand);
6dd4ee7c 6352
c03b45b8
MX
6353 return error;
6354}
6dd4ee7c 6355
c03b45b8
MX
6356int ext4_expand_extra_isize(struct inode *inode,
6357 unsigned int new_extra_isize,
6358 struct ext4_iloc *iloc)
6359{
6360 handle_t *handle;
6361 int no_expand;
6362 int error, rc;
6363
6364 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
6365 brelse(iloc->bh);
6366 return -EOVERFLOW;
6dd4ee7c
KS
6367 }
6368
c03b45b8
MX
6369 handle = ext4_journal_start(inode, EXT4_HT_INODE,
6370 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
6371 if (IS_ERR(handle)) {
6372 error = PTR_ERR(handle);
6373 brelse(iloc->bh);
6374 return error;
6375 }
6376
6377 ext4_write_lock_xattr(inode, &no_expand);
6378
ddccb6db 6379 BUFFER_TRACE(iloc->bh, "get_write_access");
188c299e
JK
6380 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
6381 EXT4_JTR_NONE);
3b10fdc6 6382 if (error) {
c03b45b8 6383 brelse(iloc->bh);
7f420d64 6384 goto out_unlock;
3b10fdc6 6385 }
cf0a5e81 6386
c03b45b8
MX
6387 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
6388 handle, &no_expand);
6389
6390 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
6391 if (!error)
6392 error = rc;
6393
7f420d64 6394out_unlock:
c03b45b8 6395 ext4_write_unlock_xattr(inode, &no_expand);
c03b45b8 6396 ext4_journal_stop(handle);
3b10fdc6 6397 return error;
6dd4ee7c
KS
6398}
6399
ac27a0ec
DK
6400/*
6401 * What we do here is to mark the in-core inode as clean with respect to inode
6402 * dirtiness (it may still be data-dirty).
6403 * This means that the in-core inode may be reaped by prune_icache
6404 * without having to perform any I/O. This is a very good thing,
6405 * because *any* task may call prune_icache - even ones which
6406 * have a transaction open against a different journal.
6407 *
6408 * Is this cheating? Not really. Sure, we haven't written the
6409 * inode out, but prune_icache isn't a user-visible syncing function.
6410 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6411 * we start and wait on commits.
ac27a0ec 6412 */
4209ae12
HS
6413int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
6414 const char *func, unsigned int line)
ac27a0ec 6415{
617ba13b 6416 struct ext4_iloc iloc;
6dd4ee7c 6417 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
cf0a5e81 6418 int err;
ac27a0ec
DK
6419
6420 might_sleep();
7ff9c073 6421 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
617ba13b 6422 err = ext4_reserve_inode_write(handle, inode, &iloc);
5e1021f2 6423 if (err)
4209ae12 6424 goto out;
cf0a5e81
MX
6425
6426 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6427 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6428 iloc, handle);
6429
4209ae12
HS
6430 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
6431out:
6432 if (unlikely(err))
6433 ext4_error_inode_err(inode, func, line, 0, err,
6434 "mark_inode_dirty error");
6435 return err;
ac27a0ec
DK
6436}
6437
6438/*
617ba13b 6439 * ext4_dirty_inode() is called from __mark_inode_dirty()
ac27a0ec
DK
6440 *
6441 * We're really interested in the case where a file is being extended.
6442 * i_size has been changed by generic_commit_write() and we thus need
6443 * to include the updated inode in the current transaction.
6444 *
5dd4056d 6445 * Also, dquot_alloc_block() will always dirty the inode when blocks
ac27a0ec
DK
6446 * are allocated to the file.
6447 *
6448 * If the inode is marked synchronous, we don't honour that here - doing
6449 * so would cause a commit on atime updates, which we don't bother doing.
6450 * We handle synchronous inodes at the highest possible level.
6451 */
aa385729 6452void ext4_dirty_inode(struct inode *inode, int flags)
ac27a0ec 6453{
ac27a0ec
DK
6454 handle_t *handle;
6455
9924a92a 6456 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
ac27a0ec 6457 if (IS_ERR(handle))
e2728c56 6458 return;
f3dc272f 6459 ext4_mark_inode_dirty(handle, inode);
617ba13b 6460 ext4_journal_stop(handle);
ac27a0ec
DK
6461}
6462
617ba13b 6463int ext4_change_inode_journal_flag(struct inode *inode, int val)
ac27a0ec
DK
6464{
6465 journal_t *journal;
6466 handle_t *handle;
6467 int err;
00d873c1 6468 int alloc_ctx;
ac27a0ec
DK
6469
6470 /*
6471 * We have to be very careful here: changing a data block's
6472 * journaling status dynamically is dangerous. If we write a
6473 * data block to the journal, change the status and then delete
6474 * that block, we risk forgetting to revoke the old log record
6475 * from the journal and so a subsequent replay can corrupt data.
6476 * So, first we make sure that the journal is empty and that
6477 * nobody is changing anything.
6478 */
6479
617ba13b 6480 journal = EXT4_JOURNAL(inode);
0390131b
FM
6481 if (!journal)
6482 return 0;
d699594d 6483 if (is_journal_aborted(journal))
ac27a0ec
DK
6484 return -EROFS;
6485
17335dcc 6486 /* Wait for all existing dio workers */
17335dcc
DM
6487 inode_dio_wait(inode);
6488
4c546592
DJ
6489 /*
6490 * Before flushing the journal and switching inode's aops, we have
6491 * to flush all dirty data the inode has. There can be outstanding
6492 * delayed allocations, there can be unwritten extents created by
6493 * fallocate or buffered writes in dioread_nolock mode covered by
6494 * dirty data which can be converted only after flushing the dirty
6495 * data (and journalled aops don't know how to handle these cases).
6496 */
6497 if (val) {
d4f5258e 6498 filemap_invalidate_lock(inode->i_mapping);
4c546592
DJ
6499 err = filemap_write_and_wait(inode->i_mapping);
6500 if (err < 0) {
d4f5258e 6501 filemap_invalidate_unlock(inode->i_mapping);
4c546592
DJ
6502 return err;
6503 }
6504 }
6505
00d873c1 6506 alloc_ctx = ext4_writepages_down_write(inode->i_sb);
dab291af 6507 jbd2_journal_lock_updates(journal);
ac27a0ec
DK
6508
6509 /*
6510 * OK, there are no updates running now, and all cached data is
6511 * synced to disk. We are now in a completely consistent state
6512 * which doesn't have anything in the journal, and we know that
6513 * no filesystem updates are running, so it is safe to modify
6514 * the inode's in-core data-journaling state flag now.
6515 */
6516
6517 if (val)
12e9b892 6518 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5872ddaa 6519 else {
01d5d965 6520 err = jbd2_journal_flush(journal, 0);
4f879ca6
JK
6521 if (err < 0) {
6522 jbd2_journal_unlock_updates(journal);
00d873c1 6523 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
4f879ca6
JK
6524 return err;
6525 }
12e9b892 6526 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5872ddaa 6527 }
617ba13b 6528 ext4_set_aops(inode);
ac27a0ec 6529
dab291af 6530 jbd2_journal_unlock_updates(journal);
00d873c1 6531 ext4_writepages_up_write(inode->i_sb, alloc_ctx);
c8585c6f 6532
4c546592 6533 if (val)
d4f5258e 6534 filemap_invalidate_unlock(inode->i_mapping);
ac27a0ec
DK
6535
6536 /* Finally we can mark the inode as dirty. */
6537
9924a92a 6538 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
ac27a0ec
DK
6539 if (IS_ERR(handle))
6540 return PTR_ERR(handle);
6541
aa75f4d3 6542 ext4_fc_mark_ineligible(inode->i_sb,
e85c81ba 6543 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
617ba13b 6544 err = ext4_mark_inode_dirty(handle, inode);
0390131b 6545 ext4_handle_sync(handle);
617ba13b
MC
6546 ext4_journal_stop(handle);
6547 ext4_std_error(inode->i_sb, err);
ac27a0ec
DK
6548
6549 return err;
6550}
2e9ee850 6551
188c299e
JK
6552static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6553 struct buffer_head *bh)
2e9ee850
AK
6554{
6555 return !buffer_mapped(bh);
6556}
6557
401b25aa 6558vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
2e9ee850 6559{
11bac800 6560 struct vm_area_struct *vma = vmf->vma;
9ea0e45b 6561 struct folio *folio = page_folio(vmf->page);
2e9ee850
AK
6562 loff_t size;
6563 unsigned long len;
401b25aa
SJ
6564 int err;
6565 vm_fault_t ret;
2e9ee850 6566 struct file *file = vma->vm_file;
496ad9aa 6567 struct inode *inode = file_inode(file);
2e9ee850 6568 struct address_space *mapping = inode->i_mapping;
9ea7df53
JK
6569 handle_t *handle;
6570 get_block_t *get_block;
6571 int retries = 0;
2e9ee850 6572
02b016ca
TT
6573 if (unlikely(IS_IMMUTABLE(inode)))
6574 return VM_FAULT_SIGBUS;
6575
8e8ad8a5 6576 sb_start_pagefault(inode->i_sb);
041bbb6d 6577 file_update_time(vma->vm_file);
ea3d7209 6578
d4f5258e 6579 filemap_invalidate_lock_shared(mapping);
7b4cc978 6580
401b25aa
SJ
6581 err = ext4_convert_inline_data(inode);
6582 if (err)
7b4cc978
EB
6583 goto out_ret;
6584
64a9f144
MFO
6585 /*
6586 * On data journalling we skip straight to the transaction handle:
6587 * there's no delalloc; page truncated will be checked later; the
6588 * early return w/ all buffers mapped (calculates size/len) can't
6589 * be used; and there's no dioread_nolock, so only ext4_get_block.
6590 */
6591 if (ext4_should_journal_data(inode))
6592 goto retry_alloc;
6593
9ea7df53
JK
6594 /* Delalloc case is easy... */
6595 if (test_opt(inode->i_sb, DELALLOC) &&
9ea7df53
JK
6596 !ext4_nonda_switch(inode->i_sb)) {
6597 do {
401b25aa 6598 err = block_page_mkwrite(vma, vmf,
9ea7df53 6599 ext4_da_get_block_prep);
401b25aa 6600 } while (err == -ENOSPC &&
9ea7df53
JK
6601 ext4_should_retry_alloc(inode->i_sb, &retries));
6602 goto out_ret;
2e9ee850 6603 }
0e499890 6604
9ea0e45b 6605 folio_lock(folio);
9ea7df53
JK
6606 size = i_size_read(inode);
6607 /* Page got truncated from under us? */
9ea0e45b
MW
6608 if (folio->mapping != mapping || folio_pos(folio) > size) {
6609 folio_unlock(folio);
9ea7df53
JK
6610 ret = VM_FAULT_NOPAGE;
6611 goto out;
0e499890 6612 }
2e9ee850 6613
9ea0e45b
MW
6614 len = folio_size(folio);
6615 if (folio_pos(folio) + len > size)
6616 len = size - folio_pos(folio);
a827eaff 6617 /*
9ea7df53
JK
6618 * Return if we have all the buffers mapped. This avoids the need to do
6619 * journal_start/journal_stop which can block and take a long time
64a9f144
MFO
6620 *
6621 * This cannot be done for data journalling, as we have to add the
6622 * inode to the transaction's list to writeprotect pages on commit.
a827eaff 6623 */
9ea0e45b
MW
6624 if (folio_buffers(folio)) {
6625 if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
f19d5870
TM
6626 0, len, NULL,
6627 ext4_bh_unmapped)) {
9ea7df53 6628 /* Wait so that we don't change page under IO */
9ea0e45b 6629 folio_wait_stable(folio);
9ea7df53
JK
6630 ret = VM_FAULT_LOCKED;
6631 goto out;
a827eaff 6632 }
2e9ee850 6633 }
9ea0e45b 6634 folio_unlock(folio);
9ea7df53
JK
6635 /* OK, we need to fill the hole... */
6636 if (ext4_should_dioread_nolock(inode))
705965bd 6637 get_block = ext4_get_block_unwritten;
9ea7df53
JK
6638 else
6639 get_block = ext4_get_block;
6640retry_alloc:
9924a92a
TT
6641 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6642 ext4_writepage_trans_blocks(inode));
9ea7df53 6643 if (IS_ERR(handle)) {
c2ec175c 6644 ret = VM_FAULT_SIGBUS;
9ea7df53
JK
6645 goto out;
6646 }
64a9f144
MFO
6647 /*
6648 * Data journalling can't use block_page_mkwrite() because it
6649 * will set_buffer_dirty() before do_journal_get_write_access()
6650 * thus might hit warning messages for dirty metadata buffers.
6651 */
6652 if (!ext4_should_journal_data(inode)) {
6653 err = block_page_mkwrite(vma, vmf, get_block);
6654 } else {
9ea0e45b 6655 folio_lock(folio);
64a9f144
MFO
6656 size = i_size_read(inode);
6657 /* Page got truncated from under us? */
9ea0e45b 6658 if (folio->mapping != mapping || folio_pos(folio) > size) {
64a9f144 6659 ret = VM_FAULT_NOPAGE;
afb585a9 6660 goto out_error;
9ea7df53 6661 }
64a9f144 6662
9ea0e45b
MW
6663 len = folio_size(folio);
6664 if (folio_pos(folio) + len > size)
6665 len = size - folio_pos(folio);
64a9f144 6666
cb3de5fc
SZ
6667 err = ext4_block_write_begin(handle, folio, 0, len,
6668 ext4_get_block);
64a9f144 6669 if (!err) {
afb585a9 6670 ret = VM_FAULT_SIGBUS;
80be8c5c 6671 if (ext4_journal_folio_buffers(handle, folio, len))
afb585a9 6672 goto out_error;
64a9f144 6673 } else {
9ea0e45b 6674 folio_unlock(folio);
64a9f144 6675 }
9ea7df53
JK
6676 }
6677 ext4_journal_stop(handle);
401b25aa 6678 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
9ea7df53
JK
6679 goto retry_alloc;
6680out_ret:
2ba39cc4 6681 ret = vmf_fs_error(err);
9ea7df53 6682out:
d4f5258e 6683 filemap_invalidate_unlock_shared(mapping);
8e8ad8a5 6684 sb_end_pagefault(inode->i_sb);
2e9ee850 6685 return ret;
afb585a9 6686out_error:
9ea0e45b 6687 folio_unlock(folio);
afb585a9
MFO
6688 ext4_journal_stop(handle);
6689 goto out;
2e9ee850 6690}