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