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