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