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