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