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