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