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