blob: 1429d01d836bba08a2f28b12fba6edefe71b05fe [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
51#define MPAGE_DA_EXTENT_TAIL 0x01
52
53static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
54 struct ext4_inode_info *ei)
55{
56 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57 __u32 csum;
58 __u16 dummy_csum = 0;
59 int offset = offsetof(struct ext4_inode, i_checksum_lo);
60 unsigned int csum_size = sizeof(dummy_csum);
61
62 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
63 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
64 offset += csum_size;
65 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
66 EXT4_GOOD_OLD_INODE_SIZE - offset);
67
68 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
69 offset = offsetof(struct ext4_inode, i_checksum_hi);
70 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
71 EXT4_GOOD_OLD_INODE_SIZE,
72 offset - EXT4_GOOD_OLD_INODE_SIZE);
73 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
74 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
75 csum_size);
76 offset += csum_size;
77 }
78 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
79 EXT4_INODE_SIZE(inode->i_sb) - offset);
80 }
81
82 return csum;
83}
84
85static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
86 struct ext4_inode_info *ei)
87{
88 __u32 provided, calculated;
89
90 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
91 cpu_to_le32(EXT4_OS_LINUX) ||
92 !ext4_has_metadata_csum(inode->i_sb))
93 return 1;
94
95 provided = le16_to_cpu(raw->i_checksum_lo);
96 calculated = ext4_inode_csum(inode, raw, ei);
97 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
98 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
99 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 else
101 calculated &= 0xFFFF;
102
103 return provided == calculated;
104}
105
106static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
107 struct ext4_inode_info *ei)
108{
109 __u32 csum;
110
111 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
112 cpu_to_le32(EXT4_OS_LINUX) ||
113 !ext4_has_metadata_csum(inode->i_sb))
114 return;
115
116 csum = ext4_inode_csum(inode, raw, ei);
117 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
118 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
119 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
120 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
121}
122
123static inline int ext4_begin_ordered_truncate(struct inode *inode,
124 loff_t new_size)
125{
126 trace_ext4_begin_ordered_truncate(inode, new_size);
127 /*
128 * If jinode is zero, then we never opened the file for
129 * writing, so there's no need to call
130 * jbd2_journal_begin_ordered_truncate() since there's no
131 * outstanding writes we need to flush.
132 */
133 if (!EXT4_I(inode)->jinode)
134 return 0;
135 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
136 EXT4_I(inode)->jinode,
137 new_size);
138}
139
140static void ext4_invalidatepage(struct page *page, unsigned int offset,
141 unsigned int length);
142static int __ext4_journalled_writepage(struct page *page, unsigned int len);
143static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
144static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
145 int pextents);
146
147/*
148 * Test whether an inode is a fast symlink.
149 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
150 */
151int ext4_inode_is_fast_symlink(struct inode *inode)
152{
153 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
154 int ea_blocks = EXT4_I(inode)->i_file_acl ?
155 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
156
157 if (ext4_has_inline_data(inode))
158 return 0;
159
160 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
161 }
162 return S_ISLNK(inode->i_mode) && inode->i_size &&
163 (inode->i_size < EXT4_N_BLOCKS * 4);
164}
165
166/*
167 * Restart the transaction associated with *handle. This does a commit,
168 * so before we call here everything must be consistently dirtied against
169 * this transaction.
170 */
171int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
172 int nblocks)
173{
174 int ret;
175
176 /*
177 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
178 * moment, get_block can be called only for blocks inside i_size since
179 * page cache has been already dropped and writes are blocked by
180 * i_mutex. So we can safely drop the i_data_sem here.
181 */
182 BUG_ON(EXT4_JOURNAL(inode) == NULL);
183 jbd_debug(2, "restarting handle %p\n", handle);
184 up_write(&EXT4_I(inode)->i_data_sem);
185 ret = ext4_journal_restart(handle, nblocks);
186 down_write(&EXT4_I(inode)->i_data_sem);
187 ext4_discard_preallocations(inode);
188
189 return ret;
190}
191
192/*
193 * Called at the last iput() if i_nlink is zero.
194 */
195void ext4_evict_inode(struct inode *inode)
196{
197 handle_t *handle;
198 int err;
Olivier Deprez0e641232021-09-23 10:07:05 +0200199 /*
200 * Credits for final inode cleanup and freeing:
201 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
202 * (xattr block freeing), bitmap, group descriptor (inode freeing)
203 */
204 int extra_credits = 6;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000205 struct ext4_xattr_inode_array *ea_inode_array = NULL;
Olivier Deprez0e641232021-09-23 10:07:05 +0200206 bool freeze_protected = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000207
208 trace_ext4_evict_inode(inode);
209
210 if (inode->i_nlink) {
211 /*
212 * When journalling data dirty buffers are tracked only in the
213 * journal. So although mm thinks everything is clean and
214 * ready for reaping the inode might still have some pages to
215 * write in the running transaction or waiting to be
216 * checkpointed. Thus calling jbd2_journal_invalidatepage()
217 * (via truncate_inode_pages()) to discard these buffers can
218 * cause data loss. Also even if we did not discard these
219 * buffers, we would have no way to find them after the inode
220 * is reaped and thus user could see stale data if he tries to
221 * read them before the transaction is checkpointed. So be
222 * careful and force everything to disk here... We use
223 * ei->i_datasync_tid to store the newest transaction
224 * containing inode's data.
225 *
226 * Note that directories do not have this problem because they
227 * don't use page cache.
228 */
229 if (inode->i_ino != EXT4_JOURNAL_INO &&
230 ext4_should_journal_data(inode) &&
231 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
232 inode->i_data.nrpages) {
233 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
234 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
235
236 jbd2_complete_transaction(journal, commit_tid);
237 filemap_write_and_wait(&inode->i_data);
238 }
239 truncate_inode_pages_final(&inode->i_data);
240
241 goto no_delete;
242 }
243
244 if (is_bad_inode(inode))
245 goto no_delete;
246 dquot_initialize(inode);
247
248 if (ext4_should_order_data(inode))
249 ext4_begin_ordered_truncate(inode, 0);
250 truncate_inode_pages_final(&inode->i_data);
251
252 /*
253 * Protect us against freezing - iput() caller didn't have to have any
Olivier Deprez0e641232021-09-23 10:07:05 +0200254 * protection against it. When we are in a running transaction though,
255 * we are already protected against freezing and we cannot grab further
256 * protection due to lock ordering constraints.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000257 */
Olivier Deprez0e641232021-09-23 10:07:05 +0200258 if (!ext4_journal_current_handle()) {
259 sb_start_intwrite(inode->i_sb);
260 freeze_protected = true;
261 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000262
263 if (!IS_NOQUOTA(inode))
264 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
265
Olivier Deprez0e641232021-09-23 10:07:05 +0200266 /*
267 * Block bitmap, group descriptor, and inode are accounted in both
268 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
269 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000270 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
Olivier Deprez0e641232021-09-23 10:07:05 +0200271 ext4_blocks_for_truncate(inode) + extra_credits - 3);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000272 if (IS_ERR(handle)) {
273 ext4_std_error(inode->i_sb, PTR_ERR(handle));
274 /*
275 * If we're going to skip the normal cleanup, we still need to
276 * make sure that the in-core orphan linked list is properly
277 * cleaned up.
278 */
279 ext4_orphan_del(NULL, inode);
Olivier Deprez0e641232021-09-23 10:07:05 +0200280 if (freeze_protected)
281 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000282 goto no_delete;
283 }
284
285 if (IS_SYNC(inode))
286 ext4_handle_sync(handle);
287
288 /*
289 * Set inode->i_size to 0 before calling ext4_truncate(). We need
290 * special handling of symlinks here because i_size is used to
291 * determine whether ext4_inode_info->i_data contains symlink data or
292 * block mappings. Setting i_size to 0 will remove its fast symlink
293 * status. Erase i_data so that it becomes a valid empty block map.
294 */
295 if (ext4_inode_is_fast_symlink(inode))
296 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
297 inode->i_size = 0;
298 err = ext4_mark_inode_dirty(handle, inode);
299 if (err) {
300 ext4_warning(inode->i_sb,
301 "couldn't mark inode dirty (err %d)", err);
302 goto stop_handle;
303 }
304 if (inode->i_blocks) {
305 err = ext4_truncate(inode);
306 if (err) {
307 ext4_error(inode->i_sb,
308 "couldn't truncate inode %lu (err %d)",
309 inode->i_ino, err);
310 goto stop_handle;
311 }
312 }
313
314 /* Remove xattr references. */
315 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
316 extra_credits);
317 if (err) {
318 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
319stop_handle:
320 ext4_journal_stop(handle);
321 ext4_orphan_del(NULL, inode);
Olivier Deprez0e641232021-09-23 10:07:05 +0200322 if (freeze_protected)
323 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000324 ext4_xattr_inode_array_free(ea_inode_array);
325 goto no_delete;
326 }
327
328 /*
329 * Kill off the orphan record which ext4_truncate created.
330 * AKPM: I think this can be inside the above `if'.
331 * Note that ext4_orphan_del() has to be able to cope with the
332 * deletion of a non-existent orphan - this is because we don't
333 * know if ext4_truncate() actually created an orphan record.
334 * (Well, we could do this if we need to, but heck - it works)
335 */
336 ext4_orphan_del(handle, inode);
337 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
338
339 /*
340 * One subtle ordering requirement: if anything has gone wrong
341 * (transaction abort, IO errors, whatever), then we can still
342 * do these next steps (the fs will already have been marked as
343 * having errors), but we can't free the inode if the mark_dirty
344 * fails.
345 */
346 if (ext4_mark_inode_dirty(handle, inode))
347 /* If that failed, just do the required in-core inode clear. */
348 ext4_clear_inode(inode);
349 else
350 ext4_free_inode(handle, inode);
351 ext4_journal_stop(handle);
Olivier Deprez0e641232021-09-23 10:07:05 +0200352 if (freeze_protected)
353 sb_end_intwrite(inode->i_sb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000354 ext4_xattr_inode_array_free(ea_inode_array);
355 return;
356no_delete:
357 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
358}
359
360#ifdef CONFIG_QUOTA
361qsize_t *ext4_get_reserved_space(struct inode *inode)
362{
363 return &EXT4_I(inode)->i_reserved_quota;
364}
365#endif
366
367/*
368 * Called with i_data_sem down, which is important since we can call
369 * ext4_discard_preallocations() from here.
370 */
371void ext4_da_update_reserve_space(struct inode *inode,
372 int used, int quota_claim)
373{
374 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
375 struct ext4_inode_info *ei = EXT4_I(inode);
376
377 spin_lock(&ei->i_block_reservation_lock);
378 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
379 if (unlikely(used > ei->i_reserved_data_blocks)) {
380 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
381 "with only %d reserved data blocks",
382 __func__, inode->i_ino, used,
383 ei->i_reserved_data_blocks);
384 WARN_ON(1);
385 used = ei->i_reserved_data_blocks;
386 }
387
388 /* Update per-inode reservations */
389 ei->i_reserved_data_blocks -= used;
390 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
391
392 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
393
394 /* Update quota subsystem for data blocks */
395 if (quota_claim)
396 dquot_claim_block(inode, EXT4_C2B(sbi, used));
397 else {
398 /*
399 * We did fallocate with an offset that is already delayed
400 * allocated. So on delayed allocated writeback we should
401 * not re-claim the quota for fallocated blocks.
402 */
403 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
404 }
405
406 /*
407 * If we have done all the pending block allocations and if
408 * there aren't any writers on the inode, we can discard the
409 * inode's preallocations.
410 */
411 if ((ei->i_reserved_data_blocks == 0) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000412 !inode_is_open_for_write(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000413 ext4_discard_preallocations(inode);
414}
415
416static int __check_block_validity(struct inode *inode, const char *func,
417 unsigned int line,
418 struct ext4_map_blocks *map)
419{
David Brazdil0f672f62019-12-10 10:32:29 +0000420 if (ext4_has_feature_journal(inode->i_sb) &&
421 (inode->i_ino ==
422 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
423 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
425 map->m_len)) {
426 ext4_error_inode(inode, func, line, map->m_pblk,
427 "lblock %lu mapped to illegal pblock %llu "
428 "(length %d)", (unsigned long) map->m_lblk,
429 map->m_pblk, map->m_len);
430 return -EFSCORRUPTED;
431 }
432 return 0;
433}
434
435int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
436 ext4_lblk_t len)
437{
438 int ret;
439
David Brazdil0f672f62019-12-10 10:32:29 +0000440 if (IS_ENCRYPTED(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000441 return fscrypt_zeroout_range(inode, lblk, pblk, len);
442
443 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
444 if (ret > 0)
445 ret = 0;
446
447 return ret;
448}
449
450#define check_block_validity(inode, map) \
451 __check_block_validity((inode), __func__, __LINE__, (map))
452
453#ifdef ES_AGGRESSIVE_TEST
454static void ext4_map_blocks_es_recheck(handle_t *handle,
455 struct inode *inode,
456 struct ext4_map_blocks *es_map,
457 struct ext4_map_blocks *map,
458 int flags)
459{
460 int retval;
461
462 map->m_flags = 0;
463 /*
464 * There is a race window that the result is not the same.
465 * e.g. xfstests #223 when dioread_nolock enables. The reason
466 * is that we lookup a block mapping in extent status tree with
467 * out taking i_data_sem. So at the time the unwritten extent
468 * could be converted.
469 */
470 down_read(&EXT4_I(inode)->i_data_sem);
471 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
472 retval = ext4_ext_map_blocks(handle, inode, map, flags &
473 EXT4_GET_BLOCKS_KEEP_SIZE);
474 } else {
475 retval = ext4_ind_map_blocks(handle, inode, map, flags &
476 EXT4_GET_BLOCKS_KEEP_SIZE);
477 }
478 up_read((&EXT4_I(inode)->i_data_sem));
479
480 /*
481 * We don't check m_len because extent will be collpased in status
482 * tree. So the m_len might not equal.
483 */
484 if (es_map->m_lblk != map->m_lblk ||
485 es_map->m_flags != map->m_flags ||
486 es_map->m_pblk != map->m_pblk) {
487 printk("ES cache assertion failed for inode: %lu "
488 "es_cached ex [%d/%d/%llu/%x] != "
489 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
490 inode->i_ino, es_map->m_lblk, es_map->m_len,
491 es_map->m_pblk, es_map->m_flags, map->m_lblk,
492 map->m_len, map->m_pblk, map->m_flags,
493 retval, flags);
494 }
495}
496#endif /* ES_AGGRESSIVE_TEST */
497
498/*
499 * The ext4_map_blocks() function tries to look up the requested blocks,
500 * and returns if the blocks are already mapped.
501 *
502 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
503 * and store the allocated blocks in the result buffer head and mark it
504 * mapped.
505 *
506 * If file type is extents based, it will call ext4_ext_map_blocks(),
507 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
508 * based files
509 *
510 * On success, it returns the number of blocks being mapped or allocated. if
511 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
512 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
513 *
514 * It returns 0 if plain look up failed (blocks have not been allocated), in
515 * that case, @map is returned as unmapped but we still do fill map->m_len to
516 * indicate the length of a hole starting at map->m_lblk.
517 *
518 * It returns the error in case of allocation failure.
519 */
520int ext4_map_blocks(handle_t *handle, struct inode *inode,
521 struct ext4_map_blocks *map, int flags)
522{
523 struct extent_status es;
524 int retval;
525 int ret = 0;
526#ifdef ES_AGGRESSIVE_TEST
527 struct ext4_map_blocks orig_map;
528
529 memcpy(&orig_map, map, sizeof(*map));
530#endif
531
532 map->m_flags = 0;
533 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
534 "logical block %lu\n", inode->i_ino, flags, map->m_len,
535 (unsigned long) map->m_lblk);
536
537 /*
538 * ext4_map_blocks returns an int, and m_len is an unsigned int
539 */
540 if (unlikely(map->m_len > INT_MAX))
541 map->m_len = INT_MAX;
542
543 /* We can handle the block number less than EXT_MAX_BLOCKS */
544 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
545 return -EFSCORRUPTED;
546
547 /* Lookup extent status tree firstly */
David Brazdil0f672f62019-12-10 10:32:29 +0000548 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000549 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
550 map->m_pblk = ext4_es_pblock(&es) +
551 map->m_lblk - es.es_lblk;
552 map->m_flags |= ext4_es_is_written(&es) ?
553 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
554 retval = es.es_len - (map->m_lblk - es.es_lblk);
555 if (retval > map->m_len)
556 retval = map->m_len;
557 map->m_len = retval;
558 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
559 map->m_pblk = 0;
560 retval = es.es_len - (map->m_lblk - es.es_lblk);
561 if (retval > map->m_len)
562 retval = map->m_len;
563 map->m_len = retval;
564 retval = 0;
565 } else {
David Brazdil0f672f62019-12-10 10:32:29 +0000566 BUG();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000567 }
568#ifdef ES_AGGRESSIVE_TEST
569 ext4_map_blocks_es_recheck(handle, inode, map,
570 &orig_map, flags);
571#endif
572 goto found;
573 }
574
575 /*
576 * Try to see if we can get the block without requesting a new
577 * file system block.
578 */
579 down_read(&EXT4_I(inode)->i_data_sem);
580 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
581 retval = ext4_ext_map_blocks(handle, inode, map, flags &
582 EXT4_GET_BLOCKS_KEEP_SIZE);
583 } else {
584 retval = ext4_ind_map_blocks(handle, inode, map, flags &
585 EXT4_GET_BLOCKS_KEEP_SIZE);
586 }
587 if (retval > 0) {
588 unsigned int status;
589
590 if (unlikely(retval != map->m_len)) {
591 ext4_warning(inode->i_sb,
592 "ES len assertion failed for inode "
593 "%lu: retval %d != map->m_len %d",
594 inode->i_ino, retval, map->m_len);
595 WARN_ON(1);
596 }
597
598 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
599 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
600 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
601 !(status & EXTENT_STATUS_WRITTEN) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000602 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
603 map->m_lblk + map->m_len - 1))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000604 status |= EXTENT_STATUS_DELAYED;
605 ret = ext4_es_insert_extent(inode, map->m_lblk,
606 map->m_len, map->m_pblk, status);
607 if (ret < 0)
608 retval = ret;
609 }
610 up_read((&EXT4_I(inode)->i_data_sem));
611
612found:
613 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
614 ret = check_block_validity(inode, map);
615 if (ret != 0)
616 return ret;
617 }
618
619 /* If it is only a block(s) look up */
620 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
621 return retval;
622
623 /*
624 * Returns if the blocks have already allocated
625 *
626 * Note that if blocks have been preallocated
627 * ext4_ext_get_block() returns the create = 0
628 * with buffer head unmapped.
629 */
630 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
631 /*
632 * If we need to convert extent to unwritten
633 * we continue and do the actual work in
634 * ext4_ext_map_blocks()
635 */
636 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
637 return retval;
638
639 /*
640 * Here we clear m_flags because after allocating an new extent,
641 * it will be set again.
642 */
643 map->m_flags &= ~EXT4_MAP_FLAGS;
644
645 /*
646 * New blocks allocate and/or writing to unwritten extent
647 * will possibly result in updating i_data, so we take
648 * the write lock of i_data_sem, and call get_block()
649 * with create == 1 flag.
650 */
651 down_write(&EXT4_I(inode)->i_data_sem);
652
653 /*
654 * We need to check for EXT4 here because migrate
655 * could have changed the inode type in between
656 */
657 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
658 retval = ext4_ext_map_blocks(handle, inode, map, flags);
659 } else {
660 retval = ext4_ind_map_blocks(handle, inode, map, flags);
661
662 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
663 /*
664 * We allocated new blocks which will result in
665 * i_data's format changing. Force the migrate
666 * to fail by clearing migrate flags
667 */
668 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
669 }
670
671 /*
672 * Update reserved blocks/metadata blocks after successful
673 * block allocation which had been deferred till now. We don't
674 * support fallocate for non extent files. So we can update
675 * reserve space here.
676 */
677 if ((retval > 0) &&
678 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
679 ext4_da_update_reserve_space(inode, retval, 1);
680 }
681
682 if (retval > 0) {
683 unsigned int status;
684
685 if (unlikely(retval != map->m_len)) {
686 ext4_warning(inode->i_sb,
687 "ES len assertion failed for inode "
688 "%lu: retval %d != map->m_len %d",
689 inode->i_ino, retval, map->m_len);
690 WARN_ON(1);
691 }
692
693 /*
694 * We have to zeroout blocks before inserting them into extent
695 * status tree. Otherwise someone could look them up there and
696 * use them before they are really zeroed. We also have to
697 * unmap metadata before zeroing as otherwise writeback can
698 * overwrite zeros with stale data from block device.
699 */
700 if (flags & EXT4_GET_BLOCKS_ZERO &&
701 map->m_flags & EXT4_MAP_MAPPED &&
702 map->m_flags & EXT4_MAP_NEW) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000703 ret = ext4_issue_zeroout(inode, map->m_lblk,
704 map->m_pblk, map->m_len);
705 if (ret) {
706 retval = ret;
707 goto out_sem;
708 }
709 }
710
711 /*
712 * If the extent has been zeroed out, we don't need to update
713 * extent status tree.
714 */
715 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000716 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000717 if (ext4_es_is_written(&es))
718 goto out_sem;
719 }
720 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
721 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
722 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
723 !(status & EXTENT_STATUS_WRITTEN) &&
David Brazdil0f672f62019-12-10 10:32:29 +0000724 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
725 map->m_lblk + map->m_len - 1))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000726 status |= EXTENT_STATUS_DELAYED;
727 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
728 map->m_pblk, status);
729 if (ret < 0) {
730 retval = ret;
731 goto out_sem;
732 }
733 }
734
735out_sem:
736 up_write((&EXT4_I(inode)->i_data_sem));
737 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
738 ret = check_block_validity(inode, map);
739 if (ret != 0)
740 return ret;
741
742 /*
743 * Inodes with freshly allocated blocks where contents will be
744 * visible after transaction commit must be on transaction's
745 * ordered data list.
746 */
747 if (map->m_flags & EXT4_MAP_NEW &&
748 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
749 !(flags & EXT4_GET_BLOCKS_ZERO) &&
750 !ext4_is_quota_file(inode) &&
751 ext4_should_order_data(inode)) {
David Brazdil0f672f62019-12-10 10:32:29 +0000752 loff_t start_byte =
753 (loff_t)map->m_lblk << inode->i_blkbits;
754 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
755
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000756 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
David Brazdil0f672f62019-12-10 10:32:29 +0000757 ret = ext4_jbd2_inode_add_wait(handle, inode,
758 start_byte, length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000759 else
David Brazdil0f672f62019-12-10 10:32:29 +0000760 ret = ext4_jbd2_inode_add_write(handle, inode,
761 start_byte, length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000762 if (ret)
763 return ret;
764 }
765 }
766 return retval;
767}
768
769/*
770 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
771 * we have to be careful as someone else may be manipulating b_state as well.
772 */
773static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
774{
775 unsigned long old_state;
776 unsigned long new_state;
777
778 flags &= EXT4_MAP_FLAGS;
779
780 /* Dummy buffer_head? Set non-atomically. */
781 if (!bh->b_page) {
782 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
783 return;
784 }
785 /*
786 * Someone else may be modifying b_state. Be careful! This is ugly but
787 * once we get rid of using bh as a container for mapping information
788 * to pass to / from get_block functions, this can go away.
789 */
790 do {
791 old_state = READ_ONCE(bh->b_state);
792 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
793 } while (unlikely(
794 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
795}
796
797static int _ext4_get_block(struct inode *inode, sector_t iblock,
798 struct buffer_head *bh, int flags)
799{
800 struct ext4_map_blocks map;
801 int ret = 0;
802
803 if (ext4_has_inline_data(inode))
804 return -ERANGE;
805
806 map.m_lblk = iblock;
807 map.m_len = bh->b_size >> inode->i_blkbits;
808
809 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
810 flags);
811 if (ret > 0) {
812 map_bh(bh, inode->i_sb, map.m_pblk);
813 ext4_update_bh_state(bh, map.m_flags);
814 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
815 ret = 0;
816 } else if (ret == 0) {
817 /* hole case, need to fill in bh->b_size */
818 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
819 }
820 return ret;
821}
822
823int ext4_get_block(struct inode *inode, sector_t iblock,
824 struct buffer_head *bh, int create)
825{
826 return _ext4_get_block(inode, iblock, bh,
827 create ? EXT4_GET_BLOCKS_CREATE : 0);
828}
829
830/*
831 * Get block function used when preparing for buffered write if we require
832 * creating an unwritten extent if blocks haven't been allocated. The extent
833 * will be converted to written after the IO is complete.
834 */
835int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
836 struct buffer_head *bh_result, int create)
837{
838 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
839 inode->i_ino, create);
840 return _ext4_get_block(inode, iblock, bh_result,
841 EXT4_GET_BLOCKS_IO_CREATE_EXT);
842}
843
844/* Maximum number of blocks we map for direct IO at once. */
845#define DIO_MAX_BLOCKS 4096
846
847/*
848 * Get blocks function for the cases that need to start a transaction -
849 * generally difference cases of direct IO and DAX IO. It also handles retries
850 * in case of ENOSPC.
851 */
852static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
853 struct buffer_head *bh_result, int flags)
854{
855 int dio_credits;
856 handle_t *handle;
857 int retries = 0;
858 int ret;
859
860 /* Trim mapping request to maximum we can map at once for DIO */
861 if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
862 bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
863 dio_credits = ext4_chunk_trans_blocks(inode,
864 bh_result->b_size >> inode->i_blkbits);
865retry:
866 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
867 if (IS_ERR(handle))
868 return PTR_ERR(handle);
869
870 ret = _ext4_get_block(inode, iblock, bh_result, flags);
871 ext4_journal_stop(handle);
872
873 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
874 goto retry;
875 return ret;
876}
877
878/* Get block function for DIO reads and writes to inodes without extents */
879int ext4_dio_get_block(struct inode *inode, sector_t iblock,
880 struct buffer_head *bh, int create)
881{
882 /* We don't expect handle for direct IO */
883 WARN_ON_ONCE(ext4_journal_current_handle());
884
885 if (!create)
886 return _ext4_get_block(inode, iblock, bh, 0);
887 return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
888}
889
890/*
891 * Get block function for AIO DIO writes when we create unwritten extent if
892 * blocks are not allocated yet. The extent will be converted to written
893 * after IO is complete.
894 */
895static int ext4_dio_get_block_unwritten_async(struct inode *inode,
896 sector_t iblock, struct buffer_head *bh_result, int create)
897{
898 int ret;
899
900 /* We don't expect handle for direct IO */
901 WARN_ON_ONCE(ext4_journal_current_handle());
902
903 ret = ext4_get_block_trans(inode, iblock, bh_result,
904 EXT4_GET_BLOCKS_IO_CREATE_EXT);
905
906 /*
907 * When doing DIO using unwritten extents, we need io_end to convert
908 * unwritten extents to written on IO completion. We allocate io_end
909 * once we spot unwritten extent and store it in b_private. Generic
910 * DIO code keeps b_private set and furthermore passes the value to
911 * our completion callback in 'private' argument.
912 */
913 if (!ret && buffer_unwritten(bh_result)) {
914 if (!bh_result->b_private) {
915 ext4_io_end_t *io_end;
916
917 io_end = ext4_init_io_end(inode, GFP_KERNEL);
918 if (!io_end)
919 return -ENOMEM;
920 bh_result->b_private = io_end;
921 ext4_set_io_unwritten_flag(inode, io_end);
922 }
923 set_buffer_defer_completion(bh_result);
924 }
925
926 return ret;
927}
928
929/*
930 * Get block function for non-AIO DIO writes when we create unwritten extent if
931 * blocks are not allocated yet. The extent will be converted to written
932 * after IO is complete by ext4_direct_IO_write().
933 */
934static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
935 sector_t iblock, struct buffer_head *bh_result, int create)
936{
937 int ret;
938
939 /* We don't expect handle for direct IO */
940 WARN_ON_ONCE(ext4_journal_current_handle());
941
942 ret = ext4_get_block_trans(inode, iblock, bh_result,
943 EXT4_GET_BLOCKS_IO_CREATE_EXT);
944
945 /*
946 * Mark inode as having pending DIO writes to unwritten extents.
947 * ext4_direct_IO_write() checks this flag and converts extents to
948 * written.
949 */
950 if (!ret && buffer_unwritten(bh_result))
951 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
952
953 return ret;
954}
955
956static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
957 struct buffer_head *bh_result, int create)
958{
959 int ret;
960
961 ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
962 inode->i_ino, create);
963 /* We don't expect handle for direct IO */
964 WARN_ON_ONCE(ext4_journal_current_handle());
965
966 ret = _ext4_get_block(inode, iblock, bh_result, 0);
967 /*
968 * Blocks should have been preallocated! ext4_file_write_iter() checks
969 * that.
970 */
971 WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
972
973 return ret;
974}
975
976
977/*
978 * `handle' can be NULL if create is zero
979 */
980struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
981 ext4_lblk_t block, int map_flags)
982{
983 struct ext4_map_blocks map;
984 struct buffer_head *bh;
985 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
986 int err;
987
988 J_ASSERT(handle != NULL || create == 0);
989
990 map.m_lblk = block;
991 map.m_len = 1;
992 err = ext4_map_blocks(handle, inode, &map, map_flags);
993
994 if (err == 0)
995 return create ? ERR_PTR(-ENOSPC) : NULL;
996 if (err < 0)
997 return ERR_PTR(err);
998
999 bh = sb_getblk(inode->i_sb, map.m_pblk);
1000 if (unlikely(!bh))
1001 return ERR_PTR(-ENOMEM);
1002 if (map.m_flags & EXT4_MAP_NEW) {
1003 J_ASSERT(create != 0);
1004 J_ASSERT(handle != NULL);
1005
1006 /*
1007 * Now that we do not always journal data, we should
1008 * keep in mind whether this should always journal the
1009 * new buffer as metadata. For now, regular file
1010 * writes use ext4_get_block instead, so it's not a
1011 * problem.
1012 */
1013 lock_buffer(bh);
1014 BUFFER_TRACE(bh, "call get_create_access");
1015 err = ext4_journal_get_create_access(handle, bh);
1016 if (unlikely(err)) {
1017 unlock_buffer(bh);
1018 goto errout;
1019 }
1020 if (!buffer_uptodate(bh)) {
1021 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1022 set_buffer_uptodate(bh);
1023 }
1024 unlock_buffer(bh);
1025 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1026 err = ext4_handle_dirty_metadata(handle, inode, bh);
1027 if (unlikely(err))
1028 goto errout;
1029 } else
1030 BUFFER_TRACE(bh, "not a new buffer");
1031 return bh;
1032errout:
1033 brelse(bh);
1034 return ERR_PTR(err);
1035}
1036
1037struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1038 ext4_lblk_t block, int map_flags)
1039{
1040 struct buffer_head *bh;
1041
1042 bh = ext4_getblk(handle, inode, block, map_flags);
1043 if (IS_ERR(bh))
1044 return bh;
David Brazdil0f672f62019-12-10 10:32:29 +00001045 if (!bh || ext4_buffer_uptodate(bh))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001046 return bh;
1047 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
1048 wait_on_buffer(bh);
1049 if (buffer_uptodate(bh))
1050 return bh;
1051 put_bh(bh);
1052 return ERR_PTR(-EIO);
1053}
1054
1055/* Read a contiguous batch of blocks. */
1056int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1057 bool wait, struct buffer_head **bhs)
1058{
1059 int i, err;
1060
1061 for (i = 0; i < bh_count; i++) {
1062 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1063 if (IS_ERR(bhs[i])) {
1064 err = PTR_ERR(bhs[i]);
1065 bh_count = i;
1066 goto out_brelse;
1067 }
1068 }
1069
1070 for (i = 0; i < bh_count; i++)
1071 /* Note that NULL bhs[i] is valid because of holes. */
David Brazdil0f672f62019-12-10 10:32:29 +00001072 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001073 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
1074 &bhs[i]);
1075
1076 if (!wait)
1077 return 0;
1078
1079 for (i = 0; i < bh_count; i++)
1080 if (bhs[i])
1081 wait_on_buffer(bhs[i]);
1082
1083 for (i = 0; i < bh_count; i++) {
1084 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1085 err = -EIO;
1086 goto out_brelse;
1087 }
1088 }
1089 return 0;
1090
1091out_brelse:
1092 for (i = 0; i < bh_count; i++) {
1093 brelse(bhs[i]);
1094 bhs[i] = NULL;
1095 }
1096 return err;
1097}
1098
1099int ext4_walk_page_buffers(handle_t *handle,
1100 struct buffer_head *head,
1101 unsigned from,
1102 unsigned to,
1103 int *partial,
1104 int (*fn)(handle_t *handle,
1105 struct buffer_head *bh))
1106{
1107 struct buffer_head *bh;
1108 unsigned block_start, block_end;
1109 unsigned blocksize = head->b_size;
1110 int err, ret = 0;
1111 struct buffer_head *next;
1112
1113 for (bh = head, block_start = 0;
1114 ret == 0 && (bh != head || !block_start);
1115 block_start = block_end, bh = next) {
1116 next = bh->b_this_page;
1117 block_end = block_start + blocksize;
1118 if (block_end <= from || block_start >= to) {
1119 if (partial && !buffer_uptodate(bh))
1120 *partial = 1;
1121 continue;
1122 }
1123 err = (*fn)(handle, bh);
1124 if (!ret)
1125 ret = err;
1126 }
1127 return ret;
1128}
1129
1130/*
1131 * To preserve ordering, it is essential that the hole instantiation and
1132 * the data write be encapsulated in a single transaction. We cannot
1133 * close off a transaction and start a new one between the ext4_get_block()
1134 * and the commit_write(). So doing the jbd2_journal_start at the start of
1135 * prepare_write() is the right place.
1136 *
1137 * Also, this function can nest inside ext4_writepage(). In that case, we
1138 * *know* that ext4_writepage() has generated enough buffer credits to do the
1139 * whole page. So we won't block on the journal in that case, which is good,
1140 * because the caller may be PF_MEMALLOC.
1141 *
1142 * By accident, ext4 can be reentered when a transaction is open via
1143 * quota file writes. If we were to commit the transaction while thus
1144 * reentered, there can be a deadlock - we would be holding a quota
1145 * lock, and the commit would never complete if another thread had a
1146 * transaction open and was blocking on the quota lock - a ranking
1147 * violation.
1148 *
1149 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1150 * will _not_ run commit under these circumstances because handle->h_ref
1151 * is elevated. We'll still have enough credits for the tiny quotafile
1152 * write.
1153 */
1154int do_journal_get_write_access(handle_t *handle,
1155 struct buffer_head *bh)
1156{
1157 int dirty = buffer_dirty(bh);
1158 int ret;
1159
1160 if (!buffer_mapped(bh) || buffer_freed(bh))
1161 return 0;
1162 /*
1163 * __block_write_begin() could have dirtied some buffers. Clean
1164 * the dirty bit as jbd2_journal_get_write_access() could complain
1165 * otherwise about fs integrity issues. Setting of the dirty bit
1166 * by __block_write_begin() isn't a real problem here as we clear
1167 * the bit before releasing a page lock and thus writeback cannot
1168 * ever write the buffer.
1169 */
1170 if (dirty)
1171 clear_buffer_dirty(bh);
1172 BUFFER_TRACE(bh, "get write access");
1173 ret = ext4_journal_get_write_access(handle, bh);
1174 if (!ret && dirty)
1175 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1176 return ret;
1177}
1178
David Brazdil0f672f62019-12-10 10:32:29 +00001179#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001180static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1181 get_block_t *get_block)
1182{
1183 unsigned from = pos & (PAGE_SIZE - 1);
1184 unsigned to = from + len;
1185 struct inode *inode = page->mapping->host;
1186 unsigned block_start, block_end;
1187 sector_t block;
1188 int err = 0;
1189 unsigned blocksize = inode->i_sb->s_blocksize;
1190 unsigned bbits;
David Brazdil0f672f62019-12-10 10:32:29 +00001191 struct buffer_head *bh, *head, *wait[2];
1192 int nr_wait = 0;
1193 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001194
1195 BUG_ON(!PageLocked(page));
1196 BUG_ON(from > PAGE_SIZE);
1197 BUG_ON(to > PAGE_SIZE);
1198 BUG_ON(from > to);
1199
1200 if (!page_has_buffers(page))
1201 create_empty_buffers(page, blocksize, 0);
1202 head = page_buffers(page);
1203 bbits = ilog2(blocksize);
1204 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1205
1206 for (bh = head, block_start = 0; bh != head || !block_start;
1207 block++, block_start = block_end, bh = bh->b_this_page) {
1208 block_end = block_start + blocksize;
1209 if (block_end <= from || block_start >= to) {
1210 if (PageUptodate(page)) {
1211 if (!buffer_uptodate(bh))
1212 set_buffer_uptodate(bh);
1213 }
1214 continue;
1215 }
1216 if (buffer_new(bh))
1217 clear_buffer_new(bh);
1218 if (!buffer_mapped(bh)) {
1219 WARN_ON(bh->b_size != blocksize);
1220 err = get_block(inode, block, bh, 1);
1221 if (err)
1222 break;
1223 if (buffer_new(bh)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001224 if (PageUptodate(page)) {
1225 clear_buffer_new(bh);
1226 set_buffer_uptodate(bh);
1227 mark_buffer_dirty(bh);
1228 continue;
1229 }
1230 if (block_end > to || block_start < from)
1231 zero_user_segments(page, to, block_end,
1232 block_start, from);
1233 continue;
1234 }
1235 }
1236 if (PageUptodate(page)) {
1237 if (!buffer_uptodate(bh))
1238 set_buffer_uptodate(bh);
1239 continue;
1240 }
1241 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1242 !buffer_unwritten(bh) &&
1243 (block_start < from || block_end > to)) {
1244 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
David Brazdil0f672f62019-12-10 10:32:29 +00001245 wait[nr_wait++] = bh;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001246 }
1247 }
1248 /*
1249 * If we issued read requests, let them complete.
1250 */
David Brazdil0f672f62019-12-10 10:32:29 +00001251 for (i = 0; i < nr_wait; i++) {
1252 wait_on_buffer(wait[i]);
1253 if (!buffer_uptodate(wait[i]))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001254 err = -EIO;
1255 }
David Brazdil0f672f62019-12-10 10:32:29 +00001256 if (unlikely(err)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001257 page_zero_new_buffers(page, from, to);
David Brazdil0f672f62019-12-10 10:32:29 +00001258 } else if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) {
1259 for (i = 0; i < nr_wait; i++) {
1260 int err2;
1261
1262 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1263 bh_offset(wait[i]));
1264 if (err2) {
1265 clear_buffer_uptodate(wait[i]);
1266 err = err2;
1267 }
1268 }
1269 }
1270
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001271 return err;
1272}
1273#endif
1274
1275static int ext4_write_begin(struct file *file, struct address_space *mapping,
1276 loff_t pos, unsigned len, unsigned flags,
1277 struct page **pagep, void **fsdata)
1278{
1279 struct inode *inode = mapping->host;
1280 int ret, needed_blocks;
1281 handle_t *handle;
1282 int retries = 0;
1283 struct page *page;
1284 pgoff_t index;
1285 unsigned from, to;
1286
1287 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1288 return -EIO;
1289
1290 trace_ext4_write_begin(inode, pos, len, flags);
1291 /*
1292 * Reserve one block more for addition to orphan list in case
1293 * we allocate blocks but write fails for some reason
1294 */
1295 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1296 index = pos >> PAGE_SHIFT;
1297 from = pos & (PAGE_SIZE - 1);
1298 to = from + len;
1299
1300 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1301 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1302 flags, pagep);
1303 if (ret < 0)
1304 return ret;
1305 if (ret == 1)
1306 return 0;
1307 }
1308
1309 /*
1310 * grab_cache_page_write_begin() can take a long time if the
1311 * system is thrashing due to memory pressure, or if the page
1312 * is being written back. So grab it first before we start
1313 * the transaction handle. This also allows us to allocate
1314 * the page (if needed) without using GFP_NOFS.
1315 */
1316retry_grab:
1317 page = grab_cache_page_write_begin(mapping, index, flags);
1318 if (!page)
1319 return -ENOMEM;
1320 unlock_page(page);
1321
1322retry_journal:
1323 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1324 if (IS_ERR(handle)) {
1325 put_page(page);
1326 return PTR_ERR(handle);
1327 }
1328
1329 lock_page(page);
1330 if (page->mapping != mapping) {
1331 /* The page got truncated from under us */
1332 unlock_page(page);
1333 put_page(page);
1334 ext4_journal_stop(handle);
1335 goto retry_grab;
1336 }
1337 /* In case writeback began while the page was unlocked */
1338 wait_for_stable_page(page);
1339
David Brazdil0f672f62019-12-10 10:32:29 +00001340#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001341 if (ext4_should_dioread_nolock(inode))
1342 ret = ext4_block_write_begin(page, pos, len,
1343 ext4_get_block_unwritten);
1344 else
1345 ret = ext4_block_write_begin(page, pos, len,
1346 ext4_get_block);
1347#else
1348 if (ext4_should_dioread_nolock(inode))
1349 ret = __block_write_begin(page, pos, len,
1350 ext4_get_block_unwritten);
1351 else
1352 ret = __block_write_begin(page, pos, len, ext4_get_block);
1353#endif
1354 if (!ret && ext4_should_journal_data(inode)) {
1355 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1356 from, to, NULL,
1357 do_journal_get_write_access);
1358 }
1359
1360 if (ret) {
David Brazdil0f672f62019-12-10 10:32:29 +00001361 bool extended = (pos + len > inode->i_size) &&
1362 !ext4_verity_in_progress(inode);
1363
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001364 unlock_page(page);
1365 /*
1366 * __block_write_begin may have instantiated a few blocks
1367 * outside i_size. Trim these off again. Don't need
1368 * i_size_read because we hold i_mutex.
1369 *
1370 * Add inode to orphan list in case we crash before
1371 * truncate finishes
1372 */
David Brazdil0f672f62019-12-10 10:32:29 +00001373 if (extended && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001374 ext4_orphan_add(handle, inode);
1375
1376 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00001377 if (extended) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001378 ext4_truncate_failed_write(inode);
1379 /*
1380 * If truncate failed early the inode might
1381 * still be on the orphan list; we need to
1382 * make sure the inode is removed from the
1383 * orphan list in that case.
1384 */
1385 if (inode->i_nlink)
1386 ext4_orphan_del(NULL, inode);
1387 }
1388
1389 if (ret == -ENOSPC &&
1390 ext4_should_retry_alloc(inode->i_sb, &retries))
1391 goto retry_journal;
1392 put_page(page);
1393 return ret;
1394 }
1395 *pagep = page;
1396 return ret;
1397}
1398
1399/* For write_end() in data=journal mode */
1400static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1401{
1402 int ret;
1403 if (!buffer_mapped(bh) || buffer_freed(bh))
1404 return 0;
1405 set_buffer_uptodate(bh);
1406 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1407 clear_buffer_meta(bh);
1408 clear_buffer_prio(bh);
1409 return ret;
1410}
1411
1412/*
1413 * We need to pick up the new inode size which generic_commit_write gave us
1414 * `file' can be NULL - eg, when called from page_symlink().
1415 *
1416 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1417 * buffers are managed internally.
1418 */
1419static int ext4_write_end(struct file *file,
1420 struct address_space *mapping,
1421 loff_t pos, unsigned len, unsigned copied,
1422 struct page *page, void *fsdata)
1423{
1424 handle_t *handle = ext4_journal_current_handle();
1425 struct inode *inode = mapping->host;
1426 loff_t old_size = inode->i_size;
1427 int ret = 0, ret2;
1428 int i_size_changed = 0;
1429 int inline_data = ext4_has_inline_data(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00001430 bool verity = ext4_verity_in_progress(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001431
1432 trace_ext4_write_end(inode, pos, len, copied);
1433 if (inline_data) {
1434 ret = ext4_write_inline_data_end(inode, pos, len,
1435 copied, page);
1436 if (ret < 0) {
1437 unlock_page(page);
1438 put_page(page);
1439 goto errout;
1440 }
1441 copied = ret;
1442 } else
1443 copied = block_write_end(file, mapping, pos,
1444 len, copied, page, fsdata);
1445 /*
1446 * it's important to update i_size while still holding page lock:
1447 * page writeout could otherwise come in and zero beyond i_size.
David Brazdil0f672f62019-12-10 10:32:29 +00001448 *
1449 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1450 * blocks are being written past EOF, so skip the i_size update.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001451 */
David Brazdil0f672f62019-12-10 10:32:29 +00001452 if (!verity)
1453 i_size_changed = ext4_update_inode_size(inode, pos + copied);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001454 unlock_page(page);
1455 put_page(page);
1456
David Brazdil0f672f62019-12-10 10:32:29 +00001457 if (old_size < pos && !verity)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001458 pagecache_isize_extended(inode, old_size, pos);
1459 /*
1460 * Don't mark the inode dirty under page lock. First, it unnecessarily
1461 * makes the holding time of page lock longer. Second, it forces lock
1462 * ordering of page lock and transaction start for journaling
1463 * filesystems.
1464 */
1465 if (i_size_changed || inline_data)
1466 ext4_mark_inode_dirty(handle, inode);
1467
David Brazdil0f672f62019-12-10 10:32:29 +00001468 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001469 /* if we have allocated more blocks and copied
1470 * less. We will have blocks allocated outside
1471 * inode->i_size. So truncate them
1472 */
1473 ext4_orphan_add(handle, inode);
1474errout:
1475 ret2 = ext4_journal_stop(handle);
1476 if (!ret)
1477 ret = ret2;
1478
David Brazdil0f672f62019-12-10 10:32:29 +00001479 if (pos + len > inode->i_size && !verity) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001480 ext4_truncate_failed_write(inode);
1481 /*
1482 * If truncate failed early the inode might still be
1483 * on the orphan list; we need to make sure the inode
1484 * is removed from the orphan list in that case.
1485 */
1486 if (inode->i_nlink)
1487 ext4_orphan_del(NULL, inode);
1488 }
1489
1490 return ret ? ret : copied;
1491}
1492
1493/*
1494 * This is a private version of page_zero_new_buffers() which doesn't
1495 * set the buffer to be dirty, since in data=journalled mode we need
1496 * to call ext4_handle_dirty_metadata() instead.
1497 */
1498static void ext4_journalled_zero_new_buffers(handle_t *handle,
1499 struct page *page,
1500 unsigned from, unsigned to)
1501{
1502 unsigned int block_start = 0, block_end;
1503 struct buffer_head *head, *bh;
1504
1505 bh = head = page_buffers(page);
1506 do {
1507 block_end = block_start + bh->b_size;
1508 if (buffer_new(bh)) {
1509 if (block_end > from && block_start < to) {
1510 if (!PageUptodate(page)) {
1511 unsigned start, size;
1512
1513 start = max(from, block_start);
1514 size = min(to, block_end) - start;
1515
1516 zero_user(page, start, size);
1517 write_end_fn(handle, bh);
1518 }
1519 clear_buffer_new(bh);
1520 }
1521 }
1522 block_start = block_end;
1523 bh = bh->b_this_page;
1524 } while (bh != head);
1525}
1526
1527static int ext4_journalled_write_end(struct file *file,
1528 struct address_space *mapping,
1529 loff_t pos, unsigned len, unsigned copied,
1530 struct page *page, void *fsdata)
1531{
1532 handle_t *handle = ext4_journal_current_handle();
1533 struct inode *inode = mapping->host;
1534 loff_t old_size = inode->i_size;
1535 int ret = 0, ret2;
1536 int partial = 0;
1537 unsigned from, to;
1538 int size_changed = 0;
1539 int inline_data = ext4_has_inline_data(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00001540 bool verity = ext4_verity_in_progress(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001541
1542 trace_ext4_journalled_write_end(inode, pos, len, copied);
1543 from = pos & (PAGE_SIZE - 1);
1544 to = from + len;
1545
1546 BUG_ON(!ext4_handle_valid(handle));
1547
1548 if (inline_data) {
1549 ret = ext4_write_inline_data_end(inode, pos, len,
1550 copied, page);
1551 if (ret < 0) {
1552 unlock_page(page);
1553 put_page(page);
1554 goto errout;
1555 }
1556 copied = ret;
1557 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1558 copied = 0;
1559 ext4_journalled_zero_new_buffers(handle, page, from, to);
1560 } else {
1561 if (unlikely(copied < len))
1562 ext4_journalled_zero_new_buffers(handle, page,
1563 from + copied, to);
1564 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1565 from + copied, &partial,
1566 write_end_fn);
1567 if (!partial)
1568 SetPageUptodate(page);
1569 }
David Brazdil0f672f62019-12-10 10:32:29 +00001570 if (!verity)
1571 size_changed = ext4_update_inode_size(inode, pos + copied);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001572 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1573 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1574 unlock_page(page);
1575 put_page(page);
1576
David Brazdil0f672f62019-12-10 10:32:29 +00001577 if (old_size < pos && !verity)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001578 pagecache_isize_extended(inode, old_size, pos);
1579
1580 if (size_changed || inline_data) {
1581 ret2 = ext4_mark_inode_dirty(handle, inode);
1582 if (!ret)
1583 ret = ret2;
1584 }
1585
David Brazdil0f672f62019-12-10 10:32:29 +00001586 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001587 /* if we have allocated more blocks and copied
1588 * less. We will have blocks allocated outside
1589 * inode->i_size. So truncate them
1590 */
1591 ext4_orphan_add(handle, inode);
1592
1593errout:
1594 ret2 = ext4_journal_stop(handle);
1595 if (!ret)
1596 ret = ret2;
David Brazdil0f672f62019-12-10 10:32:29 +00001597 if (pos + len > inode->i_size && !verity) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001598 ext4_truncate_failed_write(inode);
1599 /*
1600 * If truncate failed early the inode might still be
1601 * on the orphan list; we need to make sure the inode
1602 * is removed from the orphan list in that case.
1603 */
1604 if (inode->i_nlink)
1605 ext4_orphan_del(NULL, inode);
1606 }
1607
1608 return ret ? ret : copied;
1609}
1610
1611/*
1612 * Reserve space for a single cluster
1613 */
1614static int ext4_da_reserve_space(struct inode *inode)
1615{
1616 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1617 struct ext4_inode_info *ei = EXT4_I(inode);
1618 int ret;
1619
1620 /*
1621 * We will charge metadata quota at writeout time; this saves
1622 * us from metadata over-estimation, though we may go over by
1623 * a small amount in the end. Here we just reserve for data.
1624 */
1625 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1626 if (ret)
1627 return ret;
1628
1629 spin_lock(&ei->i_block_reservation_lock);
1630 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1631 spin_unlock(&ei->i_block_reservation_lock);
1632 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1633 return -ENOSPC;
1634 }
1635 ei->i_reserved_data_blocks++;
1636 trace_ext4_da_reserve_space(inode);
1637 spin_unlock(&ei->i_block_reservation_lock);
1638
1639 return 0; /* success */
1640}
1641
David Brazdil0f672f62019-12-10 10:32:29 +00001642void ext4_da_release_space(struct inode *inode, int to_free)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001643{
1644 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1645 struct ext4_inode_info *ei = EXT4_I(inode);
1646
1647 if (!to_free)
1648 return; /* Nothing to release, exit */
1649
1650 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1651
1652 trace_ext4_da_release_space(inode, to_free);
1653 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1654 /*
1655 * if there aren't enough reserved blocks, then the
1656 * counter is messed up somewhere. Since this
1657 * function is called from invalidate page, it's
1658 * harmless to return without any action.
1659 */
1660 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1661 "ino %lu, to_free %d with only %d reserved "
1662 "data blocks", inode->i_ino, to_free,
1663 ei->i_reserved_data_blocks);
1664 WARN_ON(1);
1665 to_free = ei->i_reserved_data_blocks;
1666 }
1667 ei->i_reserved_data_blocks -= to_free;
1668
1669 /* update fs dirty data blocks counter */
1670 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1671
1672 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1673
1674 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1675}
1676
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001677/*
1678 * Delayed allocation stuff
1679 */
1680
1681struct mpage_da_data {
1682 struct inode *inode;
1683 struct writeback_control *wbc;
1684
1685 pgoff_t first_page; /* The first page to write */
1686 pgoff_t next_page; /* Current page to examine */
1687 pgoff_t last_page; /* Last page to examine */
1688 /*
1689 * Extent to map - this can be after first_page because that can be
1690 * fully mapped. We somewhat abuse m_flags to store whether the extent
1691 * is delalloc or unwritten.
1692 */
1693 struct ext4_map_blocks map;
1694 struct ext4_io_submit io_submit; /* IO submission data */
1695 unsigned int do_map:1;
1696};
1697
1698static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1699 bool invalidate)
1700{
1701 int nr_pages, i;
1702 pgoff_t index, end;
1703 struct pagevec pvec;
1704 struct inode *inode = mpd->inode;
1705 struct address_space *mapping = inode->i_mapping;
1706
1707 /* This is necessary when next_page == 0. */
1708 if (mpd->first_page >= mpd->next_page)
1709 return;
1710
1711 index = mpd->first_page;
1712 end = mpd->next_page - 1;
1713 if (invalidate) {
1714 ext4_lblk_t start, last;
1715 start = index << (PAGE_SHIFT - inode->i_blkbits);
1716 last = end << (PAGE_SHIFT - inode->i_blkbits);
1717 ext4_es_remove_extent(inode, start, last - start + 1);
1718 }
1719
1720 pagevec_init(&pvec);
1721 while (index <= end) {
1722 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1723 if (nr_pages == 0)
1724 break;
1725 for (i = 0; i < nr_pages; i++) {
1726 struct page *page = pvec.pages[i];
1727
1728 BUG_ON(!PageLocked(page));
1729 BUG_ON(PageWriteback(page));
1730 if (invalidate) {
1731 if (page_mapped(page))
1732 clear_page_dirty_for_io(page);
1733 block_invalidatepage(page, 0, PAGE_SIZE);
1734 ClearPageUptodate(page);
1735 }
1736 unlock_page(page);
1737 }
1738 pagevec_release(&pvec);
1739 }
1740}
1741
1742static void ext4_print_free_blocks(struct inode *inode)
1743{
1744 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1745 struct super_block *sb = inode->i_sb;
1746 struct ext4_inode_info *ei = EXT4_I(inode);
1747
1748 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1749 EXT4_C2B(EXT4_SB(inode->i_sb),
1750 ext4_count_free_clusters(sb)));
1751 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1752 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1753 (long long) EXT4_C2B(EXT4_SB(sb),
1754 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1755 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1756 (long long) EXT4_C2B(EXT4_SB(sb),
1757 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1758 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1759 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1760 ei->i_reserved_data_blocks);
1761 return;
1762}
1763
1764static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1765{
1766 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1767}
1768
1769/*
David Brazdil0f672f62019-12-10 10:32:29 +00001770 * ext4_insert_delayed_block - adds a delayed block to the extents status
1771 * tree, incrementing the reserved cluster/block
1772 * count or making a pending reservation
1773 * where needed
1774 *
1775 * @inode - file containing the newly added block
1776 * @lblk - logical block to be added
1777 *
1778 * Returns 0 on success, negative error code on failure.
1779 */
1780static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1781{
1782 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1783 int ret;
1784 bool allocated = false;
1785
1786 /*
1787 * If the cluster containing lblk is shared with a delayed,
1788 * written, or unwritten extent in a bigalloc file system, it's
1789 * already been accounted for and does not need to be reserved.
1790 * A pending reservation must be made for the cluster if it's
1791 * shared with a written or unwritten extent and doesn't already
1792 * have one. Written and unwritten extents can be purged from the
1793 * extents status tree if the system is under memory pressure, so
1794 * it's necessary to examine the extent tree if a search of the
1795 * extents status tree doesn't get a match.
1796 */
1797 if (sbi->s_cluster_ratio == 1) {
1798 ret = ext4_da_reserve_space(inode);
1799 if (ret != 0) /* ENOSPC */
1800 goto errout;
1801 } else { /* bigalloc */
1802 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1803 if (!ext4_es_scan_clu(inode,
1804 &ext4_es_is_mapped, lblk)) {
1805 ret = ext4_clu_mapped(inode,
1806 EXT4_B2C(sbi, lblk));
1807 if (ret < 0)
1808 goto errout;
1809 if (ret == 0) {
1810 ret = ext4_da_reserve_space(inode);
1811 if (ret != 0) /* ENOSPC */
1812 goto errout;
1813 } else {
1814 allocated = true;
1815 }
1816 } else {
1817 allocated = true;
1818 }
1819 }
1820 }
1821
1822 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1823
1824errout:
1825 return ret;
1826}
1827
1828/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001829 * This function is grabs code from the very beginning of
1830 * ext4_map_blocks, but assumes that the caller is from delayed write
1831 * time. This function looks up the requested blocks and sets the
1832 * buffer delay bit under the protection of i_data_sem.
1833 */
1834static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1835 struct ext4_map_blocks *map,
1836 struct buffer_head *bh)
1837{
1838 struct extent_status es;
1839 int retval;
1840 sector_t invalid_block = ~((sector_t) 0xffff);
1841#ifdef ES_AGGRESSIVE_TEST
1842 struct ext4_map_blocks orig_map;
1843
1844 memcpy(&orig_map, map, sizeof(*map));
1845#endif
1846
1847 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1848 invalid_block = ~0;
1849
1850 map->m_flags = 0;
1851 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1852 "logical block %lu\n", inode->i_ino, map->m_len,
1853 (unsigned long) map->m_lblk);
1854
1855 /* Lookup extent status tree firstly */
David Brazdil0f672f62019-12-10 10:32:29 +00001856 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001857 if (ext4_es_is_hole(&es)) {
1858 retval = 0;
1859 down_read(&EXT4_I(inode)->i_data_sem);
1860 goto add_delayed;
1861 }
1862
1863 /*
1864 * Delayed extent could be allocated by fallocate.
1865 * So we need to check it.
1866 */
1867 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1868 map_bh(bh, inode->i_sb, invalid_block);
1869 set_buffer_new(bh);
1870 set_buffer_delay(bh);
1871 return 0;
1872 }
1873
1874 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1875 retval = es.es_len - (iblock - es.es_lblk);
1876 if (retval > map->m_len)
1877 retval = map->m_len;
1878 map->m_len = retval;
1879 if (ext4_es_is_written(&es))
1880 map->m_flags |= EXT4_MAP_MAPPED;
1881 else if (ext4_es_is_unwritten(&es))
1882 map->m_flags |= EXT4_MAP_UNWRITTEN;
1883 else
David Brazdil0f672f62019-12-10 10:32:29 +00001884 BUG();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001885
1886#ifdef ES_AGGRESSIVE_TEST
1887 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1888#endif
1889 return retval;
1890 }
1891
1892 /*
1893 * Try to see if we can get the block without requesting a new
1894 * file system block.
1895 */
1896 down_read(&EXT4_I(inode)->i_data_sem);
1897 if (ext4_has_inline_data(inode))
1898 retval = 0;
1899 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1900 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1901 else
1902 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1903
1904add_delayed:
1905 if (retval == 0) {
1906 int ret;
David Brazdil0f672f62019-12-10 10:32:29 +00001907
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001908 /*
1909 * XXX: __block_prepare_write() unmaps passed block,
1910 * is it OK?
1911 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001912
David Brazdil0f672f62019-12-10 10:32:29 +00001913 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1914 if (ret != 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001915 retval = ret;
1916 goto out_unlock;
1917 }
1918
1919 map_bh(bh, inode->i_sb, invalid_block);
1920 set_buffer_new(bh);
1921 set_buffer_delay(bh);
1922 } else if (retval > 0) {
1923 int ret;
1924 unsigned int status;
1925
1926 if (unlikely(retval != map->m_len)) {
1927 ext4_warning(inode->i_sb,
1928 "ES len assertion failed for inode "
1929 "%lu: retval %d != map->m_len %d",
1930 inode->i_ino, retval, map->m_len);
1931 WARN_ON(1);
1932 }
1933
1934 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1935 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1936 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1937 map->m_pblk, status);
1938 if (ret != 0)
1939 retval = ret;
1940 }
1941
1942out_unlock:
1943 up_read((&EXT4_I(inode)->i_data_sem));
1944
1945 return retval;
1946}
1947
1948/*
1949 * This is a special get_block_t callback which is used by
1950 * ext4_da_write_begin(). It will either return mapped block or
1951 * reserve space for a single block.
1952 *
1953 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1954 * We also have b_blocknr = -1 and b_bdev initialized properly
1955 *
1956 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1957 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1958 * initialized properly.
1959 */
1960int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1961 struct buffer_head *bh, int create)
1962{
1963 struct ext4_map_blocks map;
1964 int ret = 0;
1965
1966 BUG_ON(create == 0);
1967 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1968
1969 map.m_lblk = iblock;
1970 map.m_len = 1;
1971
1972 /*
1973 * first, we need to know whether the block is allocated already
1974 * preallocated blocks are unmapped but should treated
1975 * the same as allocated blocks.
1976 */
1977 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1978 if (ret <= 0)
1979 return ret;
1980
1981 map_bh(bh, inode->i_sb, map.m_pblk);
1982 ext4_update_bh_state(bh, map.m_flags);
1983
1984 if (buffer_unwritten(bh)) {
1985 /* A delayed write to unwritten bh should be marked
1986 * new and mapped. Mapped ensures that we don't do
1987 * get_block multiple times when we write to the same
1988 * offset and new ensures that we do proper zero out
1989 * for partial write.
1990 */
1991 set_buffer_new(bh);
1992 set_buffer_mapped(bh);
1993 }
1994 return 0;
1995}
1996
1997static int bget_one(handle_t *handle, struct buffer_head *bh)
1998{
1999 get_bh(bh);
2000 return 0;
2001}
2002
2003static int bput_one(handle_t *handle, struct buffer_head *bh)
2004{
2005 put_bh(bh);
2006 return 0;
2007}
2008
2009static int __ext4_journalled_writepage(struct page *page,
2010 unsigned int len)
2011{
2012 struct address_space *mapping = page->mapping;
2013 struct inode *inode = mapping->host;
2014 struct buffer_head *page_bufs = NULL;
2015 handle_t *handle = NULL;
2016 int ret = 0, err = 0;
2017 int inline_data = ext4_has_inline_data(inode);
2018 struct buffer_head *inode_bh = NULL;
2019
2020 ClearPageChecked(page);
2021
2022 if (inline_data) {
2023 BUG_ON(page->index != 0);
2024 BUG_ON(len > ext4_get_max_inline_size(inode));
2025 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2026 if (inode_bh == NULL)
2027 goto out;
2028 } else {
2029 page_bufs = page_buffers(page);
2030 if (!page_bufs) {
2031 BUG();
2032 goto out;
2033 }
2034 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2035 NULL, bget_one);
2036 }
2037 /*
2038 * We need to release the page lock before we start the
2039 * journal, so grab a reference so the page won't disappear
2040 * out from under us.
2041 */
2042 get_page(page);
2043 unlock_page(page);
2044
2045 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2046 ext4_writepage_trans_blocks(inode));
2047 if (IS_ERR(handle)) {
2048 ret = PTR_ERR(handle);
2049 put_page(page);
2050 goto out_no_pagelock;
2051 }
2052 BUG_ON(!ext4_handle_valid(handle));
2053
2054 lock_page(page);
2055 put_page(page);
2056 if (page->mapping != mapping) {
2057 /* The page got truncated from under us */
2058 ext4_journal_stop(handle);
2059 ret = 0;
2060 goto out;
2061 }
2062
2063 if (inline_data) {
2064 ret = ext4_mark_inode_dirty(handle, inode);
2065 } else {
2066 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2067 do_journal_get_write_access);
2068
2069 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2070 write_end_fn);
2071 }
2072 if (ret == 0)
2073 ret = err;
2074 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2075 err = ext4_journal_stop(handle);
2076 if (!ret)
2077 ret = err;
2078
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002079 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2080out:
2081 unlock_page(page);
2082out_no_pagelock:
Olivier Deprez0e641232021-09-23 10:07:05 +02002083 if (!inline_data && page_bufs)
2084 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
2085 NULL, bput_one);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002086 brelse(inode_bh);
2087 return ret;
2088}
2089
2090/*
2091 * Note that we don't need to start a transaction unless we're journaling data
2092 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2093 * need to file the inode to the transaction's list in ordered mode because if
2094 * we are writing back data added by write(), the inode is already there and if
2095 * we are writing back data modified via mmap(), no one guarantees in which
2096 * transaction the data will hit the disk. In case we are journaling data, we
2097 * cannot start transaction directly because transaction start ranks above page
2098 * lock so we have to do some magic.
2099 *
2100 * This function can get called via...
2101 * - ext4_writepages after taking page lock (have journal handle)
2102 * - journal_submit_inode_data_buffers (no journal handle)
2103 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2104 * - grab_page_cache when doing write_begin (have journal handle)
2105 *
2106 * We don't do any block allocation in this function. If we have page with
2107 * multiple blocks we need to write those buffer_heads that are mapped. This
2108 * is important for mmaped based write. So if we do with blocksize 1K
2109 * truncate(f, 1024);
2110 * a = mmap(f, 0, 4096);
2111 * a[0] = 'a';
2112 * truncate(f, 4096);
2113 * we have in the page first buffer_head mapped via page_mkwrite call back
2114 * but other buffer_heads would be unmapped but dirty (dirty done via the
2115 * do_wp_page). So writepage should write the first block. If we modify
2116 * the mmap area beyond 1024 we will again get a page_fault and the
2117 * page_mkwrite callback will do the block allocation and mark the
2118 * buffer_heads mapped.
2119 *
2120 * We redirty the page if we have any buffer_heads that is either delay or
2121 * unwritten in the page.
2122 *
2123 * We can get recursively called as show below.
2124 *
2125 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2126 * ext4_writepage()
2127 *
2128 * But since we don't do any block allocation we should not deadlock.
2129 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2130 */
2131static int ext4_writepage(struct page *page,
2132 struct writeback_control *wbc)
2133{
2134 int ret = 0;
2135 loff_t size;
2136 unsigned int len;
2137 struct buffer_head *page_bufs = NULL;
2138 struct inode *inode = page->mapping->host;
2139 struct ext4_io_submit io_submit;
2140 bool keep_towrite = false;
2141
2142 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
Olivier Deprez0e641232021-09-23 10:07:05 +02002143 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002144 unlock_page(page);
2145 return -EIO;
2146 }
2147
2148 trace_ext4_writepage(page);
2149 size = i_size_read(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00002150 if (page->index == size >> PAGE_SHIFT &&
2151 !ext4_verity_in_progress(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002152 len = size & ~PAGE_MASK;
2153 else
2154 len = PAGE_SIZE;
2155
2156 page_bufs = page_buffers(page);
2157 /*
2158 * We cannot do block allocation or other extent handling in this
2159 * function. If there are buffers needing that, we have to redirty
2160 * the page. But we may reach here when we do a journal commit via
2161 * journal_submit_inode_data_buffers() and in that case we must write
2162 * allocated buffers to achieve data=ordered mode guarantees.
2163 *
2164 * Also, if there is only one buffer per page (the fs block
2165 * size == the page size), if one buffer needs block
2166 * allocation or needs to modify the extent tree to clear the
2167 * unwritten flag, we know that the page can't be written at
2168 * all, so we might as well refuse the write immediately.
2169 * Unfortunately if the block size != page size, we can't as
2170 * easily detect this case using ext4_walk_page_buffers(), but
2171 * for the extremely common case, this is an optimization that
2172 * skips a useless round trip through ext4_bio_write_page().
2173 */
2174 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2175 ext4_bh_delay_or_unwritten)) {
2176 redirty_page_for_writepage(wbc, page);
2177 if ((current->flags & PF_MEMALLOC) ||
2178 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2179 /*
2180 * For memory cleaning there's no point in writing only
2181 * some buffers. So just bail out. Warn if we came here
2182 * from direct reclaim.
2183 */
2184 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2185 == PF_MEMALLOC);
2186 unlock_page(page);
2187 return 0;
2188 }
2189 keep_towrite = true;
2190 }
2191
2192 if (PageChecked(page) && ext4_should_journal_data(inode))
2193 /*
2194 * It's mmapped pagecache. Add buffers and journal it. There
2195 * doesn't seem much point in redirtying the page here.
2196 */
2197 return __ext4_journalled_writepage(page, len);
2198
2199 ext4_io_submit_init(&io_submit, wbc);
2200 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2201 if (!io_submit.io_end) {
2202 redirty_page_for_writepage(wbc, page);
2203 unlock_page(page);
2204 return -ENOMEM;
2205 }
2206 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2207 ext4_io_submit(&io_submit);
2208 /* Drop io_end reference we got from init */
2209 ext4_put_io_end_defer(io_submit.io_end);
2210 return ret;
2211}
2212
2213static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2214{
2215 int len;
2216 loff_t size;
2217 int err;
2218
2219 BUG_ON(page->index != mpd->first_page);
2220 clear_page_dirty_for_io(page);
2221 /*
2222 * We have to be very careful here! Nothing protects writeback path
2223 * against i_size changes and the page can be writeably mapped into
2224 * page tables. So an application can be growing i_size and writing
2225 * data through mmap while writeback runs. clear_page_dirty_for_io()
2226 * write-protects our page in page tables and the page cannot get
2227 * written to again until we release page lock. So only after
2228 * clear_page_dirty_for_io() we are safe to sample i_size for
2229 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2230 * on the barrier provided by TestClearPageDirty in
2231 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2232 * after page tables are updated.
2233 */
2234 size = i_size_read(mpd->inode);
David Brazdil0f672f62019-12-10 10:32:29 +00002235 if (page->index == size >> PAGE_SHIFT &&
2236 !ext4_verity_in_progress(mpd->inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002237 len = size & ~PAGE_MASK;
2238 else
2239 len = PAGE_SIZE;
2240 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2241 if (!err)
2242 mpd->wbc->nr_to_write--;
2243 mpd->first_page++;
2244
2245 return err;
2246}
2247
2248#define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2249
2250/*
2251 * mballoc gives us at most this number of blocks...
2252 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2253 * The rest of mballoc seems to handle chunks up to full group size.
2254 */
2255#define MAX_WRITEPAGES_EXTENT_LEN 2048
2256
2257/*
2258 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2259 *
2260 * @mpd - extent of blocks
2261 * @lblk - logical number of the block in the file
2262 * @bh - buffer head we want to add to the extent
2263 *
2264 * The function is used to collect contig. blocks in the same state. If the
2265 * buffer doesn't require mapping for writeback and we haven't started the
2266 * extent of buffers to map yet, the function returns 'true' immediately - the
2267 * caller can write the buffer right away. Otherwise the function returns true
2268 * if the block has been added to the extent, false if the block couldn't be
2269 * added.
2270 */
2271static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2272 struct buffer_head *bh)
2273{
2274 struct ext4_map_blocks *map = &mpd->map;
2275
2276 /* Buffer that doesn't need mapping for writeback? */
2277 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2278 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2279 /* So far no extent to map => we write the buffer right away */
2280 if (map->m_len == 0)
2281 return true;
2282 return false;
2283 }
2284
2285 /* First block in the extent? */
2286 if (map->m_len == 0) {
2287 /* We cannot map unless handle is started... */
2288 if (!mpd->do_map)
2289 return false;
2290 map->m_lblk = lblk;
2291 map->m_len = 1;
2292 map->m_flags = bh->b_state & BH_FLAGS;
2293 return true;
2294 }
2295
2296 /* Don't go larger than mballoc is willing to allocate */
2297 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2298 return false;
2299
2300 /* Can we merge the block to our big extent? */
2301 if (lblk == map->m_lblk + map->m_len &&
2302 (bh->b_state & BH_FLAGS) == map->m_flags) {
2303 map->m_len++;
2304 return true;
2305 }
2306 return false;
2307}
2308
2309/*
2310 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2311 *
2312 * @mpd - extent of blocks for mapping
2313 * @head - the first buffer in the page
2314 * @bh - buffer we should start processing from
2315 * @lblk - logical number of the block in the file corresponding to @bh
2316 *
2317 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2318 * the page for IO if all buffers in this page were mapped and there's no
2319 * accumulated extent of buffers to map or add buffers in the page to the
2320 * extent of buffers to map. The function returns 1 if the caller can continue
2321 * by processing the next page, 0 if it should stop adding buffers to the
2322 * extent to map because we cannot extend it anymore. It can also return value
2323 * < 0 in case of error during IO submission.
2324 */
2325static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2326 struct buffer_head *head,
2327 struct buffer_head *bh,
2328 ext4_lblk_t lblk)
2329{
2330 struct inode *inode = mpd->inode;
2331 int err;
2332 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2333 >> inode->i_blkbits;
2334
David Brazdil0f672f62019-12-10 10:32:29 +00002335 if (ext4_verity_in_progress(inode))
2336 blocks = EXT_MAX_BLOCKS;
2337
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002338 do {
2339 BUG_ON(buffer_locked(bh));
2340
2341 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2342 /* Found extent to map? */
2343 if (mpd->map.m_len)
2344 return 0;
2345 /* Buffer needs mapping and handle is not started? */
2346 if (!mpd->do_map)
2347 return 0;
2348 /* Everything mapped so far and we hit EOF */
2349 break;
2350 }
2351 } while (lblk++, (bh = bh->b_this_page) != head);
2352 /* So far everything mapped? Submit the page for IO. */
2353 if (mpd->map.m_len == 0) {
2354 err = mpage_submit_page(mpd, head->b_page);
2355 if (err < 0)
2356 return err;
2357 }
2358 return lblk < blocks;
2359}
2360
2361/*
2362 * mpage_map_buffers - update buffers corresponding to changed extent and
2363 * submit fully mapped pages for IO
2364 *
2365 * @mpd - description of extent to map, on return next extent to map
2366 *
2367 * Scan buffers corresponding to changed extent (we expect corresponding pages
2368 * to be already locked) and update buffer state according to new extent state.
2369 * We map delalloc buffers to their physical location, clear unwritten bits,
2370 * and mark buffers as uninit when we perform writes to unwritten extents
2371 * and do extent conversion after IO is finished. If the last page is not fully
2372 * mapped, we update @map to the next extent in the last page that needs
2373 * mapping. Otherwise we submit the page for IO.
2374 */
2375static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2376{
2377 struct pagevec pvec;
2378 int nr_pages, i;
2379 struct inode *inode = mpd->inode;
2380 struct buffer_head *head, *bh;
2381 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2382 pgoff_t start, end;
2383 ext4_lblk_t lblk;
2384 sector_t pblock;
2385 int err;
2386
2387 start = mpd->map.m_lblk >> bpp_bits;
2388 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2389 lblk = start << bpp_bits;
2390 pblock = mpd->map.m_pblk;
2391
2392 pagevec_init(&pvec);
2393 while (start <= end) {
2394 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2395 &start, end);
2396 if (nr_pages == 0)
2397 break;
2398 for (i = 0; i < nr_pages; i++) {
2399 struct page *page = pvec.pages[i];
2400
2401 bh = head = page_buffers(page);
2402 do {
2403 if (lblk < mpd->map.m_lblk)
2404 continue;
2405 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2406 /*
2407 * Buffer after end of mapped extent.
2408 * Find next buffer in the page to map.
2409 */
2410 mpd->map.m_len = 0;
2411 mpd->map.m_flags = 0;
2412 /*
2413 * FIXME: If dioread_nolock supports
2414 * blocksize < pagesize, we need to make
2415 * sure we add size mapped so far to
2416 * io_end->size as the following call
2417 * can submit the page for IO.
2418 */
2419 err = mpage_process_page_bufs(mpd, head,
2420 bh, lblk);
2421 pagevec_release(&pvec);
2422 if (err > 0)
2423 err = 0;
2424 return err;
2425 }
2426 if (buffer_delay(bh)) {
2427 clear_buffer_delay(bh);
2428 bh->b_blocknr = pblock++;
2429 }
2430 clear_buffer_unwritten(bh);
2431 } while (lblk++, (bh = bh->b_this_page) != head);
2432
2433 /*
2434 * FIXME: This is going to break if dioread_nolock
2435 * supports blocksize < pagesize as we will try to
2436 * convert potentially unmapped parts of inode.
2437 */
2438 mpd->io_submit.io_end->size += PAGE_SIZE;
2439 /* Page fully mapped - let IO run! */
2440 err = mpage_submit_page(mpd, page);
2441 if (err < 0) {
2442 pagevec_release(&pvec);
2443 return err;
2444 }
2445 }
2446 pagevec_release(&pvec);
2447 }
2448 /* Extent fully mapped and matches with page boundary. We are done. */
2449 mpd->map.m_len = 0;
2450 mpd->map.m_flags = 0;
2451 return 0;
2452}
2453
2454static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2455{
2456 struct inode *inode = mpd->inode;
2457 struct ext4_map_blocks *map = &mpd->map;
2458 int get_blocks_flags;
2459 int err, dioread_nolock;
2460
2461 trace_ext4_da_write_pages_extent(inode, map);
2462 /*
2463 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2464 * to convert an unwritten extent to be initialized (in the case
2465 * where we have written into one or more preallocated blocks). It is
2466 * possible that we're going to need more metadata blocks than
2467 * previously reserved. However we must not fail because we're in
2468 * writeback and there is nothing we can do about it so it might result
2469 * in data loss. So use reserved blocks to allocate metadata if
2470 * possible.
2471 *
2472 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2473 * the blocks in question are delalloc blocks. This indicates
2474 * that the blocks and quotas has already been checked when
2475 * the data was copied into the page cache.
2476 */
2477 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2478 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2479 EXT4_GET_BLOCKS_IO_SUBMIT;
2480 dioread_nolock = ext4_should_dioread_nolock(inode);
2481 if (dioread_nolock)
2482 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2483 if (map->m_flags & (1 << BH_Delay))
2484 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2485
2486 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2487 if (err < 0)
2488 return err;
2489 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2490 if (!mpd->io_submit.io_end->handle &&
2491 ext4_handle_valid(handle)) {
2492 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2493 handle->h_rsv_handle = NULL;
2494 }
2495 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2496 }
2497
2498 BUG_ON(map->m_len == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002499 return 0;
2500}
2501
2502/*
2503 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2504 * mpd->len and submit pages underlying it for IO
2505 *
2506 * @handle - handle for journal operations
2507 * @mpd - extent to map
2508 * @give_up_on_write - we set this to true iff there is a fatal error and there
2509 * is no hope of writing the data. The caller should discard
2510 * dirty pages to avoid infinite loops.
2511 *
2512 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2513 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2514 * them to initialized or split the described range from larger unwritten
2515 * extent. Note that we need not map all the described range since allocation
2516 * can return less blocks or the range is covered by more unwritten extents. We
2517 * cannot map more because we are limited by reserved transaction credits. On
2518 * the other hand we always make sure that the last touched page is fully
2519 * mapped so that it can be written out (and thus forward progress is
2520 * guaranteed). After mapping we submit all mapped pages for IO.
2521 */
2522static int mpage_map_and_submit_extent(handle_t *handle,
2523 struct mpage_da_data *mpd,
2524 bool *give_up_on_write)
2525{
2526 struct inode *inode = mpd->inode;
2527 struct ext4_map_blocks *map = &mpd->map;
2528 int err;
2529 loff_t disksize;
2530 int progress = 0;
2531
2532 mpd->io_submit.io_end->offset =
2533 ((loff_t)map->m_lblk) << inode->i_blkbits;
2534 do {
2535 err = mpage_map_one_extent(handle, mpd);
2536 if (err < 0) {
2537 struct super_block *sb = inode->i_sb;
2538
2539 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2540 EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2541 goto invalidate_dirty_pages;
2542 /*
2543 * Let the uper layers retry transient errors.
2544 * In the case of ENOSPC, if ext4_count_free_blocks()
2545 * is non-zero, a commit should free up blocks.
2546 */
2547 if ((err == -ENOMEM) ||
2548 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2549 if (progress)
2550 goto update_disksize;
2551 return err;
2552 }
2553 ext4_msg(sb, KERN_CRIT,
2554 "Delayed block allocation failed for "
2555 "inode %lu at logical offset %llu with"
2556 " max blocks %u with error %d",
2557 inode->i_ino,
2558 (unsigned long long)map->m_lblk,
2559 (unsigned)map->m_len, -err);
2560 ext4_msg(sb, KERN_CRIT,
2561 "This should not happen!! Data will "
2562 "be lost\n");
2563 if (err == -ENOSPC)
2564 ext4_print_free_blocks(inode);
2565 invalidate_dirty_pages:
2566 *give_up_on_write = true;
2567 return err;
2568 }
2569 progress = 1;
2570 /*
2571 * Update buffer state, submit mapped pages, and get us new
2572 * extent to map
2573 */
2574 err = mpage_map_and_submit_buffers(mpd);
2575 if (err < 0)
2576 goto update_disksize;
2577 } while (map->m_len);
2578
2579update_disksize:
2580 /*
2581 * Update on-disk size after IO is submitted. Races with
2582 * truncate are avoided by checking i_size under i_data_sem.
2583 */
2584 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
Olivier Deprez0e641232021-09-23 10:07:05 +02002585 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002586 int err2;
2587 loff_t i_size;
2588
2589 down_write(&EXT4_I(inode)->i_data_sem);
2590 i_size = i_size_read(inode);
2591 if (disksize > i_size)
2592 disksize = i_size;
2593 if (disksize > EXT4_I(inode)->i_disksize)
2594 EXT4_I(inode)->i_disksize = disksize;
2595 up_write(&EXT4_I(inode)->i_data_sem);
2596 err2 = ext4_mark_inode_dirty(handle, inode);
2597 if (err2)
2598 ext4_error(inode->i_sb,
2599 "Failed to mark inode %lu dirty",
2600 inode->i_ino);
2601 if (!err)
2602 err = err2;
2603 }
2604 return err;
2605}
2606
2607/*
2608 * Calculate the total number of credits to reserve for one writepages
2609 * iteration. This is called from ext4_writepages(). We map an extent of
2610 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2611 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2612 * bpp - 1 blocks in bpp different extents.
2613 */
2614static int ext4_da_writepages_trans_blocks(struct inode *inode)
2615{
2616 int bpp = ext4_journal_blocks_per_page(inode);
2617
2618 return ext4_meta_trans_blocks(inode,
2619 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2620}
2621
2622/*
2623 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2624 * and underlying extent to map
2625 *
2626 * @mpd - where to look for pages
2627 *
2628 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2629 * IO immediately. When we find a page which isn't mapped we start accumulating
2630 * extent of buffers underlying these pages that needs mapping (formed by
2631 * either delayed or unwritten buffers). We also lock the pages containing
2632 * these buffers. The extent found is returned in @mpd structure (starting at
2633 * mpd->lblk with length mpd->len blocks).
2634 *
2635 * Note that this function can attach bios to one io_end structure which are
2636 * neither logically nor physically contiguous. Although it may seem as an
2637 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2638 * case as we need to track IO to all buffers underlying a page in one io_end.
2639 */
2640static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2641{
2642 struct address_space *mapping = mpd->inode->i_mapping;
2643 struct pagevec pvec;
2644 unsigned int nr_pages;
2645 long left = mpd->wbc->nr_to_write;
2646 pgoff_t index = mpd->first_page;
2647 pgoff_t end = mpd->last_page;
David Brazdil0f672f62019-12-10 10:32:29 +00002648 xa_mark_t tag;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002649 int i, err = 0;
2650 int blkbits = mpd->inode->i_blkbits;
2651 ext4_lblk_t lblk;
2652 struct buffer_head *head;
2653
2654 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2655 tag = PAGECACHE_TAG_TOWRITE;
2656 else
2657 tag = PAGECACHE_TAG_DIRTY;
2658
2659 pagevec_init(&pvec);
2660 mpd->map.m_len = 0;
2661 mpd->next_page = index;
2662 while (index <= end) {
2663 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2664 tag);
2665 if (nr_pages == 0)
2666 goto out;
2667
2668 for (i = 0; i < nr_pages; i++) {
2669 struct page *page = pvec.pages[i];
2670
2671 /*
2672 * Accumulated enough dirty pages? This doesn't apply
2673 * to WB_SYNC_ALL mode. For integrity sync we have to
2674 * keep going because someone may be concurrently
2675 * dirtying pages, and we might have synced a lot of
2676 * newly appeared dirty pages, but have not synced all
2677 * of the old dirty pages.
2678 */
2679 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2680 goto out;
2681
2682 /* If we can't merge this page, we are done. */
2683 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2684 goto out;
2685
2686 lock_page(page);
2687 /*
2688 * If the page is no longer dirty, or its mapping no
2689 * longer corresponds to inode we are writing (which
2690 * means it has been truncated or invalidated), or the
2691 * page is already under writeback and we are not doing
2692 * a data integrity writeback, skip the page
2693 */
2694 if (!PageDirty(page) ||
2695 (PageWriteback(page) &&
2696 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2697 unlikely(page->mapping != mapping)) {
2698 unlock_page(page);
2699 continue;
2700 }
2701
2702 wait_on_page_writeback(page);
2703 BUG_ON(PageWriteback(page));
2704
2705 if (mpd->map.m_len == 0)
2706 mpd->first_page = page->index;
2707 mpd->next_page = page->index + 1;
2708 /* Add all dirty buffers to mpd */
2709 lblk = ((ext4_lblk_t)page->index) <<
2710 (PAGE_SHIFT - blkbits);
2711 head = page_buffers(page);
2712 err = mpage_process_page_bufs(mpd, head, head, lblk);
2713 if (err <= 0)
2714 goto out;
2715 err = 0;
2716 left--;
2717 }
2718 pagevec_release(&pvec);
2719 cond_resched();
2720 }
2721 return 0;
2722out:
2723 pagevec_release(&pvec);
2724 return err;
2725}
2726
2727static int ext4_writepages(struct address_space *mapping,
2728 struct writeback_control *wbc)
2729{
2730 pgoff_t writeback_index = 0;
2731 long nr_to_write = wbc->nr_to_write;
2732 int range_whole = 0;
2733 int cycled = 1;
2734 handle_t *handle = NULL;
2735 struct mpage_da_data mpd;
2736 struct inode *inode = mapping->host;
2737 int needed_blocks, rsv_blocks = 0, ret = 0;
2738 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2739 bool done;
2740 struct blk_plug plug;
2741 bool give_up_on_write = false;
2742
2743 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2744 return -EIO;
2745
Olivier Deprez0e641232021-09-23 10:07:05 +02002746 percpu_down_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002747 trace_ext4_writepages(inode, wbc);
2748
2749 /*
2750 * No pages to write? This is mainly a kludge to avoid starting
2751 * a transaction for special inodes like journal inode on last iput()
2752 * because that could violate lock ordering on umount
2753 */
2754 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2755 goto out_writepages;
2756
2757 if (ext4_should_journal_data(inode)) {
2758 ret = generic_writepages(mapping, wbc);
2759 goto out_writepages;
2760 }
2761
2762 /*
2763 * If the filesystem has aborted, it is read-only, so return
2764 * right away instead of dumping stack traces later on that
2765 * will obscure the real source of the problem. We test
2766 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2767 * the latter could be true if the filesystem is mounted
2768 * read-only, and in that case, ext4_writepages should
2769 * *never* be called, so if that ever happens, we would want
2770 * the stack trace.
2771 */
2772 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2773 sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2774 ret = -EROFS;
2775 goto out_writepages;
2776 }
2777
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002778 /*
2779 * If we have inline data and arrive here, it means that
2780 * we will soon create the block for the 1st page, so
2781 * we'd better clear the inline data here.
2782 */
2783 if (ext4_has_inline_data(inode)) {
2784 /* Just inode will be modified... */
2785 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2786 if (IS_ERR(handle)) {
2787 ret = PTR_ERR(handle);
2788 goto out_writepages;
2789 }
2790 BUG_ON(ext4_test_inode_state(inode,
2791 EXT4_STATE_MAY_INLINE_DATA));
2792 ext4_destroy_inline_data(handle, inode);
2793 ext4_journal_stop(handle);
2794 }
2795
David Brazdil0f672f62019-12-10 10:32:29 +00002796 if (ext4_should_dioread_nolock(inode)) {
2797 /*
2798 * We may need to convert up to one extent per block in
2799 * the page and we may dirty the inode.
2800 */
2801 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2802 PAGE_SIZE >> inode->i_blkbits);
2803 }
2804
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002805 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2806 range_whole = 1;
2807
2808 if (wbc->range_cyclic) {
2809 writeback_index = mapping->writeback_index;
2810 if (writeback_index)
2811 cycled = 0;
2812 mpd.first_page = writeback_index;
2813 mpd.last_page = -1;
2814 } else {
2815 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2816 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2817 }
2818
2819 mpd.inode = inode;
2820 mpd.wbc = wbc;
2821 ext4_io_submit_init(&mpd.io_submit, wbc);
2822retry:
2823 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2824 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2825 done = false;
2826 blk_start_plug(&plug);
2827
2828 /*
2829 * First writeback pages that don't need mapping - we can avoid
2830 * starting a transaction unnecessarily and also avoid being blocked
2831 * in the block layer on device congestion while having transaction
2832 * started.
2833 */
2834 mpd.do_map = 0;
2835 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2836 if (!mpd.io_submit.io_end) {
2837 ret = -ENOMEM;
2838 goto unplug;
2839 }
2840 ret = mpage_prepare_extent_to_map(&mpd);
David Brazdil0f672f62019-12-10 10:32:29 +00002841 /* Unlock pages we didn't use */
2842 mpage_release_unused_pages(&mpd, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002843 /* Submit prepared bio */
2844 ext4_io_submit(&mpd.io_submit);
2845 ext4_put_io_end_defer(mpd.io_submit.io_end);
2846 mpd.io_submit.io_end = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002847 if (ret < 0)
2848 goto unplug;
2849
2850 while (!done && mpd.first_page <= mpd.last_page) {
2851 /* For each extent of pages we use new io_end */
2852 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2853 if (!mpd.io_submit.io_end) {
2854 ret = -ENOMEM;
2855 break;
2856 }
2857
2858 /*
2859 * We have two constraints: We find one extent to map and we
2860 * must always write out whole page (makes a difference when
2861 * blocksize < pagesize) so that we don't block on IO when we
2862 * try to write out the rest of the page. Journalled mode is
2863 * not supported by delalloc.
2864 */
2865 BUG_ON(ext4_should_journal_data(inode));
2866 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2867
2868 /* start a new transaction */
2869 handle = ext4_journal_start_with_reserve(inode,
2870 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2871 if (IS_ERR(handle)) {
2872 ret = PTR_ERR(handle);
2873 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2874 "%ld pages, ino %lu; err %d", __func__,
2875 wbc->nr_to_write, inode->i_ino, ret);
2876 /* Release allocated io_end */
2877 ext4_put_io_end(mpd.io_submit.io_end);
2878 mpd.io_submit.io_end = NULL;
2879 break;
2880 }
2881 mpd.do_map = 1;
2882
2883 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2884 ret = mpage_prepare_extent_to_map(&mpd);
2885 if (!ret) {
2886 if (mpd.map.m_len)
2887 ret = mpage_map_and_submit_extent(handle, &mpd,
2888 &give_up_on_write);
2889 else {
2890 /*
2891 * We scanned the whole range (or exhausted
2892 * nr_to_write), submitted what was mapped and
2893 * didn't find anything needing mapping. We are
2894 * done.
2895 */
2896 done = true;
2897 }
2898 }
2899 /*
2900 * Caution: If the handle is synchronous,
2901 * ext4_journal_stop() can wait for transaction commit
2902 * to finish which may depend on writeback of pages to
2903 * complete or on page lock to be released. In that
2904 * case, we have to wait until after after we have
2905 * submitted all the IO, released page locks we hold,
2906 * and dropped io_end reference (for extent conversion
2907 * to be able to complete) before stopping the handle.
2908 */
2909 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2910 ext4_journal_stop(handle);
2911 handle = NULL;
2912 mpd.do_map = 0;
2913 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002914 /* Unlock pages we didn't use */
2915 mpage_release_unused_pages(&mpd, give_up_on_write);
David Brazdil0f672f62019-12-10 10:32:29 +00002916 /* Submit prepared bio */
2917 ext4_io_submit(&mpd.io_submit);
2918
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002919 /*
2920 * Drop our io_end reference we got from init. We have
2921 * to be careful and use deferred io_end finishing if
2922 * we are still holding the transaction as we can
2923 * release the last reference to io_end which may end
2924 * up doing unwritten extent conversion.
2925 */
2926 if (handle) {
2927 ext4_put_io_end_defer(mpd.io_submit.io_end);
2928 ext4_journal_stop(handle);
2929 } else
2930 ext4_put_io_end(mpd.io_submit.io_end);
2931 mpd.io_submit.io_end = NULL;
2932
2933 if (ret == -ENOSPC && sbi->s_journal) {
2934 /*
2935 * Commit the transaction which would
2936 * free blocks released in the transaction
2937 * and try again
2938 */
2939 jbd2_journal_force_commit_nested(sbi->s_journal);
2940 ret = 0;
2941 continue;
2942 }
2943 /* Fatal error - ENOMEM, EIO... */
2944 if (ret)
2945 break;
2946 }
2947unplug:
2948 blk_finish_plug(&plug);
2949 if (!ret && !cycled && wbc->nr_to_write > 0) {
2950 cycled = 1;
2951 mpd.last_page = writeback_index - 1;
2952 mpd.first_page = 0;
2953 goto retry;
2954 }
2955
2956 /* Update index */
2957 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2958 /*
2959 * Set the writeback_index so that range_cyclic
2960 * mode will write it back later
2961 */
2962 mapping->writeback_index = mpd.first_page;
2963
2964out_writepages:
2965 trace_ext4_writepages_result(inode, wbc, ret,
2966 nr_to_write - wbc->nr_to_write);
Olivier Deprez0e641232021-09-23 10:07:05 +02002967 percpu_up_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002968 return ret;
2969}
2970
2971static int ext4_dax_writepages(struct address_space *mapping,
2972 struct writeback_control *wbc)
2973{
2974 int ret;
2975 long nr_to_write = wbc->nr_to_write;
2976 struct inode *inode = mapping->host;
2977 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2978
2979 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2980 return -EIO;
2981
Olivier Deprez0e641232021-09-23 10:07:05 +02002982 percpu_down_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002983 trace_ext4_writepages(inode, wbc);
2984
2985 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev, wbc);
2986 trace_ext4_writepages_result(inode, wbc, ret,
2987 nr_to_write - wbc->nr_to_write);
Olivier Deprez0e641232021-09-23 10:07:05 +02002988 percpu_up_read(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002989 return ret;
2990}
2991
2992static int ext4_nonda_switch(struct super_block *sb)
2993{
2994 s64 free_clusters, dirty_clusters;
2995 struct ext4_sb_info *sbi = EXT4_SB(sb);
2996
2997 /*
2998 * switch to non delalloc mode if we are running low
2999 * on free block. The free block accounting via percpu
3000 * counters can get slightly wrong with percpu_counter_batch getting
3001 * accumulated on each CPU without updating global counters
3002 * Delalloc need an accurate free block accounting. So switch
3003 * to non delalloc when we are near to error range.
3004 */
3005 free_clusters =
3006 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3007 dirty_clusters =
3008 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
3009 /*
3010 * Start pushing delalloc when 1/2 of free blocks are dirty.
3011 */
3012 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
3013 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
3014
3015 if (2 * free_clusters < 3 * dirty_clusters ||
3016 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
3017 /*
3018 * free block count is less than 150% of dirty blocks
3019 * or free blocks is less than watermark
3020 */
3021 return 1;
3022 }
3023 return 0;
3024}
3025
3026/* We always reserve for an inode update; the superblock could be there too */
3027static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
3028{
3029 if (likely(ext4_has_feature_large_file(inode->i_sb)))
3030 return 1;
3031
3032 if (pos + len <= 0x7fffffffULL)
3033 return 1;
3034
3035 /* We might need to update the superblock to set LARGE_FILE */
3036 return 2;
3037}
3038
3039static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3040 loff_t pos, unsigned len, unsigned flags,
3041 struct page **pagep, void **fsdata)
3042{
3043 int ret, retries = 0;
3044 struct page *page;
3045 pgoff_t index;
3046 struct inode *inode = mapping->host;
3047 handle_t *handle;
3048
3049 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3050 return -EIO;
3051
3052 index = pos >> PAGE_SHIFT;
3053
David Brazdil0f672f62019-12-10 10:32:29 +00003054 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
3055 ext4_verity_in_progress(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003056 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3057 return ext4_write_begin(file, mapping, pos,
3058 len, flags, pagep, fsdata);
3059 }
3060 *fsdata = (void *)0;
3061 trace_ext4_da_write_begin(inode, pos, len, flags);
3062
3063 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3064 ret = ext4_da_write_inline_data_begin(mapping, inode,
3065 pos, len, flags,
3066 pagep, fsdata);
3067 if (ret < 0)
3068 return ret;
3069 if (ret == 1)
3070 return 0;
3071 }
3072
3073 /*
3074 * grab_cache_page_write_begin() can take a long time if the
3075 * system is thrashing due to memory pressure, or if the page
3076 * is being written back. So grab it first before we start
3077 * the transaction handle. This also allows us to allocate
3078 * the page (if needed) without using GFP_NOFS.
3079 */
3080retry_grab:
3081 page = grab_cache_page_write_begin(mapping, index, flags);
3082 if (!page)
3083 return -ENOMEM;
3084 unlock_page(page);
3085
3086 /*
3087 * With delayed allocation, we don't log the i_disksize update
3088 * if there is delayed block allocation. But we still need
3089 * to journalling the i_disksize update if writes to the end
3090 * of file which has an already mapped buffer.
3091 */
3092retry_journal:
3093 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3094 ext4_da_write_credits(inode, pos, len));
3095 if (IS_ERR(handle)) {
3096 put_page(page);
3097 return PTR_ERR(handle);
3098 }
3099
3100 lock_page(page);
3101 if (page->mapping != mapping) {
3102 /* The page got truncated from under us */
3103 unlock_page(page);
3104 put_page(page);
3105 ext4_journal_stop(handle);
3106 goto retry_grab;
3107 }
3108 /* In case writeback began while the page was unlocked */
3109 wait_for_stable_page(page);
3110
David Brazdil0f672f62019-12-10 10:32:29 +00003111#ifdef CONFIG_FS_ENCRYPTION
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003112 ret = ext4_block_write_begin(page, pos, len,
3113 ext4_da_get_block_prep);
3114#else
3115 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3116#endif
3117 if (ret < 0) {
3118 unlock_page(page);
3119 ext4_journal_stop(handle);
3120 /*
3121 * block_write_begin may have instantiated a few blocks
3122 * outside i_size. Trim these off again. Don't need
3123 * i_size_read because we hold i_mutex.
3124 */
3125 if (pos + len > inode->i_size)
3126 ext4_truncate_failed_write(inode);
3127
3128 if (ret == -ENOSPC &&
3129 ext4_should_retry_alloc(inode->i_sb, &retries))
3130 goto retry_journal;
3131
3132 put_page(page);
3133 return ret;
3134 }
3135
3136 *pagep = page;
3137 return ret;
3138}
3139
3140/*
3141 * Check if we should update i_disksize
3142 * when write to the end of file but not require block allocation
3143 */
3144static int ext4_da_should_update_i_disksize(struct page *page,
3145 unsigned long offset)
3146{
3147 struct buffer_head *bh;
3148 struct inode *inode = page->mapping->host;
3149 unsigned int idx;
3150 int i;
3151
3152 bh = page_buffers(page);
3153 idx = offset >> inode->i_blkbits;
3154
3155 for (i = 0; i < idx; i++)
3156 bh = bh->b_this_page;
3157
3158 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3159 return 0;
3160 return 1;
3161}
3162
3163static int ext4_da_write_end(struct file *file,
3164 struct address_space *mapping,
3165 loff_t pos, unsigned len, unsigned copied,
3166 struct page *page, void *fsdata)
3167{
3168 struct inode *inode = mapping->host;
3169 int ret = 0, ret2;
3170 handle_t *handle = ext4_journal_current_handle();
3171 loff_t new_i_size;
3172 unsigned long start, end;
3173 int write_mode = (int)(unsigned long)fsdata;
3174
3175 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3176 return ext4_write_end(file, mapping, pos,
3177 len, copied, page, fsdata);
3178
3179 trace_ext4_da_write_end(inode, pos, len, copied);
3180 start = pos & (PAGE_SIZE - 1);
3181 end = start + copied - 1;
3182
3183 /*
3184 * generic_write_end() will run mark_inode_dirty() if i_size
3185 * changes. So let's piggyback the i_disksize mark_inode_dirty
3186 * into that.
3187 */
3188 new_i_size = pos + copied;
3189 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3190 if (ext4_has_inline_data(inode) ||
3191 ext4_da_should_update_i_disksize(page, end)) {
3192 ext4_update_i_disksize(inode, new_i_size);
3193 /* We need to mark inode dirty even if
3194 * new_i_size is less that inode->i_size
3195 * bu greater than i_disksize.(hint delalloc)
3196 */
3197 ext4_mark_inode_dirty(handle, inode);
3198 }
3199 }
3200
3201 if (write_mode != CONVERT_INLINE_DATA &&
3202 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3203 ext4_has_inline_data(inode))
3204 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3205 page);
3206 else
3207 ret2 = generic_write_end(file, mapping, pos, len, copied,
3208 page, fsdata);
3209
3210 copied = ret2;
3211 if (ret2 < 0)
3212 ret = ret2;
3213 ret2 = ext4_journal_stop(handle);
3214 if (!ret)
3215 ret = ret2;
3216
3217 return ret ? ret : copied;
3218}
3219
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003220/*
3221 * Force all delayed allocation blocks to be allocated for a given inode.
3222 */
3223int ext4_alloc_da_blocks(struct inode *inode)
3224{
3225 trace_ext4_alloc_da_blocks(inode);
3226
3227 if (!EXT4_I(inode)->i_reserved_data_blocks)
3228 return 0;
3229
3230 /*
3231 * We do something simple for now. The filemap_flush() will
3232 * also start triggering a write of the data blocks, which is
3233 * not strictly speaking necessary (and for users of
3234 * laptop_mode, not even desirable). However, to do otherwise
3235 * would require replicating code paths in:
3236 *
3237 * ext4_writepages() ->
3238 * write_cache_pages() ---> (via passed in callback function)
3239 * __mpage_da_writepage() -->
3240 * mpage_add_bh_to_extent()
3241 * mpage_da_map_blocks()
3242 *
3243 * The problem is that write_cache_pages(), located in
3244 * mm/page-writeback.c, marks pages clean in preparation for
3245 * doing I/O, which is not desirable if we're not planning on
3246 * doing I/O at all.
3247 *
3248 * We could call write_cache_pages(), and then redirty all of
3249 * the pages by calling redirty_page_for_writepage() but that
3250 * would be ugly in the extreme. So instead we would need to
3251 * replicate parts of the code in the above functions,
3252 * simplifying them because we wouldn't actually intend to
3253 * write out the pages, but rather only collect contiguous
3254 * logical block extents, call the multi-block allocator, and
3255 * then update the buffer heads with the block allocations.
3256 *
3257 * For now, though, we'll cheat by calling filemap_flush(),
3258 * which will map the blocks, and start the I/O, but not
3259 * actually wait for the I/O to complete.
3260 */
3261 return filemap_flush(inode->i_mapping);
3262}
3263
3264/*
3265 * bmap() is special. It gets used by applications such as lilo and by
3266 * the swapper to find the on-disk block of a specific piece of data.
3267 *
3268 * Naturally, this is dangerous if the block concerned is still in the
3269 * journal. If somebody makes a swapfile on an ext4 data-journaling
3270 * filesystem and enables swap, then they may get a nasty shock when the
3271 * data getting swapped to that swapfile suddenly gets overwritten by
3272 * the original zero's written out previously to the journal and
3273 * awaiting writeback in the kernel's buffer cache.
3274 *
3275 * So, if we see any bmap calls here on a modified, data-journaled file,
3276 * take extra steps to flush any blocks which might be in the cache.
3277 */
3278static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3279{
3280 struct inode *inode = mapping->host;
3281 journal_t *journal;
3282 int err;
3283
3284 /*
3285 * We can get here for an inline file via the FIBMAP ioctl
3286 */
3287 if (ext4_has_inline_data(inode))
3288 return 0;
3289
3290 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3291 test_opt(inode->i_sb, DELALLOC)) {
3292 /*
3293 * With delalloc we want to sync the file
3294 * so that we can make sure we allocate
3295 * blocks for file
3296 */
3297 filemap_write_and_wait(mapping);
3298 }
3299
3300 if (EXT4_JOURNAL(inode) &&
3301 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3302 /*
3303 * This is a REALLY heavyweight approach, but the use of
3304 * bmap on dirty files is expected to be extremely rare:
3305 * only if we run lilo or swapon on a freshly made file
3306 * do we expect this to happen.
3307 *
3308 * (bmap requires CAP_SYS_RAWIO so this does not
3309 * represent an unprivileged user DOS attack --- we'd be
3310 * in trouble if mortal users could trigger this path at
3311 * will.)
3312 *
3313 * NB. EXT4_STATE_JDATA is not set on files other than
3314 * regular files. If somebody wants to bmap a directory
3315 * or symlink and gets confused because the buffer
3316 * hasn't yet been flushed to disk, they deserve
3317 * everything they get.
3318 */
3319
3320 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3321 journal = EXT4_JOURNAL(inode);
3322 jbd2_journal_lock_updates(journal);
3323 err = jbd2_journal_flush(journal);
3324 jbd2_journal_unlock_updates(journal);
3325
3326 if (err)
3327 return 0;
3328 }
3329
3330 return generic_block_bmap(mapping, block, ext4_get_block);
3331}
3332
3333static int ext4_readpage(struct file *file, struct page *page)
3334{
3335 int ret = -EAGAIN;
3336 struct inode *inode = page->mapping->host;
3337
3338 trace_ext4_readpage(page);
3339
3340 if (ext4_has_inline_data(inode))
3341 ret = ext4_readpage_inline(inode, page);
3342
3343 if (ret == -EAGAIN)
3344 return ext4_mpage_readpages(page->mapping, NULL, page, 1,
3345 false);
3346
3347 return ret;
3348}
3349
3350static int
3351ext4_readpages(struct file *file, struct address_space *mapping,
3352 struct list_head *pages, unsigned nr_pages)
3353{
3354 struct inode *inode = mapping->host;
3355
3356 /* If the file has inline data, no need to do readpages. */
3357 if (ext4_has_inline_data(inode))
3358 return 0;
3359
3360 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages, true);
3361}
3362
3363static void ext4_invalidatepage(struct page *page, unsigned int offset,
3364 unsigned int length)
3365{
3366 trace_ext4_invalidatepage(page, offset, length);
3367
3368 /* No journalling happens on data buffers when this function is used */
3369 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3370
3371 block_invalidatepage(page, offset, length);
3372}
3373
3374static int __ext4_journalled_invalidatepage(struct page *page,
3375 unsigned int offset,
3376 unsigned int length)
3377{
3378 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3379
3380 trace_ext4_journalled_invalidatepage(page, offset, length);
3381
3382 /*
3383 * If it's a full truncate we just forget about the pending dirtying
3384 */
3385 if (offset == 0 && length == PAGE_SIZE)
3386 ClearPageChecked(page);
3387
3388 return jbd2_journal_invalidatepage(journal, page, offset, length);
3389}
3390
3391/* Wrapper for aops... */
3392static void ext4_journalled_invalidatepage(struct page *page,
3393 unsigned int offset,
3394 unsigned int length)
3395{
3396 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3397}
3398
3399static int ext4_releasepage(struct page *page, gfp_t wait)
3400{
3401 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3402
3403 trace_ext4_releasepage(page);
3404
3405 /* Page has dirty journalled data -> cannot release */
3406 if (PageChecked(page))
3407 return 0;
3408 if (journal)
3409 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3410 else
3411 return try_to_free_buffers(page);
3412}
3413
3414static bool ext4_inode_datasync_dirty(struct inode *inode)
3415{
3416 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3417
3418 if (journal)
3419 return !jbd2_transaction_committed(journal,
3420 EXT4_I(inode)->i_datasync_tid);
3421 /* Any metadata buffers to write? */
3422 if (!list_empty(&inode->i_mapping->private_list))
3423 return true;
3424 return inode->i_state & I_DIRTY_DATASYNC;
3425}
3426
3427static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3428 unsigned flags, struct iomap *iomap)
3429{
3430 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3431 unsigned int blkbits = inode->i_blkbits;
3432 unsigned long first_block, last_block;
3433 struct ext4_map_blocks map;
3434 bool delalloc = false;
3435 int ret;
3436
3437 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3438 return -EINVAL;
3439 first_block = offset >> blkbits;
3440 last_block = min_t(loff_t, (offset + length - 1) >> blkbits,
3441 EXT4_MAX_LOGICAL_BLOCK);
3442
3443 if (flags & IOMAP_REPORT) {
3444 if (ext4_has_inline_data(inode)) {
3445 ret = ext4_inline_data_iomap(inode, iomap);
3446 if (ret != -EAGAIN) {
3447 if (ret == 0 && offset >= iomap->length)
3448 ret = -ENOENT;
3449 return ret;
3450 }
3451 }
3452 } else {
3453 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3454 return -ERANGE;
3455 }
3456
3457 map.m_lblk = first_block;
3458 map.m_len = last_block - first_block + 1;
3459
3460 if (flags & IOMAP_REPORT) {
3461 ret = ext4_map_blocks(NULL, inode, &map, 0);
3462 if (ret < 0)
3463 return ret;
3464
3465 if (ret == 0) {
3466 ext4_lblk_t end = map.m_lblk + map.m_len - 1;
3467 struct extent_status es;
3468
David Brazdil0f672f62019-12-10 10:32:29 +00003469 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3470 map.m_lblk, end, &es);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003471
3472 if (!es.es_len || es.es_lblk > end) {
3473 /* entire range is a hole */
3474 } else if (es.es_lblk > map.m_lblk) {
3475 /* range starts with a hole */
3476 map.m_len = es.es_lblk - map.m_lblk;
3477 } else {
3478 ext4_lblk_t offs = 0;
3479
3480 if (es.es_lblk < map.m_lblk)
3481 offs = map.m_lblk - es.es_lblk;
3482 map.m_lblk = es.es_lblk + offs;
3483 map.m_len = es.es_len - offs;
3484 delalloc = true;
3485 }
3486 }
3487 } else if (flags & IOMAP_WRITE) {
3488 int dio_credits;
3489 handle_t *handle;
3490 int retries = 0;
3491
3492 /* Trim mapping request to maximum we can map at once for DIO */
3493 if (map.m_len > DIO_MAX_BLOCKS)
3494 map.m_len = DIO_MAX_BLOCKS;
3495 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3496retry:
3497 /*
3498 * Either we allocate blocks and then we don't get unwritten
3499 * extent so we have reserved enough credits, or the blocks
3500 * are already allocated and unwritten and in that case
3501 * extent conversion fits in the credits as well.
3502 */
3503 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3504 dio_credits);
3505 if (IS_ERR(handle))
3506 return PTR_ERR(handle);
3507
3508 ret = ext4_map_blocks(handle, inode, &map,
3509 EXT4_GET_BLOCKS_CREATE_ZERO);
3510 if (ret < 0) {
3511 ext4_journal_stop(handle);
3512 if (ret == -ENOSPC &&
3513 ext4_should_retry_alloc(inode->i_sb, &retries))
3514 goto retry;
3515 return ret;
3516 }
3517
3518 /*
3519 * If we added blocks beyond i_size, we need to make sure they
3520 * will get truncated if we crash before updating i_size in
3521 * ext4_iomap_end(). For faults we don't need to do that (and
3522 * even cannot because for orphan list operations inode_lock is
3523 * required) - if we happen to instantiate block beyond i_size,
3524 * it is because we race with truncate which has already added
3525 * the inode to the orphan list.
3526 */
3527 if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3528 (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
3529 int err;
3530
3531 err = ext4_orphan_add(handle, inode);
3532 if (err < 0) {
3533 ext4_journal_stop(handle);
3534 return err;
3535 }
3536 }
3537 ext4_journal_stop(handle);
3538 } else {
3539 ret = ext4_map_blocks(NULL, inode, &map, 0);
3540 if (ret < 0)
3541 return ret;
3542 }
3543
Olivier Deprez0e641232021-09-23 10:07:05 +02003544 /*
3545 * Writes that span EOF might trigger an I/O size update on completion,
3546 * so consider them to be dirty for the purposes of O_DSYNC, even if
3547 * there is no other metadata changes being made or are pending here.
3548 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003549 iomap->flags = 0;
Olivier Deprez0e641232021-09-23 10:07:05 +02003550 if (ext4_inode_datasync_dirty(inode) ||
3551 offset + length > i_size_read(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003552 iomap->flags |= IOMAP_F_DIRTY;
3553 iomap->bdev = inode->i_sb->s_bdev;
3554 iomap->dax_dev = sbi->s_daxdev;
3555 iomap->offset = (u64)first_block << blkbits;
3556 iomap->length = (u64)map.m_len << blkbits;
3557
3558 if (ret == 0) {
3559 iomap->type = delalloc ? IOMAP_DELALLOC : IOMAP_HOLE;
3560 iomap->addr = IOMAP_NULL_ADDR;
3561 } else {
3562 if (map.m_flags & EXT4_MAP_MAPPED) {
3563 iomap->type = IOMAP_MAPPED;
3564 } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3565 iomap->type = IOMAP_UNWRITTEN;
3566 } else {
3567 WARN_ON_ONCE(1);
3568 return -EIO;
3569 }
3570 iomap->addr = (u64)map.m_pblk << blkbits;
3571 }
3572
3573 if (map.m_flags & EXT4_MAP_NEW)
3574 iomap->flags |= IOMAP_F_NEW;
3575
3576 return 0;
3577}
3578
3579static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3580 ssize_t written, unsigned flags, struct iomap *iomap)
3581{
3582 int ret = 0;
3583 handle_t *handle;
3584 int blkbits = inode->i_blkbits;
3585 bool truncate = false;
3586
3587 if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
3588 return 0;
3589
3590 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3591 if (IS_ERR(handle)) {
3592 ret = PTR_ERR(handle);
3593 goto orphan_del;
3594 }
3595 if (ext4_update_inode_size(inode, offset + written))
3596 ext4_mark_inode_dirty(handle, inode);
3597 /*
3598 * We may need to truncate allocated but not written blocks beyond EOF.
3599 */
3600 if (iomap->offset + iomap->length >
3601 ALIGN(inode->i_size, 1 << blkbits)) {
3602 ext4_lblk_t written_blk, end_blk;
3603
3604 written_blk = (offset + written) >> blkbits;
3605 end_blk = (offset + length) >> blkbits;
3606 if (written_blk < end_blk && ext4_can_truncate(inode))
3607 truncate = true;
3608 }
3609 /*
3610 * Remove inode from orphan list if we were extending a inode and
3611 * everything went fine.
3612 */
3613 if (!truncate && inode->i_nlink &&
3614 !list_empty(&EXT4_I(inode)->i_orphan))
3615 ext4_orphan_del(handle, inode);
3616 ext4_journal_stop(handle);
3617 if (truncate) {
3618 ext4_truncate_failed_write(inode);
3619orphan_del:
3620 /*
3621 * If truncate failed early the inode might still be on the
3622 * orphan list; we need to make sure the inode is removed from
3623 * the orphan list in that case.
3624 */
3625 if (inode->i_nlink)
3626 ext4_orphan_del(NULL, inode);
3627 }
3628 return ret;
3629}
3630
3631const struct iomap_ops ext4_iomap_ops = {
3632 .iomap_begin = ext4_iomap_begin,
3633 .iomap_end = ext4_iomap_end,
3634};
3635
3636static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3637 ssize_t size, void *private)
3638{
3639 ext4_io_end_t *io_end = private;
3640
3641 /* if not async direct IO just return */
3642 if (!io_end)
3643 return 0;
3644
3645 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3646 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3647 io_end, io_end->inode->i_ino, iocb, offset, size);
3648
3649 /*
3650 * Error during AIO DIO. We cannot convert unwritten extents as the
3651 * data was not written. Just clear the unwritten flag and drop io_end.
3652 */
3653 if (size <= 0) {
3654 ext4_clear_io_unwritten_flag(io_end);
3655 size = 0;
3656 }
3657 io_end->offset = offset;
3658 io_end->size = size;
3659 ext4_put_io_end(io_end);
3660
3661 return 0;
3662}
3663
3664/*
3665 * Handling of direct IO writes.
3666 *
3667 * For ext4 extent files, ext4 will do direct-io write even to holes,
3668 * preallocated extents, and those write extend the file, no need to
3669 * fall back to buffered IO.
3670 *
3671 * For holes, we fallocate those blocks, mark them as unwritten
3672 * If those blocks were preallocated, we mark sure they are split, but
3673 * still keep the range to write as unwritten.
3674 *
3675 * The unwritten extents will be converted to written when DIO is completed.
3676 * For async direct IO, since the IO may still pending when return, we
3677 * set up an end_io call back function, which will do the conversion
3678 * when async direct IO completed.
3679 *
3680 * If the O_DIRECT write will extend the file then add this inode to the
3681 * orphan list. So recovery will truncate it back to the original size
3682 * if the machine crashes during the write.
3683 *
3684 */
3685static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
3686{
3687 struct file *file = iocb->ki_filp;
3688 struct inode *inode = file->f_mapping->host;
3689 struct ext4_inode_info *ei = EXT4_I(inode);
3690 ssize_t ret;
3691 loff_t offset = iocb->ki_pos;
3692 size_t count = iov_iter_count(iter);
3693 int overwrite = 0;
3694 get_block_t *get_block_func = NULL;
3695 int dio_flags = 0;
3696 loff_t final_size = offset + count;
3697 int orphan = 0;
3698 handle_t *handle;
3699
3700 if (final_size > inode->i_size || final_size > ei->i_disksize) {
3701 /* Credits for sb + inode write */
3702 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3703 if (IS_ERR(handle)) {
3704 ret = PTR_ERR(handle);
3705 goto out;
3706 }
3707 ret = ext4_orphan_add(handle, inode);
3708 if (ret) {
3709 ext4_journal_stop(handle);
3710 goto out;
3711 }
3712 orphan = 1;
3713 ext4_update_i_disksize(inode, inode->i_size);
3714 ext4_journal_stop(handle);
3715 }
3716
3717 BUG_ON(iocb->private == NULL);
3718
3719 /*
3720 * Make all waiters for direct IO properly wait also for extent
3721 * conversion. This also disallows race between truncate() and
3722 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3723 */
3724 inode_dio_begin(inode);
3725
3726 /* If we do a overwrite dio, i_mutex locking can be released */
3727 overwrite = *((int *)iocb->private);
3728
3729 if (overwrite)
3730 inode_unlock(inode);
3731
3732 /*
3733 * For extent mapped files we could direct write to holes and fallocate.
3734 *
3735 * Allocated blocks to fill the hole are marked as unwritten to prevent
3736 * parallel buffered read to expose the stale data before DIO complete
3737 * the data IO.
3738 *
3739 * As to previously fallocated extents, ext4 get_block will just simply
3740 * mark the buffer mapped but still keep the extents unwritten.
3741 *
3742 * For non AIO case, we will convert those unwritten extents to written
3743 * after return back from blockdev_direct_IO. That way we save us from
3744 * allocating io_end structure and also the overhead of offloading
3745 * the extent convertion to a workqueue.
3746 *
3747 * For async DIO, the conversion needs to be deferred when the
3748 * IO is completed. The ext4 end_io callback function will be
3749 * called to take care of the conversion work. Here for async
3750 * case, we allocate an io_end structure to hook to the iocb.
3751 */
3752 iocb->private = NULL;
3753 if (overwrite)
3754 get_block_func = ext4_dio_get_block_overwrite;
3755 else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
3756 round_down(offset, i_blocksize(inode)) >= inode->i_size) {
3757 get_block_func = ext4_dio_get_block;
3758 dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3759 } else if (is_sync_kiocb(iocb)) {
3760 get_block_func = ext4_dio_get_block_unwritten_sync;
3761 dio_flags = DIO_LOCKING;
3762 } else {
3763 get_block_func = ext4_dio_get_block_unwritten_async;
3764 dio_flags = DIO_LOCKING;
3765 }
3766 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3767 get_block_func, ext4_end_io_dio, NULL,
3768 dio_flags);
3769
3770 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3771 EXT4_STATE_DIO_UNWRITTEN)) {
3772 int err;
3773 /*
3774 * for non AIO case, since the IO is already
3775 * completed, we could do the conversion right here
3776 */
3777 err = ext4_convert_unwritten_extents(NULL, inode,
3778 offset, ret);
3779 if (err < 0)
3780 ret = err;
3781 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3782 }
3783
3784 inode_dio_end(inode);
3785 /* take i_mutex locking again if we do a ovewrite dio */
3786 if (overwrite)
3787 inode_lock(inode);
3788
3789 if (ret < 0 && final_size > inode->i_size)
3790 ext4_truncate_failed_write(inode);
3791
3792 /* Handle extending of i_size after direct IO write */
3793 if (orphan) {
3794 int err;
3795
3796 /* Credits for sb + inode write */
3797 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3798 if (IS_ERR(handle)) {
3799 /*
3800 * We wrote the data but cannot extend
3801 * i_size. Bail out. In async io case, we do
3802 * not return error here because we have
3803 * already submmitted the corresponding
3804 * bio. Returning error here makes the caller
3805 * think that this IO is done and failed
3806 * resulting in race with bio's completion
3807 * handler.
3808 */
3809 if (!ret)
3810 ret = PTR_ERR(handle);
3811 if (inode->i_nlink)
3812 ext4_orphan_del(NULL, inode);
3813
3814 goto out;
3815 }
3816 if (inode->i_nlink)
3817 ext4_orphan_del(handle, inode);
3818 if (ret > 0) {
3819 loff_t end = offset + ret;
3820 if (end > inode->i_size || end > ei->i_disksize) {
3821 ext4_update_i_disksize(inode, end);
3822 if (end > inode->i_size)
3823 i_size_write(inode, end);
3824 /*
3825 * We're going to return a positive `ret'
3826 * here due to non-zero-length I/O, so there's
3827 * no way of reporting error returns from
3828 * ext4_mark_inode_dirty() to userspace. So
3829 * ignore it.
3830 */
3831 ext4_mark_inode_dirty(handle, inode);
3832 }
3833 }
3834 err = ext4_journal_stop(handle);
3835 if (ret == 0)
3836 ret = err;
3837 }
3838out:
3839 return ret;
3840}
3841
3842static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
3843{
3844 struct address_space *mapping = iocb->ki_filp->f_mapping;
3845 struct inode *inode = mapping->host;
3846 size_t count = iov_iter_count(iter);
3847 ssize_t ret;
Olivier Deprez0e641232021-09-23 10:07:05 +02003848 loff_t offset = iocb->ki_pos;
3849 loff_t size = i_size_read(inode);
3850
3851 if (offset >= size)
3852 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003853
3854 /*
3855 * Shared inode_lock is enough for us - it protects against concurrent
3856 * writes & truncates and since we take care of writing back page cache,
3857 * we are protected against page writeback as well.
3858 */
Olivier Deprez0e641232021-09-23 10:07:05 +02003859 if (iocb->ki_flags & IOCB_NOWAIT) {
3860 if (!inode_trylock_shared(inode))
3861 return -EAGAIN;
3862 } else {
3863 inode_lock_shared(inode);
3864 }
3865
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003866 ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
3867 iocb->ki_pos + count - 1);
3868 if (ret)
3869 goto out_unlock;
3870 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
3871 iter, ext4_dio_get_block, NULL, NULL, 0);
3872out_unlock:
3873 inode_unlock_shared(inode);
3874 return ret;
3875}
3876
3877static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
3878{
3879 struct file *file = iocb->ki_filp;
3880 struct inode *inode = file->f_mapping->host;
3881 size_t count = iov_iter_count(iter);
3882 loff_t offset = iocb->ki_pos;
3883 ssize_t ret;
3884
David Brazdil0f672f62019-12-10 10:32:29 +00003885#ifdef CONFIG_FS_ENCRYPTION
3886 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003887 return 0;
3888#endif
David Brazdil0f672f62019-12-10 10:32:29 +00003889 if (fsverity_active(inode))
3890 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003891
3892 /*
3893 * If we are doing data journalling we don't support O_DIRECT
3894 */
3895 if (ext4_should_journal_data(inode))
3896 return 0;
3897
3898 /* Let buffer I/O handle the inline data case. */
3899 if (ext4_has_inline_data(inode))
3900 return 0;
3901
3902 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3903 if (iov_iter_rw(iter) == READ)
3904 ret = ext4_direct_IO_read(iocb, iter);
3905 else
3906 ret = ext4_direct_IO_write(iocb, iter);
3907 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3908 return ret;
3909}
3910
3911/*
3912 * Pages can be marked dirty completely asynchronously from ext4's journalling
3913 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3914 * much here because ->set_page_dirty is called under VFS locks. The page is
3915 * not necessarily locked.
3916 *
3917 * We cannot just dirty the page and leave attached buffers clean, because the
3918 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3919 * or jbddirty because all the journalling code will explode.
3920 *
3921 * So what we do is to mark the page "pending dirty" and next time writepage
3922 * is called, propagate that into the buffers appropriately.
3923 */
3924static int ext4_journalled_set_page_dirty(struct page *page)
3925{
3926 SetPageChecked(page);
3927 return __set_page_dirty_nobuffers(page);
3928}
3929
3930static int ext4_set_page_dirty(struct page *page)
3931{
3932 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3933 WARN_ON_ONCE(!page_has_buffers(page));
3934 return __set_page_dirty_buffers(page);
3935}
3936
3937static const struct address_space_operations ext4_aops = {
3938 .readpage = ext4_readpage,
3939 .readpages = ext4_readpages,
3940 .writepage = ext4_writepage,
3941 .writepages = ext4_writepages,
3942 .write_begin = ext4_write_begin,
3943 .write_end = ext4_write_end,
3944 .set_page_dirty = ext4_set_page_dirty,
3945 .bmap = ext4_bmap,
3946 .invalidatepage = ext4_invalidatepage,
3947 .releasepage = ext4_releasepage,
3948 .direct_IO = ext4_direct_IO,
3949 .migratepage = buffer_migrate_page,
3950 .is_partially_uptodate = block_is_partially_uptodate,
3951 .error_remove_page = generic_error_remove_page,
3952};
3953
3954static const struct address_space_operations ext4_journalled_aops = {
3955 .readpage = ext4_readpage,
3956 .readpages = ext4_readpages,
3957 .writepage = ext4_writepage,
3958 .writepages = ext4_writepages,
3959 .write_begin = ext4_write_begin,
3960 .write_end = ext4_journalled_write_end,
3961 .set_page_dirty = ext4_journalled_set_page_dirty,
3962 .bmap = ext4_bmap,
3963 .invalidatepage = ext4_journalled_invalidatepage,
3964 .releasepage = ext4_releasepage,
3965 .direct_IO = ext4_direct_IO,
3966 .is_partially_uptodate = block_is_partially_uptodate,
3967 .error_remove_page = generic_error_remove_page,
3968};
3969
3970static const struct address_space_operations ext4_da_aops = {
3971 .readpage = ext4_readpage,
3972 .readpages = ext4_readpages,
3973 .writepage = ext4_writepage,
3974 .writepages = ext4_writepages,
3975 .write_begin = ext4_da_write_begin,
3976 .write_end = ext4_da_write_end,
3977 .set_page_dirty = ext4_set_page_dirty,
3978 .bmap = ext4_bmap,
David Brazdil0f672f62019-12-10 10:32:29 +00003979 .invalidatepage = ext4_invalidatepage,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003980 .releasepage = ext4_releasepage,
3981 .direct_IO = ext4_direct_IO,
3982 .migratepage = buffer_migrate_page,
3983 .is_partially_uptodate = block_is_partially_uptodate,
3984 .error_remove_page = generic_error_remove_page,
3985};
3986
3987static const struct address_space_operations ext4_dax_aops = {
3988 .writepages = ext4_dax_writepages,
3989 .direct_IO = noop_direct_IO,
3990 .set_page_dirty = noop_set_page_dirty,
3991 .bmap = ext4_bmap,
3992 .invalidatepage = noop_invalidatepage,
3993};
3994
3995void ext4_set_aops(struct inode *inode)
3996{
3997 switch (ext4_inode_journal_mode(inode)) {
3998 case EXT4_INODE_ORDERED_DATA_MODE:
3999 case EXT4_INODE_WRITEBACK_DATA_MODE:
4000 break;
4001 case EXT4_INODE_JOURNAL_DATA_MODE:
4002 inode->i_mapping->a_ops = &ext4_journalled_aops;
4003 return;
4004 default:
4005 BUG();
4006 }
4007 if (IS_DAX(inode))
4008 inode->i_mapping->a_ops = &ext4_dax_aops;
4009 else if (test_opt(inode->i_sb, DELALLOC))
4010 inode->i_mapping->a_ops = &ext4_da_aops;
4011 else
4012 inode->i_mapping->a_ops = &ext4_aops;
4013}
4014
4015static int __ext4_block_zero_page_range(handle_t *handle,
4016 struct address_space *mapping, loff_t from, loff_t length)
4017{
4018 ext4_fsblk_t index = from >> PAGE_SHIFT;
4019 unsigned offset = from & (PAGE_SIZE-1);
4020 unsigned blocksize, pos;
4021 ext4_lblk_t iblock;
4022 struct inode *inode = mapping->host;
4023 struct buffer_head *bh;
4024 struct page *page;
4025 int err = 0;
4026
4027 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
4028 mapping_gfp_constraint(mapping, ~__GFP_FS));
4029 if (!page)
4030 return -ENOMEM;
4031
4032 blocksize = inode->i_sb->s_blocksize;
4033
4034 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
4035
4036 if (!page_has_buffers(page))
4037 create_empty_buffers(page, blocksize, 0);
4038
4039 /* Find the buffer that contains "offset" */
4040 bh = page_buffers(page);
4041 pos = blocksize;
4042 while (offset >= pos) {
4043 bh = bh->b_this_page;
4044 iblock++;
4045 pos += blocksize;
4046 }
4047 if (buffer_freed(bh)) {
4048 BUFFER_TRACE(bh, "freed: skip");
4049 goto unlock;
4050 }
4051 if (!buffer_mapped(bh)) {
4052 BUFFER_TRACE(bh, "unmapped");
4053 ext4_get_block(inode, iblock, bh, 0);
4054 /* unmapped? It's a hole - nothing to do */
4055 if (!buffer_mapped(bh)) {
4056 BUFFER_TRACE(bh, "still unmapped");
4057 goto unlock;
4058 }
4059 }
4060
4061 /* Ok, it's mapped. Make sure it's up-to-date */
4062 if (PageUptodate(page))
4063 set_buffer_uptodate(bh);
4064
4065 if (!buffer_uptodate(bh)) {
4066 err = -EIO;
4067 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
4068 wait_on_buffer(bh);
4069 /* Uhhuh. Read error. Complain and punt. */
4070 if (!buffer_uptodate(bh))
4071 goto unlock;
David Brazdil0f672f62019-12-10 10:32:29 +00004072 if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004073 /* We expect the key to be set. */
4074 BUG_ON(!fscrypt_has_encryption_key(inode));
David Brazdil0f672f62019-12-10 10:32:29 +00004075 WARN_ON_ONCE(fscrypt_decrypt_pagecache_blocks(
4076 page, blocksize, bh_offset(bh)));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004077 }
4078 }
4079 if (ext4_should_journal_data(inode)) {
4080 BUFFER_TRACE(bh, "get write access");
4081 err = ext4_journal_get_write_access(handle, bh);
4082 if (err)
4083 goto unlock;
4084 }
4085 zero_user(page, offset, length);
4086 BUFFER_TRACE(bh, "zeroed end of block");
4087
4088 if (ext4_should_journal_data(inode)) {
4089 err = ext4_handle_dirty_metadata(handle, inode, bh);
4090 } else {
4091 err = 0;
4092 mark_buffer_dirty(bh);
4093 if (ext4_should_order_data(inode))
David Brazdil0f672f62019-12-10 10:32:29 +00004094 err = ext4_jbd2_inode_add_write(handle, inode, from,
4095 length);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004096 }
4097
4098unlock:
4099 unlock_page(page);
4100 put_page(page);
4101 return err;
4102}
4103
4104/*
4105 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4106 * starting from file offset 'from'. The range to be zero'd must
4107 * be contained with in one block. If the specified range exceeds
4108 * the end of the block it will be shortened to end of the block
4109 * that cooresponds to 'from'
4110 */
4111static int ext4_block_zero_page_range(handle_t *handle,
4112 struct address_space *mapping, loff_t from, loff_t length)
4113{
4114 struct inode *inode = mapping->host;
4115 unsigned offset = from & (PAGE_SIZE-1);
4116 unsigned blocksize = inode->i_sb->s_blocksize;
4117 unsigned max = blocksize - (offset & (blocksize - 1));
4118
4119 /*
4120 * correct length if it does not fall between
4121 * 'from' and the end of the block
4122 */
4123 if (length > max || length < 0)
4124 length = max;
4125
4126 if (IS_DAX(inode)) {
4127 return iomap_zero_range(inode, from, length, NULL,
4128 &ext4_iomap_ops);
4129 }
4130 return __ext4_block_zero_page_range(handle, mapping, from, length);
4131}
4132
4133/*
4134 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4135 * up to the end of the block which corresponds to `from'.
4136 * This required during truncate. We need to physically zero the tail end
4137 * of that block so it doesn't yield old data if the file is later grown.
4138 */
4139static int ext4_block_truncate_page(handle_t *handle,
4140 struct address_space *mapping, loff_t from)
4141{
4142 unsigned offset = from & (PAGE_SIZE-1);
4143 unsigned length;
4144 unsigned blocksize;
4145 struct inode *inode = mapping->host;
4146
4147 /* If we are processing an encrypted inode during orphan list handling */
David Brazdil0f672f62019-12-10 10:32:29 +00004148 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004149 return 0;
4150
4151 blocksize = inode->i_sb->s_blocksize;
4152 length = blocksize - (offset & (blocksize - 1));
4153
4154 return ext4_block_zero_page_range(handle, mapping, from, length);
4155}
4156
4157int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4158 loff_t lstart, loff_t length)
4159{
4160 struct super_block *sb = inode->i_sb;
4161 struct address_space *mapping = inode->i_mapping;
4162 unsigned partial_start, partial_end;
4163 ext4_fsblk_t start, end;
4164 loff_t byte_end = (lstart + length - 1);
4165 int err = 0;
4166
4167 partial_start = lstart & (sb->s_blocksize - 1);
4168 partial_end = byte_end & (sb->s_blocksize - 1);
4169
4170 start = lstart >> sb->s_blocksize_bits;
4171 end = byte_end >> sb->s_blocksize_bits;
4172
4173 /* Handle partial zero within the single block */
4174 if (start == end &&
4175 (partial_start || (partial_end != sb->s_blocksize - 1))) {
4176 err = ext4_block_zero_page_range(handle, mapping,
4177 lstart, length);
4178 return err;
4179 }
4180 /* Handle partial zero out on the start of the range */
4181 if (partial_start) {
4182 err = ext4_block_zero_page_range(handle, mapping,
4183 lstart, sb->s_blocksize);
4184 if (err)
4185 return err;
4186 }
4187 /* Handle partial zero out on the end of the range */
4188 if (partial_end != sb->s_blocksize - 1)
4189 err = ext4_block_zero_page_range(handle, mapping,
4190 byte_end - partial_end,
4191 partial_end + 1);
4192 return err;
4193}
4194
4195int ext4_can_truncate(struct inode *inode)
4196{
4197 if (S_ISREG(inode->i_mode))
4198 return 1;
4199 if (S_ISDIR(inode->i_mode))
4200 return 1;
4201 if (S_ISLNK(inode->i_mode))
4202 return !ext4_inode_is_fast_symlink(inode);
4203 return 0;
4204}
4205
4206/*
4207 * We have to make sure i_disksize gets properly updated before we truncate
4208 * page cache due to hole punching or zero range. Otherwise i_disksize update
4209 * can get lost as it may have been postponed to submission of writeback but
4210 * that will never happen after we truncate page cache.
4211 */
4212int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4213 loff_t len)
4214{
4215 handle_t *handle;
4216 loff_t size = i_size_read(inode);
4217
4218 WARN_ON(!inode_is_locked(inode));
4219 if (offset > size || offset + len < size)
4220 return 0;
4221
4222 if (EXT4_I(inode)->i_disksize >= size)
4223 return 0;
4224
4225 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4226 if (IS_ERR(handle))
4227 return PTR_ERR(handle);
4228 ext4_update_i_disksize(inode, size);
4229 ext4_mark_inode_dirty(handle, inode);
4230 ext4_journal_stop(handle);
4231
4232 return 0;
4233}
4234
4235static void ext4_wait_dax_page(struct ext4_inode_info *ei)
4236{
4237 up_write(&ei->i_mmap_sem);
4238 schedule();
4239 down_write(&ei->i_mmap_sem);
4240}
4241
4242int ext4_break_layouts(struct inode *inode)
4243{
4244 struct ext4_inode_info *ei = EXT4_I(inode);
4245 struct page *page;
4246 int error;
4247
4248 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
4249 return -EINVAL;
4250
4251 do {
4252 page = dax_layout_busy_page(inode->i_mapping);
4253 if (!page)
4254 return 0;
4255
4256 error = ___wait_var_event(&page->_refcount,
4257 atomic_read(&page->_refcount) == 1,
4258 TASK_INTERRUPTIBLE, 0, 0,
4259 ext4_wait_dax_page(ei));
4260 } while (error == 0);
4261
4262 return error;
4263}
4264
4265/*
4266 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4267 * associated with the given offset and length
4268 *
4269 * @inode: File inode
4270 * @offset: The offset where the hole will begin
4271 * @len: The length of the hole
4272 *
4273 * Returns: 0 on success or negative on failure
4274 */
4275
4276int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4277{
4278 struct super_block *sb = inode->i_sb;
4279 ext4_lblk_t first_block, stop_block;
4280 struct address_space *mapping = inode->i_mapping;
4281 loff_t first_block_offset, last_block_offset;
4282 handle_t *handle;
4283 unsigned int credits;
4284 int ret = 0;
4285
4286 if (!S_ISREG(inode->i_mode))
4287 return -EOPNOTSUPP;
4288
4289 trace_ext4_punch_hole(inode, offset, length, 0);
4290
David Brazdil0f672f62019-12-10 10:32:29 +00004291 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4292 if (ext4_has_inline_data(inode)) {
4293 down_write(&EXT4_I(inode)->i_mmap_sem);
4294 ret = ext4_convert_inline_data(inode);
4295 up_write(&EXT4_I(inode)->i_mmap_sem);
4296 if (ret)
4297 return ret;
4298 }
4299
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004300 /*
4301 * Write out all dirty pages to avoid race conditions
4302 * Then release them.
4303 */
4304 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4305 ret = filemap_write_and_wait_range(mapping, offset,
4306 offset + length - 1);
4307 if (ret)
4308 return ret;
4309 }
4310
4311 inode_lock(inode);
4312
4313 /* No need to punch hole beyond i_size */
4314 if (offset >= inode->i_size)
4315 goto out_mutex;
4316
4317 /*
4318 * If the hole extends beyond i_size, set the hole
4319 * to end after the page that contains i_size
4320 */
4321 if (offset + length > inode->i_size) {
4322 length = inode->i_size +
4323 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4324 offset;
4325 }
4326
4327 if (offset & (sb->s_blocksize - 1) ||
4328 (offset + length) & (sb->s_blocksize - 1)) {
4329 /*
4330 * Attach jinode to inode for jbd2 if we do any zeroing of
4331 * partial block
4332 */
4333 ret = ext4_inode_attach_jinode(inode);
4334 if (ret < 0)
4335 goto out_mutex;
4336
4337 }
4338
4339 /* Wait all existing dio workers, newcomers will block on i_mutex */
4340 inode_dio_wait(inode);
4341
4342 /*
4343 * Prevent page faults from reinstantiating pages we have released from
4344 * page cache.
4345 */
4346 down_write(&EXT4_I(inode)->i_mmap_sem);
4347
4348 ret = ext4_break_layouts(inode);
4349 if (ret)
4350 goto out_dio;
4351
4352 first_block_offset = round_up(offset, sb->s_blocksize);
4353 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4354
4355 /* Now release the pages and zero block aligned part of pages*/
4356 if (last_block_offset > first_block_offset) {
4357 ret = ext4_update_disksize_before_punch(inode, offset, length);
4358 if (ret)
4359 goto out_dio;
4360 truncate_pagecache_range(inode, first_block_offset,
4361 last_block_offset);
4362 }
4363
4364 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4365 credits = ext4_writepage_trans_blocks(inode);
4366 else
4367 credits = ext4_blocks_for_truncate(inode);
4368 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4369 if (IS_ERR(handle)) {
4370 ret = PTR_ERR(handle);
4371 ext4_std_error(sb, ret);
4372 goto out_dio;
4373 }
4374
4375 ret = ext4_zero_partial_blocks(handle, inode, offset,
4376 length);
4377 if (ret)
4378 goto out_stop;
4379
4380 first_block = (offset + sb->s_blocksize - 1) >>
4381 EXT4_BLOCK_SIZE_BITS(sb);
4382 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4383
4384 /* If there are blocks to remove, do it */
4385 if (stop_block > first_block) {
4386
4387 down_write(&EXT4_I(inode)->i_data_sem);
4388 ext4_discard_preallocations(inode);
4389
4390 ret = ext4_es_remove_extent(inode, first_block,
4391 stop_block - first_block);
4392 if (ret) {
4393 up_write(&EXT4_I(inode)->i_data_sem);
4394 goto out_stop;
4395 }
4396
4397 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4398 ret = ext4_ext_remove_space(inode, first_block,
4399 stop_block - 1);
4400 else
4401 ret = ext4_ind_remove_space(handle, inode, first_block,
4402 stop_block);
4403
4404 up_write(&EXT4_I(inode)->i_data_sem);
4405 }
4406 if (IS_SYNC(inode))
4407 ext4_handle_sync(handle);
4408
4409 inode->i_mtime = inode->i_ctime = current_time(inode);
4410 ext4_mark_inode_dirty(handle, inode);
4411 if (ret >= 0)
4412 ext4_update_inode_fsync_trans(handle, inode, 1);
4413out_stop:
4414 ext4_journal_stop(handle);
4415out_dio:
4416 up_write(&EXT4_I(inode)->i_mmap_sem);
4417out_mutex:
4418 inode_unlock(inode);
4419 return ret;
4420}
4421
4422int ext4_inode_attach_jinode(struct inode *inode)
4423{
4424 struct ext4_inode_info *ei = EXT4_I(inode);
4425 struct jbd2_inode *jinode;
4426
4427 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4428 return 0;
4429
4430 jinode = jbd2_alloc_inode(GFP_KERNEL);
4431 spin_lock(&inode->i_lock);
4432 if (!ei->jinode) {
4433 if (!jinode) {
4434 spin_unlock(&inode->i_lock);
4435 return -ENOMEM;
4436 }
4437 ei->jinode = jinode;
4438 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4439 jinode = NULL;
4440 }
4441 spin_unlock(&inode->i_lock);
4442 if (unlikely(jinode != NULL))
4443 jbd2_free_inode(jinode);
4444 return 0;
4445}
4446
4447/*
4448 * ext4_truncate()
4449 *
4450 * We block out ext4_get_block() block instantiations across the entire
4451 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4452 * simultaneously on behalf of the same inode.
4453 *
4454 * As we work through the truncate and commit bits of it to the journal there
4455 * is one core, guiding principle: the file's tree must always be consistent on
4456 * disk. We must be able to restart the truncate after a crash.
4457 *
4458 * The file's tree may be transiently inconsistent in memory (although it
4459 * probably isn't), but whenever we close off and commit a journal transaction,
4460 * the contents of (the filesystem + the journal) must be consistent and
4461 * restartable. It's pretty simple, really: bottom up, right to left (although
4462 * left-to-right works OK too).
4463 *
4464 * Note that at recovery time, journal replay occurs *before* the restart of
4465 * truncate against the orphan inode list.
4466 *
4467 * The committed inode has the new, desired i_size (which is the same as
4468 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4469 * that this inode's truncate did not complete and it will again call
4470 * ext4_truncate() to have another go. So there will be instantiated blocks
4471 * to the right of the truncation point in a crashed ext4 filesystem. But
4472 * that's fine - as long as they are linked from the inode, the post-crash
4473 * ext4_truncate() run will find them and release them.
4474 */
4475int ext4_truncate(struct inode *inode)
4476{
4477 struct ext4_inode_info *ei = EXT4_I(inode);
4478 unsigned int credits;
4479 int err = 0;
4480 handle_t *handle;
4481 struct address_space *mapping = inode->i_mapping;
4482
4483 /*
4484 * There is a possibility that we're either freeing the inode
4485 * or it's a completely new inode. In those cases we might not
4486 * have i_mutex locked because it's not necessary.
4487 */
4488 if (!(inode->i_state & (I_NEW|I_FREEING)))
4489 WARN_ON(!inode_is_locked(inode));
4490 trace_ext4_truncate_enter(inode);
4491
4492 if (!ext4_can_truncate(inode))
4493 return 0;
4494
4495 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4496
4497 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4498 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4499
4500 if (ext4_has_inline_data(inode)) {
4501 int has_inline = 1;
4502
4503 err = ext4_inline_data_truncate(inode, &has_inline);
4504 if (err)
4505 return err;
4506 if (has_inline)
4507 return 0;
4508 }
4509
4510 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4511 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4512 if (ext4_inode_attach_jinode(inode) < 0)
4513 return 0;
4514 }
4515
4516 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4517 credits = ext4_writepage_trans_blocks(inode);
4518 else
4519 credits = ext4_blocks_for_truncate(inode);
4520
4521 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4522 if (IS_ERR(handle))
4523 return PTR_ERR(handle);
4524
4525 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4526 ext4_block_truncate_page(handle, mapping, inode->i_size);
4527
4528 /*
4529 * We add the inode to the orphan list, so that if this
4530 * truncate spans multiple transactions, and we crash, we will
4531 * resume the truncate when the filesystem recovers. It also
4532 * marks the inode dirty, to catch the new size.
4533 *
4534 * Implication: the file must always be in a sane, consistent
4535 * truncatable state while each transaction commits.
4536 */
4537 err = ext4_orphan_add(handle, inode);
4538 if (err)
4539 goto out_stop;
4540
4541 down_write(&EXT4_I(inode)->i_data_sem);
4542
4543 ext4_discard_preallocations(inode);
4544
4545 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4546 err = ext4_ext_truncate(handle, inode);
4547 else
4548 ext4_ind_truncate(handle, inode);
4549
4550 up_write(&ei->i_data_sem);
4551 if (err)
4552 goto out_stop;
4553
4554 if (IS_SYNC(inode))
4555 ext4_handle_sync(handle);
4556
4557out_stop:
4558 /*
4559 * If this was a simple ftruncate() and the file will remain alive,
4560 * then we need to clear up the orphan record which we created above.
4561 * However, if this was a real unlink then we were called by
4562 * ext4_evict_inode(), and we allow that function to clean up the
4563 * orphan info for us.
4564 */
4565 if (inode->i_nlink)
4566 ext4_orphan_del(handle, inode);
4567
4568 inode->i_mtime = inode->i_ctime = current_time(inode);
4569 ext4_mark_inode_dirty(handle, inode);
4570 ext4_journal_stop(handle);
4571
4572 trace_ext4_truncate_exit(inode);
4573 return err;
4574}
4575
4576/*
4577 * ext4_get_inode_loc returns with an extra refcount against the inode's
4578 * underlying buffer_head on success. If 'in_mem' is true, we have all
4579 * data in memory that is needed to recreate the on-disk version of this
4580 * inode.
4581 */
4582static int __ext4_get_inode_loc(struct inode *inode,
4583 struct ext4_iloc *iloc, int in_mem)
4584{
4585 struct ext4_group_desc *gdp;
4586 struct buffer_head *bh;
4587 struct super_block *sb = inode->i_sb;
4588 ext4_fsblk_t block;
David Brazdil0f672f62019-12-10 10:32:29 +00004589 struct blk_plug plug;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004590 int inodes_per_block, inode_offset;
4591
4592 iloc->bh = NULL;
4593 if (inode->i_ino < EXT4_ROOT_INO ||
4594 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4595 return -EFSCORRUPTED;
4596
4597 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4598 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4599 if (!gdp)
4600 return -EIO;
4601
4602 /*
4603 * Figure out the offset within the block group inode table
4604 */
4605 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4606 inode_offset = ((inode->i_ino - 1) %
4607 EXT4_INODES_PER_GROUP(sb));
4608 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4609 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4610
4611 bh = sb_getblk(sb, block);
4612 if (unlikely(!bh))
4613 return -ENOMEM;
4614 if (!buffer_uptodate(bh)) {
4615 lock_buffer(bh);
4616
4617 /*
4618 * If the buffer has the write error flag, we have failed
4619 * to write out another inode in the same block. In this
4620 * case, we don't have to read the block because we may
4621 * read the old inode data successfully.
4622 */
4623 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4624 set_buffer_uptodate(bh);
4625
4626 if (buffer_uptodate(bh)) {
4627 /* someone brought it uptodate while we waited */
4628 unlock_buffer(bh);
4629 goto has_buffer;
4630 }
4631
4632 /*
4633 * If we have all information of the inode in memory and this
4634 * is the only valid inode in the block, we need not read the
4635 * block.
4636 */
4637 if (in_mem) {
4638 struct buffer_head *bitmap_bh;
4639 int i, start;
4640
4641 start = inode_offset & ~(inodes_per_block - 1);
4642
4643 /* Is the inode bitmap in cache? */
4644 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4645 if (unlikely(!bitmap_bh))
4646 goto make_io;
4647
4648 /*
4649 * If the inode bitmap isn't in cache then the
4650 * optimisation may end up performing two reads instead
4651 * of one, so skip it.
4652 */
4653 if (!buffer_uptodate(bitmap_bh)) {
4654 brelse(bitmap_bh);
4655 goto make_io;
4656 }
4657 for (i = start; i < start + inodes_per_block; i++) {
4658 if (i == inode_offset)
4659 continue;
4660 if (ext4_test_bit(i, bitmap_bh->b_data))
4661 break;
4662 }
4663 brelse(bitmap_bh);
4664 if (i == start + inodes_per_block) {
4665 /* all other inodes are free, so skip I/O */
4666 memset(bh->b_data, 0, bh->b_size);
4667 set_buffer_uptodate(bh);
4668 unlock_buffer(bh);
4669 goto has_buffer;
4670 }
4671 }
4672
4673make_io:
4674 /*
4675 * If we need to do any I/O, try to pre-readahead extra
4676 * blocks from the inode table.
4677 */
David Brazdil0f672f62019-12-10 10:32:29 +00004678 blk_start_plug(&plug);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004679 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4680 ext4_fsblk_t b, end, table;
4681 unsigned num;
4682 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4683
4684 table = ext4_inode_table(sb, gdp);
4685 /* s_inode_readahead_blks is always a power of 2 */
4686 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4687 if (table > b)
4688 b = table;
4689 end = b + ra_blks;
4690 num = EXT4_INODES_PER_GROUP(sb);
4691 if (ext4_has_group_desc_csum(sb))
4692 num -= ext4_itable_unused_count(sb, gdp);
4693 table += num / inodes_per_block;
4694 if (end > table)
4695 end = table;
4696 while (b <= end)
Olivier Deprez0e641232021-09-23 10:07:05 +02004697 sb_breadahead_unmovable(sb, b++);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004698 }
4699
4700 /*
4701 * There are other valid inodes in the buffer, this inode
4702 * has in-inode xattrs, or we don't have this inode in memory.
4703 * Read the block from disk.
4704 */
4705 trace_ext4_load_inode(inode);
4706 get_bh(bh);
4707 bh->b_end_io = end_buffer_read_sync;
4708 submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
David Brazdil0f672f62019-12-10 10:32:29 +00004709 blk_finish_plug(&plug);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004710 wait_on_buffer(bh);
4711 if (!buffer_uptodate(bh)) {
4712 EXT4_ERROR_INODE_BLOCK(inode, block,
4713 "unable to read itable block");
4714 brelse(bh);
4715 return -EIO;
4716 }
4717 }
4718has_buffer:
4719 iloc->bh = bh;
4720 return 0;
4721}
4722
4723int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4724{
4725 /* We have all inode data except xattrs in memory here. */
4726 return __ext4_get_inode_loc(inode, iloc,
4727 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4728}
4729
4730static bool ext4_should_use_dax(struct inode *inode)
4731{
4732 if (!test_opt(inode->i_sb, DAX))
4733 return false;
4734 if (!S_ISREG(inode->i_mode))
4735 return false;
4736 if (ext4_should_journal_data(inode))
4737 return false;
4738 if (ext4_has_inline_data(inode))
4739 return false;
David Brazdil0f672f62019-12-10 10:32:29 +00004740 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4741 return false;
4742 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004743 return false;
4744 return true;
4745}
4746
4747void ext4_set_inode_flags(struct inode *inode)
4748{
4749 unsigned int flags = EXT4_I(inode)->i_flags;
4750 unsigned int new_fl = 0;
4751
4752 if (flags & EXT4_SYNC_FL)
4753 new_fl |= S_SYNC;
4754 if (flags & EXT4_APPEND_FL)
4755 new_fl |= S_APPEND;
4756 if (flags & EXT4_IMMUTABLE_FL)
4757 new_fl |= S_IMMUTABLE;
4758 if (flags & EXT4_NOATIME_FL)
4759 new_fl |= S_NOATIME;
4760 if (flags & EXT4_DIRSYNC_FL)
4761 new_fl |= S_DIRSYNC;
4762 if (ext4_should_use_dax(inode))
4763 new_fl |= S_DAX;
4764 if (flags & EXT4_ENCRYPT_FL)
4765 new_fl |= S_ENCRYPTED;
David Brazdil0f672f62019-12-10 10:32:29 +00004766 if (flags & EXT4_CASEFOLD_FL)
4767 new_fl |= S_CASEFOLD;
4768 if (flags & EXT4_VERITY_FL)
4769 new_fl |= S_VERITY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004770 inode_set_flags(inode, new_fl,
4771 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
David Brazdil0f672f62019-12-10 10:32:29 +00004772 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004773}
4774
4775static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4776 struct ext4_inode_info *ei)
4777{
4778 blkcnt_t i_blocks ;
4779 struct inode *inode = &(ei->vfs_inode);
4780 struct super_block *sb = inode->i_sb;
4781
4782 if (ext4_has_feature_huge_file(sb)) {
4783 /* we are using combined 48 bit field */
4784 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4785 le32_to_cpu(raw_inode->i_blocks_lo);
4786 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4787 /* i_blocks represent file system block size */
4788 return i_blocks << (inode->i_blkbits - 9);
4789 } else {
4790 return i_blocks;
4791 }
4792 } else {
4793 return le32_to_cpu(raw_inode->i_blocks_lo);
4794 }
4795}
4796
4797static inline int ext4_iget_extra_inode(struct inode *inode,
4798 struct ext4_inode *raw_inode,
4799 struct ext4_inode_info *ei)
4800{
4801 __le32 *magic = (void *)raw_inode +
4802 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4803
4804 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4805 EXT4_INODE_SIZE(inode->i_sb) &&
4806 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4807 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4808 return ext4_find_inline_data_nolock(inode);
4809 } else
4810 EXT4_I(inode)->i_inline_off = 0;
4811 return 0;
4812}
4813
4814int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4815{
4816 if (!ext4_has_feature_project(inode->i_sb))
4817 return -EOPNOTSUPP;
4818 *projid = EXT4_I(inode)->i_projid;
4819 return 0;
4820}
4821
4822/*
4823 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4824 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4825 * set.
4826 */
4827static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4828{
4829 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4830 inode_set_iversion_raw(inode, val);
4831 else
4832 inode_set_iversion_queried(inode, val);
4833}
4834static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4835{
4836 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4837 return inode_peek_iversion_raw(inode);
4838 else
4839 return inode_peek_iversion(inode);
4840}
4841
David Brazdil0f672f62019-12-10 10:32:29 +00004842struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4843 ext4_iget_flags flags, const char *function,
4844 unsigned int line)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004845{
4846 struct ext4_iloc iloc;
4847 struct ext4_inode *raw_inode;
4848 struct ext4_inode_info *ei;
4849 struct inode *inode;
4850 journal_t *journal = EXT4_SB(sb)->s_journal;
4851 long ret;
4852 loff_t size;
4853 int block;
4854 uid_t i_uid;
4855 gid_t i_gid;
4856 projid_t i_projid;
4857
David Brazdil0f672f62019-12-10 10:32:29 +00004858 if ((!(flags & EXT4_IGET_SPECIAL) &&
4859 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4860 (ino < EXT4_ROOT_INO) ||
4861 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4862 if (flags & EXT4_IGET_HANDLE)
4863 return ERR_PTR(-ESTALE);
4864 __ext4_error(sb, function, line,
4865 "inode #%lu: comm %s: iget: illegal inode #",
4866 ino, current->comm);
4867 return ERR_PTR(-EFSCORRUPTED);
4868 }
4869
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004870 inode = iget_locked(sb, ino);
4871 if (!inode)
4872 return ERR_PTR(-ENOMEM);
4873 if (!(inode->i_state & I_NEW))
4874 return inode;
4875
4876 ei = EXT4_I(inode);
4877 iloc.bh = NULL;
4878
4879 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4880 if (ret < 0)
4881 goto bad_inode;
4882 raw_inode = ext4_raw_inode(&iloc);
4883
4884 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004885 ext4_error_inode(inode, function, line, 0,
4886 "iget: root inode unallocated");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004887 ret = -EFSCORRUPTED;
4888 goto bad_inode;
4889 }
4890
David Brazdil0f672f62019-12-10 10:32:29 +00004891 if ((flags & EXT4_IGET_HANDLE) &&
4892 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4893 ret = -ESTALE;
4894 goto bad_inode;
4895 }
4896
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004897 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4898 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4899 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4900 EXT4_INODE_SIZE(inode->i_sb) ||
4901 (ei->i_extra_isize & 3)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004902 ext4_error_inode(inode, function, line, 0,
4903 "iget: bad extra_isize %u "
4904 "(inode size %u)",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004905 ei->i_extra_isize,
4906 EXT4_INODE_SIZE(inode->i_sb));
4907 ret = -EFSCORRUPTED;
4908 goto bad_inode;
4909 }
4910 } else
4911 ei->i_extra_isize = 0;
4912
4913 /* Precompute checksum seed for inode metadata */
4914 if (ext4_has_metadata_csum(sb)) {
4915 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4916 __u32 csum;
4917 __le32 inum = cpu_to_le32(inode->i_ino);
4918 __le32 gen = raw_inode->i_generation;
4919 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4920 sizeof(inum));
4921 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4922 sizeof(gen));
4923 }
4924
4925 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004926 ext4_error_inode(inode, function, line, 0,
4927 "iget: checksum invalid");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004928 ret = -EFSBADCRC;
4929 goto bad_inode;
4930 }
4931
4932 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4933 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4934 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4935 if (ext4_has_feature_project(sb) &&
4936 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4937 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4938 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4939 else
4940 i_projid = EXT4_DEF_PROJID;
4941
4942 if (!(test_opt(inode->i_sb, NO_UID32))) {
4943 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4944 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4945 }
4946 i_uid_write(inode, i_uid);
4947 i_gid_write(inode, i_gid);
4948 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4949 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4950
4951 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4952 ei->i_inline_off = 0;
4953 ei->i_dir_start_lookup = 0;
4954 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4955 /* We now have enough fields to check if the inode was active or not.
4956 * This is needed because nfsd might try to access dead inodes
4957 * the test is that same one that e2fsck uses
4958 * NeilBrown 1999oct15
4959 */
4960 if (inode->i_nlink == 0) {
4961 if ((inode->i_mode == 0 ||
4962 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4963 ino != EXT4_BOOT_LOADER_INO) {
4964 /* this inode is deleted */
4965 ret = -ESTALE;
4966 goto bad_inode;
4967 }
4968 /* The only unlinked inodes we let through here have
4969 * valid i_mode and are being read by the orphan
4970 * recovery code: that's fine, we're about to complete
4971 * the process of deleting those.
4972 * OR it is the EXT4_BOOT_LOADER_INO which is
4973 * not initialized on a new filesystem. */
4974 }
4975 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4976 ext4_set_inode_flags(inode);
4977 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4978 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4979 if (ext4_has_feature_64bit(sb))
4980 ei->i_file_acl |=
4981 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4982 inode->i_size = ext4_isize(sb, raw_inode);
4983 if ((size = i_size_read(inode)) < 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00004984 ext4_error_inode(inode, function, line, 0,
4985 "iget: bad i_size value: %lld", size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004986 ret = -EFSCORRUPTED;
4987 goto bad_inode;
4988 }
Olivier Deprez0e641232021-09-23 10:07:05 +02004989 /*
4990 * If dir_index is not enabled but there's dir with INDEX flag set,
4991 * we'd normally treat htree data as empty space. But with metadata
4992 * checksumming that corrupts checksums so forbid that.
4993 */
4994 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4995 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4996 ext4_error_inode(inode, function, line, 0,
4997 "iget: Dir with htree data on filesystem without dir_index feature.");
4998 ret = -EFSCORRUPTED;
4999 goto bad_inode;
5000 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005001 ei->i_disksize = inode->i_size;
5002#ifdef CONFIG_QUOTA
5003 ei->i_reserved_quota = 0;
5004#endif
5005 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5006 ei->i_block_group = iloc.block_group;
5007 ei->i_last_alloc_group = ~0;
5008 /*
5009 * NOTE! The in-memory inode i_data array is in little-endian order
5010 * even on big-endian machines: we do NOT byteswap the block numbers!
5011 */
5012 for (block = 0; block < EXT4_N_BLOCKS; block++)
5013 ei->i_data[block] = raw_inode->i_block[block];
5014 INIT_LIST_HEAD(&ei->i_orphan);
5015
5016 /*
5017 * Set transaction id's of transactions that have to be committed
5018 * to finish f[data]sync. We set them to currently running transaction
5019 * as we cannot be sure that the inode or some of its metadata isn't
5020 * part of the transaction - the inode could have been reclaimed and
5021 * now it is reread from disk.
5022 */
5023 if (journal) {
5024 transaction_t *transaction;
5025 tid_t tid;
5026
5027 read_lock(&journal->j_state_lock);
5028 if (journal->j_running_transaction)
5029 transaction = journal->j_running_transaction;
5030 else
5031 transaction = journal->j_committing_transaction;
5032 if (transaction)
5033 tid = transaction->t_tid;
5034 else
5035 tid = journal->j_commit_sequence;
5036 read_unlock(&journal->j_state_lock);
5037 ei->i_sync_tid = tid;
5038 ei->i_datasync_tid = tid;
5039 }
5040
5041 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5042 if (ei->i_extra_isize == 0) {
5043 /* The extra space is currently unused. Use it. */
5044 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
5045 ei->i_extra_isize = sizeof(struct ext4_inode) -
5046 EXT4_GOOD_OLD_INODE_SIZE;
5047 } else {
5048 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5049 if (ret)
5050 goto bad_inode;
5051 }
5052 }
5053
5054 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5055 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5056 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5057 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5058
5059 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5060 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5061
5062 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5063 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5064 ivers |=
5065 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5066 }
5067 ext4_inode_set_iversion_queried(inode, ivers);
5068 }
5069
5070 ret = 0;
5071 if (ei->i_file_acl &&
5072 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
David Brazdil0f672f62019-12-10 10:32:29 +00005073 ext4_error_inode(inode, function, line, 0,
5074 "iget: bad extended attribute block %llu",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005075 ei->i_file_acl);
5076 ret = -EFSCORRUPTED;
5077 goto bad_inode;
5078 } else if (!ext4_has_inline_data(inode)) {
5079 /* validate the block references in the inode */
5080 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5081 (S_ISLNK(inode->i_mode) &&
5082 !ext4_inode_is_fast_symlink(inode))) {
5083 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5084 ret = ext4_ext_check_inode(inode);
5085 else
5086 ret = ext4_ind_check_inode(inode);
5087 }
5088 }
5089 if (ret)
5090 goto bad_inode;
5091
5092 if (S_ISREG(inode->i_mode)) {
5093 inode->i_op = &ext4_file_inode_operations;
5094 inode->i_fop = &ext4_file_operations;
5095 ext4_set_aops(inode);
5096 } else if (S_ISDIR(inode->i_mode)) {
5097 inode->i_op = &ext4_dir_inode_operations;
5098 inode->i_fop = &ext4_dir_operations;
5099 } else if (S_ISLNK(inode->i_mode)) {
5100 /* VFS does not allow setting these so must be corruption */
5101 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
David Brazdil0f672f62019-12-10 10:32:29 +00005102 ext4_error_inode(inode, function, line, 0,
5103 "iget: immutable or append flags "
5104 "not allowed on symlinks");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005105 ret = -EFSCORRUPTED;
5106 goto bad_inode;
5107 }
David Brazdil0f672f62019-12-10 10:32:29 +00005108 if (IS_ENCRYPTED(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005109 inode->i_op = &ext4_encrypted_symlink_inode_operations;
5110 ext4_set_aops(inode);
5111 } else if (ext4_inode_is_fast_symlink(inode)) {
5112 inode->i_link = (char *)ei->i_data;
5113 inode->i_op = &ext4_fast_symlink_inode_operations;
5114 nd_terminate_link(ei->i_data, inode->i_size,
5115 sizeof(ei->i_data) - 1);
5116 } else {
5117 inode->i_op = &ext4_symlink_inode_operations;
5118 ext4_set_aops(inode);
5119 }
5120 inode_nohighmem(inode);
5121 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5122 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5123 inode->i_op = &ext4_special_inode_operations;
5124 if (raw_inode->i_block[0])
5125 init_special_inode(inode, inode->i_mode,
5126 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5127 else
5128 init_special_inode(inode, inode->i_mode,
5129 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5130 } else if (ino == EXT4_BOOT_LOADER_INO) {
5131 make_bad_inode(inode);
5132 } else {
5133 ret = -EFSCORRUPTED;
David Brazdil0f672f62019-12-10 10:32:29 +00005134 ext4_error_inode(inode, function, line, 0,
5135 "iget: bogus i_mode (%o)", inode->i_mode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005136 goto bad_inode;
5137 }
David Brazdil0f672f62019-12-10 10:32:29 +00005138 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
5139 ext4_error_inode(inode, function, line, 0,
5140 "casefold flag without casefold feature");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005141 brelse(iloc.bh);
5142
5143 unlock_new_inode(inode);
5144 return inode;
5145
5146bad_inode:
5147 brelse(iloc.bh);
5148 iget_failed(inode);
5149 return ERR_PTR(ret);
5150}
5151
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005152static int ext4_inode_blocks_set(handle_t *handle,
5153 struct ext4_inode *raw_inode,
5154 struct ext4_inode_info *ei)
5155{
5156 struct inode *inode = &(ei->vfs_inode);
Olivier Deprez0e641232021-09-23 10:07:05 +02005157 u64 i_blocks = READ_ONCE(inode->i_blocks);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005158 struct super_block *sb = inode->i_sb;
5159
5160 if (i_blocks <= ~0U) {
5161 /*
5162 * i_blocks can be represented in a 32 bit variable
5163 * as multiple of 512 bytes
5164 */
5165 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5166 raw_inode->i_blocks_high = 0;
5167 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5168 return 0;
5169 }
5170 if (!ext4_has_feature_huge_file(sb))
5171 return -EFBIG;
5172
5173 if (i_blocks <= 0xffffffffffffULL) {
5174 /*
5175 * i_blocks can be represented in a 48 bit variable
5176 * as multiple of 512 bytes
5177 */
5178 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5179 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5180 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5181 } else {
5182 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5183 /* i_block is stored in file system block size */
5184 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5185 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5186 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5187 }
5188 return 0;
5189}
5190
5191struct other_inode {
5192 unsigned long orig_ino;
5193 struct ext4_inode *raw_inode;
5194};
5195
5196static int other_inode_match(struct inode * inode, unsigned long ino,
5197 void *data)
5198{
5199 struct other_inode *oi = (struct other_inode *) data;
5200
5201 if ((inode->i_ino != ino) ||
5202 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5203 I_DIRTY_INODE)) ||
5204 ((inode->i_state & I_DIRTY_TIME) == 0))
5205 return 0;
5206 spin_lock(&inode->i_lock);
5207 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5208 I_DIRTY_INODE)) == 0) &&
5209 (inode->i_state & I_DIRTY_TIME)) {
5210 struct ext4_inode_info *ei = EXT4_I(inode);
5211
Olivier Deprez0e641232021-09-23 10:07:05 +02005212 inode->i_state &= ~I_DIRTY_TIME;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005213 spin_unlock(&inode->i_lock);
5214
5215 spin_lock(&ei->i_raw_lock);
5216 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
5217 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
5218 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
5219 ext4_inode_csum_set(inode, oi->raw_inode, ei);
5220 spin_unlock(&ei->i_raw_lock);
5221 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
5222 return -1;
5223 }
5224 spin_unlock(&inode->i_lock);
5225 return -1;
5226}
5227
5228/*
5229 * Opportunistically update the other time fields for other inodes in
5230 * the same inode table block.
5231 */
5232static void ext4_update_other_inodes_time(struct super_block *sb,
5233 unsigned long orig_ino, char *buf)
5234{
5235 struct other_inode oi;
5236 unsigned long ino;
5237 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5238 int inode_size = EXT4_INODE_SIZE(sb);
5239
5240 oi.orig_ino = orig_ino;
5241 /*
5242 * Calculate the first inode in the inode table block. Inode
5243 * numbers are one-based. That is, the first inode in a block
5244 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5245 */
5246 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5247 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5248 if (ino == orig_ino)
5249 continue;
5250 oi.raw_inode = (struct ext4_inode *) buf;
5251 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
5252 }
5253}
5254
5255/*
5256 * Post the struct inode info into an on-disk inode location in the
5257 * buffer-cache. This gobbles the caller's reference to the
5258 * buffer_head in the inode location struct.
5259 *
5260 * The caller must have write access to iloc->bh.
5261 */
5262static int ext4_do_update_inode(handle_t *handle,
5263 struct inode *inode,
5264 struct ext4_iloc *iloc)
5265{
5266 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5267 struct ext4_inode_info *ei = EXT4_I(inode);
5268 struct buffer_head *bh = iloc->bh;
5269 struct super_block *sb = inode->i_sb;
Olivier Deprez0e641232021-09-23 10:07:05 +02005270 int err = 0, block;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005271 int need_datasync = 0, set_large_file = 0;
5272 uid_t i_uid;
5273 gid_t i_gid;
5274 projid_t i_projid;
5275
5276 spin_lock(&ei->i_raw_lock);
5277
5278 /* For fields not tracked in the in-memory inode,
5279 * initialise them to zero for new inodes. */
5280 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5281 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5282
Olivier Deprez0e641232021-09-23 10:07:05 +02005283 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5284 if (err) {
5285 spin_unlock(&ei->i_raw_lock);
5286 goto out_brelse;
5287 }
5288
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005289 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5290 i_uid = i_uid_read(inode);
5291 i_gid = i_gid_read(inode);
5292 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5293 if (!(test_opt(inode->i_sb, NO_UID32))) {
5294 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5295 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5296/*
5297 * Fix up interoperability with old kernels. Otherwise, old inodes get
5298 * re-used with the upper 16 bits of the uid/gid intact
5299 */
5300 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5301 raw_inode->i_uid_high = 0;
5302 raw_inode->i_gid_high = 0;
5303 } else {
5304 raw_inode->i_uid_high =
5305 cpu_to_le16(high_16_bits(i_uid));
5306 raw_inode->i_gid_high =
5307 cpu_to_le16(high_16_bits(i_gid));
5308 }
5309 } else {
5310 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5311 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5312 raw_inode->i_uid_high = 0;
5313 raw_inode->i_gid_high = 0;
5314 }
5315 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5316
5317 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5318 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5319 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5320 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5321
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005322 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5323 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5324 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5325 raw_inode->i_file_acl_high =
5326 cpu_to_le16(ei->i_file_acl >> 32);
5327 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
Olivier Deprez0e641232021-09-23 10:07:05 +02005328 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005329 ext4_isize_set(raw_inode, ei->i_disksize);
5330 need_datasync = 1;
5331 }
5332 if (ei->i_disksize > 0x7fffffffULL) {
5333 if (!ext4_has_feature_large_file(sb) ||
5334 EXT4_SB(sb)->s_es->s_rev_level ==
5335 cpu_to_le32(EXT4_GOOD_OLD_REV))
5336 set_large_file = 1;
5337 }
5338 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5339 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5340 if (old_valid_dev(inode->i_rdev)) {
5341 raw_inode->i_block[0] =
5342 cpu_to_le32(old_encode_dev(inode->i_rdev));
5343 raw_inode->i_block[1] = 0;
5344 } else {
5345 raw_inode->i_block[0] = 0;
5346 raw_inode->i_block[1] =
5347 cpu_to_le32(new_encode_dev(inode->i_rdev));
5348 raw_inode->i_block[2] = 0;
5349 }
5350 } else if (!ext4_has_inline_data(inode)) {
5351 for (block = 0; block < EXT4_N_BLOCKS; block++)
5352 raw_inode->i_block[block] = ei->i_data[block];
5353 }
5354
5355 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5356 u64 ivers = ext4_inode_peek_iversion(inode);
5357
5358 raw_inode->i_disk_version = cpu_to_le32(ivers);
5359 if (ei->i_extra_isize) {
5360 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5361 raw_inode->i_version_hi =
5362 cpu_to_le32(ivers >> 32);
5363 raw_inode->i_extra_isize =
5364 cpu_to_le16(ei->i_extra_isize);
5365 }
5366 }
5367
5368 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5369 i_projid != EXT4_DEF_PROJID);
5370
5371 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5372 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5373 raw_inode->i_projid = cpu_to_le32(i_projid);
5374
5375 ext4_inode_csum_set(inode, raw_inode, ei);
5376 spin_unlock(&ei->i_raw_lock);
5377 if (inode->i_sb->s_flags & SB_LAZYTIME)
5378 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5379 bh->b_data);
5380
5381 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
Olivier Deprez0e641232021-09-23 10:07:05 +02005382 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5383 if (err)
5384 goto out_brelse;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005385 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5386 if (set_large_file) {
5387 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5388 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5389 if (err)
5390 goto out_brelse;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005391 ext4_set_feature_large_file(sb);
5392 ext4_handle_sync(handle);
5393 err = ext4_handle_dirty_super(handle, sb);
5394 }
5395 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5396out_brelse:
5397 brelse(bh);
5398 ext4_std_error(inode->i_sb, err);
5399 return err;
5400}
5401
5402/*
5403 * ext4_write_inode()
5404 *
5405 * We are called from a few places:
5406 *
5407 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5408 * Here, there will be no transaction running. We wait for any running
5409 * transaction to commit.
5410 *
5411 * - Within flush work (sys_sync(), kupdate and such).
5412 * We wait on commit, if told to.
5413 *
5414 * - Within iput_final() -> write_inode_now()
5415 * We wait on commit, if told to.
5416 *
5417 * In all cases it is actually safe for us to return without doing anything,
5418 * because the inode has been copied into a raw inode buffer in
5419 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5420 * writeback.
5421 *
5422 * Note that we are absolutely dependent upon all inode dirtiers doing the
5423 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5424 * which we are interested.
5425 *
5426 * It would be a bug for them to not do this. The code:
5427 *
5428 * mark_inode_dirty(inode)
5429 * stuff();
5430 * inode->i_size = expr;
5431 *
5432 * is in error because write_inode() could occur while `stuff()' is running,
5433 * and the new i_size will be lost. Plus the inode will no longer be on the
5434 * superblock's dirty inode list.
5435 */
5436int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5437{
5438 int err;
5439
David Brazdil0f672f62019-12-10 10:32:29 +00005440 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5441 sb_rdonly(inode->i_sb))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005442 return 0;
5443
David Brazdil0f672f62019-12-10 10:32:29 +00005444 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5445 return -EIO;
5446
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005447 if (EXT4_SB(inode->i_sb)->s_journal) {
5448 if (ext4_journal_current_handle()) {
5449 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5450 dump_stack();
5451 return -EIO;
5452 }
5453
5454 /*
5455 * No need to force transaction in WB_SYNC_NONE mode. Also
5456 * ext4_sync_fs() will force the commit after everything is
5457 * written.
5458 */
5459 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5460 return 0;
5461
David Brazdil0f672f62019-12-10 10:32:29 +00005462 err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5463 EXT4_I(inode)->i_sync_tid);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005464 } else {
5465 struct ext4_iloc iloc;
5466
5467 err = __ext4_get_inode_loc(inode, &iloc, 0);
5468 if (err)
5469 return err;
5470 /*
5471 * sync(2) will flush the whole buffer cache. No need to do
5472 * it here separately for each inode.
5473 */
5474 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5475 sync_dirty_buffer(iloc.bh);
5476 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5477 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5478 "IO error syncing inode");
5479 err = -EIO;
5480 }
5481 brelse(iloc.bh);
5482 }
5483 return err;
5484}
5485
5486/*
5487 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5488 * buffers that are attached to a page stradding i_size and are undergoing
5489 * commit. In that case we have to wait for commit to finish and try again.
5490 */
5491static void ext4_wait_for_tail_page_commit(struct inode *inode)
5492{
5493 struct page *page;
5494 unsigned offset;
5495 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5496 tid_t commit_tid = 0;
5497 int ret;
5498
5499 offset = inode->i_size & (PAGE_SIZE - 1);
5500 /*
Olivier Deprez0e641232021-09-23 10:07:05 +02005501 * If the page is fully truncated, we don't need to wait for any commit
5502 * (and we even should not as __ext4_journalled_invalidatepage() may
5503 * strip all buffers from the page but keep the page dirty which can then
5504 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5505 * buffers). Also we don't need to wait for any commit if all buffers in
5506 * the page remain valid. This is most beneficial for the common case of
5507 * blocksize == PAGESIZE.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005508 */
Olivier Deprez0e641232021-09-23 10:07:05 +02005509 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005510 return;
5511 while (1) {
5512 page = find_lock_page(inode->i_mapping,
5513 inode->i_size >> PAGE_SHIFT);
5514 if (!page)
5515 return;
5516 ret = __ext4_journalled_invalidatepage(page, offset,
5517 PAGE_SIZE - offset);
5518 unlock_page(page);
5519 put_page(page);
5520 if (ret != -EBUSY)
5521 return;
5522 commit_tid = 0;
5523 read_lock(&journal->j_state_lock);
5524 if (journal->j_committing_transaction)
5525 commit_tid = journal->j_committing_transaction->t_tid;
5526 read_unlock(&journal->j_state_lock);
5527 if (commit_tid)
5528 jbd2_log_wait_commit(journal, commit_tid);
5529 }
5530}
5531
5532/*
5533 * ext4_setattr()
5534 *
5535 * Called from notify_change.
5536 *
5537 * We want to trap VFS attempts to truncate the file as soon as
5538 * possible. In particular, we want to make sure that when the VFS
5539 * shrinks i_size, we put the inode on the orphan list and modify
5540 * i_disksize immediately, so that during the subsequent flushing of
5541 * dirty pages and freeing of disk blocks, we can guarantee that any
5542 * commit will leave the blocks being flushed in an unused state on
5543 * disk. (On recovery, the inode will get truncated and the blocks will
5544 * be freed, so we have a strong guarantee that no future commit will
5545 * leave these blocks visible to the user.)
5546 *
5547 * Another thing we have to assure is that if we are in ordered mode
5548 * and inode is still attached to the committing transaction, we must
5549 * we start writeout of all the dirty pages which are being truncated.
5550 * This way we are sure that all the data written in the previous
5551 * transaction are already on disk (truncate waits for pages under
5552 * writeback).
5553 *
5554 * Called with inode->i_mutex down.
5555 */
5556int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5557{
5558 struct inode *inode = d_inode(dentry);
5559 int error, rc = 0;
5560 int orphan = 0;
5561 const unsigned int ia_valid = attr->ia_valid;
5562
5563 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5564 return -EIO;
5565
David Brazdil0f672f62019-12-10 10:32:29 +00005566 if (unlikely(IS_IMMUTABLE(inode)))
5567 return -EPERM;
5568
5569 if (unlikely(IS_APPEND(inode) &&
5570 (ia_valid & (ATTR_MODE | ATTR_UID |
5571 ATTR_GID | ATTR_TIMES_SET))))
5572 return -EPERM;
5573
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005574 error = setattr_prepare(dentry, attr);
5575 if (error)
5576 return error;
5577
5578 error = fscrypt_prepare_setattr(dentry, attr);
5579 if (error)
5580 return error;
5581
David Brazdil0f672f62019-12-10 10:32:29 +00005582 error = fsverity_prepare_setattr(dentry, attr);
5583 if (error)
5584 return error;
5585
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005586 if (is_quota_modification(inode, attr)) {
5587 error = dquot_initialize(inode);
5588 if (error)
5589 return error;
5590 }
5591 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5592 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5593 handle_t *handle;
5594
5595 /* (user+group)*(old+new) structure, inode write (sb,
5596 * inode block, ? - but truncate inode update has it) */
5597 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5598 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5599 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5600 if (IS_ERR(handle)) {
5601 error = PTR_ERR(handle);
5602 goto err_out;
5603 }
5604
5605 /* dquot_transfer() calls back ext4_get_inode_usage() which
5606 * counts xattr inode references.
5607 */
5608 down_read(&EXT4_I(inode)->xattr_sem);
5609 error = dquot_transfer(inode, attr);
5610 up_read(&EXT4_I(inode)->xattr_sem);
5611
5612 if (error) {
5613 ext4_journal_stop(handle);
5614 return error;
5615 }
5616 /* Update corresponding info in inode so that everything is in
5617 * one transaction */
5618 if (attr->ia_valid & ATTR_UID)
5619 inode->i_uid = attr->ia_uid;
5620 if (attr->ia_valid & ATTR_GID)
5621 inode->i_gid = attr->ia_gid;
5622 error = ext4_mark_inode_dirty(handle, inode);
5623 ext4_journal_stop(handle);
5624 }
5625
5626 if (attr->ia_valid & ATTR_SIZE) {
5627 handle_t *handle;
5628 loff_t oldsize = inode->i_size;
David Brazdil0f672f62019-12-10 10:32:29 +00005629 int shrink = (attr->ia_size < inode->i_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005630
5631 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5632 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5633
5634 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5635 return -EFBIG;
5636 }
5637 if (!S_ISREG(inode->i_mode))
5638 return -EINVAL;
5639
5640 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5641 inode_inc_iversion(inode);
5642
David Brazdil0f672f62019-12-10 10:32:29 +00005643 if (shrink) {
5644 if (ext4_should_order_data(inode)) {
5645 error = ext4_begin_ordered_truncate(inode,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005646 attr->ia_size);
David Brazdil0f672f62019-12-10 10:32:29 +00005647 if (error)
5648 goto err_out;
5649 }
5650 /*
5651 * Blocks are going to be removed from the inode. Wait
5652 * for dio in flight.
5653 */
5654 inode_dio_wait(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005655 }
David Brazdil0f672f62019-12-10 10:32:29 +00005656
5657 down_write(&EXT4_I(inode)->i_mmap_sem);
5658
5659 rc = ext4_break_layouts(inode);
5660 if (rc) {
5661 up_write(&EXT4_I(inode)->i_mmap_sem);
5662 return rc;
5663 }
5664
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005665 if (attr->ia_size != inode->i_size) {
5666 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5667 if (IS_ERR(handle)) {
5668 error = PTR_ERR(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00005669 goto out_mmap_sem;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005670 }
5671 if (ext4_handle_valid(handle) && shrink) {
5672 error = ext4_orphan_add(handle, inode);
5673 orphan = 1;
5674 }
5675 /*
5676 * Update c/mtime on truncate up, ext4_truncate() will
5677 * update c/mtime in shrink case below
5678 */
5679 if (!shrink) {
5680 inode->i_mtime = current_time(inode);
5681 inode->i_ctime = inode->i_mtime;
5682 }
5683 down_write(&EXT4_I(inode)->i_data_sem);
5684 EXT4_I(inode)->i_disksize = attr->ia_size;
5685 rc = ext4_mark_inode_dirty(handle, inode);
5686 if (!error)
5687 error = rc;
5688 /*
5689 * We have to update i_size under i_data_sem together
5690 * with i_disksize to avoid races with writeback code
5691 * running ext4_wb_update_i_disksize().
5692 */
5693 if (!error)
5694 i_size_write(inode, attr->ia_size);
5695 up_write(&EXT4_I(inode)->i_data_sem);
5696 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00005697 if (error)
5698 goto out_mmap_sem;
5699 if (!shrink) {
5700 pagecache_isize_extended(inode, oldsize,
5701 inode->i_size);
5702 } else if (ext4_should_journal_data(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005703 ext4_wait_for_tail_page_commit(inode);
David Brazdil0f672f62019-12-10 10:32:29 +00005704 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005705 }
5706
5707 /*
5708 * Truncate pagecache after we've waited for commit
5709 * in data=journal mode to make pages freeable.
5710 */
5711 truncate_pagecache(inode, inode->i_size);
David Brazdil0f672f62019-12-10 10:32:29 +00005712 /*
5713 * Call ext4_truncate() even if i_size didn't change to
5714 * truncate possible preallocated blocks.
5715 */
5716 if (attr->ia_size <= oldsize) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005717 rc = ext4_truncate(inode);
5718 if (rc)
5719 error = rc;
5720 }
David Brazdil0f672f62019-12-10 10:32:29 +00005721out_mmap_sem:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005722 up_write(&EXT4_I(inode)->i_mmap_sem);
5723 }
5724
5725 if (!error) {
5726 setattr_copy(inode, attr);
5727 mark_inode_dirty(inode);
5728 }
5729
5730 /*
5731 * If the call to ext4_truncate failed to get a transaction handle at
5732 * all, we need to clean up the in-core orphan list manually.
5733 */
5734 if (orphan && inode->i_nlink)
5735 ext4_orphan_del(NULL, inode);
5736
5737 if (!error && (ia_valid & ATTR_MODE))
5738 rc = posix_acl_chmod(inode, inode->i_mode);
5739
5740err_out:
5741 ext4_std_error(inode->i_sb, error);
5742 if (!error)
5743 error = rc;
5744 return error;
5745}
5746
5747int ext4_getattr(const struct path *path, struct kstat *stat,
5748 u32 request_mask, unsigned int query_flags)
5749{
5750 struct inode *inode = d_inode(path->dentry);
5751 struct ext4_inode *raw_inode;
5752 struct ext4_inode_info *ei = EXT4_I(inode);
5753 unsigned int flags;
5754
5755 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5756 stat->result_mask |= STATX_BTIME;
5757 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5758 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5759 }
5760
5761 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5762 if (flags & EXT4_APPEND_FL)
5763 stat->attributes |= STATX_ATTR_APPEND;
5764 if (flags & EXT4_COMPR_FL)
5765 stat->attributes |= STATX_ATTR_COMPRESSED;
5766 if (flags & EXT4_ENCRYPT_FL)
5767 stat->attributes |= STATX_ATTR_ENCRYPTED;
5768 if (flags & EXT4_IMMUTABLE_FL)
5769 stat->attributes |= STATX_ATTR_IMMUTABLE;
5770 if (flags & EXT4_NODUMP_FL)
5771 stat->attributes |= STATX_ATTR_NODUMP;
5772
5773 stat->attributes_mask |= (STATX_ATTR_APPEND |
5774 STATX_ATTR_COMPRESSED |
5775 STATX_ATTR_ENCRYPTED |
5776 STATX_ATTR_IMMUTABLE |
5777 STATX_ATTR_NODUMP);
5778
5779 generic_fillattr(inode, stat);
5780 return 0;
5781}
5782
5783int ext4_file_getattr(const struct path *path, struct kstat *stat,
5784 u32 request_mask, unsigned int query_flags)
5785{
5786 struct inode *inode = d_inode(path->dentry);
5787 u64 delalloc_blocks;
5788
5789 ext4_getattr(path, stat, request_mask, query_flags);
5790
5791 /*
5792 * If there is inline data in the inode, the inode will normally not
5793 * have data blocks allocated (it may have an external xattr block).
5794 * Report at least one sector for such files, so tools like tar, rsync,
5795 * others don't incorrectly think the file is completely sparse.
5796 */
5797 if (unlikely(ext4_has_inline_data(inode)))
5798 stat->blocks += (stat->size + 511) >> 9;
5799
5800 /*
5801 * We can't update i_blocks if the block allocation is delayed
5802 * otherwise in the case of system crash before the real block
5803 * allocation is done, we will have i_blocks inconsistent with
5804 * on-disk file blocks.
5805 * We always keep i_blocks updated together with real
5806 * allocation. But to not confuse with user, stat
5807 * will return the blocks that include the delayed allocation
5808 * blocks for this file.
5809 */
5810 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5811 EXT4_I(inode)->i_reserved_data_blocks);
5812 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5813 return 0;
5814}
5815
5816static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5817 int pextents)
5818{
5819 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5820 return ext4_ind_trans_blocks(inode, lblocks);
5821 return ext4_ext_index_trans_blocks(inode, pextents);
5822}
5823
5824/*
5825 * Account for index blocks, block groups bitmaps and block group
5826 * descriptor blocks if modify datablocks and index blocks
5827 * worse case, the indexs blocks spread over different block groups
5828 *
5829 * If datablocks are discontiguous, they are possible to spread over
5830 * different block groups too. If they are contiguous, with flexbg,
5831 * they could still across block group boundary.
5832 *
5833 * Also account for superblock, inode, quota and xattr blocks
5834 */
5835static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5836 int pextents)
5837{
5838 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5839 int gdpblocks;
5840 int idxblocks;
5841 int ret = 0;
5842
5843 /*
5844 * How many index blocks need to touch to map @lblocks logical blocks
5845 * to @pextents physical extents?
5846 */
5847 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5848
5849 ret = idxblocks;
5850
5851 /*
5852 * Now let's see how many group bitmaps and group descriptors need
5853 * to account
5854 */
5855 groups = idxblocks + pextents;
5856 gdpblocks = groups;
5857 if (groups > ngroups)
5858 groups = ngroups;
5859 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5860 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5861
5862 /* bitmaps and block group descriptor blocks */
5863 ret += groups + gdpblocks;
5864
5865 /* Blocks for super block, inode, quota and xattr blocks */
5866 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5867
5868 return ret;
5869}
5870
5871/*
5872 * Calculate the total number of credits to reserve to fit
5873 * the modification of a single pages into a single transaction,
5874 * which may include multiple chunks of block allocations.
5875 *
5876 * This could be called via ext4_write_begin()
5877 *
5878 * We need to consider the worse case, when
5879 * one new block per extent.
5880 */
5881int ext4_writepage_trans_blocks(struct inode *inode)
5882{
5883 int bpp = ext4_journal_blocks_per_page(inode);
5884 int ret;
5885
5886 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5887
5888 /* Account for data blocks for journalled mode */
5889 if (ext4_should_journal_data(inode))
5890 ret += bpp;
5891 return ret;
5892}
5893
5894/*
5895 * Calculate the journal credits for a chunk of data modification.
5896 *
5897 * This is called from DIO, fallocate or whoever calling
5898 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5899 *
5900 * journal buffers for data blocks are not included here, as DIO
5901 * and fallocate do no need to journal data buffers.
5902 */
5903int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5904{
5905 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5906}
5907
5908/*
5909 * The caller must have previously called ext4_reserve_inode_write().
5910 * Give this, we know that the caller already has write access to iloc->bh.
5911 */
5912int ext4_mark_iloc_dirty(handle_t *handle,
5913 struct inode *inode, struct ext4_iloc *iloc)
5914{
5915 int err = 0;
5916
5917 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5918 put_bh(iloc->bh);
5919 return -EIO;
5920 }
5921 if (IS_I_VERSION(inode))
5922 inode_inc_iversion(inode);
5923
5924 /* the do_update_inode consumes one bh->b_count */
5925 get_bh(iloc->bh);
5926
5927 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5928 err = ext4_do_update_inode(handle, inode, iloc);
5929 put_bh(iloc->bh);
5930 return err;
5931}
5932
5933/*
5934 * On success, We end up with an outstanding reference count against
5935 * iloc->bh. This _must_ be cleaned up later.
5936 */
5937
5938int
5939ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5940 struct ext4_iloc *iloc)
5941{
5942 int err;
5943
5944 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5945 return -EIO;
5946
5947 err = ext4_get_inode_loc(inode, iloc);
5948 if (!err) {
5949 BUFFER_TRACE(iloc->bh, "get_write_access");
5950 err = ext4_journal_get_write_access(handle, iloc->bh);
5951 if (err) {
5952 brelse(iloc->bh);
5953 iloc->bh = NULL;
5954 }
5955 }
5956 ext4_std_error(inode->i_sb, err);
5957 return err;
5958}
5959
5960static int __ext4_expand_extra_isize(struct inode *inode,
5961 unsigned int new_extra_isize,
5962 struct ext4_iloc *iloc,
5963 handle_t *handle, int *no_expand)
5964{
5965 struct ext4_inode *raw_inode;
5966 struct ext4_xattr_ibody_header *header;
David Brazdil0f672f62019-12-10 10:32:29 +00005967 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5968 struct ext4_inode_info *ei = EXT4_I(inode);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005969 int error;
5970
David Brazdil0f672f62019-12-10 10:32:29 +00005971 /* this was checked at iget time, but double check for good measure */
5972 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5973 (ei->i_extra_isize & 3)) {
5974 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5975 ei->i_extra_isize,
5976 EXT4_INODE_SIZE(inode->i_sb));
5977 return -EFSCORRUPTED;
5978 }
5979 if ((new_extra_isize < ei->i_extra_isize) ||
5980 (new_extra_isize < 4) ||
5981 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5982 return -EINVAL; /* Should never happen */
5983
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005984 raw_inode = ext4_raw_inode(iloc);
5985
5986 header = IHDR(inode, raw_inode);
5987
5988 /* No extended attributes present */
5989 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5990 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5991 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5992 EXT4_I(inode)->i_extra_isize, 0,
5993 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5994 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5995 return 0;
5996 }
5997
5998 /* try to expand with EAs present */
5999 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
6000 raw_inode, handle);
6001 if (error) {
6002 /*
6003 * Inode size expansion failed; don't try again
6004 */
6005 *no_expand = 1;
6006 }
6007
6008 return error;
6009}
6010
6011/*
6012 * Expand an inode by new_extra_isize bytes.
6013 * Returns 0 on success or negative error number on failure.
6014 */
6015static int ext4_try_to_expand_extra_isize(struct inode *inode,
6016 unsigned int new_extra_isize,
6017 struct ext4_iloc iloc,
6018 handle_t *handle)
6019{
6020 int no_expand;
6021 int error;
6022
6023 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
6024 return -EOVERFLOW;
6025
6026 /*
6027 * In nojournal mode, we can immediately attempt to expand
6028 * the inode. When journaled, we first need to obtain extra
6029 * buffer credits since we may write into the EA block
6030 * with this same handle. If journal_extend fails, then it will
6031 * only result in a minor loss of functionality for that inode.
6032 * If this is felt to be critical, then e2fsck should be run to
6033 * force a large enough s_min_extra_isize.
6034 */
6035 if (ext4_handle_valid(handle) &&
6036 jbd2_journal_extend(handle,
6037 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
6038 return -ENOSPC;
6039
6040 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
6041 return -EBUSY;
6042
6043 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
6044 handle, &no_expand);
6045 ext4_write_unlock_xattr(inode, &no_expand);
6046
6047 return error;
6048}
6049
6050int ext4_expand_extra_isize(struct inode *inode,
6051 unsigned int new_extra_isize,
6052 struct ext4_iloc *iloc)
6053{
6054 handle_t *handle;
6055 int no_expand;
6056 int error, rc;
6057
6058 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
6059 brelse(iloc->bh);
6060 return -EOVERFLOW;
6061 }
6062
6063 handle = ext4_journal_start(inode, EXT4_HT_INODE,
6064 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
6065 if (IS_ERR(handle)) {
6066 error = PTR_ERR(handle);
6067 brelse(iloc->bh);
6068 return error;
6069 }
6070
6071 ext4_write_lock_xattr(inode, &no_expand);
6072
David Brazdil0f672f62019-12-10 10:32:29 +00006073 BUFFER_TRACE(iloc->bh, "get_write_access");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006074 error = ext4_journal_get_write_access(handle, iloc->bh);
6075 if (error) {
6076 brelse(iloc->bh);
Olivier Deprez0e641232021-09-23 10:07:05 +02006077 goto out_unlock;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006078 }
6079
6080 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
6081 handle, &no_expand);
6082
6083 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
6084 if (!error)
6085 error = rc;
6086
Olivier Deprez0e641232021-09-23 10:07:05 +02006087out_unlock:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006088 ext4_write_unlock_xattr(inode, &no_expand);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006089 ext4_journal_stop(handle);
6090 return error;
6091}
6092
6093/*
6094 * What we do here is to mark the in-core inode as clean with respect to inode
6095 * dirtiness (it may still be data-dirty).
6096 * This means that the in-core inode may be reaped by prune_icache
6097 * without having to perform any I/O. This is a very good thing,
6098 * because *any* task may call prune_icache - even ones which
6099 * have a transaction open against a different journal.
6100 *
6101 * Is this cheating? Not really. Sure, we haven't written the
6102 * inode out, but prune_icache isn't a user-visible syncing function.
6103 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6104 * we start and wait on commits.
6105 */
6106int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
6107{
6108 struct ext4_iloc iloc;
6109 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6110 int err;
6111
6112 might_sleep();
6113 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6114 err = ext4_reserve_inode_write(handle, inode, &iloc);
6115 if (err)
6116 return err;
6117
6118 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6119 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6120 iloc, handle);
6121
6122 return ext4_mark_iloc_dirty(handle, inode, &iloc);
6123}
6124
6125/*
6126 * ext4_dirty_inode() is called from __mark_inode_dirty()
6127 *
6128 * We're really interested in the case where a file is being extended.
6129 * i_size has been changed by generic_commit_write() and we thus need
6130 * to include the updated inode in the current transaction.
6131 *
6132 * Also, dquot_alloc_block() will always dirty the inode when blocks
6133 * are allocated to the file.
6134 *
6135 * If the inode is marked synchronous, we don't honour that here - doing
6136 * so would cause a commit on atime updates, which we don't bother doing.
6137 * We handle synchronous inodes at the highest possible level.
6138 *
6139 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
6140 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
6141 * to copy into the on-disk inode structure are the timestamp files.
6142 */
6143void ext4_dirty_inode(struct inode *inode, int flags)
6144{
6145 handle_t *handle;
6146
6147 if (flags == I_DIRTY_TIME)
6148 return;
6149 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6150 if (IS_ERR(handle))
6151 goto out;
6152
6153 ext4_mark_inode_dirty(handle, inode);
6154
6155 ext4_journal_stop(handle);
6156out:
6157 return;
6158}
6159
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006160int ext4_change_inode_journal_flag(struct inode *inode, int val)
6161{
6162 journal_t *journal;
6163 handle_t *handle;
6164 int err;
6165 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6166
6167 /*
6168 * We have to be very careful here: changing a data block's
6169 * journaling status dynamically is dangerous. If we write a
6170 * data block to the journal, change the status and then delete
6171 * that block, we risk forgetting to revoke the old log record
6172 * from the journal and so a subsequent replay can corrupt data.
6173 * So, first we make sure that the journal is empty and that
6174 * nobody is changing anything.
6175 */
6176
6177 journal = EXT4_JOURNAL(inode);
6178 if (!journal)
6179 return 0;
6180 if (is_journal_aborted(journal))
6181 return -EROFS;
6182
6183 /* Wait for all existing dio workers */
6184 inode_dio_wait(inode);
6185
6186 /*
6187 * Before flushing the journal and switching inode's aops, we have
6188 * to flush all dirty data the inode has. There can be outstanding
6189 * delayed allocations, there can be unwritten extents created by
6190 * fallocate or buffered writes in dioread_nolock mode covered by
6191 * dirty data which can be converted only after flushing the dirty
6192 * data (and journalled aops don't know how to handle these cases).
6193 */
6194 if (val) {
6195 down_write(&EXT4_I(inode)->i_mmap_sem);
6196 err = filemap_write_and_wait(inode->i_mapping);
6197 if (err < 0) {
6198 up_write(&EXT4_I(inode)->i_mmap_sem);
6199 return err;
6200 }
6201 }
6202
Olivier Deprez0e641232021-09-23 10:07:05 +02006203 percpu_down_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006204 jbd2_journal_lock_updates(journal);
6205
6206 /*
6207 * OK, there are no updates running now, and all cached data is
6208 * synced to disk. We are now in a completely consistent state
6209 * which doesn't have anything in the journal, and we know that
6210 * no filesystem updates are running, so it is safe to modify
6211 * the inode's in-core data-journaling state flag now.
6212 */
6213
6214 if (val)
6215 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6216 else {
6217 err = jbd2_journal_flush(journal);
6218 if (err < 0) {
6219 jbd2_journal_unlock_updates(journal);
Olivier Deprez0e641232021-09-23 10:07:05 +02006220 percpu_up_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006221 return err;
6222 }
6223 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6224 }
6225 ext4_set_aops(inode);
6226
6227 jbd2_journal_unlock_updates(journal);
Olivier Deprez0e641232021-09-23 10:07:05 +02006228 percpu_up_write(&sbi->s_writepages_rwsem);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006229
6230 if (val)
6231 up_write(&EXT4_I(inode)->i_mmap_sem);
6232
6233 /* Finally we can mark the inode as dirty. */
6234
6235 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6236 if (IS_ERR(handle))
6237 return PTR_ERR(handle);
6238
6239 err = ext4_mark_inode_dirty(handle, inode);
6240 ext4_handle_sync(handle);
6241 ext4_journal_stop(handle);
6242 ext4_std_error(inode->i_sb, err);
6243
6244 return err;
6245}
6246
6247static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6248{
6249 return !buffer_mapped(bh);
6250}
6251
David Brazdil0f672f62019-12-10 10:32:29 +00006252vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006253{
6254 struct vm_area_struct *vma = vmf->vma;
6255 struct page *page = vmf->page;
6256 loff_t size;
6257 unsigned long len;
David Brazdil0f672f62019-12-10 10:32:29 +00006258 int err;
6259 vm_fault_t ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006260 struct file *file = vma->vm_file;
6261 struct inode *inode = file_inode(file);
6262 struct address_space *mapping = inode->i_mapping;
6263 handle_t *handle;
6264 get_block_t *get_block;
6265 int retries = 0;
6266
David Brazdil0f672f62019-12-10 10:32:29 +00006267 if (unlikely(IS_IMMUTABLE(inode)))
6268 return VM_FAULT_SIGBUS;
6269
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006270 sb_start_pagefault(inode->i_sb);
6271 file_update_time(vma->vm_file);
6272
6273 down_read(&EXT4_I(inode)->i_mmap_sem);
6274
David Brazdil0f672f62019-12-10 10:32:29 +00006275 err = ext4_convert_inline_data(inode);
6276 if (err)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006277 goto out_ret;
6278
6279 /* Delalloc case is easy... */
6280 if (test_opt(inode->i_sb, DELALLOC) &&
6281 !ext4_should_journal_data(inode) &&
6282 !ext4_nonda_switch(inode->i_sb)) {
6283 do {
David Brazdil0f672f62019-12-10 10:32:29 +00006284 err = block_page_mkwrite(vma, vmf,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006285 ext4_da_get_block_prep);
David Brazdil0f672f62019-12-10 10:32:29 +00006286 } while (err == -ENOSPC &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006287 ext4_should_retry_alloc(inode->i_sb, &retries));
6288 goto out_ret;
6289 }
6290
6291 lock_page(page);
6292 size = i_size_read(inode);
6293 /* Page got truncated from under us? */
6294 if (page->mapping != mapping || page_offset(page) > size) {
6295 unlock_page(page);
6296 ret = VM_FAULT_NOPAGE;
6297 goto out;
6298 }
6299
6300 if (page->index == size >> PAGE_SHIFT)
6301 len = size & ~PAGE_MASK;
6302 else
6303 len = PAGE_SIZE;
6304 /*
6305 * Return if we have all the buffers mapped. This avoids the need to do
6306 * journal_start/journal_stop which can block and take a long time
6307 */
6308 if (page_has_buffers(page)) {
6309 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6310 0, len, NULL,
6311 ext4_bh_unmapped)) {
6312 /* Wait so that we don't change page under IO */
6313 wait_for_stable_page(page);
6314 ret = VM_FAULT_LOCKED;
6315 goto out;
6316 }
6317 }
6318 unlock_page(page);
6319 /* OK, we need to fill the hole... */
6320 if (ext4_should_dioread_nolock(inode))
6321 get_block = ext4_get_block_unwritten;
6322 else
6323 get_block = ext4_get_block;
6324retry_alloc:
6325 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6326 ext4_writepage_trans_blocks(inode));
6327 if (IS_ERR(handle)) {
6328 ret = VM_FAULT_SIGBUS;
6329 goto out;
6330 }
David Brazdil0f672f62019-12-10 10:32:29 +00006331 err = block_page_mkwrite(vma, vmf, get_block);
6332 if (!err && ext4_should_journal_data(inode)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006333 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
6334 PAGE_SIZE, NULL, do_journal_get_write_access)) {
6335 unlock_page(page);
6336 ret = VM_FAULT_SIGBUS;
6337 ext4_journal_stop(handle);
6338 goto out;
6339 }
6340 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6341 }
6342 ext4_journal_stop(handle);
David Brazdil0f672f62019-12-10 10:32:29 +00006343 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006344 goto retry_alloc;
6345out_ret:
David Brazdil0f672f62019-12-10 10:32:29 +00006346 ret = block_page_mkwrite_return(err);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006347out:
6348 up_read(&EXT4_I(inode)->i_mmap_sem);
6349 sb_end_pagefault(inode->i_sb);
6350 return ret;
6351}
6352
David Brazdil0f672f62019-12-10 10:32:29 +00006353vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006354{
6355 struct inode *inode = file_inode(vmf->vma->vm_file);
David Brazdil0f672f62019-12-10 10:32:29 +00006356 vm_fault_t ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006357
6358 down_read(&EXT4_I(inode)->i_mmap_sem);
David Brazdil0f672f62019-12-10 10:32:29 +00006359 ret = filemap_fault(vmf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006360 up_read(&EXT4_I(inode)->i_mmap_sem);
6361
David Brazdil0f672f62019-12-10 10:32:29 +00006362 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006363}