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