blob: d59474a541897af1b4a6185c34c3cc686e7d3a8c [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// SPDX-License-Identifier: GPL-2.0
2/*
3 * linux/fs/ext4/inode.c
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 *
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
18 *
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20 */
21
22#include <linux/fs.h>
23#include <linux/time.h>
24#include <linux/highuid.h>
25#include <linux/pagemap.h>
26#include <linux/dax.h>
27#include <linux/quotaops.h>
28#include <linux/string.h>
29#include <linux/buffer_head.h>
30#include <linux/writeback.h>
31#include <linux/pagevec.h>
32#include <linux/mpage.h>
33#include <linux/namei.h>
34#include <linux/uio.h>
35#include <linux/bio.h>
36#include <linux/workqueue.h>
37#include <linux/kernel.h>
38#include <linux/printk.h>
39#include <linux/slab.h>
40#include <linux/bitops.h>
41#include <linux/iomap.h>
42#include <linux/iversion.h>
43
44#include "ext4_jbd2.h"
45#include "xattr.h"
46#include "acl.h"
47#include "truncate.h"
48
49#include <trace/events/ext4.h>
50
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000051static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
53{
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
55 __u32 csum;
56 __u16 dummy_csum = 0;
57 int offset = offsetof(struct ext4_inode, i_checksum_lo);
58 unsigned int csum_size = sizeof(dummy_csum);
59
60 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
61 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
62 offset += csum_size;
63 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
64 EXT4_GOOD_OLD_INODE_SIZE - offset);
65
66 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
67 offset = offsetof(struct ext4_inode, i_checksum_hi);
68 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
69 EXT4_GOOD_OLD_INODE_SIZE,
70 offset - EXT4_GOOD_OLD_INODE_SIZE);
71 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
72 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
73 csum_size);
74 offset += csum_size;
75 }
76 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
77 EXT4_INODE_SIZE(inode->i_sb) - offset);
78 }
79
80 return csum;
81}
82
83static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84 struct ext4_inode_info *ei)
85{
86 __u32 provided, calculated;
87
88 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89 cpu_to_le32(EXT4_OS_LINUX) ||
90 !ext4_has_metadata_csum(inode->i_sb))
91 return 1;
92
93 provided = le16_to_cpu(raw->i_checksum_lo);
94 calculated = ext4_inode_csum(inode, raw, ei);
95 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
98 else
99 calculated &= 0xFFFF;
100
101 return provided == calculated;
102}
103
Olivier Deprez157378f2022-04-04 15:47:50 +0200104void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105 struct ext4_inode_info *ei)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000106{
107 __u32 csum;
108
109 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110 cpu_to_le32(EXT4_OS_LINUX) ||
111 !ext4_has_metadata_csum(inode->i_sb))
112 return;
113
114 csum = ext4_inode_csum(inode, raw, ei);
115 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
119}
120
121static inline int ext4_begin_ordered_truncate(struct inode *inode,
122 loff_t new_size)
123{
124 trace_ext4_begin_ordered_truncate(inode, new_size);
125 /*
126 * If jinode is zero, then we never opened the file for
127 * writing, so there's no need to call
128 * jbd2_journal_begin_ordered_truncate() since there's no
129 * outstanding writes we need to flush.
130 */
131 if (!EXT4_I(inode)->jinode)
132 return 0;
133 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
134 EXT4_I(inode)->jinode,
135 new_size);
136}
137
138static void ext4_invalidatepage(struct page *page, unsigned int offset,
139 unsigned int length);
140static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143 int pextents);
144
145/*
146 * Test whether an inode is a fast symlink.
147 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
148 */
149int ext4_inode_is_fast_symlink(struct inode *inode)
150{
151 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
152 int ea_blocks = EXT4_I(inode)->i_file_acl ?
153 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
154
155 if (ext4_has_inline_data(inode))
156 return 0;
157
158 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
159 }
160 return S_ISLNK(inode->i_mode) && inode->i_size &&
161 (inode->i_size < EXT4_N_BLOCKS * 4);
162}
163
164/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000165 * Called at the last iput() if i_nlink is zero.
166 */
167void ext4_evict_inode(struct inode *inode)
168{
169 handle_t *handle;
170 int err;
Olivier Deprez0e641232021-09-23 10:07:05 +0200171 /*
172 * Credits for final inode cleanup and freeing:
173 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
174 * (xattr block freeing), bitmap, group descriptor (inode freeing)
175 */
176 int extra_credits = 6;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000177 struct ext4_xattr_inode_array *ea_inode_array = NULL;
Olivier Deprez0e641232021-09-23 10:07:05 +0200178 bool freeze_protected = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000179
180 trace_ext4_evict_inode(inode);
181
182 if (inode->i_nlink) {
183 /*
184 * When journalling data dirty buffers are tracked only in the
185 * journal. So although mm thinks everything is clean and
186 * ready for reaping the inode might still have some pages to
187 * write in the running transaction or waiting to be
188 * checkpointed. Thus calling jbd2_journal_invalidatepage()
189 * (via truncate_inode_pages()) to discard these buffers can
190 * cause data loss. Also even if we did not discard these
191 * buffers, we would have no way to find them after the inode
192 * is reaped and thus user could see stale data if he tries to
193 * read them before the transaction is checkpointed. So be
194 * careful and force everything to disk here... We use
195 * ei->i_datasync_tid to store the newest transaction
196 * containing inode's data.
197 *
198 * Note that directories do not have this problem because they
199 * don't use page cache.
200 */
201 if (inode->i_ino != EXT4_JOURNAL_INO &&
202 ext4_should_journal_data(inode) &&
203 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
204 inode->i_data.nrpages) {
205 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
206 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
207
208 jbd2_complete_transaction(journal, commit_tid);
209 filemap_write_and_wait(&inode->i_data);
210 }
211 truncate_inode_pages_final(&inode->i_data);
212
213 goto no_delete;
214 }
215
216 if (is_bad_inode(inode))
217 goto no_delete;
218 dquot_initialize(inode);
219
220 if (ext4_should_order_data(inode))
221 ext4_begin_ordered_truncate(inode, 0);
222 truncate_inode_pages_final(&inode->i_data);
223
224 /*
Olivier Deprez157378f2022-04-04 15:47:50 +0200225 * For inodes with journalled data, transaction commit could have
226 * dirtied the inode. Flush worker is ignoring it because of I_FREEING
227 * flag but we still need to remove the inode from the writeback lists.
228 */
229 if (!list_empty_careful(&inode->i_io_list)) {
230 WARN_ON_ONCE(!ext4_should_journal_data(inode));
231 inode_io_list_del(inode);
232 }
233
234 /*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000235 * Protect us against freezing - iput() caller didn't have to have any
Olivier Deprez0e641232021-09-23 10:07:05 +0200236 * protection against it. When we are in a running transaction though,
237 * we are already protected against freezing and we cannot grab further
238 * protection due to lock ordering constraints.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000239 */
Olivier Deprez0e641232021-09-23 10:07:05 +0200240 if (!ext4_journal_current_handle()) {
241 sb_start_intwrite(inode->i_sb);
242 freeze_protected = true;
243 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000244
245 if (!IS_NOQUOTA(inode))
246 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
247
Olivier Deprez0e641232021-09-23 10:07:05 +0200248 /*
249 * Block bitmap, group descriptor, and inode are accounted in both
250 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
251 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000252 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
Olivier Deprez0e641232021-09-23 10:07:05 +0200253 ext4_blocks_for_truncate(inode) + extra_credits - 3);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000254 if (IS_ERR(handle)) {
255 ext4_std_error(inode->i_sb, PTR_ERR(handle));
256 /*
257 * If we're going to skip the normal cleanup, we still need to
258 * make sure that the in-core orphan linked list is properly
259 * cleaned up.
260 */
261 ext4_orphan_del(NULL, inode);
Olivier Deprez0e641232021-09-23 10:07:05 +0200262 if (freeze_protected)
263 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000264 goto no_delete;
265 }
266
267 if (IS_SYNC(inode))
268 ext4_handle_sync(handle);
269
270 /*
271 * Set inode->i_size to 0 before calling ext4_truncate(). We need
272 * special handling of symlinks here because i_size is used to
273 * determine whether ext4_inode_info->i_data contains symlink data or
274 * block mappings. Setting i_size to 0 will remove its fast symlink
275 * status. Erase i_data so that it becomes a valid empty block map.
276 */
277 if (ext4_inode_is_fast_symlink(inode))
278 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
279 inode->i_size = 0;
280 err = ext4_mark_inode_dirty(handle, inode);
281 if (err) {
282 ext4_warning(inode->i_sb,
283 "couldn't mark inode dirty (err %d)", err);
284 goto stop_handle;
285 }
286 if (inode->i_blocks) {
287 err = ext4_truncate(inode);
288 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200289 ext4_error_err(inode->i_sb, -err,
290 "couldn't truncate inode %lu (err %d)",
291 inode->i_ino, err);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000292 goto stop_handle;
293 }
294 }
295
296 /* Remove xattr references. */
297 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
298 extra_credits);
299 if (err) {
300 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
301stop_handle:
302 ext4_journal_stop(handle);
303 ext4_orphan_del(NULL, inode);
Olivier Deprez0e641232021-09-23 10:07:05 +0200304 if (freeze_protected)
305 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000306 ext4_xattr_inode_array_free(ea_inode_array);
307 goto no_delete;
308 }
309
310 /*
311 * Kill off the orphan record which ext4_truncate created.
312 * AKPM: I think this can be inside the above `if'.
313 * Note that ext4_orphan_del() has to be able to cope with the
314 * deletion of a non-existent orphan - this is because we don't
315 * know if ext4_truncate() actually created an orphan record.
316 * (Well, we could do this if we need to, but heck - it works)
317 */
318 ext4_orphan_del(handle, inode);
319 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
320
321 /*
322 * One subtle ordering requirement: if anything has gone wrong
323 * (transaction abort, IO errors, whatever), then we can still
324 * do these next steps (the fs will already have been marked as
325 * having errors), but we can't free the inode if the mark_dirty
326 * fails.
327 */
328 if (ext4_mark_inode_dirty(handle, inode))
329 /* If that failed, just do the required in-core inode clear. */
330 ext4_clear_inode(inode);
331 else
332 ext4_free_inode(handle, inode);
333 ext4_journal_stop(handle);
Olivier Deprez0e641232021-09-23 10:07:05 +0200334 if (freeze_protected)
335 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000336 ext4_xattr_inode_array_free(ea_inode_array);
337 return;
338no_delete:
Olivier Deprez157378f2022-04-04 15:47:50 +0200339 if (!list_empty(&EXT4_I(inode)->i_fc_list))
340 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000341 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
342}
343
344#ifdef CONFIG_QUOTA
345qsize_t *ext4_get_reserved_space(struct inode *inode)
346{
347 return &EXT4_I(inode)->i_reserved_quota;
348}
349#endif
350
351/*
352 * Called with i_data_sem down, which is important since we can call
353 * ext4_discard_preallocations() from here.
354 */
355void ext4_da_update_reserve_space(struct inode *inode,
356 int used, int quota_claim)
357{
358 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
359 struct ext4_inode_info *ei = EXT4_I(inode);
360
361 spin_lock(&ei->i_block_reservation_lock);
362 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
363 if (unlikely(used > ei->i_reserved_data_blocks)) {
364 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
365 "with only %d reserved data blocks",
366 __func__, inode->i_ino, used,
367 ei->i_reserved_data_blocks);
368 WARN_ON(1);
369 used = ei->i_reserved_data_blocks;
370 }
371
372 /* Update per-inode reservations */
373 ei->i_reserved_data_blocks -= used;
374 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
375
376 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
377
378 /* Update quota subsystem for data blocks */
379 if (quota_claim)
380 dquot_claim_block(inode, EXT4_C2B(sbi, used));
381 else {
382 /*
383 * We did fallocate with an offset that is already delayed
384 * allocated. So on delayed allocated writeback we should
385 * not re-claim the quota for fallocated blocks.
386 */
387 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
388 }
389
390 /*
391 * If we have done all the pending block allocations and if
392 * there aren't any writers on the inode, we can discard the
393 * inode's preallocations.
394 */
395 if ((ei->i_reserved_data_blocks == 0) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000396 !inode_is_open_for_write(inode))
Olivier Deprez157378f2022-04-04 15:47:50 +0200397 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000398}
399
400static int __check_block_validity(struct inode *inode, const char *func,
401 unsigned int line,
402 struct ext4_map_blocks *map)
403{
David Brazdil0f672f62019-12-10 10:32:29 +0000404 if (ext4_has_feature_journal(inode->i_sb) &&
405 (inode->i_ino ==
406 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
407 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200408 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000409 ext4_error_inode(inode, func, line, map->m_pblk,
410 "lblock %lu mapped to illegal pblock %llu "
411 "(length %d)", (unsigned long) map->m_lblk,
412 map->m_pblk, map->m_len);
413 return -EFSCORRUPTED;
414 }
415 return 0;
416}
417
418int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
419 ext4_lblk_t len)
420{
421 int ret;
422
Olivier Deprez157378f2022-04-04 15:47:50 +0200423 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424 return fscrypt_zeroout_range(inode, lblk, pblk, len);
425
426 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
427 if (ret > 0)
428 ret = 0;
429
430 return ret;
431}
432
433#define check_block_validity(inode, map) \
434 __check_block_validity((inode), __func__, __LINE__, (map))
435
436#ifdef ES_AGGRESSIVE_TEST
437static void ext4_map_blocks_es_recheck(handle_t *handle,
438 struct inode *inode,
439 struct ext4_map_blocks *es_map,
440 struct ext4_map_blocks *map,
441 int flags)
442{
443 int retval;
444
445 map->m_flags = 0;
446 /*
447 * There is a race window that the result is not the same.
448 * e.g. xfstests #223 when dioread_nolock enables. The reason
449 * is that we lookup a block mapping in extent status tree with
450 * out taking i_data_sem. So at the time the unwritten extent
451 * could be converted.
452 */
453 down_read(&EXT4_I(inode)->i_data_sem);
454 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200455 retval = ext4_ext_map_blocks(handle, inode, map, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000456 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +0200457 retval = ext4_ind_map_blocks(handle, inode, map, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000458 }
459 up_read((&EXT4_I(inode)->i_data_sem));
460
461 /*
462 * We don't check m_len because extent will be collpased in status
463 * tree. So the m_len might not equal.
464 */
465 if (es_map->m_lblk != map->m_lblk ||
466 es_map->m_flags != map->m_flags ||
467 es_map->m_pblk != map->m_pblk) {
468 printk("ES cache assertion failed for inode: %lu "
469 "es_cached ex [%d/%d/%llu/%x] != "
470 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
471 inode->i_ino, es_map->m_lblk, es_map->m_len,
472 es_map->m_pblk, es_map->m_flags, map->m_lblk,
473 map->m_len, map->m_pblk, map->m_flags,
474 retval, flags);
475 }
476}
477#endif /* ES_AGGRESSIVE_TEST */
478
479/*
480 * The ext4_map_blocks() function tries to look up the requested blocks,
481 * and returns if the blocks are already mapped.
482 *
483 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
484 * and store the allocated blocks in the result buffer head and mark it
485 * mapped.
486 *
487 * If file type is extents based, it will call ext4_ext_map_blocks(),
488 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
489 * based files
490 *
491 * On success, it returns the number of blocks being mapped or allocated. if
492 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
493 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
494 *
495 * It returns 0 if plain look up failed (blocks have not been allocated), in
496 * that case, @map is returned as unmapped but we still do fill map->m_len to
497 * indicate the length of a hole starting at map->m_lblk.
498 *
499 * It returns the error in case of allocation failure.
500 */
501int ext4_map_blocks(handle_t *handle, struct inode *inode,
502 struct ext4_map_blocks *map, int flags)
503{
504 struct extent_status es;
505 int retval;
506 int ret = 0;
507#ifdef ES_AGGRESSIVE_TEST
508 struct ext4_map_blocks orig_map;
509
510 memcpy(&orig_map, map, sizeof(*map));
511#endif
512
513 map->m_flags = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200514 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
515 flags, map->m_len, (unsigned long) map->m_lblk);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000516
517 /*
518 * ext4_map_blocks returns an int, and m_len is an unsigned int
519 */
520 if (unlikely(map->m_len > INT_MAX))
521 map->m_len = INT_MAX;
522
523 /* We can handle the block number less than EXT_MAX_BLOCKS */
524 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
525 return -EFSCORRUPTED;
526
527 /* Lookup extent status tree firstly */
Olivier Deprez157378f2022-04-04 15:47:50 +0200528 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
529 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000530 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
531 map->m_pblk = ext4_es_pblock(&es) +
532 map->m_lblk - es.es_lblk;
533 map->m_flags |= ext4_es_is_written(&es) ?
534 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
535 retval = es.es_len - (map->m_lblk - es.es_lblk);
536 if (retval > map->m_len)
537 retval = map->m_len;
538 map->m_len = retval;
539 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
540 map->m_pblk = 0;
541 retval = es.es_len - (map->m_lblk - es.es_lblk);
542 if (retval > map->m_len)
543 retval = map->m_len;
544 map->m_len = retval;
545 retval = 0;
546 } else {
David Brazdil0f672f62019-12-10 10:32:29 +0000547 BUG();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000548 }
549#ifdef ES_AGGRESSIVE_TEST
550 ext4_map_blocks_es_recheck(handle, inode, map,
551 &orig_map, flags);
552#endif
553 goto found;
554 }
555
556 /*
557 * Try to see if we can get the block without requesting a new
558 * file system block.
559 */
560 down_read(&EXT4_I(inode)->i_data_sem);
561 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200562 retval = ext4_ext_map_blocks(handle, inode, map, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000563 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +0200564 retval = ext4_ind_map_blocks(handle, inode, map, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000565 }
566 if (retval > 0) {
567 unsigned int status;
568
569 if (unlikely(retval != map->m_len)) {
570 ext4_warning(inode->i_sb,
571 "ES len assertion failed for inode "
572 "%lu: retval %d != map->m_len %d",
573 inode->i_ino, retval, map->m_len);
574 WARN_ON(1);
575 }
576
577 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
578 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
579 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
580 !(status & EXTENT_STATUS_WRITTEN) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000581 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
582 map->m_lblk + map->m_len - 1))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000583 status |= EXTENT_STATUS_DELAYED;
584 ret = ext4_es_insert_extent(inode, map->m_lblk,
585 map->m_len, map->m_pblk, status);
586 if (ret < 0)
587 retval = ret;
588 }
589 up_read((&EXT4_I(inode)->i_data_sem));
590
591found:
592 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
593 ret = check_block_validity(inode, map);
594 if (ret != 0)
595 return ret;
596 }
597
598 /* If it is only a block(s) look up */
599 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
600 return retval;
601
602 /*
603 * Returns if the blocks have already allocated
604 *
605 * Note that if blocks have been preallocated
606 * ext4_ext_get_block() returns the create = 0
607 * with buffer head unmapped.
608 */
609 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
610 /*
611 * If we need to convert extent to unwritten
612 * we continue and do the actual work in
613 * ext4_ext_map_blocks()
614 */
615 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
616 return retval;
617
618 /*
619 * Here we clear m_flags because after allocating an new extent,
620 * it will be set again.
621 */
622 map->m_flags &= ~EXT4_MAP_FLAGS;
623
624 /*
625 * New blocks allocate and/or writing to unwritten extent
626 * will possibly result in updating i_data, so we take
627 * the write lock of i_data_sem, and call get_block()
628 * with create == 1 flag.
629 */
630 down_write(&EXT4_I(inode)->i_data_sem);
631
632 /*
633 * We need to check for EXT4 here because migrate
634 * could have changed the inode type in between
635 */
636 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
637 retval = ext4_ext_map_blocks(handle, inode, map, flags);
638 } else {
639 retval = ext4_ind_map_blocks(handle, inode, map, flags);
640
641 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
642 /*
643 * We allocated new blocks which will result in
644 * i_data's format changing. Force the migrate
645 * to fail by clearing migrate flags
646 */
647 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
648 }
649
650 /*
651 * Update reserved blocks/metadata blocks after successful
652 * block allocation which had been deferred till now. We don't
653 * support fallocate for non extent files. So we can update
654 * reserve space here.
655 */
656 if ((retval > 0) &&
657 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
658 ext4_da_update_reserve_space(inode, retval, 1);
659 }
660
661 if (retval > 0) {
662 unsigned int status;
663
664 if (unlikely(retval != map->m_len)) {
665 ext4_warning(inode->i_sb,
666 "ES len assertion failed for inode "
667 "%lu: retval %d != map->m_len %d",
668 inode->i_ino, retval, map->m_len);
669 WARN_ON(1);
670 }
671
672 /*
673 * We have to zeroout blocks before inserting them into extent
674 * status tree. Otherwise someone could look them up there and
675 * use them before they are really zeroed. We also have to
676 * unmap metadata before zeroing as otherwise writeback can
677 * overwrite zeros with stale data from block device.
678 */
679 if (flags & EXT4_GET_BLOCKS_ZERO &&
680 map->m_flags & EXT4_MAP_MAPPED &&
681 map->m_flags & EXT4_MAP_NEW) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000682 ret = ext4_issue_zeroout(inode, map->m_lblk,
683 map->m_pblk, map->m_len);
684 if (ret) {
685 retval = ret;
686 goto out_sem;
687 }
688 }
689
690 /*
691 * If the extent has been zeroed out, we don't need to update
692 * extent status tree.
693 */
694 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000695 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000696 if (ext4_es_is_written(&es))
697 goto out_sem;
698 }
699 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
700 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
701 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
702 !(status & EXTENT_STATUS_WRITTEN) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000703 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
704 map->m_lblk + map->m_len - 1))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000705 status |= EXTENT_STATUS_DELAYED;
706 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
707 map->m_pblk, status);
708 if (ret < 0) {
709 retval = ret;
710 goto out_sem;
711 }
712 }
713
714out_sem:
715 up_write((&EXT4_I(inode)->i_data_sem));
716 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
717 ret = check_block_validity(inode, map);
718 if (ret != 0)
719 return ret;
720
721 /*
722 * Inodes with freshly allocated blocks where contents will be
723 * visible after transaction commit must be on transaction's
724 * ordered data list.
725 */
726 if (map->m_flags & EXT4_MAP_NEW &&
727 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
728 !(flags & EXT4_GET_BLOCKS_ZERO) &&
729 !ext4_is_quota_file(inode) &&
730 ext4_should_order_data(inode)) {
David Brazdil0f672f62019-12-10 10:32:29 +0000731 loff_t start_byte =
732 (loff_t)map->m_lblk << inode->i_blkbits;
733 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
734
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000735 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
David Brazdil0f672f62019-12-10 10:32:29 +0000736 ret = ext4_jbd2_inode_add_wait(handle, inode,
737 start_byte, length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000738 else
David Brazdil0f672f62019-12-10 10:32:29 +0000739 ret = ext4_jbd2_inode_add_write(handle, inode,
740 start_byte, length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000741 if (ret)
742 return ret;
743 }
744 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200745 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
746 map->m_flags & EXT4_MAP_MAPPED))
747 ext4_fc_track_range(handle, inode, map->m_lblk,
748 map->m_lblk + map->m_len - 1);
749 if (retval < 0)
750 ext_debug(inode, "failed with err %d\n", retval);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000751 return retval;
752}
753
754/*
755 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
756 * we have to be careful as someone else may be manipulating b_state as well.
757 */
758static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
759{
760 unsigned long old_state;
761 unsigned long new_state;
762
763 flags &= EXT4_MAP_FLAGS;
764
765 /* Dummy buffer_head? Set non-atomically. */
766 if (!bh->b_page) {
767 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
768 return;
769 }
770 /*
771 * Someone else may be modifying b_state. Be careful! This is ugly but
772 * once we get rid of using bh as a container for mapping information
773 * to pass to / from get_block functions, this can go away.
774 */
775 do {
776 old_state = READ_ONCE(bh->b_state);
777 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
778 } while (unlikely(
779 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
780}
781
782static int _ext4_get_block(struct inode *inode, sector_t iblock,
783 struct buffer_head *bh, int flags)
784{
785 struct ext4_map_blocks map;
786 int ret = 0;
787
788 if (ext4_has_inline_data(inode))
789 return -ERANGE;
790
791 map.m_lblk = iblock;
792 map.m_len = bh->b_size >> inode->i_blkbits;
793
794 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
795 flags);
796 if (ret > 0) {
797 map_bh(bh, inode->i_sb, map.m_pblk);
798 ext4_update_bh_state(bh, map.m_flags);
799 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
800 ret = 0;
801 } else if (ret == 0) {
802 /* hole case, need to fill in bh->b_size */
803 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
804 }
805 return ret;
806}
807
808int ext4_get_block(struct inode *inode, sector_t iblock,
809 struct buffer_head *bh, int create)
810{
811 return _ext4_get_block(inode, iblock, bh,
812 create ? EXT4_GET_BLOCKS_CREATE : 0);
813}
814
815/*
816 * Get block function used when preparing for buffered write if we require
817 * creating an unwritten extent if blocks haven't been allocated. The extent
818 * will be converted to written after the IO is complete.
819 */
820int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
821 struct buffer_head *bh_result, int create)
822{
823 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
824 inode->i_ino, create);
825 return _ext4_get_block(inode, iblock, bh_result,
826 EXT4_GET_BLOCKS_IO_CREATE_EXT);
827}
828
829/* Maximum number of blocks we map for direct IO at once. */
830#define DIO_MAX_BLOCKS 4096
831
832/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000833 * `handle' can be NULL if create is zero
834 */
835struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
836 ext4_lblk_t block, int map_flags)
837{
838 struct ext4_map_blocks map;
839 struct buffer_head *bh;
840 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
841 int err;
842
Olivier Deprez157378f2022-04-04 15:47:50 +0200843 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
844 || handle != NULL || create == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000845
846 map.m_lblk = block;
847 map.m_len = 1;
848 err = ext4_map_blocks(handle, inode, &map, map_flags);
849
850 if (err == 0)
851 return create ? ERR_PTR(-ENOSPC) : NULL;
852 if (err < 0)
853 return ERR_PTR(err);
854
855 bh = sb_getblk(inode->i_sb, map.m_pblk);
856 if (unlikely(!bh))
857 return ERR_PTR(-ENOMEM);
858 if (map.m_flags & EXT4_MAP_NEW) {
859 J_ASSERT(create != 0);
Olivier Deprez157378f2022-04-04 15:47:50 +0200860 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
861 || (handle != NULL));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000862
863 /*
864 * Now that we do not always journal data, we should
865 * keep in mind whether this should always journal the
866 * new buffer as metadata. For now, regular file
867 * writes use ext4_get_block instead, so it's not a
868 * problem.
869 */
870 lock_buffer(bh);
871 BUFFER_TRACE(bh, "call get_create_access");
872 err = ext4_journal_get_create_access(handle, bh);
873 if (unlikely(err)) {
874 unlock_buffer(bh);
875 goto errout;
876 }
877 if (!buffer_uptodate(bh)) {
878 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
879 set_buffer_uptodate(bh);
880 }
881 unlock_buffer(bh);
882 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
883 err = ext4_handle_dirty_metadata(handle, inode, bh);
884 if (unlikely(err))
885 goto errout;
886 } else
887 BUFFER_TRACE(bh, "not a new buffer");
888 return bh;
889errout:
890 brelse(bh);
891 return ERR_PTR(err);
892}
893
894struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
895 ext4_lblk_t block, int map_flags)
896{
897 struct buffer_head *bh;
Olivier Deprez157378f2022-04-04 15:47:50 +0200898 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000899
900 bh = ext4_getblk(handle, inode, block, map_flags);
901 if (IS_ERR(bh))
902 return bh;
David Brazdil0f672f62019-12-10 10:32:29 +0000903 if (!bh || ext4_buffer_uptodate(bh))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000904 return bh;
Olivier Deprez157378f2022-04-04 15:47:50 +0200905
906 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
907 if (ret) {
908 put_bh(bh);
909 return ERR_PTR(ret);
910 }
911 return bh;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000912}
913
914/* Read a contiguous batch of blocks. */
915int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
916 bool wait, struct buffer_head **bhs)
917{
918 int i, err;
919
920 for (i = 0; i < bh_count; i++) {
921 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
922 if (IS_ERR(bhs[i])) {
923 err = PTR_ERR(bhs[i]);
924 bh_count = i;
925 goto out_brelse;
926 }
927 }
928
929 for (i = 0; i < bh_count; i++)
930 /* Note that NULL bhs[i] is valid because of holes. */
David Brazdil0f672f62019-12-10 10:32:29 +0000931 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
Olivier Deprez157378f2022-04-04 15:47:50 +0200932 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000933
934 if (!wait)
935 return 0;
936
937 for (i = 0; i < bh_count; i++)
938 if (bhs[i])
939 wait_on_buffer(bhs[i]);
940
941 for (i = 0; i < bh_count; i++) {
942 if (bhs[i] && !buffer_uptodate(bhs[i])) {
943 err = -EIO;
944 goto out_brelse;
945 }
946 }
947 return 0;
948
949out_brelse:
950 for (i = 0; i < bh_count; i++) {
951 brelse(bhs[i]);
952 bhs[i] = NULL;
953 }
954 return err;
955}
956
957int ext4_walk_page_buffers(handle_t *handle,
958 struct buffer_head *head,
959 unsigned from,
960 unsigned to,
961 int *partial,
962 int (*fn)(handle_t *handle,
963 struct buffer_head *bh))
964{
965 struct buffer_head *bh;
966 unsigned block_start, block_end;
967 unsigned blocksize = head->b_size;
968 int err, ret = 0;
969 struct buffer_head *next;
970
971 for (bh = head, block_start = 0;
972 ret == 0 && (bh != head || !block_start);
973 block_start = block_end, bh = next) {
974 next = bh->b_this_page;
975 block_end = block_start + blocksize;
976 if (block_end <= from || block_start >= to) {
977 if (partial && !buffer_uptodate(bh))
978 *partial = 1;
979 continue;
980 }
981 err = (*fn)(handle, bh);
982 if (!ret)
983 ret = err;
984 }
985 return ret;
986}
987
988/*
989 * To preserve ordering, it is essential that the hole instantiation and
990 * the data write be encapsulated in a single transaction. We cannot
991 * close off a transaction and start a new one between the ext4_get_block()
992 * and the commit_write(). So doing the jbd2_journal_start at the start of
993 * prepare_write() is the right place.
994 *
995 * Also, this function can nest inside ext4_writepage(). In that case, we
996 * *know* that ext4_writepage() has generated enough buffer credits to do the
997 * whole page. So we won't block on the journal in that case, which is good,
998 * because the caller may be PF_MEMALLOC.
999 *
1000 * By accident, ext4 can be reentered when a transaction is open via
1001 * quota file writes. If we were to commit the transaction while thus
1002 * reentered, there can be a deadlock - we would be holding a quota
1003 * lock, and the commit would never complete if another thread had a
1004 * transaction open and was blocking on the quota lock - a ranking
1005 * violation.
1006 *
1007 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1008 * will _not_ run commit under these circumstances because handle->h_ref
1009 * is elevated. We'll still have enough credits for the tiny quotafile
1010 * write.
1011 */
1012int do_journal_get_write_access(handle_t *handle,
1013 struct buffer_head *bh)
1014{
1015 int dirty = buffer_dirty(bh);
1016 int ret;
1017
1018 if (!buffer_mapped(bh) || buffer_freed(bh))
1019 return 0;
1020 /*
1021 * __block_write_begin() could have dirtied some buffers. Clean
1022 * the dirty bit as jbd2_journal_get_write_access() could complain
1023 * otherwise about fs integrity issues. Setting of the dirty bit
1024 * by __block_write_begin() isn't a real problem here as we clear
1025 * the bit before releasing a page lock and thus writeback cannot
1026 * ever write the buffer.
1027 */
1028 if (dirty)
1029 clear_buffer_dirty(bh);
1030 BUFFER_TRACE(bh, "get write access");
1031 ret = ext4_journal_get_write_access(handle, bh);
1032 if (!ret && dirty)
1033 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1034 return ret;
1035}
1036
David Brazdil0f672f62019-12-10 10:32:29 +00001037#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001038static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1039 get_block_t *get_block)
1040{
1041 unsigned from = pos & (PAGE_SIZE - 1);
1042 unsigned to = from + len;
1043 struct inode *inode = page->mapping->host;
1044 unsigned block_start, block_end;
1045 sector_t block;
1046 int err = 0;
1047 unsigned blocksize = inode->i_sb->s_blocksize;
1048 unsigned bbits;
David Brazdil0f672f62019-12-10 10:32:29 +00001049 struct buffer_head *bh, *head, *wait[2];
1050 int nr_wait = 0;
1051 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001052
1053 BUG_ON(!PageLocked(page));
1054 BUG_ON(from > PAGE_SIZE);
1055 BUG_ON(to > PAGE_SIZE);
1056 BUG_ON(from > to);
1057
1058 if (!page_has_buffers(page))
1059 create_empty_buffers(page, blocksize, 0);
1060 head = page_buffers(page);
1061 bbits = ilog2(blocksize);
1062 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1063
1064 for (bh = head, block_start = 0; bh != head || !block_start;
1065 block++, block_start = block_end, bh = bh->b_this_page) {
1066 block_end = block_start + blocksize;
1067 if (block_end <= from || block_start >= to) {
1068 if (PageUptodate(page)) {
1069 if (!buffer_uptodate(bh))
1070 set_buffer_uptodate(bh);
1071 }
1072 continue;
1073 }
1074 if (buffer_new(bh))
1075 clear_buffer_new(bh);
1076 if (!buffer_mapped(bh)) {
1077 WARN_ON(bh->b_size != blocksize);
1078 err = get_block(inode, block, bh, 1);
1079 if (err)
1080 break;
1081 if (buffer_new(bh)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001082 if (PageUptodate(page)) {
1083 clear_buffer_new(bh);
1084 set_buffer_uptodate(bh);
1085 mark_buffer_dirty(bh);
1086 continue;
1087 }
1088 if (block_end > to || block_start < from)
1089 zero_user_segments(page, to, block_end,
1090 block_start, from);
1091 continue;
1092 }
1093 }
1094 if (PageUptodate(page)) {
1095 if (!buffer_uptodate(bh))
1096 set_buffer_uptodate(bh);
1097 continue;
1098 }
1099 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1100 !buffer_unwritten(bh) &&
1101 (block_start < from || block_end > to)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001102 ext4_read_bh_lock(bh, 0, false);
David Brazdil0f672f62019-12-10 10:32:29 +00001103 wait[nr_wait++] = bh;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001104 }
1105 }
1106 /*
1107 * If we issued read requests, let them complete.
1108 */
David Brazdil0f672f62019-12-10 10:32:29 +00001109 for (i = 0; i < nr_wait; i++) {
1110 wait_on_buffer(wait[i]);
1111 if (!buffer_uptodate(wait[i]))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001112 err = -EIO;
1113 }
David Brazdil0f672f62019-12-10 10:32:29 +00001114 if (unlikely(err)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001115 page_zero_new_buffers(page, from, to);
Olivier Deprez157378f2022-04-04 15:47:50 +02001116 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001117 for (i = 0; i < nr_wait; i++) {
1118 int err2;
1119
1120 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1121 bh_offset(wait[i]));
1122 if (err2) {
1123 clear_buffer_uptodate(wait[i]);
1124 err = err2;
1125 }
1126 }
1127 }
1128
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001129 return err;
1130}
1131#endif
1132
1133static int ext4_write_begin(struct file *file, struct address_space *mapping,
1134 loff_t pos, unsigned len, unsigned flags,
1135 struct page **pagep, void **fsdata)
1136{
1137 struct inode *inode = mapping->host;
1138 int ret, needed_blocks;
1139 handle_t *handle;
1140 int retries = 0;
1141 struct page *page;
1142 pgoff_t index;
1143 unsigned from, to;
1144
1145 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1146 return -EIO;
1147
1148 trace_ext4_write_begin(inode, pos, len, flags);
1149 /*
1150 * Reserve one block more for addition to orphan list in case
1151 * we allocate blocks but write fails for some reason
1152 */
1153 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1154 index = pos >> PAGE_SHIFT;
1155 from = pos & (PAGE_SIZE - 1);
1156 to = from + len;
1157
1158 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1159 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1160 flags, pagep);
1161 if (ret < 0)
1162 return ret;
1163 if (ret == 1)
1164 return 0;
1165 }
1166
1167 /*
1168 * grab_cache_page_write_begin() can take a long time if the
1169 * system is thrashing due to memory pressure, or if the page
1170 * is being written back. So grab it first before we start
1171 * the transaction handle. This also allows us to allocate
1172 * the page (if needed) without using GFP_NOFS.
1173 */
1174retry_grab:
1175 page = grab_cache_page_write_begin(mapping, index, flags);
1176 if (!page)
1177 return -ENOMEM;
1178 unlock_page(page);
1179
1180retry_journal:
1181 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1182 if (IS_ERR(handle)) {
1183 put_page(page);
1184 return PTR_ERR(handle);
1185 }
1186
1187 lock_page(page);
1188 if (page->mapping != mapping) {
1189 /* The page got truncated from under us */
1190 unlock_page(page);
1191 put_page(page);
1192 ext4_journal_stop(handle);
1193 goto retry_grab;
1194 }
1195 /* In case writeback began while the page was unlocked */
1196 wait_for_stable_page(page);
1197
David Brazdil0f672f62019-12-10 10:32:29 +00001198#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001199 if (ext4_should_dioread_nolock(inode))
1200 ret = ext4_block_write_begin(page, pos, len,
1201 ext4_get_block_unwritten);
1202 else
1203 ret = ext4_block_write_begin(page, pos, len,
1204 ext4_get_block);
1205#else
1206 if (ext4_should_dioread_nolock(inode))
1207 ret = __block_write_begin(page, pos, len,
1208 ext4_get_block_unwritten);
1209 else
1210 ret = __block_write_begin(page, pos, len, ext4_get_block);
1211#endif
1212 if (!ret && ext4_should_journal_data(inode)) {
1213 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1214 from, to, NULL,
1215 do_journal_get_write_access);
1216 }
1217
1218 if (ret) {
David Brazdil0f672f62019-12-10 10:32:29 +00001219 bool extended = (pos + len > inode->i_size) &&
1220 !ext4_verity_in_progress(inode);
1221
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001222 unlock_page(page);
1223 /*
1224 * __block_write_begin may have instantiated a few blocks
1225 * outside i_size. Trim these off again. Don't need
1226 * i_size_read because we hold i_mutex.
1227 *
1228 * Add inode to orphan list in case we crash before
1229 * truncate finishes
1230 */
David Brazdil0f672f62019-12-10 10:32:29 +00001231 if (extended && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001232 ext4_orphan_add(handle, inode);
1233
1234 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00001235 if (extended) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001236 ext4_truncate_failed_write(inode);
1237 /*
1238 * If truncate failed early the inode might
1239 * still be on the orphan list; we need to
1240 * make sure the inode is removed from the
1241 * orphan list in that case.
1242 */
1243 if (inode->i_nlink)
1244 ext4_orphan_del(NULL, inode);
1245 }
1246
1247 if (ret == -ENOSPC &&
1248 ext4_should_retry_alloc(inode->i_sb, &retries))
1249 goto retry_journal;
1250 put_page(page);
1251 return ret;
1252 }
1253 *pagep = page;
1254 return ret;
1255}
1256
1257/* For write_end() in data=journal mode */
1258static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1259{
1260 int ret;
1261 if (!buffer_mapped(bh) || buffer_freed(bh))
1262 return 0;
1263 set_buffer_uptodate(bh);
1264 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1265 clear_buffer_meta(bh);
1266 clear_buffer_prio(bh);
1267 return ret;
1268}
1269
1270/*
1271 * We need to pick up the new inode size which generic_commit_write gave us
1272 * `file' can be NULL - eg, when called from page_symlink().
1273 *
1274 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1275 * buffers are managed internally.
1276 */
1277static int ext4_write_end(struct file *file,
1278 struct address_space *mapping,
1279 loff_t pos, unsigned len, unsigned copied,
1280 struct page *page, void *fsdata)
1281{
1282 handle_t *handle = ext4_journal_current_handle();
1283 struct inode *inode = mapping->host;
1284 loff_t old_size = inode->i_size;
1285 int ret = 0, ret2;
1286 int i_size_changed = 0;
1287 int inline_data = ext4_has_inline_data(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00001288 bool verity = ext4_verity_in_progress(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001289
1290 trace_ext4_write_end(inode, pos, len, copied);
1291 if (inline_data) {
1292 ret = ext4_write_inline_data_end(inode, pos, len,
1293 copied, page);
1294 if (ret < 0) {
1295 unlock_page(page);
1296 put_page(page);
1297 goto errout;
1298 }
1299 copied = ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02001300 ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001301 } else
1302 copied = block_write_end(file, mapping, pos,
1303 len, copied, page, fsdata);
1304 /*
1305 * it's important to update i_size while still holding page lock:
1306 * page writeout could otherwise come in and zero beyond i_size.
David Brazdil0f672f62019-12-10 10:32:29 +00001307 *
1308 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1309 * blocks are being written past EOF, so skip the i_size update.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001310 */
David Brazdil0f672f62019-12-10 10:32:29 +00001311 if (!verity)
1312 i_size_changed = ext4_update_inode_size(inode, pos + copied);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001313 unlock_page(page);
1314 put_page(page);
1315
David Brazdil0f672f62019-12-10 10:32:29 +00001316 if (old_size < pos && !verity)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001317 pagecache_isize_extended(inode, old_size, pos);
1318 /*
1319 * Don't mark the inode dirty under page lock. First, it unnecessarily
1320 * makes the holding time of page lock longer. Second, it forces lock
1321 * ordering of page lock and transaction start for journaling
1322 * filesystems.
1323 */
1324 if (i_size_changed || inline_data)
Olivier Deprez157378f2022-04-04 15:47:50 +02001325 ret = ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001326
Olivier Deprez157378f2022-04-04 15:47:50 +02001327errout:
David Brazdil0f672f62019-12-10 10:32:29 +00001328 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001329 /* if we have allocated more blocks and copied
1330 * less. We will have blocks allocated outside
1331 * inode->i_size. So truncate them
1332 */
1333 ext4_orphan_add(handle, inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02001334
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001335 ret2 = ext4_journal_stop(handle);
1336 if (!ret)
1337 ret = ret2;
1338
David Brazdil0f672f62019-12-10 10:32:29 +00001339 if (pos + len > inode->i_size && !verity) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001340 ext4_truncate_failed_write(inode);
1341 /*
1342 * If truncate failed early the inode might still be
1343 * on the orphan list; we need to make sure the inode
1344 * is removed from the orphan list in that case.
1345 */
1346 if (inode->i_nlink)
1347 ext4_orphan_del(NULL, inode);
1348 }
1349
1350 return ret ? ret : copied;
1351}
1352
1353/*
1354 * This is a private version of page_zero_new_buffers() which doesn't
1355 * set the buffer to be dirty, since in data=journalled mode we need
1356 * to call ext4_handle_dirty_metadata() instead.
1357 */
1358static void ext4_journalled_zero_new_buffers(handle_t *handle,
1359 struct page *page,
1360 unsigned from, unsigned to)
1361{
1362 unsigned int block_start = 0, block_end;
1363 struct buffer_head *head, *bh;
1364
1365 bh = head = page_buffers(page);
1366 do {
1367 block_end = block_start + bh->b_size;
1368 if (buffer_new(bh)) {
1369 if (block_end > from && block_start < to) {
1370 if (!PageUptodate(page)) {
1371 unsigned start, size;
1372
1373 start = max(from, block_start);
1374 size = min(to, block_end) - start;
1375
1376 zero_user(page, start, size);
1377 write_end_fn(handle, bh);
1378 }
1379 clear_buffer_new(bh);
1380 }
1381 }
1382 block_start = block_end;
1383 bh = bh->b_this_page;
1384 } while (bh != head);
1385}
1386
1387static int ext4_journalled_write_end(struct file *file,
1388 struct address_space *mapping,
1389 loff_t pos, unsigned len, unsigned copied,
1390 struct page *page, void *fsdata)
1391{
1392 handle_t *handle = ext4_journal_current_handle();
1393 struct inode *inode = mapping->host;
1394 loff_t old_size = inode->i_size;
1395 int ret = 0, ret2;
1396 int partial = 0;
1397 unsigned from, to;
1398 int size_changed = 0;
1399 int inline_data = ext4_has_inline_data(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00001400 bool verity = ext4_verity_in_progress(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001401
1402 trace_ext4_journalled_write_end(inode, pos, len, copied);
1403 from = pos & (PAGE_SIZE - 1);
1404 to = from + len;
1405
1406 BUG_ON(!ext4_handle_valid(handle));
1407
1408 if (inline_data) {
1409 ret = ext4_write_inline_data_end(inode, pos, len,
1410 copied, page);
1411 if (ret < 0) {
1412 unlock_page(page);
1413 put_page(page);
1414 goto errout;
1415 }
1416 copied = ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02001417 ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001418 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1419 copied = 0;
1420 ext4_journalled_zero_new_buffers(handle, page, from, to);
1421 } else {
1422 if (unlikely(copied < len))
1423 ext4_journalled_zero_new_buffers(handle, page,
1424 from + copied, to);
1425 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1426 from + copied, &partial,
1427 write_end_fn);
1428 if (!partial)
1429 SetPageUptodate(page);
1430 }
David Brazdil0f672f62019-12-10 10:32:29 +00001431 if (!verity)
1432 size_changed = ext4_update_inode_size(inode, pos + copied);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001433 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1434 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1435 unlock_page(page);
1436 put_page(page);
1437
David Brazdil0f672f62019-12-10 10:32:29 +00001438 if (old_size < pos && !verity)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001439 pagecache_isize_extended(inode, old_size, pos);
1440
1441 if (size_changed || inline_data) {
1442 ret2 = ext4_mark_inode_dirty(handle, inode);
1443 if (!ret)
1444 ret = ret2;
1445 }
1446
Olivier Deprez157378f2022-04-04 15:47:50 +02001447errout:
David Brazdil0f672f62019-12-10 10:32:29 +00001448 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001449 /* if we have allocated more blocks and copied
1450 * less. We will have blocks allocated outside
1451 * inode->i_size. So truncate them
1452 */
1453 ext4_orphan_add(handle, inode);
1454
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001455 ret2 = ext4_journal_stop(handle);
1456 if (!ret)
1457 ret = ret2;
David Brazdil0f672f62019-12-10 10:32:29 +00001458 if (pos + len > inode->i_size && !verity) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001459 ext4_truncate_failed_write(inode);
1460 /*
1461 * If truncate failed early the inode might still be
1462 * on the orphan list; we need to make sure the inode
1463 * is removed from the orphan list in that case.
1464 */
1465 if (inode->i_nlink)
1466 ext4_orphan_del(NULL, inode);
1467 }
1468
1469 return ret ? ret : copied;
1470}
1471
1472/*
1473 * Reserve space for a single cluster
1474 */
1475static int ext4_da_reserve_space(struct inode *inode)
1476{
1477 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1478 struct ext4_inode_info *ei = EXT4_I(inode);
1479 int ret;
1480
1481 /*
1482 * We will charge metadata quota at writeout time; this saves
1483 * us from metadata over-estimation, though we may go over by
1484 * a small amount in the end. Here we just reserve for data.
1485 */
1486 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1487 if (ret)
1488 return ret;
1489
1490 spin_lock(&ei->i_block_reservation_lock);
1491 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1492 spin_unlock(&ei->i_block_reservation_lock);
1493 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1494 return -ENOSPC;
1495 }
1496 ei->i_reserved_data_blocks++;
1497 trace_ext4_da_reserve_space(inode);
1498 spin_unlock(&ei->i_block_reservation_lock);
1499
1500 return 0; /* success */
1501}
1502
David Brazdil0f672f62019-12-10 10:32:29 +00001503void ext4_da_release_space(struct inode *inode, int to_free)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001504{
1505 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1506 struct ext4_inode_info *ei = EXT4_I(inode);
1507
1508 if (!to_free)
1509 return; /* Nothing to release, exit */
1510
1511 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1512
1513 trace_ext4_da_release_space(inode, to_free);
1514 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1515 /*
1516 * if there aren't enough reserved blocks, then the
1517 * counter is messed up somewhere. Since this
1518 * function is called from invalidate page, it's
1519 * harmless to return without any action.
1520 */
1521 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1522 "ino %lu, to_free %d with only %d reserved "
1523 "data blocks", inode->i_ino, to_free,
1524 ei->i_reserved_data_blocks);
1525 WARN_ON(1);
1526 to_free = ei->i_reserved_data_blocks;
1527 }
1528 ei->i_reserved_data_blocks -= to_free;
1529
1530 /* update fs dirty data blocks counter */
1531 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1532
1533 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1534
1535 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1536}
1537
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001538/*
1539 * Delayed allocation stuff
1540 */
1541
1542struct mpage_da_data {
1543 struct inode *inode;
1544 struct writeback_control *wbc;
1545
1546 pgoff_t first_page; /* The first page to write */
1547 pgoff_t next_page; /* Current page to examine */
1548 pgoff_t last_page; /* Last page to examine */
1549 /*
1550 * Extent to map - this can be after first_page because that can be
1551 * fully mapped. We somewhat abuse m_flags to store whether the extent
1552 * is delalloc or unwritten.
1553 */
1554 struct ext4_map_blocks map;
1555 struct ext4_io_submit io_submit; /* IO submission data */
1556 unsigned int do_map:1;
Olivier Deprez157378f2022-04-04 15:47:50 +02001557 unsigned int scanned_until_end:1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001558};
1559
1560static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1561 bool invalidate)
1562{
1563 int nr_pages, i;
1564 pgoff_t index, end;
1565 struct pagevec pvec;
1566 struct inode *inode = mpd->inode;
1567 struct address_space *mapping = inode->i_mapping;
1568
1569 /* This is necessary when next_page == 0. */
1570 if (mpd->first_page >= mpd->next_page)
1571 return;
1572
Olivier Deprez157378f2022-04-04 15:47:50 +02001573 mpd->scanned_until_end = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001574 index = mpd->first_page;
1575 end = mpd->next_page - 1;
1576 if (invalidate) {
1577 ext4_lblk_t start, last;
1578 start = index << (PAGE_SHIFT - inode->i_blkbits);
1579 last = end << (PAGE_SHIFT - inode->i_blkbits);
1580 ext4_es_remove_extent(inode, start, last - start + 1);
1581 }
1582
1583 pagevec_init(&pvec);
1584 while (index <= end) {
1585 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1586 if (nr_pages == 0)
1587 break;
1588 for (i = 0; i < nr_pages; i++) {
1589 struct page *page = pvec.pages[i];
1590
1591 BUG_ON(!PageLocked(page));
1592 BUG_ON(PageWriteback(page));
1593 if (invalidate) {
1594 if (page_mapped(page))
1595 clear_page_dirty_for_io(page);
1596 block_invalidatepage(page, 0, PAGE_SIZE);
1597 ClearPageUptodate(page);
1598 }
1599 unlock_page(page);
1600 }
1601 pagevec_release(&pvec);
1602 }
1603}
1604
1605static void ext4_print_free_blocks(struct inode *inode)
1606{
1607 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1608 struct super_block *sb = inode->i_sb;
1609 struct ext4_inode_info *ei = EXT4_I(inode);
1610
1611 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1612 EXT4_C2B(EXT4_SB(inode->i_sb),
1613 ext4_count_free_clusters(sb)));
1614 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1615 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1616 (long long) EXT4_C2B(EXT4_SB(sb),
1617 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1618 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1619 (long long) EXT4_C2B(EXT4_SB(sb),
1620 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1621 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1622 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1623 ei->i_reserved_data_blocks);
1624 return;
1625}
1626
1627static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1628{
1629 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1630}
1631
1632/*
David Brazdil0f672f62019-12-10 10:32:29 +00001633 * ext4_insert_delayed_block - adds a delayed block to the extents status
1634 * tree, incrementing the reserved cluster/block
1635 * count or making a pending reservation
1636 * where needed
1637 *
1638 * @inode - file containing the newly added block
1639 * @lblk - logical block to be added
1640 *
1641 * Returns 0 on success, negative error code on failure.
1642 */
1643static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1644{
1645 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1646 int ret;
1647 bool allocated = false;
Olivier Deprez157378f2022-04-04 15:47:50 +02001648 bool reserved = false;
David Brazdil0f672f62019-12-10 10:32:29 +00001649
1650 /*
1651 * If the cluster containing lblk is shared with a delayed,
1652 * written, or unwritten extent in a bigalloc file system, it's
1653 * already been accounted for and does not need to be reserved.
1654 * A pending reservation must be made for the cluster if it's
1655 * shared with a written or unwritten extent and doesn't already
1656 * have one. Written and unwritten extents can be purged from the
1657 * extents status tree if the system is under memory pressure, so
1658 * it's necessary to examine the extent tree if a search of the
1659 * extents status tree doesn't get a match.
1660 */
1661 if (sbi->s_cluster_ratio == 1) {
1662 ret = ext4_da_reserve_space(inode);
1663 if (ret != 0) /* ENOSPC */
1664 goto errout;
Olivier Deprez157378f2022-04-04 15:47:50 +02001665 reserved = true;
David Brazdil0f672f62019-12-10 10:32:29 +00001666 } else { /* bigalloc */
1667 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1668 if (!ext4_es_scan_clu(inode,
1669 &ext4_es_is_mapped, lblk)) {
1670 ret = ext4_clu_mapped(inode,
1671 EXT4_B2C(sbi, lblk));
1672 if (ret < 0)
1673 goto errout;
1674 if (ret == 0) {
1675 ret = ext4_da_reserve_space(inode);
1676 if (ret != 0) /* ENOSPC */
1677 goto errout;
Olivier Deprez157378f2022-04-04 15:47:50 +02001678 reserved = true;
David Brazdil0f672f62019-12-10 10:32:29 +00001679 } else {
1680 allocated = true;
1681 }
1682 } else {
1683 allocated = true;
1684 }
1685 }
1686 }
1687
1688 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
Olivier Deprez157378f2022-04-04 15:47:50 +02001689 if (ret && reserved)
1690 ext4_da_release_space(inode, 1);
David Brazdil0f672f62019-12-10 10:32:29 +00001691
1692errout:
1693 return ret;
1694}
1695
1696/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001697 * This function is grabs code from the very beginning of
1698 * ext4_map_blocks, but assumes that the caller is from delayed write
1699 * time. This function looks up the requested blocks and sets the
1700 * buffer delay bit under the protection of i_data_sem.
1701 */
1702static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1703 struct ext4_map_blocks *map,
1704 struct buffer_head *bh)
1705{
1706 struct extent_status es;
1707 int retval;
1708 sector_t invalid_block = ~((sector_t) 0xffff);
1709#ifdef ES_AGGRESSIVE_TEST
1710 struct ext4_map_blocks orig_map;
1711
1712 memcpy(&orig_map, map, sizeof(*map));
1713#endif
1714
1715 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1716 invalid_block = ~0;
1717
1718 map->m_flags = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001719 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001720 (unsigned long) map->m_lblk);
1721
1722 /* Lookup extent status tree firstly */
David Brazdil0f672f62019-12-10 10:32:29 +00001723 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001724 if (ext4_es_is_hole(&es)) {
1725 retval = 0;
1726 down_read(&EXT4_I(inode)->i_data_sem);
1727 goto add_delayed;
1728 }
1729
1730 /*
1731 * Delayed extent could be allocated by fallocate.
1732 * So we need to check it.
1733 */
1734 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1735 map_bh(bh, inode->i_sb, invalid_block);
1736 set_buffer_new(bh);
1737 set_buffer_delay(bh);
1738 return 0;
1739 }
1740
1741 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1742 retval = es.es_len - (iblock - es.es_lblk);
1743 if (retval > map->m_len)
1744 retval = map->m_len;
1745 map->m_len = retval;
1746 if (ext4_es_is_written(&es))
1747 map->m_flags |= EXT4_MAP_MAPPED;
1748 else if (ext4_es_is_unwritten(&es))
1749 map->m_flags |= EXT4_MAP_UNWRITTEN;
1750 else
David Brazdil0f672f62019-12-10 10:32:29 +00001751 BUG();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001752
1753#ifdef ES_AGGRESSIVE_TEST
1754 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1755#endif
1756 return retval;
1757 }
1758
1759 /*
1760 * Try to see if we can get the block without requesting a new
1761 * file system block.
1762 */
1763 down_read(&EXT4_I(inode)->i_data_sem);
1764 if (ext4_has_inline_data(inode))
1765 retval = 0;
1766 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1767 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1768 else
1769 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1770
1771add_delayed:
1772 if (retval == 0) {
1773 int ret;
David Brazdil0f672f62019-12-10 10:32:29 +00001774
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001775 /*
1776 * XXX: __block_prepare_write() unmaps passed block,
1777 * is it OK?
1778 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001779
David Brazdil0f672f62019-12-10 10:32:29 +00001780 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1781 if (ret != 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001782 retval = ret;
1783 goto out_unlock;
1784 }
1785
1786 map_bh(bh, inode->i_sb, invalid_block);
1787 set_buffer_new(bh);
1788 set_buffer_delay(bh);
1789 } else if (retval > 0) {
1790 int ret;
1791 unsigned int status;
1792
1793 if (unlikely(retval != map->m_len)) {
1794 ext4_warning(inode->i_sb,
1795 "ES len assertion failed for inode "
1796 "%lu: retval %d != map->m_len %d",
1797 inode->i_ino, retval, map->m_len);
1798 WARN_ON(1);
1799 }
1800
1801 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1802 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1803 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1804 map->m_pblk, status);
1805 if (ret != 0)
1806 retval = ret;
1807 }
1808
1809out_unlock:
1810 up_read((&EXT4_I(inode)->i_data_sem));
1811
1812 return retval;
1813}
1814
1815/*
1816 * This is a special get_block_t callback which is used by
1817 * ext4_da_write_begin(). It will either return mapped block or
1818 * reserve space for a single block.
1819 *
1820 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1821 * We also have b_blocknr = -1 and b_bdev initialized properly
1822 *
1823 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1824 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1825 * initialized properly.
1826 */
1827int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1828 struct buffer_head *bh, int create)
1829{
1830 struct ext4_map_blocks map;
1831 int ret = 0;
1832
1833 BUG_ON(create == 0);
1834 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1835
1836 map.m_lblk = iblock;
1837 map.m_len = 1;
1838
1839 /*
1840 * first, we need to know whether the block is allocated already
1841 * preallocated blocks are unmapped but should treated
1842 * the same as allocated blocks.
1843 */
1844 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1845 if (ret <= 0)
1846 return ret;
1847
1848 map_bh(bh, inode->i_sb, map.m_pblk);
1849 ext4_update_bh_state(bh, map.m_flags);
1850
1851 if (buffer_unwritten(bh)) {
1852 /* A delayed write to unwritten bh should be marked
1853 * new and mapped. Mapped ensures that we don't do
1854 * get_block multiple times when we write to the same
1855 * offset and new ensures that we do proper zero out
1856 * for partial write.
1857 */
1858 set_buffer_new(bh);
1859 set_buffer_mapped(bh);
1860 }
1861 return 0;
1862}
1863
1864static int bget_one(handle_t *handle, struct buffer_head *bh)
1865{
1866 get_bh(bh);
1867 return 0;
1868}
1869
1870static int bput_one(handle_t *handle, struct buffer_head *bh)
1871{
1872 put_bh(bh);
1873 return 0;
1874}
1875
1876static int __ext4_journalled_writepage(struct page *page,
1877 unsigned int len)
1878{
1879 struct address_space *mapping = page->mapping;
1880 struct inode *inode = mapping->host;
1881 struct buffer_head *page_bufs = NULL;
1882 handle_t *handle = NULL;
1883 int ret = 0, err = 0;
1884 int inline_data = ext4_has_inline_data(inode);
1885 struct buffer_head *inode_bh = NULL;
1886
1887 ClearPageChecked(page);
1888
1889 if (inline_data) {
1890 BUG_ON(page->index != 0);
1891 BUG_ON(len > ext4_get_max_inline_size(inode));
1892 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1893 if (inode_bh == NULL)
1894 goto out;
1895 } else {
1896 page_bufs = page_buffers(page);
1897 if (!page_bufs) {
1898 BUG();
1899 goto out;
1900 }
1901 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1902 NULL, bget_one);
1903 }
1904 /*
1905 * We need to release the page lock before we start the
1906 * journal, so grab a reference so the page won't disappear
1907 * out from under us.
1908 */
1909 get_page(page);
1910 unlock_page(page);
1911
1912 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1913 ext4_writepage_trans_blocks(inode));
1914 if (IS_ERR(handle)) {
1915 ret = PTR_ERR(handle);
1916 put_page(page);
1917 goto out_no_pagelock;
1918 }
1919 BUG_ON(!ext4_handle_valid(handle));
1920
1921 lock_page(page);
1922 put_page(page);
1923 if (page->mapping != mapping) {
1924 /* The page got truncated from under us */
1925 ext4_journal_stop(handle);
1926 ret = 0;
1927 goto out;
1928 }
1929
1930 if (inline_data) {
1931 ret = ext4_mark_inode_dirty(handle, inode);
1932 } else {
1933 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1934 do_journal_get_write_access);
1935
1936 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1937 write_end_fn);
1938 }
1939 if (ret == 0)
1940 ret = err;
Olivier Deprez157378f2022-04-04 15:47:50 +02001941 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1942 if (ret == 0)
1943 ret = err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001944 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1945 err = ext4_journal_stop(handle);
1946 if (!ret)
1947 ret = err;
1948
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001949 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1950out:
1951 unlock_page(page);
1952out_no_pagelock:
Olivier Deprez0e641232021-09-23 10:07:05 +02001953 if (!inline_data && page_bufs)
1954 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1955 NULL, bput_one);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001956 brelse(inode_bh);
1957 return ret;
1958}
1959
1960/*
1961 * Note that we don't need to start a transaction unless we're journaling data
1962 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1963 * need to file the inode to the transaction's list in ordered mode because if
1964 * we are writing back data added by write(), the inode is already there and if
1965 * we are writing back data modified via mmap(), no one guarantees in which
1966 * transaction the data will hit the disk. In case we are journaling data, we
1967 * cannot start transaction directly because transaction start ranks above page
1968 * lock so we have to do some magic.
1969 *
1970 * This function can get called via...
1971 * - ext4_writepages after taking page lock (have journal handle)
1972 * - journal_submit_inode_data_buffers (no journal handle)
1973 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1974 * - grab_page_cache when doing write_begin (have journal handle)
1975 *
1976 * We don't do any block allocation in this function. If we have page with
1977 * multiple blocks we need to write those buffer_heads that are mapped. This
1978 * is important for mmaped based write. So if we do with blocksize 1K
1979 * truncate(f, 1024);
1980 * a = mmap(f, 0, 4096);
1981 * a[0] = 'a';
1982 * truncate(f, 4096);
1983 * we have in the page first buffer_head mapped via page_mkwrite call back
1984 * but other buffer_heads would be unmapped but dirty (dirty done via the
1985 * do_wp_page). So writepage should write the first block. If we modify
1986 * the mmap area beyond 1024 we will again get a page_fault and the
1987 * page_mkwrite callback will do the block allocation and mark the
1988 * buffer_heads mapped.
1989 *
1990 * We redirty the page if we have any buffer_heads that is either delay or
1991 * unwritten in the page.
1992 *
1993 * We can get recursively called as show below.
1994 *
1995 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1996 * ext4_writepage()
1997 *
1998 * But since we don't do any block allocation we should not deadlock.
1999 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2000 */
2001static int ext4_writepage(struct page *page,
2002 struct writeback_control *wbc)
2003{
2004 int ret = 0;
2005 loff_t size;
2006 unsigned int len;
2007 struct buffer_head *page_bufs = NULL;
2008 struct inode *inode = page->mapping->host;
2009 struct ext4_io_submit io_submit;
2010 bool keep_towrite = false;
2011
2012 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
Olivier Deprez0e641232021-09-23 10:07:05 +02002013 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002014 unlock_page(page);
2015 return -EIO;
2016 }
2017
2018 trace_ext4_writepage(page);
2019 size = i_size_read(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00002020 if (page->index == size >> PAGE_SHIFT &&
2021 !ext4_verity_in_progress(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002022 len = size & ~PAGE_MASK;
2023 else
2024 len = PAGE_SIZE;
2025
2026 page_bufs = page_buffers(page);
2027 /*
2028 * We cannot do block allocation or other extent handling in this
2029 * function. If there are buffers needing that, we have to redirty
2030 * the page. But we may reach here when we do a journal commit via
2031 * journal_submit_inode_data_buffers() and in that case we must write
2032 * allocated buffers to achieve data=ordered mode guarantees.
2033 *
2034 * Also, if there is only one buffer per page (the fs block
2035 * size == the page size), if one buffer needs block
2036 * allocation or needs to modify the extent tree to clear the
2037 * unwritten flag, we know that the page can't be written at
2038 * all, so we might as well refuse the write immediately.
2039 * Unfortunately if the block size != page size, we can't as
2040 * easily detect this case using ext4_walk_page_buffers(), but
2041 * for the extremely common case, this is an optimization that
2042 * skips a useless round trip through ext4_bio_write_page().
2043 */
2044 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2045 ext4_bh_delay_or_unwritten)) {
2046 redirty_page_for_writepage(wbc, page);
2047 if ((current->flags & PF_MEMALLOC) ||
2048 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2049 /*
2050 * For memory cleaning there's no point in writing only
2051 * some buffers. So just bail out. Warn if we came here
2052 * from direct reclaim.
2053 */
2054 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2055 == PF_MEMALLOC);
2056 unlock_page(page);
2057 return 0;
2058 }
2059 keep_towrite = true;
2060 }
2061
2062 if (PageChecked(page) && ext4_should_journal_data(inode))
2063 /*
2064 * It's mmapped pagecache. Add buffers and journal it. There
2065 * doesn't seem much point in redirtying the page here.
2066 */
2067 return __ext4_journalled_writepage(page, len);
2068
2069 ext4_io_submit_init(&io_submit, wbc);
2070 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2071 if (!io_submit.io_end) {
2072 redirty_page_for_writepage(wbc, page);
2073 unlock_page(page);
2074 return -ENOMEM;
2075 }
2076 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2077 ext4_io_submit(&io_submit);
2078 /* Drop io_end reference we got from init */
2079 ext4_put_io_end_defer(io_submit.io_end);
2080 return ret;
2081}
2082
2083static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2084{
2085 int len;
2086 loff_t size;
2087 int err;
2088
2089 BUG_ON(page->index != mpd->first_page);
2090 clear_page_dirty_for_io(page);
2091 /*
2092 * We have to be very careful here! Nothing protects writeback path
2093 * against i_size changes and the page can be writeably mapped into
2094 * page tables. So an application can be growing i_size and writing
2095 * data through mmap while writeback runs. clear_page_dirty_for_io()
2096 * write-protects our page in page tables and the page cannot get
2097 * written to again until we release page lock. So only after
2098 * clear_page_dirty_for_io() we are safe to sample i_size for
2099 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2100 * on the barrier provided by TestClearPageDirty in
2101 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2102 * after page tables are updated.
2103 */
2104 size = i_size_read(mpd->inode);
David Brazdil0f672f62019-12-10 10:32:29 +00002105 if (page->index == size >> PAGE_SHIFT &&
2106 !ext4_verity_in_progress(mpd->inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002107 len = size & ~PAGE_MASK;
2108 else
2109 len = PAGE_SIZE;
2110 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2111 if (!err)
2112 mpd->wbc->nr_to_write--;
2113 mpd->first_page++;
2114
2115 return err;
2116}
2117
Olivier Deprez157378f2022-04-04 15:47:50 +02002118#define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002119
2120/*
2121 * mballoc gives us at most this number of blocks...
2122 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2123 * The rest of mballoc seems to handle chunks up to full group size.
2124 */
2125#define MAX_WRITEPAGES_EXTENT_LEN 2048
2126
2127/*
2128 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2129 *
2130 * @mpd - extent of blocks
2131 * @lblk - logical number of the block in the file
2132 * @bh - buffer head we want to add to the extent
2133 *
2134 * The function is used to collect contig. blocks in the same state. If the
2135 * buffer doesn't require mapping for writeback and we haven't started the
2136 * extent of buffers to map yet, the function returns 'true' immediately - the
2137 * caller can write the buffer right away. Otherwise the function returns true
2138 * if the block has been added to the extent, false if the block couldn't be
2139 * added.
2140 */
2141static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2142 struct buffer_head *bh)
2143{
2144 struct ext4_map_blocks *map = &mpd->map;
2145
2146 /* Buffer that doesn't need mapping for writeback? */
2147 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2148 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2149 /* So far no extent to map => we write the buffer right away */
2150 if (map->m_len == 0)
2151 return true;
2152 return false;
2153 }
2154
2155 /* First block in the extent? */
2156 if (map->m_len == 0) {
2157 /* We cannot map unless handle is started... */
2158 if (!mpd->do_map)
2159 return false;
2160 map->m_lblk = lblk;
2161 map->m_len = 1;
2162 map->m_flags = bh->b_state & BH_FLAGS;
2163 return true;
2164 }
2165
2166 /* Don't go larger than mballoc is willing to allocate */
2167 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2168 return false;
2169
2170 /* Can we merge the block to our big extent? */
2171 if (lblk == map->m_lblk + map->m_len &&
2172 (bh->b_state & BH_FLAGS) == map->m_flags) {
2173 map->m_len++;
2174 return true;
2175 }
2176 return false;
2177}
2178
2179/*
2180 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2181 *
2182 * @mpd - extent of blocks for mapping
2183 * @head - the first buffer in the page
2184 * @bh - buffer we should start processing from
2185 * @lblk - logical number of the block in the file corresponding to @bh
2186 *
2187 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2188 * the page for IO if all buffers in this page were mapped and there's no
2189 * accumulated extent of buffers to map or add buffers in the page to the
2190 * extent of buffers to map. The function returns 1 if the caller can continue
2191 * by processing the next page, 0 if it should stop adding buffers to the
2192 * extent to map because we cannot extend it anymore. It can also return value
2193 * < 0 in case of error during IO submission.
2194 */
2195static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2196 struct buffer_head *head,
2197 struct buffer_head *bh,
2198 ext4_lblk_t lblk)
2199{
2200 struct inode *inode = mpd->inode;
2201 int err;
2202 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2203 >> inode->i_blkbits;
2204
David Brazdil0f672f62019-12-10 10:32:29 +00002205 if (ext4_verity_in_progress(inode))
2206 blocks = EXT_MAX_BLOCKS;
2207
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002208 do {
2209 BUG_ON(buffer_locked(bh));
2210
2211 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2212 /* Found extent to map? */
2213 if (mpd->map.m_len)
2214 return 0;
2215 /* Buffer needs mapping and handle is not started? */
2216 if (!mpd->do_map)
2217 return 0;
2218 /* Everything mapped so far and we hit EOF */
2219 break;
2220 }
2221 } while (lblk++, (bh = bh->b_this_page) != head);
2222 /* So far everything mapped? Submit the page for IO. */
2223 if (mpd->map.m_len == 0) {
2224 err = mpage_submit_page(mpd, head->b_page);
2225 if (err < 0)
2226 return err;
2227 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002228 if (lblk >= blocks) {
2229 mpd->scanned_until_end = 1;
2230 return 0;
2231 }
2232 return 1;
2233}
2234
2235/*
2236 * mpage_process_page - update page buffers corresponding to changed extent and
2237 * may submit fully mapped page for IO
2238 *
2239 * @mpd - description of extent to map, on return next extent to map
2240 * @m_lblk - logical block mapping.
2241 * @m_pblk - corresponding physical mapping.
2242 * @map_bh - determines on return whether this page requires any further
2243 * mapping or not.
2244 * Scan given page buffers corresponding to changed extent and update buffer
2245 * state according to new extent state.
2246 * We map delalloc buffers to their physical location, clear unwritten bits.
2247 * If the given page is not fully mapped, we update @map to the next extent in
2248 * the given page that needs mapping & return @map_bh as true.
2249 */
2250static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2251 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2252 bool *map_bh)
2253{
2254 struct buffer_head *head, *bh;
2255 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2256 ext4_lblk_t lblk = *m_lblk;
2257 ext4_fsblk_t pblock = *m_pblk;
2258 int err = 0;
2259 int blkbits = mpd->inode->i_blkbits;
2260 ssize_t io_end_size = 0;
2261 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2262
2263 bh = head = page_buffers(page);
2264 do {
2265 if (lblk < mpd->map.m_lblk)
2266 continue;
2267 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2268 /*
2269 * Buffer after end of mapped extent.
2270 * Find next buffer in the page to map.
2271 */
2272 mpd->map.m_len = 0;
2273 mpd->map.m_flags = 0;
2274 io_end_vec->size += io_end_size;
2275 io_end_size = 0;
2276
2277 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2278 if (err > 0)
2279 err = 0;
2280 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2281 io_end_vec = ext4_alloc_io_end_vec(io_end);
2282 if (IS_ERR(io_end_vec)) {
2283 err = PTR_ERR(io_end_vec);
2284 goto out;
2285 }
2286 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2287 }
2288 *map_bh = true;
2289 goto out;
2290 }
2291 if (buffer_delay(bh)) {
2292 clear_buffer_delay(bh);
2293 bh->b_blocknr = pblock++;
2294 }
2295 clear_buffer_unwritten(bh);
2296 io_end_size += (1 << blkbits);
2297 } while (lblk++, (bh = bh->b_this_page) != head);
2298
2299 io_end_vec->size += io_end_size;
2300 io_end_size = 0;
2301 *map_bh = false;
2302out:
2303 *m_lblk = lblk;
2304 *m_pblk = pblock;
2305 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002306}
2307
2308/*
2309 * mpage_map_buffers - update buffers corresponding to changed extent and
2310 * submit fully mapped pages for IO
2311 *
2312 * @mpd - description of extent to map, on return next extent to map
2313 *
2314 * Scan buffers corresponding to changed extent (we expect corresponding pages
2315 * to be already locked) and update buffer state according to new extent state.
2316 * We map delalloc buffers to their physical location, clear unwritten bits,
2317 * and mark buffers as uninit when we perform writes to unwritten extents
2318 * and do extent conversion after IO is finished. If the last page is not fully
2319 * mapped, we update @map to the next extent in the last page that needs
2320 * mapping. Otherwise we submit the page for IO.
2321 */
2322static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2323{
2324 struct pagevec pvec;
2325 int nr_pages, i;
2326 struct inode *inode = mpd->inode;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002327 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2328 pgoff_t start, end;
2329 ext4_lblk_t lblk;
Olivier Deprez157378f2022-04-04 15:47:50 +02002330 ext4_fsblk_t pblock;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002331 int err;
Olivier Deprez157378f2022-04-04 15:47:50 +02002332 bool map_bh = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002333
2334 start = mpd->map.m_lblk >> bpp_bits;
2335 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2336 lblk = start << bpp_bits;
2337 pblock = mpd->map.m_pblk;
2338
2339 pagevec_init(&pvec);
2340 while (start <= end) {
2341 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2342 &start, end);
2343 if (nr_pages == 0)
2344 break;
2345 for (i = 0; i < nr_pages; i++) {
2346 struct page *page = pvec.pages[i];
2347
Olivier Deprez157378f2022-04-04 15:47:50 +02002348 err = mpage_process_page(mpd, page, &lblk, &pblock,
2349 &map_bh);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002350 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02002351 * If map_bh is true, means page may require further bh
2352 * mapping, or maybe the page was submitted for IO.
2353 * So we return to call further extent mapping.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002354 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002355 if (err < 0 || map_bh)
2356 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002357 /* Page fully mapped - let IO run! */
2358 err = mpage_submit_page(mpd, page);
Olivier Deprez157378f2022-04-04 15:47:50 +02002359 if (err < 0)
2360 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002361 }
2362 pagevec_release(&pvec);
2363 }
2364 /* Extent fully mapped and matches with page boundary. We are done. */
2365 mpd->map.m_len = 0;
2366 mpd->map.m_flags = 0;
2367 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02002368out:
2369 pagevec_release(&pvec);
2370 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002371}
2372
2373static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2374{
2375 struct inode *inode = mpd->inode;
2376 struct ext4_map_blocks *map = &mpd->map;
2377 int get_blocks_flags;
2378 int err, dioread_nolock;
2379
2380 trace_ext4_da_write_pages_extent(inode, map);
2381 /*
2382 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2383 * to convert an unwritten extent to be initialized (in the case
2384 * where we have written into one or more preallocated blocks). It is
2385 * possible that we're going to need more metadata blocks than
2386 * previously reserved. However we must not fail because we're in
2387 * writeback and there is nothing we can do about it so it might result
2388 * in data loss. So use reserved blocks to allocate metadata if
2389 * possible.
2390 *
2391 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2392 * the blocks in question are delalloc blocks. This indicates
2393 * that the blocks and quotas has already been checked when
2394 * the data was copied into the page cache.
2395 */
2396 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2397 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2398 EXT4_GET_BLOCKS_IO_SUBMIT;
2399 dioread_nolock = ext4_should_dioread_nolock(inode);
2400 if (dioread_nolock)
2401 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
Olivier Deprez157378f2022-04-04 15:47:50 +02002402 if (map->m_flags & BIT(BH_Delay))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002403 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2404
2405 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2406 if (err < 0)
2407 return err;
2408 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2409 if (!mpd->io_submit.io_end->handle &&
2410 ext4_handle_valid(handle)) {
2411 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2412 handle->h_rsv_handle = NULL;
2413 }
2414 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2415 }
2416
2417 BUG_ON(map->m_len == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002418 return 0;
2419}
2420
2421/*
2422 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2423 * mpd->len and submit pages underlying it for IO
2424 *
2425 * @handle - handle for journal operations
2426 * @mpd - extent to map
2427 * @give_up_on_write - we set this to true iff there is a fatal error and there
2428 * is no hope of writing the data. The caller should discard
2429 * dirty pages to avoid infinite loops.
2430 *
2431 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2432 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2433 * them to initialized or split the described range from larger unwritten
2434 * extent. Note that we need not map all the described range since allocation
2435 * can return less blocks or the range is covered by more unwritten extents. We
2436 * cannot map more because we are limited by reserved transaction credits. On
2437 * the other hand we always make sure that the last touched page is fully
2438 * mapped so that it can be written out (and thus forward progress is
2439 * guaranteed). After mapping we submit all mapped pages for IO.
2440 */
2441static int mpage_map_and_submit_extent(handle_t *handle,
2442 struct mpage_da_data *mpd,
2443 bool *give_up_on_write)
2444{
2445 struct inode *inode = mpd->inode;
2446 struct ext4_map_blocks *map = &mpd->map;
2447 int err;
2448 loff_t disksize;
2449 int progress = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02002450 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2451 struct ext4_io_end_vec *io_end_vec;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002452
Olivier Deprez157378f2022-04-04 15:47:50 +02002453 io_end_vec = ext4_alloc_io_end_vec(io_end);
2454 if (IS_ERR(io_end_vec))
2455 return PTR_ERR(io_end_vec);
2456 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002457 do {
2458 err = mpage_map_one_extent(handle, mpd);
2459 if (err < 0) {
2460 struct super_block *sb = inode->i_sb;
2461
2462 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
Olivier Deprez157378f2022-04-04 15:47:50 +02002463 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002464 goto invalidate_dirty_pages;
2465 /*
2466 * Let the uper layers retry transient errors.
2467 * In the case of ENOSPC, if ext4_count_free_blocks()
2468 * is non-zero, a commit should free up blocks.
2469 */
2470 if ((err == -ENOMEM) ||
2471 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2472 if (progress)
2473 goto update_disksize;
2474 return err;
2475 }
2476 ext4_msg(sb, KERN_CRIT,
2477 "Delayed block allocation failed for "
2478 "inode %lu at logical offset %llu with"
2479 " max blocks %u with error %d",
2480 inode->i_ino,
2481 (unsigned long long)map->m_lblk,
2482 (unsigned)map->m_len, -err);
2483 ext4_msg(sb, KERN_CRIT,
2484 "This should not happen!! Data will "
2485 "be lost\n");
2486 if (err == -ENOSPC)
2487 ext4_print_free_blocks(inode);
2488 invalidate_dirty_pages:
2489 *give_up_on_write = true;
2490 return err;
2491 }
2492 progress = 1;
2493 /*
2494 * Update buffer state, submit mapped pages, and get us new
2495 * extent to map
2496 */
2497 err = mpage_map_and_submit_buffers(mpd);
2498 if (err < 0)
2499 goto update_disksize;
2500 } while (map->m_len);
2501
2502update_disksize:
2503 /*
2504 * Update on-disk size after IO is submitted. Races with
2505 * truncate are avoided by checking i_size under i_data_sem.
2506 */
2507 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
Olivier Deprez0e641232021-09-23 10:07:05 +02002508 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002509 int err2;
2510 loff_t i_size;
2511
2512 down_write(&EXT4_I(inode)->i_data_sem);
2513 i_size = i_size_read(inode);
2514 if (disksize > i_size)
2515 disksize = i_size;
2516 if (disksize > EXT4_I(inode)->i_disksize)
2517 EXT4_I(inode)->i_disksize = disksize;
2518 up_write(&EXT4_I(inode)->i_data_sem);
2519 err2 = ext4_mark_inode_dirty(handle, inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02002520 if (err2) {
2521 ext4_error_err(inode->i_sb, -err2,
2522 "Failed to mark inode %lu dirty",
2523 inode->i_ino);
2524 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002525 if (!err)
2526 err = err2;
2527 }
2528 return err;
2529}
2530
2531/*
2532 * Calculate the total number of credits to reserve for one writepages
2533 * iteration. This is called from ext4_writepages(). We map an extent of
2534 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2535 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2536 * bpp - 1 blocks in bpp different extents.
2537 */
2538static int ext4_da_writepages_trans_blocks(struct inode *inode)
2539{
2540 int bpp = ext4_journal_blocks_per_page(inode);
2541
2542 return ext4_meta_trans_blocks(inode,
2543 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2544}
2545
2546/*
2547 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2548 * and underlying extent to map
2549 *
2550 * @mpd - where to look for pages
2551 *
2552 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2553 * IO immediately. When we find a page which isn't mapped we start accumulating
2554 * extent of buffers underlying these pages that needs mapping (formed by
2555 * either delayed or unwritten buffers). We also lock the pages containing
2556 * these buffers. The extent found is returned in @mpd structure (starting at
2557 * mpd->lblk with length mpd->len blocks).
2558 *
2559 * Note that this function can attach bios to one io_end structure which are
2560 * neither logically nor physically contiguous. Although it may seem as an
2561 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2562 * case as we need to track IO to all buffers underlying a page in one io_end.
2563 */
2564static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2565{
2566 struct address_space *mapping = mpd->inode->i_mapping;
2567 struct pagevec pvec;
2568 unsigned int nr_pages;
2569 long left = mpd->wbc->nr_to_write;
2570 pgoff_t index = mpd->first_page;
2571 pgoff_t end = mpd->last_page;
David Brazdil0f672f62019-12-10 10:32:29 +00002572 xa_mark_t tag;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002573 int i, err = 0;
2574 int blkbits = mpd->inode->i_blkbits;
2575 ext4_lblk_t lblk;
2576 struct buffer_head *head;
2577
2578 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2579 tag = PAGECACHE_TAG_TOWRITE;
2580 else
2581 tag = PAGECACHE_TAG_DIRTY;
2582
2583 pagevec_init(&pvec);
2584 mpd->map.m_len = 0;
2585 mpd->next_page = index;
2586 while (index <= end) {
2587 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2588 tag);
2589 if (nr_pages == 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02002590 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002591
2592 for (i = 0; i < nr_pages; i++) {
2593 struct page *page = pvec.pages[i];
2594
2595 /*
2596 * Accumulated enough dirty pages? This doesn't apply
2597 * to WB_SYNC_ALL mode. For integrity sync we have to
2598 * keep going because someone may be concurrently
2599 * dirtying pages, and we might have synced a lot of
2600 * newly appeared dirty pages, but have not synced all
2601 * of the old dirty pages.
2602 */
2603 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2604 goto out;
2605
2606 /* If we can't merge this page, we are done. */
2607 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2608 goto out;
2609
2610 lock_page(page);
2611 /*
2612 * If the page is no longer dirty, or its mapping no
2613 * longer corresponds to inode we are writing (which
2614 * means it has been truncated or invalidated), or the
2615 * page is already under writeback and we are not doing
2616 * a data integrity writeback, skip the page
2617 */
2618 if (!PageDirty(page) ||
2619 (PageWriteback(page) &&
2620 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2621 unlikely(page->mapping != mapping)) {
2622 unlock_page(page);
2623 continue;
2624 }
2625
2626 wait_on_page_writeback(page);
2627 BUG_ON(PageWriteback(page));
2628
2629 if (mpd->map.m_len == 0)
2630 mpd->first_page = page->index;
2631 mpd->next_page = page->index + 1;
2632 /* Add all dirty buffers to mpd */
2633 lblk = ((ext4_lblk_t)page->index) <<
2634 (PAGE_SHIFT - blkbits);
2635 head = page_buffers(page);
2636 err = mpage_process_page_bufs(mpd, head, head, lblk);
2637 if (err <= 0)
2638 goto out;
2639 err = 0;
2640 left--;
2641 }
2642 pagevec_release(&pvec);
2643 cond_resched();
2644 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002645 mpd->scanned_until_end = 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002646 return 0;
2647out:
2648 pagevec_release(&pvec);
2649 return err;
2650}
2651
2652static int ext4_writepages(struct address_space *mapping,
2653 struct writeback_control *wbc)
2654{
2655 pgoff_t writeback_index = 0;
2656 long nr_to_write = wbc->nr_to_write;
2657 int range_whole = 0;
2658 int cycled = 1;
2659 handle_t *handle = NULL;
2660 struct mpage_da_data mpd;
2661 struct inode *inode = mapping->host;
2662 int needed_blocks, rsv_blocks = 0, ret = 0;
2663 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002664 struct blk_plug plug;
2665 bool give_up_on_write = false;
2666
2667 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2668 return -EIO;
2669
Olivier Deprez0e641232021-09-23 10:07:05 +02002670 percpu_down_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002671 trace_ext4_writepages(inode, wbc);
2672
2673 /*
2674 * No pages to write? This is mainly a kludge to avoid starting
2675 * a transaction for special inodes like journal inode on last iput()
2676 * because that could violate lock ordering on umount
2677 */
2678 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2679 goto out_writepages;
2680
2681 if (ext4_should_journal_data(inode)) {
2682 ret = generic_writepages(mapping, wbc);
2683 goto out_writepages;
2684 }
2685
2686 /*
2687 * If the filesystem has aborted, it is read-only, so return
2688 * right away instead of dumping stack traces later on that
2689 * will obscure the real source of the problem. We test
2690 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2691 * the latter could be true if the filesystem is mounted
2692 * read-only, and in that case, ext4_writepages should
2693 * *never* be called, so if that ever happens, we would want
2694 * the stack trace.
2695 */
2696 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
Olivier Deprez157378f2022-04-04 15:47:50 +02002697 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002698 ret = -EROFS;
2699 goto out_writepages;
2700 }
2701
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002702 /*
2703 * If we have inline data and arrive here, it means that
2704 * we will soon create the block for the 1st page, so
2705 * we'd better clear the inline data here.
2706 */
2707 if (ext4_has_inline_data(inode)) {
2708 /* Just inode will be modified... */
2709 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2710 if (IS_ERR(handle)) {
2711 ret = PTR_ERR(handle);
2712 goto out_writepages;
2713 }
2714 BUG_ON(ext4_test_inode_state(inode,
2715 EXT4_STATE_MAY_INLINE_DATA));
2716 ext4_destroy_inline_data(handle, inode);
2717 ext4_journal_stop(handle);
2718 }
2719
David Brazdil0f672f62019-12-10 10:32:29 +00002720 if (ext4_should_dioread_nolock(inode)) {
2721 /*
2722 * We may need to convert up to one extent per block in
2723 * the page and we may dirty the inode.
2724 */
2725 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2726 PAGE_SIZE >> inode->i_blkbits);
2727 }
2728
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002729 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2730 range_whole = 1;
2731
2732 if (wbc->range_cyclic) {
2733 writeback_index = mapping->writeback_index;
2734 if (writeback_index)
2735 cycled = 0;
2736 mpd.first_page = writeback_index;
2737 mpd.last_page = -1;
2738 } else {
2739 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2740 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2741 }
2742
2743 mpd.inode = inode;
2744 mpd.wbc = wbc;
2745 ext4_io_submit_init(&mpd.io_submit, wbc);
2746retry:
2747 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2748 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002749 blk_start_plug(&plug);
2750
2751 /*
2752 * First writeback pages that don't need mapping - we can avoid
2753 * starting a transaction unnecessarily and also avoid being blocked
2754 * in the block layer on device congestion while having transaction
2755 * started.
2756 */
2757 mpd.do_map = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02002758 mpd.scanned_until_end = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002759 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2760 if (!mpd.io_submit.io_end) {
2761 ret = -ENOMEM;
2762 goto unplug;
2763 }
2764 ret = mpage_prepare_extent_to_map(&mpd);
David Brazdil0f672f62019-12-10 10:32:29 +00002765 /* Unlock pages we didn't use */
2766 mpage_release_unused_pages(&mpd, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002767 /* Submit prepared bio */
2768 ext4_io_submit(&mpd.io_submit);
2769 ext4_put_io_end_defer(mpd.io_submit.io_end);
2770 mpd.io_submit.io_end = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002771 if (ret < 0)
2772 goto unplug;
2773
Olivier Deprez157378f2022-04-04 15:47:50 +02002774 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002775 /* For each extent of pages we use new io_end */
2776 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2777 if (!mpd.io_submit.io_end) {
2778 ret = -ENOMEM;
2779 break;
2780 }
2781
2782 /*
2783 * We have two constraints: We find one extent to map and we
2784 * must always write out whole page (makes a difference when
2785 * blocksize < pagesize) so that we don't block on IO when we
2786 * try to write out the rest of the page. Journalled mode is
2787 * not supported by delalloc.
2788 */
2789 BUG_ON(ext4_should_journal_data(inode));
2790 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2791
2792 /* start a new transaction */
2793 handle = ext4_journal_start_with_reserve(inode,
2794 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2795 if (IS_ERR(handle)) {
2796 ret = PTR_ERR(handle);
2797 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2798 "%ld pages, ino %lu; err %d", __func__,
2799 wbc->nr_to_write, inode->i_ino, ret);
2800 /* Release allocated io_end */
2801 ext4_put_io_end(mpd.io_submit.io_end);
2802 mpd.io_submit.io_end = NULL;
2803 break;
2804 }
2805 mpd.do_map = 1;
2806
2807 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2808 ret = mpage_prepare_extent_to_map(&mpd);
Olivier Deprez157378f2022-04-04 15:47:50 +02002809 if (!ret && mpd.map.m_len)
2810 ret = mpage_map_and_submit_extent(handle, &mpd,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002811 &give_up_on_write);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002812 /*
2813 * Caution: If the handle is synchronous,
2814 * ext4_journal_stop() can wait for transaction commit
2815 * to finish which may depend on writeback of pages to
2816 * complete or on page lock to be released. In that
Olivier Deprez157378f2022-04-04 15:47:50 +02002817 * case, we have to wait until after we have
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002818 * submitted all the IO, released page locks we hold,
2819 * and dropped io_end reference (for extent conversion
2820 * to be able to complete) before stopping the handle.
2821 */
2822 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2823 ext4_journal_stop(handle);
2824 handle = NULL;
2825 mpd.do_map = 0;
2826 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002827 /* Unlock pages we didn't use */
2828 mpage_release_unused_pages(&mpd, give_up_on_write);
David Brazdil0f672f62019-12-10 10:32:29 +00002829 /* Submit prepared bio */
2830 ext4_io_submit(&mpd.io_submit);
2831
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002832 /*
2833 * Drop our io_end reference we got from init. We have
2834 * to be careful and use deferred io_end finishing if
2835 * we are still holding the transaction as we can
2836 * release the last reference to io_end which may end
2837 * up doing unwritten extent conversion.
2838 */
2839 if (handle) {
2840 ext4_put_io_end_defer(mpd.io_submit.io_end);
2841 ext4_journal_stop(handle);
2842 } else
2843 ext4_put_io_end(mpd.io_submit.io_end);
2844 mpd.io_submit.io_end = NULL;
2845
2846 if (ret == -ENOSPC && sbi->s_journal) {
2847 /*
2848 * Commit the transaction which would
2849 * free blocks released in the transaction
2850 * and try again
2851 */
2852 jbd2_journal_force_commit_nested(sbi->s_journal);
2853 ret = 0;
2854 continue;
2855 }
2856 /* Fatal error - ENOMEM, EIO... */
2857 if (ret)
2858 break;
2859 }
2860unplug:
2861 blk_finish_plug(&plug);
2862 if (!ret && !cycled && wbc->nr_to_write > 0) {
2863 cycled = 1;
2864 mpd.last_page = writeback_index - 1;
2865 mpd.first_page = 0;
2866 goto retry;
2867 }
2868
2869 /* Update index */
2870 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2871 /*
2872 * Set the writeback_index so that range_cyclic
2873 * mode will write it back later
2874 */
2875 mapping->writeback_index = mpd.first_page;
2876
2877out_writepages:
2878 trace_ext4_writepages_result(inode, wbc, ret,
2879 nr_to_write - wbc->nr_to_write);
Olivier Deprez0e641232021-09-23 10:07:05 +02002880 percpu_up_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002881 return ret;
2882}
2883
2884static int ext4_dax_writepages(struct address_space *mapping,
2885 struct writeback_control *wbc)
2886{
2887 int ret;
2888 long nr_to_write = wbc->nr_to_write;
2889 struct inode *inode = mapping->host;
2890 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2891
2892 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2893 return -EIO;
2894
Olivier Deprez0e641232021-09-23 10:07:05 +02002895 percpu_down_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002896 trace_ext4_writepages(inode, wbc);
2897
Olivier Deprez157378f2022-04-04 15:47:50 +02002898 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002899 trace_ext4_writepages_result(inode, wbc, ret,
2900 nr_to_write - wbc->nr_to_write);
Olivier Deprez0e641232021-09-23 10:07:05 +02002901 percpu_up_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002902 return ret;
2903}
2904
2905static int ext4_nonda_switch(struct super_block *sb)
2906{
2907 s64 free_clusters, dirty_clusters;
2908 struct ext4_sb_info *sbi = EXT4_SB(sb);
2909
2910 /*
2911 * switch to non delalloc mode if we are running low
2912 * on free block. The free block accounting via percpu
2913 * counters can get slightly wrong with percpu_counter_batch getting
2914 * accumulated on each CPU without updating global counters
2915 * Delalloc need an accurate free block accounting. So switch
2916 * to non delalloc when we are near to error range.
2917 */
2918 free_clusters =
2919 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2920 dirty_clusters =
2921 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2922 /*
2923 * Start pushing delalloc when 1/2 of free blocks are dirty.
2924 */
2925 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2926 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2927
2928 if (2 * free_clusters < 3 * dirty_clusters ||
2929 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2930 /*
2931 * free block count is less than 150% of dirty blocks
2932 * or free blocks is less than watermark
2933 */
2934 return 1;
2935 }
2936 return 0;
2937}
2938
2939/* We always reserve for an inode update; the superblock could be there too */
2940static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2941{
2942 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2943 return 1;
2944
2945 if (pos + len <= 0x7fffffffULL)
2946 return 1;
2947
2948 /* We might need to update the superblock to set LARGE_FILE */
2949 return 2;
2950}
2951
2952static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2953 loff_t pos, unsigned len, unsigned flags,
2954 struct page **pagep, void **fsdata)
2955{
2956 int ret, retries = 0;
2957 struct page *page;
2958 pgoff_t index;
2959 struct inode *inode = mapping->host;
2960 handle_t *handle;
2961
2962 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2963 return -EIO;
2964
2965 index = pos >> PAGE_SHIFT;
2966
David Brazdil0f672f62019-12-10 10:32:29 +00002967 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2968 ext4_verity_in_progress(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002969 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2970 return ext4_write_begin(file, mapping, pos,
2971 len, flags, pagep, fsdata);
2972 }
2973 *fsdata = (void *)0;
2974 trace_ext4_da_write_begin(inode, pos, len, flags);
2975
2976 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2977 ret = ext4_da_write_inline_data_begin(mapping, inode,
2978 pos, len, flags,
2979 pagep, fsdata);
2980 if (ret < 0)
2981 return ret;
2982 if (ret == 1)
2983 return 0;
2984 }
2985
2986 /*
2987 * grab_cache_page_write_begin() can take a long time if the
2988 * system is thrashing due to memory pressure, or if the page
2989 * is being written back. So grab it first before we start
2990 * the transaction handle. This also allows us to allocate
2991 * the page (if needed) without using GFP_NOFS.
2992 */
2993retry_grab:
2994 page = grab_cache_page_write_begin(mapping, index, flags);
2995 if (!page)
2996 return -ENOMEM;
2997 unlock_page(page);
2998
2999 /*
3000 * With delayed allocation, we don't log the i_disksize update
3001 * if there is delayed block allocation. But we still need
3002 * to journalling the i_disksize update if writes to the end
3003 * of file which has an already mapped buffer.
3004 */
3005retry_journal:
3006 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3007 ext4_da_write_credits(inode, pos, len));
3008 if (IS_ERR(handle)) {
3009 put_page(page);
3010 return PTR_ERR(handle);
3011 }
3012
3013 lock_page(page);
3014 if (page->mapping != mapping) {
3015 /* The page got truncated from under us */
3016 unlock_page(page);
3017 put_page(page);
3018 ext4_journal_stop(handle);
3019 goto retry_grab;
3020 }
3021 /* In case writeback began while the page was unlocked */
3022 wait_for_stable_page(page);
3023
David Brazdil0f672f62019-12-10 10:32:29 +00003024#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003025 ret = ext4_block_write_begin(page, pos, len,
3026 ext4_da_get_block_prep);
3027#else
3028 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3029#endif
3030 if (ret < 0) {
3031 unlock_page(page);
3032 ext4_journal_stop(handle);
3033 /*
3034 * block_write_begin may have instantiated a few blocks
3035 * outside i_size. Trim these off again. Don't need
3036 * i_size_read because we hold i_mutex.
3037 */
3038 if (pos + len > inode->i_size)
3039 ext4_truncate_failed_write(inode);
3040
3041 if (ret == -ENOSPC &&
3042 ext4_should_retry_alloc(inode->i_sb, &retries))
3043 goto retry_journal;
3044
3045 put_page(page);
3046 return ret;
3047 }
3048
3049 *pagep = page;
3050 return ret;
3051}
3052
3053/*
3054 * Check if we should update i_disksize
3055 * when write to the end of file but not require block allocation
3056 */
3057static int ext4_da_should_update_i_disksize(struct page *page,
3058 unsigned long offset)
3059{
3060 struct buffer_head *bh;
3061 struct inode *inode = page->mapping->host;
3062 unsigned int idx;
3063 int i;
3064
3065 bh = page_buffers(page);
3066 idx = offset >> inode->i_blkbits;
3067
3068 for (i = 0; i < idx; i++)
3069 bh = bh->b_this_page;
3070
3071 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3072 return 0;
3073 return 1;
3074}
3075
3076static int ext4_da_write_end(struct file *file,
3077 struct address_space *mapping,
3078 loff_t pos, unsigned len, unsigned copied,
3079 struct page *page, void *fsdata)
3080{
3081 struct inode *inode = mapping->host;
3082 int ret = 0, ret2;
3083 handle_t *handle = ext4_journal_current_handle();
3084 loff_t new_i_size;
3085 unsigned long start, end;
3086 int write_mode = (int)(unsigned long)fsdata;
3087
3088 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3089 return ext4_write_end(file, mapping, pos,
3090 len, copied, page, fsdata);
3091
3092 trace_ext4_da_write_end(inode, pos, len, copied);
3093 start = pos & (PAGE_SIZE - 1);
3094 end = start + copied - 1;
3095
3096 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02003097 * Since we are holding inode lock, we are sure i_disksize <=
3098 * i_size. We also know that if i_disksize < i_size, there are
3099 * delalloc writes pending in the range upto i_size. If the end of
3100 * the current write is <= i_size, there's no need to touch
3101 * i_disksize since writeback will push i_disksize upto i_size
3102 * eventually. If the end of the current write is > i_size and
3103 * inside an allocated block (ext4_da_should_update_i_disksize()
3104 * check), we need to update i_disksize here as neither
3105 * ext4_writepage() nor certain ext4_writepages() paths not
3106 * allocating blocks update i_disksize.
3107 *
3108 * Note that we defer inode dirtying to generic_write_end() /
3109 * ext4_da_write_inline_data_end().
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003110 */
3111 new_i_size = pos + copied;
Olivier Deprez157378f2022-04-04 15:47:50 +02003112 if (copied && new_i_size > inode->i_size) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003113 if (ext4_has_inline_data(inode) ||
Olivier Deprez157378f2022-04-04 15:47:50 +02003114 ext4_da_should_update_i_disksize(page, end))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003115 ext4_update_i_disksize(inode, new_i_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003116 }
3117
3118 if (write_mode != CONVERT_INLINE_DATA &&
3119 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3120 ext4_has_inline_data(inode))
Olivier Deprez157378f2022-04-04 15:47:50 +02003121 ret = ext4_da_write_inline_data_end(inode, pos, len, copied,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003122 page);
3123 else
Olivier Deprez157378f2022-04-04 15:47:50 +02003124 ret = generic_write_end(file, mapping, pos, len, copied,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003125 page, fsdata);
3126
Olivier Deprez157378f2022-04-04 15:47:50 +02003127 copied = ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003128 ret2 = ext4_journal_stop(handle);
Olivier Deprez157378f2022-04-04 15:47:50 +02003129 if (unlikely(ret2 && !ret))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003130 ret = ret2;
3131
3132 return ret ? ret : copied;
3133}
3134
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003135/*
3136 * Force all delayed allocation blocks to be allocated for a given inode.
3137 */
3138int ext4_alloc_da_blocks(struct inode *inode)
3139{
3140 trace_ext4_alloc_da_blocks(inode);
3141
3142 if (!EXT4_I(inode)->i_reserved_data_blocks)
3143 return 0;
3144
3145 /*
3146 * We do something simple for now. The filemap_flush() will
3147 * also start triggering a write of the data blocks, which is
3148 * not strictly speaking necessary (and for users of
3149 * laptop_mode, not even desirable). However, to do otherwise
3150 * would require replicating code paths in:
3151 *
3152 * ext4_writepages() ->
3153 * write_cache_pages() ---> (via passed in callback function)
3154 * __mpage_da_writepage() -->
3155 * mpage_add_bh_to_extent()
3156 * mpage_da_map_blocks()
3157 *
3158 * The problem is that write_cache_pages(), located in
3159 * mm/page-writeback.c, marks pages clean in preparation for
3160 * doing I/O, which is not desirable if we're not planning on
3161 * doing I/O at all.
3162 *
3163 * We could call write_cache_pages(), and then redirty all of
3164 * the pages by calling redirty_page_for_writepage() but that
3165 * would be ugly in the extreme. So instead we would need to
3166 * replicate parts of the code in the above functions,
3167 * simplifying them because we wouldn't actually intend to
3168 * write out the pages, but rather only collect contiguous
3169 * logical block extents, call the multi-block allocator, and
3170 * then update the buffer heads with the block allocations.
3171 *
3172 * For now, though, we'll cheat by calling filemap_flush(),
3173 * which will map the blocks, and start the I/O, but not
3174 * actually wait for the I/O to complete.
3175 */
3176 return filemap_flush(inode->i_mapping);
3177}
3178
3179/*
3180 * bmap() is special. It gets used by applications such as lilo and by
3181 * the swapper to find the on-disk block of a specific piece of data.
3182 *
3183 * Naturally, this is dangerous if the block concerned is still in the
3184 * journal. If somebody makes a swapfile on an ext4 data-journaling
3185 * filesystem and enables swap, then they may get a nasty shock when the
3186 * data getting swapped to that swapfile suddenly gets overwritten by
3187 * the original zero's written out previously to the journal and
3188 * awaiting writeback in the kernel's buffer cache.
3189 *
3190 * So, if we see any bmap calls here on a modified, data-journaled file,
3191 * take extra steps to flush any blocks which might be in the cache.
3192 */
3193static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3194{
3195 struct inode *inode = mapping->host;
3196 journal_t *journal;
3197 int err;
3198
3199 /*
3200 * We can get here for an inline file via the FIBMAP ioctl
3201 */
3202 if (ext4_has_inline_data(inode))
3203 return 0;
3204
3205 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3206 test_opt(inode->i_sb, DELALLOC)) {
3207 /*
3208 * With delalloc we want to sync the file
3209 * so that we can make sure we allocate
3210 * blocks for file
3211 */
3212 filemap_write_and_wait(mapping);
3213 }
3214
3215 if (EXT4_JOURNAL(inode) &&
3216 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3217 /*
3218 * This is a REALLY heavyweight approach, but the use of
3219 * bmap on dirty files is expected to be extremely rare:
3220 * only if we run lilo or swapon on a freshly made file
3221 * do we expect this to happen.
3222 *
3223 * (bmap requires CAP_SYS_RAWIO so this does not
3224 * represent an unprivileged user DOS attack --- we'd be
3225 * in trouble if mortal users could trigger this path at
3226 * will.)
3227 *
3228 * NB. EXT4_STATE_JDATA is not set on files other than
3229 * regular files. If somebody wants to bmap a directory
3230 * or symlink and gets confused because the buffer
3231 * hasn't yet been flushed to disk, they deserve
3232 * everything they get.
3233 */
3234
3235 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3236 journal = EXT4_JOURNAL(inode);
3237 jbd2_journal_lock_updates(journal);
3238 err = jbd2_journal_flush(journal);
3239 jbd2_journal_unlock_updates(journal);
3240
3241 if (err)
3242 return 0;
3243 }
3244
Olivier Deprez157378f2022-04-04 15:47:50 +02003245 return iomap_bmap(mapping, block, &ext4_iomap_ops);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003246}
3247
3248static int ext4_readpage(struct file *file, struct page *page)
3249{
3250 int ret = -EAGAIN;
3251 struct inode *inode = page->mapping->host;
3252
3253 trace_ext4_readpage(page);
3254
3255 if (ext4_has_inline_data(inode))
3256 ret = ext4_readpage_inline(inode, page);
3257
3258 if (ret == -EAGAIN)
Olivier Deprez157378f2022-04-04 15:47:50 +02003259 return ext4_mpage_readpages(inode, NULL, page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003260
3261 return ret;
3262}
3263
Olivier Deprez157378f2022-04-04 15:47:50 +02003264static void ext4_readahead(struct readahead_control *rac)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003265{
Olivier Deprez157378f2022-04-04 15:47:50 +02003266 struct inode *inode = rac->mapping->host;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003267
Olivier Deprez157378f2022-04-04 15:47:50 +02003268 /* If the file has inline data, no need to do readahead. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003269 if (ext4_has_inline_data(inode))
Olivier Deprez157378f2022-04-04 15:47:50 +02003270 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003271
Olivier Deprez157378f2022-04-04 15:47:50 +02003272 ext4_mpage_readpages(inode, rac, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003273}
3274
3275static void ext4_invalidatepage(struct page *page, unsigned int offset,
3276 unsigned int length)
3277{
3278 trace_ext4_invalidatepage(page, offset, length);
3279
3280 /* No journalling happens on data buffers when this function is used */
3281 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3282
3283 block_invalidatepage(page, offset, length);
3284}
3285
3286static int __ext4_journalled_invalidatepage(struct page *page,
3287 unsigned int offset,
3288 unsigned int length)
3289{
3290 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3291
3292 trace_ext4_journalled_invalidatepage(page, offset, length);
3293
3294 /*
3295 * If it's a full truncate we just forget about the pending dirtying
3296 */
3297 if (offset == 0 && length == PAGE_SIZE)
3298 ClearPageChecked(page);
3299
3300 return jbd2_journal_invalidatepage(journal, page, offset, length);
3301}
3302
3303/* Wrapper for aops... */
3304static void ext4_journalled_invalidatepage(struct page *page,
3305 unsigned int offset,
3306 unsigned int length)
3307{
3308 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3309}
3310
3311static int ext4_releasepage(struct page *page, gfp_t wait)
3312{
3313 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3314
3315 trace_ext4_releasepage(page);
3316
3317 /* Page has dirty journalled data -> cannot release */
3318 if (PageChecked(page))
3319 return 0;
3320 if (journal)
Olivier Deprez157378f2022-04-04 15:47:50 +02003321 return jbd2_journal_try_to_free_buffers(journal, page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003322 else
3323 return try_to_free_buffers(page);
3324}
3325
3326static bool ext4_inode_datasync_dirty(struct inode *inode)
3327{
3328 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3329
Olivier Deprez157378f2022-04-04 15:47:50 +02003330 if (journal) {
3331 if (jbd2_transaction_committed(journal,
3332 EXT4_I(inode)->i_datasync_tid))
3333 return false;
3334 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3335 return !list_empty(&EXT4_I(inode)->i_fc_list);
3336 return true;
3337 }
3338
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003339 /* Any metadata buffers to write? */
3340 if (!list_empty(&inode->i_mapping->private_list))
3341 return true;
3342 return inode->i_state & I_DIRTY_DATASYNC;
3343}
3344
Olivier Deprez157378f2022-04-04 15:47:50 +02003345static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3346 struct ext4_map_blocks *map, loff_t offset,
3347 loff_t length)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003348{
Olivier Deprez157378f2022-04-04 15:47:50 +02003349 u8 blkbits = inode->i_blkbits;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003350
Olivier Deprez0e641232021-09-23 10:07:05 +02003351 /*
3352 * Writes that span EOF might trigger an I/O size update on completion,
Olivier Deprez157378f2022-04-04 15:47:50 +02003353 * so consider them to be dirty for the purpose of O_DSYNC, even if
3354 * there is no other metadata changes being made or are pending.
Olivier Deprez0e641232021-09-23 10:07:05 +02003355 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003356 iomap->flags = 0;
Olivier Deprez0e641232021-09-23 10:07:05 +02003357 if (ext4_inode_datasync_dirty(inode) ||
3358 offset + length > i_size_read(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003359 iomap->flags |= IOMAP_F_DIRTY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003360
Olivier Deprez157378f2022-04-04 15:47:50 +02003361 if (map->m_flags & EXT4_MAP_NEW)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003362 iomap->flags |= IOMAP_F_NEW;
3363
Olivier Deprez157378f2022-04-04 15:47:50 +02003364 iomap->bdev = inode->i_sb->s_bdev;
3365 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3366 iomap->offset = (u64) map->m_lblk << blkbits;
3367 iomap->length = (u64) map->m_len << blkbits;
3368
3369 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3370 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3371 iomap->flags |= IOMAP_F_MERGED;
3372
3373 /*
3374 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3375 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3376 * set. In order for any allocated unwritten extents to be converted
3377 * into written extents correctly within the ->end_io() handler, we
3378 * need to ensure that the iomap->type is set appropriately. Hence, the
3379 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3380 * been set first.
3381 */
3382 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3383 iomap->type = IOMAP_UNWRITTEN;
3384 iomap->addr = (u64) map->m_pblk << blkbits;
3385 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3386 iomap->type = IOMAP_MAPPED;
3387 iomap->addr = (u64) map->m_pblk << blkbits;
3388 } else {
3389 iomap->type = IOMAP_HOLE;
3390 iomap->addr = IOMAP_NULL_ADDR;
3391 }
3392}
3393
3394static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3395 unsigned int flags)
3396{
3397 handle_t *handle;
3398 u8 blkbits = inode->i_blkbits;
3399 int ret, dio_credits, m_flags = 0, retries = 0;
3400
3401 /*
3402 * Trim the mapping request to the maximum value that we can map at
3403 * once for direct I/O.
3404 */
3405 if (map->m_len > DIO_MAX_BLOCKS)
3406 map->m_len = DIO_MAX_BLOCKS;
3407 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3408
3409retry:
3410 /*
3411 * Either we allocate blocks and then don't get an unwritten extent, so
3412 * in that case we have reserved enough credits. Or, the blocks are
3413 * already allocated and unwritten. In that case, the extent conversion
3414 * fits into the credits as well.
3415 */
3416 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3417 if (IS_ERR(handle))
3418 return PTR_ERR(handle);
3419
3420 /*
3421 * DAX and direct I/O are the only two operations that are currently
3422 * supported with IOMAP_WRITE.
3423 */
3424 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3425 if (IS_DAX(inode))
3426 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3427 /*
3428 * We use i_size instead of i_disksize here because delalloc writeback
3429 * can complete at any point during the I/O and subsequently push the
3430 * i_disksize out to i_size. This could be beyond where direct I/O is
3431 * happening and thus expose allocated blocks to direct I/O reads.
3432 */
3433 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3434 m_flags = EXT4_GET_BLOCKS_CREATE;
3435 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3436 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3437
3438 ret = ext4_map_blocks(handle, inode, map, m_flags);
3439
3440 /*
3441 * We cannot fill holes in indirect tree based inodes as that could
3442 * expose stale data in the case of a crash. Use the magic error code
3443 * to fallback to buffered I/O.
3444 */
3445 if (!m_flags && !ret)
3446 ret = -ENOTBLK;
3447
3448 ext4_journal_stop(handle);
3449 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3450 goto retry;
3451
3452 return ret;
3453}
3454
3455
3456static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3457 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3458{
3459 int ret;
3460 struct ext4_map_blocks map;
3461 u8 blkbits = inode->i_blkbits;
3462
3463 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3464 return -EINVAL;
3465
3466 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3467 return -ERANGE;
3468
3469 /*
3470 * Calculate the first and last logical blocks respectively.
3471 */
3472 map.m_lblk = offset >> blkbits;
3473 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3474 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3475
3476 if (flags & IOMAP_WRITE) {
3477 /*
3478 * We check here if the blocks are already allocated, then we
3479 * don't need to start a journal txn and we can directly return
3480 * the mapping information. This could boost performance
3481 * especially in multi-threaded overwrite requests.
3482 */
3483 if (offset + length <= i_size_read(inode)) {
3484 ret = ext4_map_blocks(NULL, inode, &map, 0);
3485 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3486 goto out;
3487 }
3488 ret = ext4_iomap_alloc(inode, &map, flags);
3489 } else {
3490 ret = ext4_map_blocks(NULL, inode, &map, 0);
3491 }
3492
3493 if (ret < 0)
3494 return ret;
3495out:
3496 ext4_set_iomap(inode, iomap, &map, offset, length);
3497
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003498 return 0;
3499}
3500
Olivier Deprez157378f2022-04-04 15:47:50 +02003501static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3502 loff_t length, unsigned flags, struct iomap *iomap,
3503 struct iomap *srcmap)
3504{
3505 int ret;
3506
3507 /*
3508 * Even for writes we don't need to allocate blocks, so just pretend
3509 * we are reading to save overhead of starting a transaction.
3510 */
3511 flags &= ~IOMAP_WRITE;
3512 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3513 WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3514 return ret;
3515}
3516
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003517static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3518 ssize_t written, unsigned flags, struct iomap *iomap)
3519{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003520 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02003521 * Check to see whether an error occurred while writing out the data to
3522 * the allocated blocks. If so, return the magic error code so that we
3523 * fallback to buffered I/O and attempt to complete the remainder of
3524 * the I/O. Any blocks that may have been allocated in preparation for
3525 * the direct I/O will be reused during buffered I/O.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003526 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003527 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3528 return -ENOTBLK;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003529
Olivier Deprez157378f2022-04-04 15:47:50 +02003530 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003531}
3532
3533const struct iomap_ops ext4_iomap_ops = {
3534 .iomap_begin = ext4_iomap_begin,
3535 .iomap_end = ext4_iomap_end,
3536};
3537
Olivier Deprez157378f2022-04-04 15:47:50 +02003538const struct iomap_ops ext4_iomap_overwrite_ops = {
3539 .iomap_begin = ext4_iomap_overwrite_begin,
3540 .iomap_end = ext4_iomap_end,
3541};
3542
3543static bool ext4_iomap_is_delalloc(struct inode *inode,
3544 struct ext4_map_blocks *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003545{
Olivier Deprez157378f2022-04-04 15:47:50 +02003546 struct extent_status es;
3547 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003548
Olivier Deprez157378f2022-04-04 15:47:50 +02003549 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3550 map->m_lblk, end, &es);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003551
Olivier Deprez157378f2022-04-04 15:47:50 +02003552 if (!es.es_len || es.es_lblk > end)
3553 return false;
3554
3555 if (es.es_lblk > map->m_lblk) {
3556 map->m_len = es.es_lblk - map->m_lblk;
3557 return false;
3558 }
3559
3560 offset = map->m_lblk - es.es_lblk;
3561 map->m_len = es.es_len - offset;
3562
3563 return true;
3564}
3565
3566static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3567 loff_t length, unsigned int flags,
3568 struct iomap *iomap, struct iomap *srcmap)
3569{
3570 int ret;
3571 bool delalloc = false;
3572 struct ext4_map_blocks map;
3573 u8 blkbits = inode->i_blkbits;
3574
3575 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3576 return -EINVAL;
3577
3578 if (ext4_has_inline_data(inode)) {
3579 ret = ext4_inline_data_iomap(inode, iomap);
3580 if (ret != -EAGAIN) {
3581 if (ret == 0 && offset >= iomap->length)
3582 ret = -ENOENT;
3583 return ret;
3584 }
3585 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003586
3587 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02003588 * Calculate the first and last logical block respectively.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003589 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003590 map.m_lblk = offset >> blkbits;
3591 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3592 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3593
3594 /*
3595 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3596 * So handle it here itself instead of querying ext4_map_blocks().
3597 * Since ext4_map_blocks() will warn about it and will return
3598 * -EIO error.
3599 */
3600 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3601 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3602
3603 if (offset >= sbi->s_bitmap_maxbytes) {
3604 map.m_flags = 0;
3605 goto set_iomap;
3606 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003607 }
Olivier Deprez157378f2022-04-04 15:47:50 +02003608
3609 ret = ext4_map_blocks(NULL, inode, &map, 0);
3610 if (ret < 0)
3611 return ret;
3612 if (ret == 0)
3613 delalloc = ext4_iomap_is_delalloc(inode, &map);
3614
3615set_iomap:
3616 ext4_set_iomap(inode, iomap, &map, offset, length);
3617 if (delalloc && iomap->type == IOMAP_HOLE)
3618 iomap->type = IOMAP_DELALLOC;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003619
3620 return 0;
3621}
3622
Olivier Deprez157378f2022-04-04 15:47:50 +02003623const struct iomap_ops ext4_iomap_report_ops = {
3624 .iomap_begin = ext4_iomap_begin_report,
3625};
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003626
3627/*
3628 * Pages can be marked dirty completely asynchronously from ext4's journalling
3629 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3630 * much here because ->set_page_dirty is called under VFS locks. The page is
3631 * not necessarily locked.
3632 *
3633 * We cannot just dirty the page and leave attached buffers clean, because the
3634 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3635 * or jbddirty because all the journalling code will explode.
3636 *
3637 * So what we do is to mark the page "pending dirty" and next time writepage
3638 * is called, propagate that into the buffers appropriately.
3639 */
3640static int ext4_journalled_set_page_dirty(struct page *page)
3641{
3642 SetPageChecked(page);
3643 return __set_page_dirty_nobuffers(page);
3644}
3645
3646static int ext4_set_page_dirty(struct page *page)
3647{
3648 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3649 WARN_ON_ONCE(!page_has_buffers(page));
3650 return __set_page_dirty_buffers(page);
3651}
3652
Olivier Deprez157378f2022-04-04 15:47:50 +02003653static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3654 struct file *file, sector_t *span)
3655{
3656 return iomap_swapfile_activate(sis, file, span,
3657 &ext4_iomap_report_ops);
3658}
3659
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003660static const struct address_space_operations ext4_aops = {
3661 .readpage = ext4_readpage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003662 .readahead = ext4_readahead,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003663 .writepage = ext4_writepage,
3664 .writepages = ext4_writepages,
3665 .write_begin = ext4_write_begin,
3666 .write_end = ext4_write_end,
3667 .set_page_dirty = ext4_set_page_dirty,
3668 .bmap = ext4_bmap,
3669 .invalidatepage = ext4_invalidatepage,
3670 .releasepage = ext4_releasepage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003671 .direct_IO = noop_direct_IO,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003672 .migratepage = buffer_migrate_page,
3673 .is_partially_uptodate = block_is_partially_uptodate,
3674 .error_remove_page = generic_error_remove_page,
Olivier Deprez157378f2022-04-04 15:47:50 +02003675 .swap_activate = ext4_iomap_swap_activate,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003676};
3677
3678static const struct address_space_operations ext4_journalled_aops = {
3679 .readpage = ext4_readpage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003680 .readahead = ext4_readahead,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003681 .writepage = ext4_writepage,
3682 .writepages = ext4_writepages,
3683 .write_begin = ext4_write_begin,
3684 .write_end = ext4_journalled_write_end,
3685 .set_page_dirty = ext4_journalled_set_page_dirty,
3686 .bmap = ext4_bmap,
3687 .invalidatepage = ext4_journalled_invalidatepage,
3688 .releasepage = ext4_releasepage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003689 .direct_IO = noop_direct_IO,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003690 .is_partially_uptodate = block_is_partially_uptodate,
3691 .error_remove_page = generic_error_remove_page,
Olivier Deprez157378f2022-04-04 15:47:50 +02003692 .swap_activate = ext4_iomap_swap_activate,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003693};
3694
3695static const struct address_space_operations ext4_da_aops = {
3696 .readpage = ext4_readpage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003697 .readahead = ext4_readahead,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003698 .writepage = ext4_writepage,
3699 .writepages = ext4_writepages,
3700 .write_begin = ext4_da_write_begin,
3701 .write_end = ext4_da_write_end,
3702 .set_page_dirty = ext4_set_page_dirty,
3703 .bmap = ext4_bmap,
David Brazdil0f672f62019-12-10 10:32:29 +00003704 .invalidatepage = ext4_invalidatepage,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003705 .releasepage = ext4_releasepage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003706 .direct_IO = noop_direct_IO,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003707 .migratepage = buffer_migrate_page,
3708 .is_partially_uptodate = block_is_partially_uptodate,
3709 .error_remove_page = generic_error_remove_page,
Olivier Deprez157378f2022-04-04 15:47:50 +02003710 .swap_activate = ext4_iomap_swap_activate,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003711};
3712
3713static const struct address_space_operations ext4_dax_aops = {
3714 .writepages = ext4_dax_writepages,
3715 .direct_IO = noop_direct_IO,
3716 .set_page_dirty = noop_set_page_dirty,
3717 .bmap = ext4_bmap,
3718 .invalidatepage = noop_invalidatepage,
Olivier Deprez157378f2022-04-04 15:47:50 +02003719 .swap_activate = ext4_iomap_swap_activate,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003720};
3721
3722void ext4_set_aops(struct inode *inode)
3723{
3724 switch (ext4_inode_journal_mode(inode)) {
3725 case EXT4_INODE_ORDERED_DATA_MODE:
3726 case EXT4_INODE_WRITEBACK_DATA_MODE:
3727 break;
3728 case EXT4_INODE_JOURNAL_DATA_MODE:
3729 inode->i_mapping->a_ops = &ext4_journalled_aops;
3730 return;
3731 default:
3732 BUG();
3733 }
3734 if (IS_DAX(inode))
3735 inode->i_mapping->a_ops = &ext4_dax_aops;
3736 else if (test_opt(inode->i_sb, DELALLOC))
3737 inode->i_mapping->a_ops = &ext4_da_aops;
3738 else
3739 inode->i_mapping->a_ops = &ext4_aops;
3740}
3741
3742static int __ext4_block_zero_page_range(handle_t *handle,
3743 struct address_space *mapping, loff_t from, loff_t length)
3744{
3745 ext4_fsblk_t index = from >> PAGE_SHIFT;
3746 unsigned offset = from & (PAGE_SIZE-1);
3747 unsigned blocksize, pos;
3748 ext4_lblk_t iblock;
3749 struct inode *inode = mapping->host;
3750 struct buffer_head *bh;
3751 struct page *page;
3752 int err = 0;
3753
3754 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3755 mapping_gfp_constraint(mapping, ~__GFP_FS));
3756 if (!page)
3757 return -ENOMEM;
3758
3759 blocksize = inode->i_sb->s_blocksize;
3760
3761 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3762
3763 if (!page_has_buffers(page))
3764 create_empty_buffers(page, blocksize, 0);
3765
3766 /* Find the buffer that contains "offset" */
3767 bh = page_buffers(page);
3768 pos = blocksize;
3769 while (offset >= pos) {
3770 bh = bh->b_this_page;
3771 iblock++;
3772 pos += blocksize;
3773 }
3774 if (buffer_freed(bh)) {
3775 BUFFER_TRACE(bh, "freed: skip");
3776 goto unlock;
3777 }
3778 if (!buffer_mapped(bh)) {
3779 BUFFER_TRACE(bh, "unmapped");
3780 ext4_get_block(inode, iblock, bh, 0);
3781 /* unmapped? It's a hole - nothing to do */
3782 if (!buffer_mapped(bh)) {
3783 BUFFER_TRACE(bh, "still unmapped");
3784 goto unlock;
3785 }
3786 }
3787
3788 /* Ok, it's mapped. Make sure it's up-to-date */
3789 if (PageUptodate(page))
3790 set_buffer_uptodate(bh);
3791
3792 if (!buffer_uptodate(bh)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003793 err = ext4_read_bh_lock(bh, 0, true);
3794 if (err)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003795 goto unlock;
Olivier Deprez157378f2022-04-04 15:47:50 +02003796 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003797 /* We expect the key to be set. */
3798 BUG_ON(!fscrypt_has_encryption_key(inode));
Olivier Deprez157378f2022-04-04 15:47:50 +02003799 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3800 bh_offset(bh));
3801 if (err) {
3802 clear_buffer_uptodate(bh);
3803 goto unlock;
3804 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003805 }
3806 }
3807 if (ext4_should_journal_data(inode)) {
3808 BUFFER_TRACE(bh, "get write access");
3809 err = ext4_journal_get_write_access(handle, bh);
3810 if (err)
3811 goto unlock;
3812 }
3813 zero_user(page, offset, length);
3814 BUFFER_TRACE(bh, "zeroed end of block");
3815
3816 if (ext4_should_journal_data(inode)) {
3817 err = ext4_handle_dirty_metadata(handle, inode, bh);
3818 } else {
3819 err = 0;
3820 mark_buffer_dirty(bh);
3821 if (ext4_should_order_data(inode))
David Brazdil0f672f62019-12-10 10:32:29 +00003822 err = ext4_jbd2_inode_add_write(handle, inode, from,
3823 length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003824 }
3825
3826unlock:
3827 unlock_page(page);
3828 put_page(page);
3829 return err;
3830}
3831
3832/*
3833 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3834 * starting from file offset 'from'. The range to be zero'd must
3835 * be contained with in one block. If the specified range exceeds
3836 * the end of the block it will be shortened to end of the block
3837 * that cooresponds to 'from'
3838 */
3839static int ext4_block_zero_page_range(handle_t *handle,
3840 struct address_space *mapping, loff_t from, loff_t length)
3841{
3842 struct inode *inode = mapping->host;
3843 unsigned offset = from & (PAGE_SIZE-1);
3844 unsigned blocksize = inode->i_sb->s_blocksize;
3845 unsigned max = blocksize - (offset & (blocksize - 1));
3846
3847 /*
3848 * correct length if it does not fall between
3849 * 'from' and the end of the block
3850 */
3851 if (length > max || length < 0)
3852 length = max;
3853
3854 if (IS_DAX(inode)) {
3855 return iomap_zero_range(inode, from, length, NULL,
3856 &ext4_iomap_ops);
3857 }
3858 return __ext4_block_zero_page_range(handle, mapping, from, length);
3859}
3860
3861/*
3862 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3863 * up to the end of the block which corresponds to `from'.
3864 * This required during truncate. We need to physically zero the tail end
3865 * of that block so it doesn't yield old data if the file is later grown.
3866 */
3867static int ext4_block_truncate_page(handle_t *handle,
3868 struct address_space *mapping, loff_t from)
3869{
3870 unsigned offset = from & (PAGE_SIZE-1);
3871 unsigned length;
3872 unsigned blocksize;
3873 struct inode *inode = mapping->host;
3874
3875 /* If we are processing an encrypted inode during orphan list handling */
David Brazdil0f672f62019-12-10 10:32:29 +00003876 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003877 return 0;
3878
3879 blocksize = inode->i_sb->s_blocksize;
3880 length = blocksize - (offset & (blocksize - 1));
3881
3882 return ext4_block_zero_page_range(handle, mapping, from, length);
3883}
3884
3885int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3886 loff_t lstart, loff_t length)
3887{
3888 struct super_block *sb = inode->i_sb;
3889 struct address_space *mapping = inode->i_mapping;
3890 unsigned partial_start, partial_end;
3891 ext4_fsblk_t start, end;
3892 loff_t byte_end = (lstart + length - 1);
3893 int err = 0;
3894
3895 partial_start = lstart & (sb->s_blocksize - 1);
3896 partial_end = byte_end & (sb->s_blocksize - 1);
3897
3898 start = lstart >> sb->s_blocksize_bits;
3899 end = byte_end >> sb->s_blocksize_bits;
3900
3901 /* Handle partial zero within the single block */
3902 if (start == end &&
3903 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3904 err = ext4_block_zero_page_range(handle, mapping,
3905 lstart, length);
3906 return err;
3907 }
3908 /* Handle partial zero out on the start of the range */
3909 if (partial_start) {
3910 err = ext4_block_zero_page_range(handle, mapping,
3911 lstart, sb->s_blocksize);
3912 if (err)
3913 return err;
3914 }
3915 /* Handle partial zero out on the end of the range */
3916 if (partial_end != sb->s_blocksize - 1)
3917 err = ext4_block_zero_page_range(handle, mapping,
3918 byte_end - partial_end,
3919 partial_end + 1);
3920 return err;
3921}
3922
3923int ext4_can_truncate(struct inode *inode)
3924{
3925 if (S_ISREG(inode->i_mode))
3926 return 1;
3927 if (S_ISDIR(inode->i_mode))
3928 return 1;
3929 if (S_ISLNK(inode->i_mode))
3930 return !ext4_inode_is_fast_symlink(inode);
3931 return 0;
3932}
3933
3934/*
3935 * We have to make sure i_disksize gets properly updated before we truncate
3936 * page cache due to hole punching or zero range. Otherwise i_disksize update
3937 * can get lost as it may have been postponed to submission of writeback but
3938 * that will never happen after we truncate page cache.
3939 */
3940int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3941 loff_t len)
3942{
3943 handle_t *handle;
Olivier Deprez157378f2022-04-04 15:47:50 +02003944 int ret;
3945
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003946 loff_t size = i_size_read(inode);
3947
3948 WARN_ON(!inode_is_locked(inode));
3949 if (offset > size || offset + len < size)
3950 return 0;
3951
3952 if (EXT4_I(inode)->i_disksize >= size)
3953 return 0;
3954
3955 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3956 if (IS_ERR(handle))
3957 return PTR_ERR(handle);
3958 ext4_update_i_disksize(inode, size);
Olivier Deprez157378f2022-04-04 15:47:50 +02003959 ret = ext4_mark_inode_dirty(handle, inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003960 ext4_journal_stop(handle);
3961
Olivier Deprez157378f2022-04-04 15:47:50 +02003962 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003963}
3964
3965static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3966{
3967 up_write(&ei->i_mmap_sem);
3968 schedule();
3969 down_write(&ei->i_mmap_sem);
3970}
3971
3972int ext4_break_layouts(struct inode *inode)
3973{
3974 struct ext4_inode_info *ei = EXT4_I(inode);
3975 struct page *page;
3976 int error;
3977
3978 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3979 return -EINVAL;
3980
3981 do {
3982 page = dax_layout_busy_page(inode->i_mapping);
3983 if (!page)
3984 return 0;
3985
3986 error = ___wait_var_event(&page->_refcount,
3987 atomic_read(&page->_refcount) == 1,
3988 TASK_INTERRUPTIBLE, 0, 0,
3989 ext4_wait_dax_page(ei));
3990 } while (error == 0);
3991
3992 return error;
3993}
3994
3995/*
3996 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3997 * associated with the given offset and length
3998 *
3999 * @inode: File inode
4000 * @offset: The offset where the hole will begin
4001 * @len: The length of the hole
4002 *
4003 * Returns: 0 on success or negative on failure
4004 */
4005
4006int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4007{
4008 struct super_block *sb = inode->i_sb;
4009 ext4_lblk_t first_block, stop_block;
4010 struct address_space *mapping = inode->i_mapping;
4011 loff_t first_block_offset, last_block_offset;
4012 handle_t *handle;
4013 unsigned int credits;
Olivier Deprez157378f2022-04-04 15:47:50 +02004014 int ret = 0, ret2 = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004015
4016 trace_ext4_punch_hole(inode, offset, length, 0);
4017
David Brazdil0f672f62019-12-10 10:32:29 +00004018 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4019 if (ext4_has_inline_data(inode)) {
4020 down_write(&EXT4_I(inode)->i_mmap_sem);
4021 ret = ext4_convert_inline_data(inode);
4022 up_write(&EXT4_I(inode)->i_mmap_sem);
4023 if (ret)
4024 return ret;
4025 }
4026
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004027 /*
4028 * Write out all dirty pages to avoid race conditions
4029 * Then release them.
4030 */
4031 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4032 ret = filemap_write_and_wait_range(mapping, offset,
4033 offset + length - 1);
4034 if (ret)
4035 return ret;
4036 }
4037
4038 inode_lock(inode);
4039
4040 /* No need to punch hole beyond i_size */
4041 if (offset >= inode->i_size)
4042 goto out_mutex;
4043
4044 /*
4045 * If the hole extends beyond i_size, set the hole
4046 * to end after the page that contains i_size
4047 */
4048 if (offset + length > inode->i_size) {
4049 length = inode->i_size +
4050 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4051 offset;
4052 }
4053
4054 if (offset & (sb->s_blocksize - 1) ||
4055 (offset + length) & (sb->s_blocksize - 1)) {
4056 /*
4057 * Attach jinode to inode for jbd2 if we do any zeroing of
4058 * partial block
4059 */
4060 ret = ext4_inode_attach_jinode(inode);
4061 if (ret < 0)
4062 goto out_mutex;
4063
4064 }
4065
4066 /* Wait all existing dio workers, newcomers will block on i_mutex */
4067 inode_dio_wait(inode);
4068
4069 /*
4070 * Prevent page faults from reinstantiating pages we have released from
4071 * page cache.
4072 */
4073 down_write(&EXT4_I(inode)->i_mmap_sem);
4074
4075 ret = ext4_break_layouts(inode);
4076 if (ret)
4077 goto out_dio;
4078
4079 first_block_offset = round_up(offset, sb->s_blocksize);
4080 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4081
4082 /* Now release the pages and zero block aligned part of pages*/
4083 if (last_block_offset > first_block_offset) {
4084 ret = ext4_update_disksize_before_punch(inode, offset, length);
4085 if (ret)
4086 goto out_dio;
4087 truncate_pagecache_range(inode, first_block_offset,
4088 last_block_offset);
4089 }
4090
4091 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4092 credits = ext4_writepage_trans_blocks(inode);
4093 else
4094 credits = ext4_blocks_for_truncate(inode);
4095 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4096 if (IS_ERR(handle)) {
4097 ret = PTR_ERR(handle);
4098 ext4_std_error(sb, ret);
4099 goto out_dio;
4100 }
4101
4102 ret = ext4_zero_partial_blocks(handle, inode, offset,
4103 length);
4104 if (ret)
4105 goto out_stop;
4106
4107 first_block = (offset + sb->s_blocksize - 1) >>
4108 EXT4_BLOCK_SIZE_BITS(sb);
4109 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4110
4111 /* If there are blocks to remove, do it */
4112 if (stop_block > first_block) {
4113
4114 down_write(&EXT4_I(inode)->i_data_sem);
Olivier Deprez157378f2022-04-04 15:47:50 +02004115 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004116
4117 ret = ext4_es_remove_extent(inode, first_block,
4118 stop_block - first_block);
4119 if (ret) {
4120 up_write(&EXT4_I(inode)->i_data_sem);
4121 goto out_stop;
4122 }
4123
4124 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4125 ret = ext4_ext_remove_space(inode, first_block,
4126 stop_block - 1);
4127 else
4128 ret = ext4_ind_remove_space(handle, inode, first_block,
4129 stop_block);
4130
4131 up_write(&EXT4_I(inode)->i_data_sem);
4132 }
Olivier Deprez157378f2022-04-04 15:47:50 +02004133 ext4_fc_track_range(handle, inode, first_block, stop_block);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004134 if (IS_SYNC(inode))
4135 ext4_handle_sync(handle);
4136
4137 inode->i_mtime = inode->i_ctime = current_time(inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02004138 ret2 = ext4_mark_inode_dirty(handle, inode);
4139 if (unlikely(ret2))
4140 ret = ret2;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004141 if (ret >= 0)
4142 ext4_update_inode_fsync_trans(handle, inode, 1);
4143out_stop:
4144 ext4_journal_stop(handle);
4145out_dio:
4146 up_write(&EXT4_I(inode)->i_mmap_sem);
4147out_mutex:
4148 inode_unlock(inode);
4149 return ret;
4150}
4151
4152int ext4_inode_attach_jinode(struct inode *inode)
4153{
4154 struct ext4_inode_info *ei = EXT4_I(inode);
4155 struct jbd2_inode *jinode;
4156
4157 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4158 return 0;
4159
4160 jinode = jbd2_alloc_inode(GFP_KERNEL);
4161 spin_lock(&inode->i_lock);
4162 if (!ei->jinode) {
4163 if (!jinode) {
4164 spin_unlock(&inode->i_lock);
4165 return -ENOMEM;
4166 }
4167 ei->jinode = jinode;
4168 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4169 jinode = NULL;
4170 }
4171 spin_unlock(&inode->i_lock);
4172 if (unlikely(jinode != NULL))
4173 jbd2_free_inode(jinode);
4174 return 0;
4175}
4176
4177/*
4178 * ext4_truncate()
4179 *
4180 * We block out ext4_get_block() block instantiations across the entire
4181 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4182 * simultaneously on behalf of the same inode.
4183 *
4184 * As we work through the truncate and commit bits of it to the journal there
4185 * is one core, guiding principle: the file's tree must always be consistent on
4186 * disk. We must be able to restart the truncate after a crash.
4187 *
4188 * The file's tree may be transiently inconsistent in memory (although it
4189 * probably isn't), but whenever we close off and commit a journal transaction,
4190 * the contents of (the filesystem + the journal) must be consistent and
4191 * restartable. It's pretty simple, really: bottom up, right to left (although
4192 * left-to-right works OK too).
4193 *
4194 * Note that at recovery time, journal replay occurs *before* the restart of
4195 * truncate against the orphan inode list.
4196 *
4197 * The committed inode has the new, desired i_size (which is the same as
4198 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4199 * that this inode's truncate did not complete and it will again call
4200 * ext4_truncate() to have another go. So there will be instantiated blocks
4201 * to the right of the truncation point in a crashed ext4 filesystem. But
4202 * that's fine - as long as they are linked from the inode, the post-crash
4203 * ext4_truncate() run will find them and release them.
4204 */
4205int ext4_truncate(struct inode *inode)
4206{
4207 struct ext4_inode_info *ei = EXT4_I(inode);
4208 unsigned int credits;
Olivier Deprez157378f2022-04-04 15:47:50 +02004209 int err = 0, err2;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004210 handle_t *handle;
4211 struct address_space *mapping = inode->i_mapping;
4212
4213 /*
4214 * There is a possibility that we're either freeing the inode
4215 * or it's a completely new inode. In those cases we might not
4216 * have i_mutex locked because it's not necessary.
4217 */
4218 if (!(inode->i_state & (I_NEW|I_FREEING)))
4219 WARN_ON(!inode_is_locked(inode));
4220 trace_ext4_truncate_enter(inode);
4221
4222 if (!ext4_can_truncate(inode))
Olivier Deprez157378f2022-04-04 15:47:50 +02004223 goto out_trace;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004224
4225 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4226 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4227
4228 if (ext4_has_inline_data(inode)) {
4229 int has_inline = 1;
4230
4231 err = ext4_inline_data_truncate(inode, &has_inline);
Olivier Deprez157378f2022-04-04 15:47:50 +02004232 if (err || has_inline)
4233 goto out_trace;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004234 }
4235
4236 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4237 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4238 if (ext4_inode_attach_jinode(inode) < 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02004239 goto out_trace;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004240 }
4241
4242 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4243 credits = ext4_writepage_trans_blocks(inode);
4244 else
4245 credits = ext4_blocks_for_truncate(inode);
4246
4247 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
Olivier Deprez157378f2022-04-04 15:47:50 +02004248 if (IS_ERR(handle)) {
4249 err = PTR_ERR(handle);
4250 goto out_trace;
4251 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004252
4253 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4254 ext4_block_truncate_page(handle, mapping, inode->i_size);
4255
4256 /*
4257 * We add the inode to the orphan list, so that if this
4258 * truncate spans multiple transactions, and we crash, we will
4259 * resume the truncate when the filesystem recovers. It also
4260 * marks the inode dirty, to catch the new size.
4261 *
4262 * Implication: the file must always be in a sane, consistent
4263 * truncatable state while each transaction commits.
4264 */
4265 err = ext4_orphan_add(handle, inode);
4266 if (err)
4267 goto out_stop;
4268
4269 down_write(&EXT4_I(inode)->i_data_sem);
4270
Olivier Deprez157378f2022-04-04 15:47:50 +02004271 ext4_discard_preallocations(inode, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004272
4273 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4274 err = ext4_ext_truncate(handle, inode);
4275 else
4276 ext4_ind_truncate(handle, inode);
4277
4278 up_write(&ei->i_data_sem);
4279 if (err)
4280 goto out_stop;
4281
4282 if (IS_SYNC(inode))
4283 ext4_handle_sync(handle);
4284
4285out_stop:
4286 /*
4287 * If this was a simple ftruncate() and the file will remain alive,
4288 * then we need to clear up the orphan record which we created above.
4289 * However, if this was a real unlink then we were called by
4290 * ext4_evict_inode(), and we allow that function to clean up the
4291 * orphan info for us.
4292 */
4293 if (inode->i_nlink)
4294 ext4_orphan_del(handle, inode);
4295
4296 inode->i_mtime = inode->i_ctime = current_time(inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02004297 err2 = ext4_mark_inode_dirty(handle, inode);
4298 if (unlikely(err2 && !err))
4299 err = err2;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004300 ext4_journal_stop(handle);
4301
Olivier Deprez157378f2022-04-04 15:47:50 +02004302out_trace:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004303 trace_ext4_truncate_exit(inode);
4304 return err;
4305}
4306
4307/*
4308 * ext4_get_inode_loc returns with an extra refcount against the inode's
4309 * underlying buffer_head on success. If 'in_mem' is true, we have all
4310 * data in memory that is needed to recreate the on-disk version of this
4311 * inode.
4312 */
Olivier Deprez157378f2022-04-04 15:47:50 +02004313static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4314 struct ext4_iloc *iloc, int in_mem,
4315 ext4_fsblk_t *ret_block)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004316{
4317 struct ext4_group_desc *gdp;
4318 struct buffer_head *bh;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004319 ext4_fsblk_t block;
David Brazdil0f672f62019-12-10 10:32:29 +00004320 struct blk_plug plug;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004321 int inodes_per_block, inode_offset;
4322
4323 iloc->bh = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02004324 if (ino < EXT4_ROOT_INO ||
4325 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004326 return -EFSCORRUPTED;
4327
Olivier Deprez157378f2022-04-04 15:47:50 +02004328 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004329 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4330 if (!gdp)
4331 return -EIO;
4332
4333 /*
4334 * Figure out the offset within the block group inode table
4335 */
4336 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
Olivier Deprez157378f2022-04-04 15:47:50 +02004337 inode_offset = ((ino - 1) %
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004338 EXT4_INODES_PER_GROUP(sb));
4339 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4340 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4341
4342 bh = sb_getblk(sb, block);
4343 if (unlikely(!bh))
4344 return -ENOMEM;
Olivier Deprez157378f2022-04-04 15:47:50 +02004345 if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
4346 goto simulate_eio;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004347 if (!buffer_uptodate(bh)) {
4348 lock_buffer(bh);
4349
Olivier Deprez157378f2022-04-04 15:47:50 +02004350 if (ext4_buffer_uptodate(bh)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004351 /* someone brought it uptodate while we waited */
4352 unlock_buffer(bh);
4353 goto has_buffer;
4354 }
4355
4356 /*
4357 * If we have all information of the inode in memory and this
4358 * is the only valid inode in the block, we need not read the
4359 * block.
4360 */
4361 if (in_mem) {
4362 struct buffer_head *bitmap_bh;
4363 int i, start;
4364
4365 start = inode_offset & ~(inodes_per_block - 1);
4366
4367 /* Is the inode bitmap in cache? */
4368 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4369 if (unlikely(!bitmap_bh))
4370 goto make_io;
4371
4372 /*
4373 * If the inode bitmap isn't in cache then the
4374 * optimisation may end up performing two reads instead
4375 * of one, so skip it.
4376 */
4377 if (!buffer_uptodate(bitmap_bh)) {
4378 brelse(bitmap_bh);
4379 goto make_io;
4380 }
4381 for (i = start; i < start + inodes_per_block; i++) {
4382 if (i == inode_offset)
4383 continue;
4384 if (ext4_test_bit(i, bitmap_bh->b_data))
4385 break;
4386 }
4387 brelse(bitmap_bh);
4388 if (i == start + inodes_per_block) {
4389 /* all other inodes are free, so skip I/O */
4390 memset(bh->b_data, 0, bh->b_size);
4391 set_buffer_uptodate(bh);
4392 unlock_buffer(bh);
4393 goto has_buffer;
4394 }
4395 }
4396
4397make_io:
4398 /*
4399 * If we need to do any I/O, try to pre-readahead extra
4400 * blocks from the inode table.
4401 */
David Brazdil0f672f62019-12-10 10:32:29 +00004402 blk_start_plug(&plug);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004403 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4404 ext4_fsblk_t b, end, table;
4405 unsigned num;
4406 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4407
4408 table = ext4_inode_table(sb, gdp);
4409 /* s_inode_readahead_blks is always a power of 2 */
4410 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4411 if (table > b)
4412 b = table;
4413 end = b + ra_blks;
4414 num = EXT4_INODES_PER_GROUP(sb);
4415 if (ext4_has_group_desc_csum(sb))
4416 num -= ext4_itable_unused_count(sb, gdp);
4417 table += num / inodes_per_block;
4418 if (end > table)
4419 end = table;
4420 while (b <= end)
Olivier Deprez157378f2022-04-04 15:47:50 +02004421 ext4_sb_breadahead_unmovable(sb, b++);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004422 }
4423
4424 /*
4425 * There are other valid inodes in the buffer, this inode
4426 * has in-inode xattrs, or we don't have this inode in memory.
4427 * Read the block from disk.
4428 */
Olivier Deprez157378f2022-04-04 15:47:50 +02004429 trace_ext4_load_inode(sb, ino);
4430 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +00004431 blk_finish_plug(&plug);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004432 wait_on_buffer(bh);
4433 if (!buffer_uptodate(bh)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004434 simulate_eio:
4435 if (ret_block)
4436 *ret_block = block;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004437 brelse(bh);
4438 return -EIO;
4439 }
4440 }
4441has_buffer:
4442 iloc->bh = bh;
4443 return 0;
4444}
4445
Olivier Deprez157378f2022-04-04 15:47:50 +02004446static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4447 struct ext4_iloc *iloc)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004448{
Olivier Deprez157378f2022-04-04 15:47:50 +02004449 ext4_fsblk_t err_blk = 0;
4450 int ret;
4451
4452 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4453 &err_blk);
4454
4455 if (ret == -EIO)
4456 ext4_error_inode_block(inode, err_blk, EIO,
4457 "unable to read itable block");
4458
4459 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004460}
4461
Olivier Deprez157378f2022-04-04 15:47:50 +02004462int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004463{
Olivier Deprez157378f2022-04-04 15:47:50 +02004464 ext4_fsblk_t err_blk = 0;
4465 int ret;
4466
4467 /* We have all inode data except xattrs in memory here. */
4468 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4469 !ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4470
4471 if (ret == -EIO)
4472 ext4_error_inode_block(inode, err_blk, EIO,
4473 "unable to read itable block");
4474
4475 return ret;
4476}
4477
4478
4479int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4480 struct ext4_iloc *iloc)
4481{
4482 return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4483}
4484
4485static bool ext4_should_enable_dax(struct inode *inode)
4486{
4487 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4488
4489 if (test_opt2(inode->i_sb, DAX_NEVER))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004490 return false;
4491 if (!S_ISREG(inode->i_mode))
4492 return false;
4493 if (ext4_should_journal_data(inode))
4494 return false;
4495 if (ext4_has_inline_data(inode))
4496 return false;
David Brazdil0f672f62019-12-10 10:32:29 +00004497 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4498 return false;
4499 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004500 return false;
Olivier Deprez157378f2022-04-04 15:47:50 +02004501 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4502 return false;
4503 if (test_opt(inode->i_sb, DAX_ALWAYS))
4504 return true;
4505
4506 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004507}
4508
Olivier Deprez157378f2022-04-04 15:47:50 +02004509void ext4_set_inode_flags(struct inode *inode, bool init)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004510{
4511 unsigned int flags = EXT4_I(inode)->i_flags;
4512 unsigned int new_fl = 0;
4513
Olivier Deprez157378f2022-04-04 15:47:50 +02004514 WARN_ON_ONCE(IS_DAX(inode) && init);
4515
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004516 if (flags & EXT4_SYNC_FL)
4517 new_fl |= S_SYNC;
4518 if (flags & EXT4_APPEND_FL)
4519 new_fl |= S_APPEND;
4520 if (flags & EXT4_IMMUTABLE_FL)
4521 new_fl |= S_IMMUTABLE;
4522 if (flags & EXT4_NOATIME_FL)
4523 new_fl |= S_NOATIME;
4524 if (flags & EXT4_DIRSYNC_FL)
4525 new_fl |= S_DIRSYNC;
Olivier Deprez157378f2022-04-04 15:47:50 +02004526
4527 /* Because of the way inode_set_flags() works we must preserve S_DAX
4528 * here if already set. */
4529 new_fl |= (inode->i_flags & S_DAX);
4530 if (init && ext4_should_enable_dax(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004531 new_fl |= S_DAX;
Olivier Deprez157378f2022-04-04 15:47:50 +02004532
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004533 if (flags & EXT4_ENCRYPT_FL)
4534 new_fl |= S_ENCRYPTED;
David Brazdil0f672f62019-12-10 10:32:29 +00004535 if (flags & EXT4_CASEFOLD_FL)
4536 new_fl |= S_CASEFOLD;
4537 if (flags & EXT4_VERITY_FL)
4538 new_fl |= S_VERITY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004539 inode_set_flags(inode, new_fl,
4540 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
David Brazdil0f672f62019-12-10 10:32:29 +00004541 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004542}
4543
4544static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4545 struct ext4_inode_info *ei)
4546{
4547 blkcnt_t i_blocks ;
4548 struct inode *inode = &(ei->vfs_inode);
4549 struct super_block *sb = inode->i_sb;
4550
4551 if (ext4_has_feature_huge_file(sb)) {
4552 /* we are using combined 48 bit field */
4553 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4554 le32_to_cpu(raw_inode->i_blocks_lo);
4555 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4556 /* i_blocks represent file system block size */
4557 return i_blocks << (inode->i_blkbits - 9);
4558 } else {
4559 return i_blocks;
4560 }
4561 } else {
4562 return le32_to_cpu(raw_inode->i_blocks_lo);
4563 }
4564}
4565
4566static inline int ext4_iget_extra_inode(struct inode *inode,
4567 struct ext4_inode *raw_inode,
4568 struct ext4_inode_info *ei)
4569{
4570 __le32 *magic = (void *)raw_inode +
4571 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4572
4573 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4574 EXT4_INODE_SIZE(inode->i_sb) &&
4575 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4576 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4577 return ext4_find_inline_data_nolock(inode);
4578 } else
4579 EXT4_I(inode)->i_inline_off = 0;
4580 return 0;
4581}
4582
4583int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4584{
4585 if (!ext4_has_feature_project(inode->i_sb))
4586 return -EOPNOTSUPP;
4587 *projid = EXT4_I(inode)->i_projid;
4588 return 0;
4589}
4590
4591/*
4592 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4593 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4594 * set.
4595 */
4596static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4597{
4598 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4599 inode_set_iversion_raw(inode, val);
4600 else
4601 inode_set_iversion_queried(inode, val);
4602}
4603static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4604{
4605 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4606 return inode_peek_iversion_raw(inode);
4607 else
4608 return inode_peek_iversion(inode);
4609}
4610
David Brazdil0f672f62019-12-10 10:32:29 +00004611struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4612 ext4_iget_flags flags, const char *function,
4613 unsigned int line)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004614{
4615 struct ext4_iloc iloc;
4616 struct ext4_inode *raw_inode;
4617 struct ext4_inode_info *ei;
4618 struct inode *inode;
4619 journal_t *journal = EXT4_SB(sb)->s_journal;
4620 long ret;
4621 loff_t size;
4622 int block;
4623 uid_t i_uid;
4624 gid_t i_gid;
4625 projid_t i_projid;
4626
David Brazdil0f672f62019-12-10 10:32:29 +00004627 if ((!(flags & EXT4_IGET_SPECIAL) &&
4628 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4629 (ino < EXT4_ROOT_INO) ||
4630 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4631 if (flags & EXT4_IGET_HANDLE)
4632 return ERR_PTR(-ESTALE);
Olivier Deprez157378f2022-04-04 15:47:50 +02004633 __ext4_error(sb, function, line, EFSCORRUPTED, 0,
David Brazdil0f672f62019-12-10 10:32:29 +00004634 "inode #%lu: comm %s: iget: illegal inode #",
4635 ino, current->comm);
4636 return ERR_PTR(-EFSCORRUPTED);
4637 }
4638
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004639 inode = iget_locked(sb, ino);
4640 if (!inode)
4641 return ERR_PTR(-ENOMEM);
4642 if (!(inode->i_state & I_NEW))
4643 return inode;
4644
4645 ei = EXT4_I(inode);
4646 iloc.bh = NULL;
4647
Olivier Deprez157378f2022-04-04 15:47:50 +02004648 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004649 if (ret < 0)
4650 goto bad_inode;
4651 raw_inode = ext4_raw_inode(&iloc);
4652
4653 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004654 ext4_error_inode(inode, function, line, 0,
4655 "iget: root inode unallocated");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004656 ret = -EFSCORRUPTED;
4657 goto bad_inode;
4658 }
4659
David Brazdil0f672f62019-12-10 10:32:29 +00004660 if ((flags & EXT4_IGET_HANDLE) &&
4661 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4662 ret = -ESTALE;
4663 goto bad_inode;
4664 }
4665
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004666 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4667 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4668 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4669 EXT4_INODE_SIZE(inode->i_sb) ||
4670 (ei->i_extra_isize & 3)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004671 ext4_error_inode(inode, function, line, 0,
4672 "iget: bad extra_isize %u "
4673 "(inode size %u)",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004674 ei->i_extra_isize,
4675 EXT4_INODE_SIZE(inode->i_sb));
4676 ret = -EFSCORRUPTED;
4677 goto bad_inode;
4678 }
4679 } else
4680 ei->i_extra_isize = 0;
4681
4682 /* Precompute checksum seed for inode metadata */
4683 if (ext4_has_metadata_csum(sb)) {
4684 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4685 __u32 csum;
4686 __le32 inum = cpu_to_le32(inode->i_ino);
4687 __le32 gen = raw_inode->i_generation;
4688 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4689 sizeof(inum));
4690 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4691 sizeof(gen));
4692 }
4693
Olivier Deprez157378f2022-04-04 15:47:50 +02004694 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4695 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4696 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4697 ext4_error_inode_err(inode, function, line, 0,
4698 EFSBADCRC, "iget: checksum invalid");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004699 ret = -EFSBADCRC;
4700 goto bad_inode;
4701 }
4702
4703 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4704 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4705 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4706 if (ext4_has_feature_project(sb) &&
4707 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4708 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4709 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4710 else
4711 i_projid = EXT4_DEF_PROJID;
4712
4713 if (!(test_opt(inode->i_sb, NO_UID32))) {
4714 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4715 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4716 }
4717 i_uid_write(inode, i_uid);
4718 i_gid_write(inode, i_gid);
4719 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4720 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4721
4722 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4723 ei->i_inline_off = 0;
4724 ei->i_dir_start_lookup = 0;
4725 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4726 /* We now have enough fields to check if the inode was active or not.
4727 * This is needed because nfsd might try to access dead inodes
4728 * the test is that same one that e2fsck uses
4729 * NeilBrown 1999oct15
4730 */
4731 if (inode->i_nlink == 0) {
4732 if ((inode->i_mode == 0 ||
4733 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4734 ino != EXT4_BOOT_LOADER_INO) {
4735 /* this inode is deleted */
4736 ret = -ESTALE;
4737 goto bad_inode;
4738 }
4739 /* The only unlinked inodes we let through here have
4740 * valid i_mode and are being read by the orphan
4741 * recovery code: that's fine, we're about to complete
4742 * the process of deleting those.
4743 * OR it is the EXT4_BOOT_LOADER_INO which is
4744 * not initialized on a new filesystem. */
4745 }
4746 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02004747 ext4_set_inode_flags(inode, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004748 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4749 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4750 if (ext4_has_feature_64bit(sb))
4751 ei->i_file_acl |=
4752 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4753 inode->i_size = ext4_isize(sb, raw_inode);
4754 if ((size = i_size_read(inode)) < 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00004755 ext4_error_inode(inode, function, line, 0,
4756 "iget: bad i_size value: %lld", size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004757 ret = -EFSCORRUPTED;
4758 goto bad_inode;
4759 }
Olivier Deprez0e641232021-09-23 10:07:05 +02004760 /*
4761 * If dir_index is not enabled but there's dir with INDEX flag set,
4762 * we'd normally treat htree data as empty space. But with metadata
4763 * checksumming that corrupts checksums so forbid that.
4764 */
4765 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4766 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4767 ext4_error_inode(inode, function, line, 0,
4768 "iget: Dir with htree data on filesystem without dir_index feature.");
4769 ret = -EFSCORRUPTED;
4770 goto bad_inode;
4771 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004772 ei->i_disksize = inode->i_size;
4773#ifdef CONFIG_QUOTA
4774 ei->i_reserved_quota = 0;
4775#endif
4776 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4777 ei->i_block_group = iloc.block_group;
4778 ei->i_last_alloc_group = ~0;
4779 /*
4780 * NOTE! The in-memory inode i_data array is in little-endian order
4781 * even on big-endian machines: we do NOT byteswap the block numbers!
4782 */
4783 for (block = 0; block < EXT4_N_BLOCKS; block++)
4784 ei->i_data[block] = raw_inode->i_block[block];
4785 INIT_LIST_HEAD(&ei->i_orphan);
Olivier Deprez157378f2022-04-04 15:47:50 +02004786 ext4_fc_init_inode(&ei->vfs_inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004787
4788 /*
4789 * Set transaction id's of transactions that have to be committed
4790 * to finish f[data]sync. We set them to currently running transaction
4791 * as we cannot be sure that the inode or some of its metadata isn't
4792 * part of the transaction - the inode could have been reclaimed and
4793 * now it is reread from disk.
4794 */
4795 if (journal) {
4796 transaction_t *transaction;
4797 tid_t tid;
4798
4799 read_lock(&journal->j_state_lock);
4800 if (journal->j_running_transaction)
4801 transaction = journal->j_running_transaction;
4802 else
4803 transaction = journal->j_committing_transaction;
4804 if (transaction)
4805 tid = transaction->t_tid;
4806 else
4807 tid = journal->j_commit_sequence;
4808 read_unlock(&journal->j_state_lock);
4809 ei->i_sync_tid = tid;
4810 ei->i_datasync_tid = tid;
4811 }
4812
4813 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4814 if (ei->i_extra_isize == 0) {
4815 /* The extra space is currently unused. Use it. */
4816 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4817 ei->i_extra_isize = sizeof(struct ext4_inode) -
4818 EXT4_GOOD_OLD_INODE_SIZE;
4819 } else {
4820 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4821 if (ret)
4822 goto bad_inode;
4823 }
4824 }
4825
4826 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4827 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4828 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4829 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4830
4831 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4832 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4833
4834 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4835 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4836 ivers |=
4837 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4838 }
4839 ext4_inode_set_iversion_queried(inode, ivers);
4840 }
4841
4842 ret = 0;
4843 if (ei->i_file_acl &&
Olivier Deprez157378f2022-04-04 15:47:50 +02004844 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004845 ext4_error_inode(inode, function, line, 0,
4846 "iget: bad extended attribute block %llu",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004847 ei->i_file_acl);
4848 ret = -EFSCORRUPTED;
4849 goto bad_inode;
4850 } else if (!ext4_has_inline_data(inode)) {
4851 /* validate the block references in the inode */
Olivier Deprez157378f2022-04-04 15:47:50 +02004852 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4853 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4854 (S_ISLNK(inode->i_mode) &&
4855 !ext4_inode_is_fast_symlink(inode)))) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004856 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4857 ret = ext4_ext_check_inode(inode);
4858 else
4859 ret = ext4_ind_check_inode(inode);
4860 }
4861 }
4862 if (ret)
4863 goto bad_inode;
4864
4865 if (S_ISREG(inode->i_mode)) {
4866 inode->i_op = &ext4_file_inode_operations;
4867 inode->i_fop = &ext4_file_operations;
4868 ext4_set_aops(inode);
4869 } else if (S_ISDIR(inode->i_mode)) {
4870 inode->i_op = &ext4_dir_inode_operations;
4871 inode->i_fop = &ext4_dir_operations;
4872 } else if (S_ISLNK(inode->i_mode)) {
4873 /* VFS does not allow setting these so must be corruption */
4874 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004875 ext4_error_inode(inode, function, line, 0,
4876 "iget: immutable or append flags "
4877 "not allowed on symlinks");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004878 ret = -EFSCORRUPTED;
4879 goto bad_inode;
4880 }
David Brazdil0f672f62019-12-10 10:32:29 +00004881 if (IS_ENCRYPTED(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004882 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4883 ext4_set_aops(inode);
4884 } else if (ext4_inode_is_fast_symlink(inode)) {
4885 inode->i_link = (char *)ei->i_data;
4886 inode->i_op = &ext4_fast_symlink_inode_operations;
4887 nd_terminate_link(ei->i_data, inode->i_size,
4888 sizeof(ei->i_data) - 1);
4889 } else {
4890 inode->i_op = &ext4_symlink_inode_operations;
4891 ext4_set_aops(inode);
4892 }
4893 inode_nohighmem(inode);
4894 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4895 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4896 inode->i_op = &ext4_special_inode_operations;
4897 if (raw_inode->i_block[0])
4898 init_special_inode(inode, inode->i_mode,
4899 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4900 else
4901 init_special_inode(inode, inode->i_mode,
4902 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4903 } else if (ino == EXT4_BOOT_LOADER_INO) {
4904 make_bad_inode(inode);
4905 } else {
4906 ret = -EFSCORRUPTED;
David Brazdil0f672f62019-12-10 10:32:29 +00004907 ext4_error_inode(inode, function, line, 0,
4908 "iget: bogus i_mode (%o)", inode->i_mode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004909 goto bad_inode;
4910 }
David Brazdil0f672f62019-12-10 10:32:29 +00004911 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4912 ext4_error_inode(inode, function, line, 0,
4913 "casefold flag without casefold feature");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004914 brelse(iloc.bh);
4915
4916 unlock_new_inode(inode);
4917 return inode;
4918
4919bad_inode:
4920 brelse(iloc.bh);
4921 iget_failed(inode);
4922 return ERR_PTR(ret);
4923}
4924
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004925static int ext4_inode_blocks_set(handle_t *handle,
4926 struct ext4_inode *raw_inode,
4927 struct ext4_inode_info *ei)
4928{
4929 struct inode *inode = &(ei->vfs_inode);
Olivier Deprez0e641232021-09-23 10:07:05 +02004930 u64 i_blocks = READ_ONCE(inode->i_blocks);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004931 struct super_block *sb = inode->i_sb;
4932
4933 if (i_blocks <= ~0U) {
4934 /*
4935 * i_blocks can be represented in a 32 bit variable
4936 * as multiple of 512 bytes
4937 */
4938 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4939 raw_inode->i_blocks_high = 0;
4940 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4941 return 0;
4942 }
4943 if (!ext4_has_feature_huge_file(sb))
4944 return -EFBIG;
4945
4946 if (i_blocks <= 0xffffffffffffULL) {
4947 /*
4948 * i_blocks can be represented in a 48 bit variable
4949 * as multiple of 512 bytes
4950 */
4951 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4952 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4953 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4954 } else {
4955 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4956 /* i_block is stored in file system block size */
4957 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4958 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4959 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4960 }
4961 return 0;
4962}
4963
Olivier Deprez157378f2022-04-04 15:47:50 +02004964static void __ext4_update_other_inode_time(struct super_block *sb,
4965 unsigned long orig_ino,
4966 unsigned long ino,
4967 struct ext4_inode *raw_inode)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004968{
Olivier Deprez157378f2022-04-04 15:47:50 +02004969 struct inode *inode;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004970
Olivier Deprez157378f2022-04-04 15:47:50 +02004971 inode = find_inode_by_ino_rcu(sb, ino);
4972 if (!inode)
4973 return;
4974
4975 if ((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004976 I_DIRTY_INODE)) ||
4977 ((inode->i_state & I_DIRTY_TIME) == 0))
Olivier Deprez157378f2022-04-04 15:47:50 +02004978 return;
4979
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004980 spin_lock(&inode->i_lock);
4981 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4982 I_DIRTY_INODE)) == 0) &&
4983 (inode->i_state & I_DIRTY_TIME)) {
4984 struct ext4_inode_info *ei = EXT4_I(inode);
4985
Olivier Deprez0e641232021-09-23 10:07:05 +02004986 inode->i_state &= ~I_DIRTY_TIME;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004987 spin_unlock(&inode->i_lock);
4988
4989 spin_lock(&ei->i_raw_lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02004990 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4991 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4992 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4993 ext4_inode_csum_set(inode, raw_inode, ei);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004994 spin_unlock(&ei->i_raw_lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02004995 trace_ext4_other_inode_update_time(inode, orig_ino);
4996 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004997 }
4998 spin_unlock(&inode->i_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004999}
5000
5001/*
5002 * Opportunistically update the other time fields for other inodes in
5003 * the same inode table block.
5004 */
5005static void ext4_update_other_inodes_time(struct super_block *sb,
5006 unsigned long orig_ino, char *buf)
5007{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005008 unsigned long ino;
5009 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5010 int inode_size = EXT4_INODE_SIZE(sb);
5011
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005012 /*
5013 * Calculate the first inode in the inode table block. Inode
5014 * numbers are one-based. That is, the first inode in a block
5015 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5016 */
5017 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
Olivier Deprez157378f2022-04-04 15:47:50 +02005018 rcu_read_lock();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005019 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5020 if (ino == orig_ino)
5021 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02005022 __ext4_update_other_inode_time(sb, orig_ino, ino,
5023 (struct ext4_inode *)buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005024 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005025 rcu_read_unlock();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005026}
5027
5028/*
5029 * Post the struct inode info into an on-disk inode location in the
5030 * buffer-cache. This gobbles the caller's reference to the
5031 * buffer_head in the inode location struct.
5032 *
5033 * The caller must have write access to iloc->bh.
5034 */
5035static int ext4_do_update_inode(handle_t *handle,
5036 struct inode *inode,
5037 struct ext4_iloc *iloc)
5038{
5039 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5040 struct ext4_inode_info *ei = EXT4_I(inode);
5041 struct buffer_head *bh = iloc->bh;
5042 struct super_block *sb = inode->i_sb;
Olivier Deprez0e641232021-09-23 10:07:05 +02005043 int err = 0, block;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005044 int need_datasync = 0, set_large_file = 0;
5045 uid_t i_uid;
5046 gid_t i_gid;
5047 projid_t i_projid;
5048
5049 spin_lock(&ei->i_raw_lock);
5050
5051 /* For fields not tracked in the in-memory inode,
5052 * initialise them to zero for new inodes. */
5053 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5054 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5055
Olivier Deprez0e641232021-09-23 10:07:05 +02005056 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5057 if (err) {
5058 spin_unlock(&ei->i_raw_lock);
5059 goto out_brelse;
5060 }
5061
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005062 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5063 i_uid = i_uid_read(inode);
5064 i_gid = i_gid_read(inode);
5065 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5066 if (!(test_opt(inode->i_sb, NO_UID32))) {
5067 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5068 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5069/*
5070 * Fix up interoperability with old kernels. Otherwise, old inodes get
5071 * re-used with the upper 16 bits of the uid/gid intact
5072 */
5073 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5074 raw_inode->i_uid_high = 0;
5075 raw_inode->i_gid_high = 0;
5076 } else {
5077 raw_inode->i_uid_high =
5078 cpu_to_le16(high_16_bits(i_uid));
5079 raw_inode->i_gid_high =
5080 cpu_to_le16(high_16_bits(i_gid));
5081 }
5082 } else {
5083 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5084 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5085 raw_inode->i_uid_high = 0;
5086 raw_inode->i_gid_high = 0;
5087 }
5088 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5089
5090 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5091 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5092 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5093 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5094
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005095 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5096 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5097 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5098 raw_inode->i_file_acl_high =
5099 cpu_to_le16(ei->i_file_acl >> 32);
5100 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
Olivier Deprez0e641232021-09-23 10:07:05 +02005101 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005102 ext4_isize_set(raw_inode, ei->i_disksize);
5103 need_datasync = 1;
5104 }
5105 if (ei->i_disksize > 0x7fffffffULL) {
5106 if (!ext4_has_feature_large_file(sb) ||
5107 EXT4_SB(sb)->s_es->s_rev_level ==
5108 cpu_to_le32(EXT4_GOOD_OLD_REV))
5109 set_large_file = 1;
5110 }
5111 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5112 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5113 if (old_valid_dev(inode->i_rdev)) {
5114 raw_inode->i_block[0] =
5115 cpu_to_le32(old_encode_dev(inode->i_rdev));
5116 raw_inode->i_block[1] = 0;
5117 } else {
5118 raw_inode->i_block[0] = 0;
5119 raw_inode->i_block[1] =
5120 cpu_to_le32(new_encode_dev(inode->i_rdev));
5121 raw_inode->i_block[2] = 0;
5122 }
5123 } else if (!ext4_has_inline_data(inode)) {
5124 for (block = 0; block < EXT4_N_BLOCKS; block++)
5125 raw_inode->i_block[block] = ei->i_data[block];
5126 }
5127
5128 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5129 u64 ivers = ext4_inode_peek_iversion(inode);
5130
5131 raw_inode->i_disk_version = cpu_to_le32(ivers);
5132 if (ei->i_extra_isize) {
5133 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5134 raw_inode->i_version_hi =
5135 cpu_to_le32(ivers >> 32);
5136 raw_inode->i_extra_isize =
5137 cpu_to_le16(ei->i_extra_isize);
5138 }
5139 }
5140
5141 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5142 i_projid != EXT4_DEF_PROJID);
5143
5144 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5145 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5146 raw_inode->i_projid = cpu_to_le32(i_projid);
5147
5148 ext4_inode_csum_set(inode, raw_inode, ei);
5149 spin_unlock(&ei->i_raw_lock);
5150 if (inode->i_sb->s_flags & SB_LAZYTIME)
5151 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5152 bh->b_data);
5153
5154 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
Olivier Deprez0e641232021-09-23 10:07:05 +02005155 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5156 if (err)
5157 goto out_brelse;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005158 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5159 if (set_large_file) {
5160 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5161 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5162 if (err)
5163 goto out_brelse;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005164 ext4_set_feature_large_file(sb);
5165 ext4_handle_sync(handle);
5166 err = ext4_handle_dirty_super(handle, sb);
5167 }
5168 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5169out_brelse:
5170 brelse(bh);
5171 ext4_std_error(inode->i_sb, err);
5172 return err;
5173}
5174
5175/*
5176 * ext4_write_inode()
5177 *
5178 * We are called from a few places:
5179 *
5180 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5181 * Here, there will be no transaction running. We wait for any running
5182 * transaction to commit.
5183 *
5184 * - Within flush work (sys_sync(), kupdate and such).
5185 * We wait on commit, if told to.
5186 *
5187 * - Within iput_final() -> write_inode_now()
5188 * We wait on commit, if told to.
5189 *
5190 * In all cases it is actually safe for us to return without doing anything,
5191 * because the inode has been copied into a raw inode buffer in
5192 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5193 * writeback.
5194 *
5195 * Note that we are absolutely dependent upon all inode dirtiers doing the
5196 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5197 * which we are interested.
5198 *
5199 * It would be a bug for them to not do this. The code:
5200 *
5201 * mark_inode_dirty(inode)
5202 * stuff();
5203 * inode->i_size = expr;
5204 *
5205 * is in error because write_inode() could occur while `stuff()' is running,
5206 * and the new i_size will be lost. Plus the inode will no longer be on the
5207 * superblock's dirty inode list.
5208 */
5209int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5210{
5211 int err;
5212
David Brazdil0f672f62019-12-10 10:32:29 +00005213 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5214 sb_rdonly(inode->i_sb))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005215 return 0;
5216
David Brazdil0f672f62019-12-10 10:32:29 +00005217 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5218 return -EIO;
5219
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005220 if (EXT4_SB(inode->i_sb)->s_journal) {
5221 if (ext4_journal_current_handle()) {
5222 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5223 dump_stack();
5224 return -EIO;
5225 }
5226
5227 /*
5228 * No need to force transaction in WB_SYNC_NONE mode. Also
5229 * ext4_sync_fs() will force the commit after everything is
5230 * written.
5231 */
5232 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5233 return 0;
5234
Olivier Deprez157378f2022-04-04 15:47:50 +02005235 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
David Brazdil0f672f62019-12-10 10:32:29 +00005236 EXT4_I(inode)->i_sync_tid);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005237 } else {
5238 struct ext4_iloc iloc;
5239
Olivier Deprez157378f2022-04-04 15:47:50 +02005240 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005241 if (err)
5242 return err;
5243 /*
5244 * sync(2) will flush the whole buffer cache. No need to do
5245 * it here separately for each inode.
5246 */
5247 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5248 sync_dirty_buffer(iloc.bh);
5249 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005250 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5251 "IO error syncing inode");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005252 err = -EIO;
5253 }
5254 brelse(iloc.bh);
5255 }
5256 return err;
5257}
5258
5259/*
5260 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5261 * buffers that are attached to a page stradding i_size and are undergoing
5262 * commit. In that case we have to wait for commit to finish and try again.
5263 */
5264static void ext4_wait_for_tail_page_commit(struct inode *inode)
5265{
5266 struct page *page;
5267 unsigned offset;
5268 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5269 tid_t commit_tid = 0;
5270 int ret;
5271
5272 offset = inode->i_size & (PAGE_SIZE - 1);
5273 /*
Olivier Deprez0e641232021-09-23 10:07:05 +02005274 * If the page is fully truncated, we don't need to wait for any commit
5275 * (and we even should not as __ext4_journalled_invalidatepage() may
5276 * strip all buffers from the page but keep the page dirty which can then
5277 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5278 * buffers). Also we don't need to wait for any commit if all buffers in
5279 * the page remain valid. This is most beneficial for the common case of
5280 * blocksize == PAGESIZE.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005281 */
Olivier Deprez0e641232021-09-23 10:07:05 +02005282 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005283 return;
5284 while (1) {
5285 page = find_lock_page(inode->i_mapping,
5286 inode->i_size >> PAGE_SHIFT);
5287 if (!page)
5288 return;
5289 ret = __ext4_journalled_invalidatepage(page, offset,
5290 PAGE_SIZE - offset);
5291 unlock_page(page);
5292 put_page(page);
5293 if (ret != -EBUSY)
5294 return;
5295 commit_tid = 0;
5296 read_lock(&journal->j_state_lock);
5297 if (journal->j_committing_transaction)
5298 commit_tid = journal->j_committing_transaction->t_tid;
5299 read_unlock(&journal->j_state_lock);
5300 if (commit_tid)
5301 jbd2_log_wait_commit(journal, commit_tid);
5302 }
5303}
5304
5305/*
5306 * ext4_setattr()
5307 *
5308 * Called from notify_change.
5309 *
5310 * We want to trap VFS attempts to truncate the file as soon as
5311 * possible. In particular, we want to make sure that when the VFS
5312 * shrinks i_size, we put the inode on the orphan list and modify
5313 * i_disksize immediately, so that during the subsequent flushing of
5314 * dirty pages and freeing of disk blocks, we can guarantee that any
5315 * commit will leave the blocks being flushed in an unused state on
5316 * disk. (On recovery, the inode will get truncated and the blocks will
5317 * be freed, so we have a strong guarantee that no future commit will
5318 * leave these blocks visible to the user.)
5319 *
5320 * Another thing we have to assure is that if we are in ordered mode
5321 * and inode is still attached to the committing transaction, we must
5322 * we start writeout of all the dirty pages which are being truncated.
5323 * This way we are sure that all the data written in the previous
5324 * transaction are already on disk (truncate waits for pages under
5325 * writeback).
5326 *
5327 * Called with inode->i_mutex down.
5328 */
5329int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5330{
5331 struct inode *inode = d_inode(dentry);
5332 int error, rc = 0;
5333 int orphan = 0;
5334 const unsigned int ia_valid = attr->ia_valid;
5335
5336 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5337 return -EIO;
5338
David Brazdil0f672f62019-12-10 10:32:29 +00005339 if (unlikely(IS_IMMUTABLE(inode)))
5340 return -EPERM;
5341
5342 if (unlikely(IS_APPEND(inode) &&
5343 (ia_valid & (ATTR_MODE | ATTR_UID |
5344 ATTR_GID | ATTR_TIMES_SET))))
5345 return -EPERM;
5346
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005347 error = setattr_prepare(dentry, attr);
5348 if (error)
5349 return error;
5350
5351 error = fscrypt_prepare_setattr(dentry, attr);
5352 if (error)
5353 return error;
5354
David Brazdil0f672f62019-12-10 10:32:29 +00005355 error = fsverity_prepare_setattr(dentry, attr);
5356 if (error)
5357 return error;
5358
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005359 if (is_quota_modification(inode, attr)) {
5360 error = dquot_initialize(inode);
5361 if (error)
5362 return error;
5363 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005364 ext4_fc_start_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005365 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5366 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5367 handle_t *handle;
5368
5369 /* (user+group)*(old+new) structure, inode write (sb,
5370 * inode block, ? - but truncate inode update has it) */
5371 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5372 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5373 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5374 if (IS_ERR(handle)) {
5375 error = PTR_ERR(handle);
5376 goto err_out;
5377 }
5378
5379 /* dquot_transfer() calls back ext4_get_inode_usage() which
5380 * counts xattr inode references.
5381 */
5382 down_read(&EXT4_I(inode)->xattr_sem);
5383 error = dquot_transfer(inode, attr);
5384 up_read(&EXT4_I(inode)->xattr_sem);
5385
5386 if (error) {
5387 ext4_journal_stop(handle);
Olivier Deprez157378f2022-04-04 15:47:50 +02005388 ext4_fc_stop_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005389 return error;
5390 }
5391 /* Update corresponding info in inode so that everything is in
5392 * one transaction */
5393 if (attr->ia_valid & ATTR_UID)
5394 inode->i_uid = attr->ia_uid;
5395 if (attr->ia_valid & ATTR_GID)
5396 inode->i_gid = attr->ia_gid;
5397 error = ext4_mark_inode_dirty(handle, inode);
5398 ext4_journal_stop(handle);
Olivier Deprez157378f2022-04-04 15:47:50 +02005399 if (unlikely(error)) {
5400 ext4_fc_stop_update(inode);
5401 return error;
5402 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005403 }
5404
5405 if (attr->ia_valid & ATTR_SIZE) {
5406 handle_t *handle;
5407 loff_t oldsize = inode->i_size;
David Brazdil0f672f62019-12-10 10:32:29 +00005408 int shrink = (attr->ia_size < inode->i_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005409
5410 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5411 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5412
Olivier Deprez157378f2022-04-04 15:47:50 +02005413 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5414 ext4_fc_stop_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005415 return -EFBIG;
Olivier Deprez157378f2022-04-04 15:47:50 +02005416 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005417 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005418 if (!S_ISREG(inode->i_mode)) {
5419 ext4_fc_stop_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005420 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005421 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005422
5423 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5424 inode_inc_iversion(inode);
5425
David Brazdil0f672f62019-12-10 10:32:29 +00005426 if (shrink) {
5427 if (ext4_should_order_data(inode)) {
5428 error = ext4_begin_ordered_truncate(inode,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005429 attr->ia_size);
David Brazdil0f672f62019-12-10 10:32:29 +00005430 if (error)
5431 goto err_out;
5432 }
5433 /*
5434 * Blocks are going to be removed from the inode. Wait
5435 * for dio in flight.
5436 */
5437 inode_dio_wait(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005438 }
David Brazdil0f672f62019-12-10 10:32:29 +00005439
5440 down_write(&EXT4_I(inode)->i_mmap_sem);
5441
5442 rc = ext4_break_layouts(inode);
5443 if (rc) {
5444 up_write(&EXT4_I(inode)->i_mmap_sem);
Olivier Deprez157378f2022-04-04 15:47:50 +02005445 goto err_out;
David Brazdil0f672f62019-12-10 10:32:29 +00005446 }
5447
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005448 if (attr->ia_size != inode->i_size) {
5449 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5450 if (IS_ERR(handle)) {
5451 error = PTR_ERR(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00005452 goto out_mmap_sem;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005453 }
5454 if (ext4_handle_valid(handle) && shrink) {
5455 error = ext4_orphan_add(handle, inode);
5456 orphan = 1;
5457 }
5458 /*
5459 * Update c/mtime on truncate up, ext4_truncate() will
5460 * update c/mtime in shrink case below
5461 */
5462 if (!shrink) {
5463 inode->i_mtime = current_time(inode);
5464 inode->i_ctime = inode->i_mtime;
5465 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005466
5467 if (shrink)
5468 ext4_fc_track_range(handle, inode,
5469 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5470 inode->i_sb->s_blocksize_bits,
5471 EXT_MAX_BLOCKS - 1);
5472 else
5473 ext4_fc_track_range(
5474 handle, inode,
5475 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5476 inode->i_sb->s_blocksize_bits,
5477 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5478 inode->i_sb->s_blocksize_bits);
5479
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005480 down_write(&EXT4_I(inode)->i_data_sem);
5481 EXT4_I(inode)->i_disksize = attr->ia_size;
5482 rc = ext4_mark_inode_dirty(handle, inode);
5483 if (!error)
5484 error = rc;
5485 /*
5486 * We have to update i_size under i_data_sem together
5487 * with i_disksize to avoid races with writeback code
5488 * running ext4_wb_update_i_disksize().
5489 */
5490 if (!error)
5491 i_size_write(inode, attr->ia_size);
5492 up_write(&EXT4_I(inode)->i_data_sem);
5493 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00005494 if (error)
5495 goto out_mmap_sem;
5496 if (!shrink) {
5497 pagecache_isize_extended(inode, oldsize,
5498 inode->i_size);
5499 } else if (ext4_should_journal_data(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005500 ext4_wait_for_tail_page_commit(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00005501 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005502 }
5503
5504 /*
5505 * Truncate pagecache after we've waited for commit
5506 * in data=journal mode to make pages freeable.
5507 */
5508 truncate_pagecache(inode, inode->i_size);
David Brazdil0f672f62019-12-10 10:32:29 +00005509 /*
5510 * Call ext4_truncate() even if i_size didn't change to
5511 * truncate possible preallocated blocks.
5512 */
5513 if (attr->ia_size <= oldsize) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005514 rc = ext4_truncate(inode);
5515 if (rc)
5516 error = rc;
5517 }
David Brazdil0f672f62019-12-10 10:32:29 +00005518out_mmap_sem:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005519 up_write(&EXT4_I(inode)->i_mmap_sem);
5520 }
5521
5522 if (!error) {
5523 setattr_copy(inode, attr);
5524 mark_inode_dirty(inode);
5525 }
5526
5527 /*
5528 * If the call to ext4_truncate failed to get a transaction handle at
5529 * all, we need to clean up the in-core orphan list manually.
5530 */
5531 if (orphan && inode->i_nlink)
5532 ext4_orphan_del(NULL, inode);
5533
5534 if (!error && (ia_valid & ATTR_MODE))
5535 rc = posix_acl_chmod(inode, inode->i_mode);
5536
5537err_out:
Olivier Deprez157378f2022-04-04 15:47:50 +02005538 if (error)
5539 ext4_std_error(inode->i_sb, error);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005540 if (!error)
5541 error = rc;
Olivier Deprez157378f2022-04-04 15:47:50 +02005542 ext4_fc_stop_update(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005543 return error;
5544}
5545
5546int ext4_getattr(const struct path *path, struct kstat *stat,
5547 u32 request_mask, unsigned int query_flags)
5548{
5549 struct inode *inode = d_inode(path->dentry);
5550 struct ext4_inode *raw_inode;
5551 struct ext4_inode_info *ei = EXT4_I(inode);
5552 unsigned int flags;
5553
Olivier Deprez157378f2022-04-04 15:47:50 +02005554 if ((request_mask & STATX_BTIME) &&
5555 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005556 stat->result_mask |= STATX_BTIME;
5557 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5558 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5559 }
5560
5561 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5562 if (flags & EXT4_APPEND_FL)
5563 stat->attributes |= STATX_ATTR_APPEND;
5564 if (flags & EXT4_COMPR_FL)
5565 stat->attributes |= STATX_ATTR_COMPRESSED;
5566 if (flags & EXT4_ENCRYPT_FL)
5567 stat->attributes |= STATX_ATTR_ENCRYPTED;
5568 if (flags & EXT4_IMMUTABLE_FL)
5569 stat->attributes |= STATX_ATTR_IMMUTABLE;
5570 if (flags & EXT4_NODUMP_FL)
5571 stat->attributes |= STATX_ATTR_NODUMP;
Olivier Deprez157378f2022-04-04 15:47:50 +02005572 if (flags & EXT4_VERITY_FL)
5573 stat->attributes |= STATX_ATTR_VERITY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005574
5575 stat->attributes_mask |= (STATX_ATTR_APPEND |
5576 STATX_ATTR_COMPRESSED |
5577 STATX_ATTR_ENCRYPTED |
5578 STATX_ATTR_IMMUTABLE |
Olivier Deprez157378f2022-04-04 15:47:50 +02005579 STATX_ATTR_NODUMP |
5580 STATX_ATTR_VERITY);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005581
5582 generic_fillattr(inode, stat);
5583 return 0;
5584}
5585
5586int ext4_file_getattr(const struct path *path, struct kstat *stat,
5587 u32 request_mask, unsigned int query_flags)
5588{
5589 struct inode *inode = d_inode(path->dentry);
5590 u64 delalloc_blocks;
5591
5592 ext4_getattr(path, stat, request_mask, query_flags);
5593
5594 /*
5595 * If there is inline data in the inode, the inode will normally not
5596 * have data blocks allocated (it may have an external xattr block).
5597 * Report at least one sector for such files, so tools like tar, rsync,
5598 * others don't incorrectly think the file is completely sparse.
5599 */
5600 if (unlikely(ext4_has_inline_data(inode)))
5601 stat->blocks += (stat->size + 511) >> 9;
5602
5603 /*
5604 * We can't update i_blocks if the block allocation is delayed
5605 * otherwise in the case of system crash before the real block
5606 * allocation is done, we will have i_blocks inconsistent with
5607 * on-disk file blocks.
5608 * We always keep i_blocks updated together with real
5609 * allocation. But to not confuse with user, stat
5610 * will return the blocks that include the delayed allocation
5611 * blocks for this file.
5612 */
5613 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5614 EXT4_I(inode)->i_reserved_data_blocks);
5615 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5616 return 0;
5617}
5618
5619static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5620 int pextents)
5621{
5622 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5623 return ext4_ind_trans_blocks(inode, lblocks);
5624 return ext4_ext_index_trans_blocks(inode, pextents);
5625}
5626
5627/*
5628 * Account for index blocks, block groups bitmaps and block group
5629 * descriptor blocks if modify datablocks and index blocks
5630 * worse case, the indexs blocks spread over different block groups
5631 *
5632 * If datablocks are discontiguous, they are possible to spread over
5633 * different block groups too. If they are contiguous, with flexbg,
5634 * they could still across block group boundary.
5635 *
5636 * Also account for superblock, inode, quota and xattr blocks
5637 */
5638static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5639 int pextents)
5640{
5641 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5642 int gdpblocks;
5643 int idxblocks;
5644 int ret = 0;
5645
5646 /*
5647 * How many index blocks need to touch to map @lblocks logical blocks
5648 * to @pextents physical extents?
5649 */
5650 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5651
5652 ret = idxblocks;
5653
5654 /*
5655 * Now let's see how many group bitmaps and group descriptors need
5656 * to account
5657 */
5658 groups = idxblocks + pextents;
5659 gdpblocks = groups;
5660 if (groups > ngroups)
5661 groups = ngroups;
5662 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5663 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5664
5665 /* bitmaps and block group descriptor blocks */
5666 ret += groups + gdpblocks;
5667
5668 /* Blocks for super block, inode, quota and xattr blocks */
5669 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5670
5671 return ret;
5672}
5673
5674/*
5675 * Calculate the total number of credits to reserve to fit
5676 * the modification of a single pages into a single transaction,
5677 * which may include multiple chunks of block allocations.
5678 *
5679 * This could be called via ext4_write_begin()
5680 *
5681 * We need to consider the worse case, when
5682 * one new block per extent.
5683 */
5684int ext4_writepage_trans_blocks(struct inode *inode)
5685{
5686 int bpp = ext4_journal_blocks_per_page(inode);
5687 int ret;
5688
5689 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5690
5691 /* Account for data blocks for journalled mode */
5692 if (ext4_should_journal_data(inode))
5693 ret += bpp;
5694 return ret;
5695}
5696
5697/*
5698 * Calculate the journal credits for a chunk of data modification.
5699 *
5700 * This is called from DIO, fallocate or whoever calling
5701 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5702 *
5703 * journal buffers for data blocks are not included here, as DIO
5704 * and fallocate do no need to journal data buffers.
5705 */
5706int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5707{
5708 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5709}
5710
5711/*
5712 * The caller must have previously called ext4_reserve_inode_write().
5713 * Give this, we know that the caller already has write access to iloc->bh.
5714 */
5715int ext4_mark_iloc_dirty(handle_t *handle,
5716 struct inode *inode, struct ext4_iloc *iloc)
5717{
5718 int err = 0;
5719
5720 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5721 put_bh(iloc->bh);
5722 return -EIO;
5723 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005724 ext4_fc_track_inode(handle, inode);
5725
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005726 if (IS_I_VERSION(inode))
5727 inode_inc_iversion(inode);
5728
5729 /* the do_update_inode consumes one bh->b_count */
5730 get_bh(iloc->bh);
5731
5732 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5733 err = ext4_do_update_inode(handle, inode, iloc);
5734 put_bh(iloc->bh);
5735 return err;
5736}
5737
5738/*
5739 * On success, We end up with an outstanding reference count against
5740 * iloc->bh. This _must_ be cleaned up later.
5741 */
5742
5743int
5744ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5745 struct ext4_iloc *iloc)
5746{
5747 int err;
5748
5749 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5750 return -EIO;
5751
5752 err = ext4_get_inode_loc(inode, iloc);
5753 if (!err) {
5754 BUFFER_TRACE(iloc->bh, "get_write_access");
5755 err = ext4_journal_get_write_access(handle, iloc->bh);
5756 if (err) {
5757 brelse(iloc->bh);
5758 iloc->bh = NULL;
5759 }
5760 }
5761 ext4_std_error(inode->i_sb, err);
5762 return err;
5763}
5764
5765static int __ext4_expand_extra_isize(struct inode *inode,
5766 unsigned int new_extra_isize,
5767 struct ext4_iloc *iloc,
5768 handle_t *handle, int *no_expand)
5769{
5770 struct ext4_inode *raw_inode;
5771 struct ext4_xattr_ibody_header *header;
David Brazdil0f672f62019-12-10 10:32:29 +00005772 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5773 struct ext4_inode_info *ei = EXT4_I(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005774 int error;
5775
David Brazdil0f672f62019-12-10 10:32:29 +00005776 /* this was checked at iget time, but double check for good measure */
5777 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5778 (ei->i_extra_isize & 3)) {
5779 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5780 ei->i_extra_isize,
5781 EXT4_INODE_SIZE(inode->i_sb));
5782 return -EFSCORRUPTED;
5783 }
5784 if ((new_extra_isize < ei->i_extra_isize) ||
5785 (new_extra_isize < 4) ||
5786 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5787 return -EINVAL; /* Should never happen */
5788
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005789 raw_inode = ext4_raw_inode(iloc);
5790
5791 header = IHDR(inode, raw_inode);
5792
5793 /* No extended attributes present */
5794 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5795 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5796 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5797 EXT4_I(inode)->i_extra_isize, 0,
5798 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5799 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5800 return 0;
5801 }
5802
5803 /* try to expand with EAs present */
5804 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5805 raw_inode, handle);
5806 if (error) {
5807 /*
5808 * Inode size expansion failed; don't try again
5809 */
5810 *no_expand = 1;
5811 }
5812
5813 return error;
5814}
5815
5816/*
5817 * Expand an inode by new_extra_isize bytes.
5818 * Returns 0 on success or negative error number on failure.
5819 */
5820static int ext4_try_to_expand_extra_isize(struct inode *inode,
5821 unsigned int new_extra_isize,
5822 struct ext4_iloc iloc,
5823 handle_t *handle)
5824{
5825 int no_expand;
5826 int error;
5827
5828 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5829 return -EOVERFLOW;
5830
5831 /*
5832 * In nojournal mode, we can immediately attempt to expand
5833 * the inode. When journaled, we first need to obtain extra
5834 * buffer credits since we may write into the EA block
5835 * with this same handle. If journal_extend fails, then it will
5836 * only result in a minor loss of functionality for that inode.
5837 * If this is felt to be critical, then e2fsck should be run to
5838 * force a large enough s_min_extra_isize.
5839 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005840 if (ext4_journal_extend(handle,
5841 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005842 return -ENOSPC;
5843
5844 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5845 return -EBUSY;
5846
5847 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5848 handle, &no_expand);
5849 ext4_write_unlock_xattr(inode, &no_expand);
5850
5851 return error;
5852}
5853
5854int ext4_expand_extra_isize(struct inode *inode,
5855 unsigned int new_extra_isize,
5856 struct ext4_iloc *iloc)
5857{
5858 handle_t *handle;
5859 int no_expand;
5860 int error, rc;
5861
5862 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5863 brelse(iloc->bh);
5864 return -EOVERFLOW;
5865 }
5866
5867 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5868 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5869 if (IS_ERR(handle)) {
5870 error = PTR_ERR(handle);
5871 brelse(iloc->bh);
5872 return error;
5873 }
5874
5875 ext4_write_lock_xattr(inode, &no_expand);
5876
David Brazdil0f672f62019-12-10 10:32:29 +00005877 BUFFER_TRACE(iloc->bh, "get_write_access");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005878 error = ext4_journal_get_write_access(handle, iloc->bh);
5879 if (error) {
5880 brelse(iloc->bh);
Olivier Deprez0e641232021-09-23 10:07:05 +02005881 goto out_unlock;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005882 }
5883
5884 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5885 handle, &no_expand);
5886
5887 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5888 if (!error)
5889 error = rc;
5890
Olivier Deprez0e641232021-09-23 10:07:05 +02005891out_unlock:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005892 ext4_write_unlock_xattr(inode, &no_expand);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005893 ext4_journal_stop(handle);
5894 return error;
5895}
5896
5897/*
5898 * What we do here is to mark the in-core inode as clean with respect to inode
5899 * dirtiness (it may still be data-dirty).
5900 * This means that the in-core inode may be reaped by prune_icache
5901 * without having to perform any I/O. This is a very good thing,
5902 * because *any* task may call prune_icache - even ones which
5903 * have a transaction open against a different journal.
5904 *
5905 * Is this cheating? Not really. Sure, we haven't written the
5906 * inode out, but prune_icache isn't a user-visible syncing function.
5907 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5908 * we start and wait on commits.
5909 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005910int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5911 const char *func, unsigned int line)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005912{
5913 struct ext4_iloc iloc;
5914 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5915 int err;
5916
5917 might_sleep();
5918 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5919 err = ext4_reserve_inode_write(handle, inode, &iloc);
5920 if (err)
Olivier Deprez157378f2022-04-04 15:47:50 +02005921 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005922
5923 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5924 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5925 iloc, handle);
5926
Olivier Deprez157378f2022-04-04 15:47:50 +02005927 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5928out:
5929 if (unlikely(err))
5930 ext4_error_inode_err(inode, func, line, 0, err,
5931 "mark_inode_dirty error");
5932 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005933}
5934
5935/*
5936 * ext4_dirty_inode() is called from __mark_inode_dirty()
5937 *
5938 * We're really interested in the case where a file is being extended.
5939 * i_size has been changed by generic_commit_write() and we thus need
5940 * to include the updated inode in the current transaction.
5941 *
5942 * Also, dquot_alloc_block() will always dirty the inode when blocks
5943 * are allocated to the file.
5944 *
5945 * If the inode is marked synchronous, we don't honour that here - doing
5946 * so would cause a commit on atime updates, which we don't bother doing.
5947 * We handle synchronous inodes at the highest possible level.
5948 *
5949 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5950 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5951 * to copy into the on-disk inode structure are the timestamp files.
5952 */
5953void ext4_dirty_inode(struct inode *inode, int flags)
5954{
5955 handle_t *handle;
5956
5957 if (flags == I_DIRTY_TIME)
5958 return;
5959 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5960 if (IS_ERR(handle))
5961 goto out;
5962
5963 ext4_mark_inode_dirty(handle, inode);
5964
5965 ext4_journal_stop(handle);
5966out:
5967 return;
5968}
5969
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005970int ext4_change_inode_journal_flag(struct inode *inode, int val)
5971{
5972 journal_t *journal;
5973 handle_t *handle;
5974 int err;
5975 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5976
5977 /*
5978 * We have to be very careful here: changing a data block's
5979 * journaling status dynamically is dangerous. If we write a
5980 * data block to the journal, change the status and then delete
5981 * that block, we risk forgetting to revoke the old log record
5982 * from the journal and so a subsequent replay can corrupt data.
5983 * So, first we make sure that the journal is empty and that
5984 * nobody is changing anything.
5985 */
5986
5987 journal = EXT4_JOURNAL(inode);
5988 if (!journal)
5989 return 0;
5990 if (is_journal_aborted(journal))
5991 return -EROFS;
5992
5993 /* Wait for all existing dio workers */
5994 inode_dio_wait(inode);
5995
5996 /*
5997 * Before flushing the journal and switching inode's aops, we have
5998 * to flush all dirty data the inode has. There can be outstanding
5999 * delayed allocations, there can be unwritten extents created by
6000 * fallocate or buffered writes in dioread_nolock mode covered by
6001 * dirty data which can be converted only after flushing the dirty
6002 * data (and journalled aops don't know how to handle these cases).
6003 */
6004 if (val) {
6005 down_write(&EXT4_I(inode)->i_mmap_sem);
6006 err = filemap_write_and_wait(inode->i_mapping);
6007 if (err < 0) {
6008 up_write(&EXT4_I(inode)->i_mmap_sem);
6009 return err;
6010 }
6011 }
6012
Olivier Deprez0e641232021-09-23 10:07:05 +02006013 percpu_down_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006014 jbd2_journal_lock_updates(journal);
6015
6016 /*
6017 * OK, there are no updates running now, and all cached data is
6018 * synced to disk. We are now in a completely consistent state
6019 * which doesn't have anything in the journal, and we know that
6020 * no filesystem updates are running, so it is safe to modify
6021 * the inode's in-core data-journaling state flag now.
6022 */
6023
6024 if (val)
6025 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6026 else {
6027 err = jbd2_journal_flush(journal);
6028 if (err < 0) {
6029 jbd2_journal_unlock_updates(journal);
Olivier Deprez0e641232021-09-23 10:07:05 +02006030 percpu_up_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006031 return err;
6032 }
6033 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6034 }
6035 ext4_set_aops(inode);
6036
6037 jbd2_journal_unlock_updates(journal);
Olivier Deprez0e641232021-09-23 10:07:05 +02006038 percpu_up_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006039
6040 if (val)
6041 up_write(&EXT4_I(inode)->i_mmap_sem);
6042
6043 /* Finally we can mark the inode as dirty. */
6044
6045 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6046 if (IS_ERR(handle))
6047 return PTR_ERR(handle);
6048
Olivier Deprez157378f2022-04-04 15:47:50 +02006049 ext4_fc_mark_ineligible(inode->i_sb,
6050 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006051 err = ext4_mark_inode_dirty(handle, inode);
6052 ext4_handle_sync(handle);
6053 ext4_journal_stop(handle);
6054 ext4_std_error(inode->i_sb, err);
6055
6056 return err;
6057}
6058
6059static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6060{
6061 return !buffer_mapped(bh);
6062}
6063
David Brazdil0f672f62019-12-10 10:32:29 +00006064vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006065{
6066 struct vm_area_struct *vma = vmf->vma;
6067 struct page *page = vmf->page;
6068 loff_t size;
6069 unsigned long len;
David Brazdil0f672f62019-12-10 10:32:29 +00006070 int err;
6071 vm_fault_t ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006072 struct file *file = vma->vm_file;
6073 struct inode *inode = file_inode(file);
6074 struct address_space *mapping = inode->i_mapping;
6075 handle_t *handle;
6076 get_block_t *get_block;
6077 int retries = 0;
6078
David Brazdil0f672f62019-12-10 10:32:29 +00006079 if (unlikely(IS_IMMUTABLE(inode)))
6080 return VM_FAULT_SIGBUS;
6081
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006082 sb_start_pagefault(inode->i_sb);
6083 file_update_time(vma->vm_file);
6084
6085 down_read(&EXT4_I(inode)->i_mmap_sem);
6086
David Brazdil0f672f62019-12-10 10:32:29 +00006087 err = ext4_convert_inline_data(inode);
6088 if (err)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006089 goto out_ret;
6090
Olivier Deprez157378f2022-04-04 15:47:50 +02006091 /*
6092 * On data journalling we skip straight to the transaction handle:
6093 * there's no delalloc; page truncated will be checked later; the
6094 * early return w/ all buffers mapped (calculates size/len) can't
6095 * be used; and there's no dioread_nolock, so only ext4_get_block.
6096 */
6097 if (ext4_should_journal_data(inode))
6098 goto retry_alloc;
6099
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006100 /* Delalloc case is easy... */
6101 if (test_opt(inode->i_sb, DELALLOC) &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006102 !ext4_nonda_switch(inode->i_sb)) {
6103 do {
David Brazdil0f672f62019-12-10 10:32:29 +00006104 err = block_page_mkwrite(vma, vmf,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006105 ext4_da_get_block_prep);
David Brazdil0f672f62019-12-10 10:32:29 +00006106 } while (err == -ENOSPC &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006107 ext4_should_retry_alloc(inode->i_sb, &retries));
6108 goto out_ret;
6109 }
6110
6111 lock_page(page);
6112 size = i_size_read(inode);
6113 /* Page got truncated from under us? */
6114 if (page->mapping != mapping || page_offset(page) > size) {
6115 unlock_page(page);
6116 ret = VM_FAULT_NOPAGE;
6117 goto out;
6118 }
6119
6120 if (page->index == size >> PAGE_SHIFT)
6121 len = size & ~PAGE_MASK;
6122 else
6123 len = PAGE_SIZE;
6124 /*
6125 * Return if we have all the buffers mapped. This avoids the need to do
6126 * journal_start/journal_stop which can block and take a long time
Olivier Deprez157378f2022-04-04 15:47:50 +02006127 *
6128 * This cannot be done for data journalling, as we have to add the
6129 * inode to the transaction's list to writeprotect pages on commit.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006130 */
6131 if (page_has_buffers(page)) {
6132 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6133 0, len, NULL,
6134 ext4_bh_unmapped)) {
6135 /* Wait so that we don't change page under IO */
6136 wait_for_stable_page(page);
6137 ret = VM_FAULT_LOCKED;
6138 goto out;
6139 }
6140 }
6141 unlock_page(page);
6142 /* OK, we need to fill the hole... */
6143 if (ext4_should_dioread_nolock(inode))
6144 get_block = ext4_get_block_unwritten;
6145 else
6146 get_block = ext4_get_block;
6147retry_alloc:
6148 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6149 ext4_writepage_trans_blocks(inode));
6150 if (IS_ERR(handle)) {
6151 ret = VM_FAULT_SIGBUS;
6152 goto out;
6153 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006154 /*
6155 * Data journalling can't use block_page_mkwrite() because it
6156 * will set_buffer_dirty() before do_journal_get_write_access()
6157 * thus might hit warning messages for dirty metadata buffers.
6158 */
6159 if (!ext4_should_journal_data(inode)) {
6160 err = block_page_mkwrite(vma, vmf, get_block);
6161 } else {
6162 lock_page(page);
6163 size = i_size_read(inode);
6164 /* Page got truncated from under us? */
6165 if (page->mapping != mapping || page_offset(page) > size) {
6166 ret = VM_FAULT_NOPAGE;
6167 goto out_error;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006168 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006169
6170 if (page->index == size >> PAGE_SHIFT)
6171 len = size & ~PAGE_MASK;
6172 else
6173 len = PAGE_SIZE;
6174
6175 err = __block_write_begin(page, 0, len, ext4_get_block);
6176 if (!err) {
6177 ret = VM_FAULT_SIGBUS;
6178 if (ext4_walk_page_buffers(handle, page_buffers(page),
6179 0, len, NULL, do_journal_get_write_access))
6180 goto out_error;
6181 if (ext4_walk_page_buffers(handle, page_buffers(page),
6182 0, len, NULL, write_end_fn))
6183 goto out_error;
6184 if (ext4_jbd2_inode_add_write(handle, inode,
6185 page_offset(page), len))
6186 goto out_error;
6187 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6188 } else {
6189 unlock_page(page);
6190 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006191 }
6192 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00006193 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006194 goto retry_alloc;
6195out_ret:
David Brazdil0f672f62019-12-10 10:32:29 +00006196 ret = block_page_mkwrite_return(err);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006197out:
6198 up_read(&EXT4_I(inode)->i_mmap_sem);
6199 sb_end_pagefault(inode->i_sb);
6200 return ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02006201out_error:
6202 unlock_page(page);
6203 ext4_journal_stop(handle);
6204 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006205}
6206
David Brazdil0f672f62019-12-10 10:32:29 +00006207vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006208{
6209 struct inode *inode = file_inode(vmf->vma->vm_file);
David Brazdil0f672f62019-12-10 10:32:29 +00006210 vm_fault_t ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006211
6212 down_read(&EXT4_I(inode)->i_mmap_sem);
David Brazdil0f672f62019-12-10 10:32:29 +00006213 ret = filemap_fault(vmf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006214 up_read(&EXT4_I(inode)->i_mmap_sem);
6215
David Brazdil0f672f62019-12-10 10:32:29 +00006216 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006217}