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 }
745 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
746 map->m_flags & EXT4_MAP_MAPPED))
747 ext4_fc_track_range(handle, inode, map->m_lblk,
748 map->m_lblk + map->m_len - 1);
749 if (retval < 0)
750 ext_debug(inode, "failed with err %d\n", retval);
751 return retval;
752 }
753
754 /*
755 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
756 * we have to be careful as someone else may be manipulating b_state as well.
757 */
ext4_update_bh_state(struct buffer_head * bh,unsigned long flags)758 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
759 {
760 unsigned long old_state;
761 unsigned long new_state;
762
763 flags &= EXT4_MAP_FLAGS;
764
765 /* Dummy buffer_head? Set non-atomically. */
766 if (!bh->b_page) {
767 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
768 return;
769 }
770 /*
771 * Someone else may be modifying b_state. Be careful! This is ugly but
772 * once we get rid of using bh as a container for mapping information
773 * to pass to / from get_block functions, this can go away.
774 */
775 do {
776 old_state = READ_ONCE(bh->b_state);
777 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
778 } while (unlikely(
779 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
780 }
781
_ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int flags)782 static int _ext4_get_block(struct inode *inode, sector_t iblock,
783 struct buffer_head *bh, int flags)
784 {
785 struct ext4_map_blocks map;
786 int ret = 0;
787
788 if (ext4_has_inline_data(inode))
789 return -ERANGE;
790
791 map.m_lblk = iblock;
792 map.m_len = bh->b_size >> inode->i_blkbits;
793
794 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
795 flags);
796 if (ret > 0) {
797 map_bh(bh, inode->i_sb, map.m_pblk);
798 ext4_update_bh_state(bh, map.m_flags);
799 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
800 ret = 0;
801 } else if (ret == 0) {
802 /* hole case, need to fill in bh->b_size */
803 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
804 }
805 return ret;
806 }
807
ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)808 int ext4_get_block(struct inode *inode, sector_t iblock,
809 struct buffer_head *bh, int create)
810 {
811 return _ext4_get_block(inode, iblock, bh,
812 create ? EXT4_GET_BLOCKS_CREATE : 0);
813 }
814
815 /*
816 * Get block function used when preparing for buffered write if we require
817 * creating an unwritten extent if blocks haven't been allocated. The extent
818 * will be converted to written after the IO is complete.
819 */
ext4_get_block_unwritten(struct inode * inode,sector_t iblock,struct buffer_head * bh_result,int create)820 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
821 struct buffer_head *bh_result, int create)
822 {
823 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
824 inode->i_ino, create);
825 return _ext4_get_block(inode, iblock, bh_result,
826 EXT4_GET_BLOCKS_IO_CREATE_EXT);
827 }
828
829 /* Maximum number of blocks we map for direct IO at once. */
830 #define DIO_MAX_BLOCKS 4096
831
832 /*
833 * `handle' can be NULL if create is zero
834 */
ext4_getblk(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)835 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
836 ext4_lblk_t block, int map_flags)
837 {
838 struct ext4_map_blocks map;
839 struct buffer_head *bh;
840 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
841 int err;
842
843 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
844 || handle != NULL || create == 0);
845
846 map.m_lblk = block;
847 map.m_len = 1;
848 err = ext4_map_blocks(handle, inode, &map, map_flags);
849
850 if (err == 0)
851 return create ? ERR_PTR(-ENOSPC) : NULL;
852 if (err < 0)
853 return ERR_PTR(err);
854
855 bh = sb_getblk(inode->i_sb, map.m_pblk);
856 if (unlikely(!bh))
857 return ERR_PTR(-ENOMEM);
858 if (map.m_flags & EXT4_MAP_NEW) {
859 J_ASSERT(create != 0);
860 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
861 || (handle != NULL));
862
863 /*
864 * Now that we do not always journal data, we should
865 * keep in mind whether this should always journal the
866 * new buffer as metadata. For now, regular file
867 * writes use ext4_get_block instead, so it's not a
868 * problem.
869 */
870 lock_buffer(bh);
871 BUFFER_TRACE(bh, "call get_create_access");
872 err = ext4_journal_get_create_access(handle, bh);
873 if (unlikely(err)) {
874 unlock_buffer(bh);
875 goto errout;
876 }
877 if (!buffer_uptodate(bh)) {
878 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
879 set_buffer_uptodate(bh);
880 }
881 unlock_buffer(bh);
882 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
883 err = ext4_handle_dirty_metadata(handle, inode, bh);
884 if (unlikely(err))
885 goto errout;
886 } else
887 BUFFER_TRACE(bh, "not a new buffer");
888 return bh;
889 errout:
890 brelse(bh);
891 return ERR_PTR(err);
892 }
893
ext4_bread(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)894 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
895 ext4_lblk_t block, int map_flags)
896 {
897 struct buffer_head *bh;
898 int ret;
899
900 bh = ext4_getblk(handle, inode, block, map_flags);
901 if (IS_ERR(bh))
902 return bh;
903 if (!bh || ext4_buffer_uptodate(bh))
904 return bh;
905
906 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
907 if (ret) {
908 put_bh(bh);
909 return ERR_PTR(ret);
910 }
911 return bh;
912 }
913
914 /* 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)915 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
916 bool wait, struct buffer_head **bhs)
917 {
918 int i, err;
919
920 for (i = 0; i < bh_count; i++) {
921 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
922 if (IS_ERR(bhs[i])) {
923 err = PTR_ERR(bhs[i]);
924 bh_count = i;
925 goto out_brelse;
926 }
927 }
928
929 for (i = 0; i < bh_count; i++)
930 /* Note that NULL bhs[i] is valid because of holes. */
931 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
932 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
933
934 if (!wait)
935 return 0;
936
937 for (i = 0; i < bh_count; i++)
938 if (bhs[i])
939 wait_on_buffer(bhs[i]);
940
941 for (i = 0; i < bh_count; i++) {
942 if (bhs[i] && !buffer_uptodate(bhs[i])) {
943 err = -EIO;
944 goto out_brelse;
945 }
946 }
947 return 0;
948
949 out_brelse:
950 for (i = 0; i < bh_count; i++) {
951 brelse(bhs[i]);
952 bhs[i] = NULL;
953 }
954 return err;
955 }
956
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))957 int ext4_walk_page_buffers(handle_t *handle,
958 struct buffer_head *head,
959 unsigned from,
960 unsigned to,
961 int *partial,
962 int (*fn)(handle_t *handle,
963 struct buffer_head *bh))
964 {
965 struct buffer_head *bh;
966 unsigned block_start, block_end;
967 unsigned blocksize = head->b_size;
968 int err, ret = 0;
969 struct buffer_head *next;
970
971 for (bh = head, block_start = 0;
972 ret == 0 && (bh != head || !block_start);
973 block_start = block_end, bh = next) {
974 next = bh->b_this_page;
975 block_end = block_start + blocksize;
976 if (block_end <= from || block_start >= to) {
977 if (partial && !buffer_uptodate(bh))
978 *partial = 1;
979 continue;
980 }
981 err = (*fn)(handle, bh);
982 if (!ret)
983 ret = err;
984 }
985 return ret;
986 }
987
988 /*
989 * To preserve ordering, it is essential that the hole instantiation and
990 * the data write be encapsulated in a single transaction. We cannot
991 * close off a transaction and start a new one between the ext4_get_block()
992 * and the commit_write(). So doing the jbd2_journal_start at the start of
993 * prepare_write() is the right place.
994 *
995 * Also, this function can nest inside ext4_writepage(). In that case, we
996 * *know* that ext4_writepage() has generated enough buffer credits to do the
997 * whole page. So we won't block on the journal in that case, which is good,
998 * because the caller may be PF_MEMALLOC.
999 *
1000 * By accident, ext4 can be reentered when a transaction is open via
1001 * quota file writes. If we were to commit the transaction while thus
1002 * reentered, there can be a deadlock - we would be holding a quota
1003 * lock, and the commit would never complete if another thread had a
1004 * transaction open and was blocking on the quota lock - a ranking
1005 * violation.
1006 *
1007 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1008 * will _not_ run commit under these circumstances because handle->h_ref
1009 * is elevated. We'll still have enough credits for the tiny quotafile
1010 * write.
1011 */
do_journal_get_write_access(handle_t * handle,struct buffer_head * bh)1012 int do_journal_get_write_access(handle_t *handle,
1013 struct buffer_head *bh)
1014 {
1015 int dirty = buffer_dirty(bh);
1016 int ret;
1017
1018 if (!buffer_mapped(bh) || buffer_freed(bh))
1019 return 0;
1020 /*
1021 * __block_write_begin() could have dirtied some buffers. Clean
1022 * the dirty bit as jbd2_journal_get_write_access() could complain
1023 * otherwise about fs integrity issues. Setting of the dirty bit
1024 * by __block_write_begin() isn't a real problem here as we clear
1025 * the bit before releasing a page lock and thus writeback cannot
1026 * ever write the buffer.
1027 */
1028 if (dirty)
1029 clear_buffer_dirty(bh);
1030 BUFFER_TRACE(bh, "get write access");
1031 ret = ext4_journal_get_write_access(handle, bh);
1032 if (!ret && dirty)
1033 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1034 return ret;
1035 }
1036
1037 #ifdef CONFIG_FS_ENCRYPTION
ext4_block_write_begin(struct page * page,loff_t pos,unsigned len,get_block_t * get_block)1038 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1039 get_block_t *get_block)
1040 {
1041 unsigned from = pos & (PAGE_SIZE - 1);
1042 unsigned to = from + len;
1043 struct inode *inode = page->mapping->host;
1044 unsigned block_start, block_end;
1045 sector_t block;
1046 int err = 0;
1047 unsigned blocksize = inode->i_sb->s_blocksize;
1048 unsigned bbits;
1049 struct buffer_head *bh, *head, *wait[2];
1050 int nr_wait = 0;
1051 int i;
1052
1053 BUG_ON(!PageLocked(page));
1054 BUG_ON(from > PAGE_SIZE);
1055 BUG_ON(to > PAGE_SIZE);
1056 BUG_ON(from > to);
1057
1058 if (!page_has_buffers(page))
1059 create_empty_buffers(page, blocksize, 0);
1060 head = page_buffers(page);
1061 bbits = ilog2(blocksize);
1062 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1063
1064 for (bh = head, block_start = 0; bh != head || !block_start;
1065 block++, block_start = block_end, bh = bh->b_this_page) {
1066 block_end = block_start + blocksize;
1067 if (block_end <= from || block_start >= to) {
1068 if (PageUptodate(page)) {
1069 if (!buffer_uptodate(bh))
1070 set_buffer_uptodate(bh);
1071 }
1072 continue;
1073 }
1074 if (buffer_new(bh))
1075 clear_buffer_new(bh);
1076 if (!buffer_mapped(bh)) {
1077 WARN_ON(bh->b_size != blocksize);
1078 err = get_block(inode, block, bh, 1);
1079 if (err)
1080 break;
1081 if (buffer_new(bh)) {
1082 if (PageUptodate(page)) {
1083 clear_buffer_new(bh);
1084 set_buffer_uptodate(bh);
1085 mark_buffer_dirty(bh);
1086 continue;
1087 }
1088 if (block_end > to || block_start < from)
1089 zero_user_segments(page, to, block_end,
1090 block_start, from);
1091 continue;
1092 }
1093 }
1094 if (PageUptodate(page)) {
1095 if (!buffer_uptodate(bh))
1096 set_buffer_uptodate(bh);
1097 continue;
1098 }
1099 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1100 !buffer_unwritten(bh) &&
1101 (block_start < from || block_end > to)) {
1102 ext4_read_bh_lock(bh, 0, false);
1103 wait[nr_wait++] = bh;
1104 }
1105 }
1106 /*
1107 * If we issued read requests, let them complete.
1108 */
1109 for (i = 0; i < nr_wait; i++) {
1110 wait_on_buffer(wait[i]);
1111 if (!buffer_uptodate(wait[i]))
1112 err = -EIO;
1113 }
1114 if (unlikely(err)) {
1115 page_zero_new_buffers(page, from, to);
1116 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1117 for (i = 0; i < nr_wait; i++) {
1118 int err2;
1119
1120 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1121 bh_offset(wait[i]));
1122 if (err2) {
1123 clear_buffer_uptodate(wait[i]);
1124 err = err2;
1125 }
1126 }
1127 }
1128
1129 return err;
1130 }
1131 #endif
1132
ext4_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)1133 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1134 loff_t pos, unsigned len, unsigned flags,
1135 struct page **pagep, void **fsdata)
1136 {
1137 struct inode *inode = mapping->host;
1138 int ret, needed_blocks;
1139 handle_t *handle;
1140 int retries = 0;
1141 struct page *page;
1142 pgoff_t index;
1143 unsigned from, to;
1144
1145 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1146 return -EIO;
1147
1148 trace_ext4_write_begin(inode, pos, len, flags);
1149 /*
1150 * Reserve one block more for addition to orphan list in case
1151 * we allocate blocks but write fails for some reason
1152 */
1153 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1154 index = pos >> PAGE_SHIFT;
1155 from = pos & (PAGE_SIZE - 1);
1156 to = from + len;
1157
1158 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1159 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1160 flags, pagep);
1161 if (ret < 0)
1162 return ret;
1163 if (ret == 1)
1164 return 0;
1165 }
1166
1167 /*
1168 * grab_cache_page_write_begin() can take a long time if the
1169 * system is thrashing due to memory pressure, or if the page
1170 * is being written back. So grab it first before we start
1171 * the transaction handle. This also allows us to allocate
1172 * the page (if needed) without using GFP_NOFS.
1173 */
1174 retry_grab:
1175 page = grab_cache_page_write_begin(mapping, index, flags);
1176 if (!page)
1177 return -ENOMEM;
1178 unlock_page(page);
1179
1180 retry_journal:
1181 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1182 if (IS_ERR(handle)) {
1183 put_page(page);
1184 return PTR_ERR(handle);
1185 }
1186
1187 lock_page(page);
1188 if (page->mapping != mapping) {
1189 /* The page got truncated from under us */
1190 unlock_page(page);
1191 put_page(page);
1192 ext4_journal_stop(handle);
1193 goto retry_grab;
1194 }
1195 /* In case writeback began while the page was unlocked */
1196 wait_for_stable_page(page);
1197
1198 #ifdef CONFIG_FS_ENCRYPTION
1199 if (ext4_should_dioread_nolock(inode))
1200 ret = ext4_block_write_begin(page, pos, len,
1201 ext4_get_block_unwritten);
1202 else
1203 ret = ext4_block_write_begin(page, pos, len,
1204 ext4_get_block);
1205 #else
1206 if (ext4_should_dioread_nolock(inode))
1207 ret = __block_write_begin(page, pos, len,
1208 ext4_get_block_unwritten);
1209 else
1210 ret = __block_write_begin(page, pos, len, ext4_get_block);
1211 #endif
1212 if (!ret && ext4_should_journal_data(inode)) {
1213 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1214 from, to, NULL,
1215 do_journal_get_write_access);
1216 }
1217
1218 if (ret) {
1219 bool extended = (pos + len > inode->i_size) &&
1220 !ext4_verity_in_progress(inode);
1221
1222 unlock_page(page);
1223 /*
1224 * __block_write_begin may have instantiated a few blocks
1225 * outside i_size. Trim these off again. Don't need
1226 * i_size_read because we hold i_mutex.
1227 *
1228 * Add inode to orphan list in case we crash before
1229 * truncate finishes
1230 */
1231 if (extended && ext4_can_truncate(inode))
1232 ext4_orphan_add(handle, inode);
1233
1234 ext4_journal_stop(handle);
1235 if (extended) {
1236 ext4_truncate_failed_write(inode);
1237 /*
1238 * If truncate failed early the inode might
1239 * still be on the orphan list; we need to
1240 * make sure the inode is removed from the
1241 * orphan list in that case.
1242 */
1243 if (inode->i_nlink)
1244 ext4_orphan_del(NULL, inode);
1245 }
1246
1247 if (ret == -ENOSPC &&
1248 ext4_should_retry_alloc(inode->i_sb, &retries))
1249 goto retry_journal;
1250 put_page(page);
1251 return ret;
1252 }
1253 *pagep = page;
1254 return ret;
1255 }
1256
1257 /* For write_end() in data=journal mode */
write_end_fn(handle_t * handle,struct buffer_head * bh)1258 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1259 {
1260 int ret;
1261 if (!buffer_mapped(bh) || buffer_freed(bh))
1262 return 0;
1263 set_buffer_uptodate(bh);
1264 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1265 clear_buffer_meta(bh);
1266 clear_buffer_prio(bh);
1267 return ret;
1268 }
1269
1270 /*
1271 * We need to pick up the new inode size which generic_commit_write gave us
1272 * `file' can be NULL - eg, when called from page_symlink().
1273 *
1274 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1275 * buffers are managed internally.
1276 */
ext4_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1277 static int ext4_write_end(struct file *file,
1278 struct address_space *mapping,
1279 loff_t pos, unsigned len, unsigned copied,
1280 struct page *page, void *fsdata)
1281 {
1282 handle_t *handle = ext4_journal_current_handle();
1283 struct inode *inode = mapping->host;
1284 loff_t old_size = inode->i_size;
1285 int ret = 0, ret2;
1286 int i_size_changed = 0;
1287 bool verity = ext4_verity_in_progress(inode);
1288
1289 trace_ext4_write_end(inode, pos, len, copied);
1290
1291 if (ext4_has_inline_data(inode))
1292 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1293
1294 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1295 /*
1296 * it's important to update i_size while still holding page lock:
1297 * page writeout could otherwise come in and zero beyond i_size.
1298 *
1299 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1300 * blocks are being written past EOF, so skip the i_size update.
1301 */
1302 if (!verity)
1303 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1304 unlock_page(page);
1305 put_page(page);
1306
1307 if (old_size < pos && !verity)
1308 pagecache_isize_extended(inode, old_size, pos);
1309 /*
1310 * Don't mark the inode dirty under page lock. First, it unnecessarily
1311 * makes the holding time of page lock longer. Second, it forces lock
1312 * ordering of page lock and transaction start for journaling
1313 * filesystems.
1314 */
1315 if (i_size_changed)
1316 ret = ext4_mark_inode_dirty(handle, inode);
1317
1318 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1319 /* if we have allocated more blocks and copied
1320 * less. We will have blocks allocated outside
1321 * inode->i_size. So truncate them
1322 */
1323 ext4_orphan_add(handle, inode);
1324
1325 ret2 = ext4_journal_stop(handle);
1326 if (!ret)
1327 ret = ret2;
1328
1329 if (pos + len > inode->i_size && !verity) {
1330 ext4_truncate_failed_write(inode);
1331 /*
1332 * If truncate failed early the inode might still be
1333 * on the orphan list; we need to make sure the inode
1334 * is removed from the orphan list in that case.
1335 */
1336 if (inode->i_nlink)
1337 ext4_orphan_del(NULL, inode);
1338 }
1339
1340 return ret ? ret : copied;
1341 }
1342
1343 /*
1344 * This is a private version of page_zero_new_buffers() which doesn't
1345 * set the buffer to be dirty, since in data=journalled mode we need
1346 * to call ext4_handle_dirty_metadata() instead.
1347 */
ext4_journalled_zero_new_buffers(handle_t * handle,struct page * page,unsigned from,unsigned to)1348 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1349 struct page *page,
1350 unsigned from, unsigned to)
1351 {
1352 unsigned int block_start = 0, block_end;
1353 struct buffer_head *head, *bh;
1354
1355 bh = head = page_buffers(page);
1356 do {
1357 block_end = block_start + bh->b_size;
1358 if (buffer_new(bh)) {
1359 if (block_end > from && block_start < to) {
1360 if (!PageUptodate(page)) {
1361 unsigned start, size;
1362
1363 start = max(from, block_start);
1364 size = min(to, block_end) - start;
1365
1366 zero_user(page, start, size);
1367 write_end_fn(handle, bh);
1368 }
1369 clear_buffer_new(bh);
1370 }
1371 }
1372 block_start = block_end;
1373 bh = bh->b_this_page;
1374 } while (bh != head);
1375 }
1376
ext4_journalled_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1377 static int ext4_journalled_write_end(struct file *file,
1378 struct address_space *mapping,
1379 loff_t pos, unsigned len, unsigned copied,
1380 struct page *page, void *fsdata)
1381 {
1382 handle_t *handle = ext4_journal_current_handle();
1383 struct inode *inode = mapping->host;
1384 loff_t old_size = inode->i_size;
1385 int ret = 0, ret2;
1386 int partial = 0;
1387 unsigned from, to;
1388 int size_changed = 0;
1389 bool verity = ext4_verity_in_progress(inode);
1390
1391 trace_ext4_journalled_write_end(inode, pos, len, copied);
1392 from = pos & (PAGE_SIZE - 1);
1393 to = from + len;
1394
1395 BUG_ON(!ext4_handle_valid(handle));
1396
1397 if (ext4_has_inline_data(inode))
1398 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1399
1400 if (unlikely(copied < len) && !PageUptodate(page)) {
1401 copied = 0;
1402 ext4_journalled_zero_new_buffers(handle, page, from, to);
1403 } else {
1404 if (unlikely(copied < len))
1405 ext4_journalled_zero_new_buffers(handle, page,
1406 from + copied, to);
1407 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1408 from + copied, &partial,
1409 write_end_fn);
1410 if (!partial)
1411 SetPageUptodate(page);
1412 }
1413 if (!verity)
1414 size_changed = ext4_update_inode_size(inode, pos + copied);
1415 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1416 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1417 unlock_page(page);
1418 put_page(page);
1419
1420 if (old_size < pos && !verity)
1421 pagecache_isize_extended(inode, old_size, pos);
1422
1423 if (size_changed) {
1424 ret2 = ext4_mark_inode_dirty(handle, inode);
1425 if (!ret)
1426 ret = ret2;
1427 }
1428
1429 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1430 /* if we have allocated more blocks and copied
1431 * less. We will have blocks allocated outside
1432 * inode->i_size. So truncate them
1433 */
1434 ext4_orphan_add(handle, inode);
1435
1436 ret2 = ext4_journal_stop(handle);
1437 if (!ret)
1438 ret = ret2;
1439 if (pos + len > inode->i_size && !verity) {
1440 ext4_truncate_failed_write(inode);
1441 /*
1442 * If truncate failed early the inode might still be
1443 * on the orphan list; we need to make sure the inode
1444 * is removed from the orphan list in that case.
1445 */
1446 if (inode->i_nlink)
1447 ext4_orphan_del(NULL, inode);
1448 }
1449
1450 return ret ? ret : copied;
1451 }
1452
1453 /*
1454 * Reserve space for a single cluster
1455 */
ext4_da_reserve_space(struct inode * inode)1456 static int ext4_da_reserve_space(struct inode *inode)
1457 {
1458 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1459 struct ext4_inode_info *ei = EXT4_I(inode);
1460 int ret;
1461
1462 /*
1463 * We will charge metadata quota at writeout time; this saves
1464 * us from metadata over-estimation, though we may go over by
1465 * a small amount in the end. Here we just reserve for data.
1466 */
1467 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1468 if (ret)
1469 return ret;
1470
1471 spin_lock(&ei->i_block_reservation_lock);
1472 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1473 spin_unlock(&ei->i_block_reservation_lock);
1474 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1475 return -ENOSPC;
1476 }
1477 ei->i_reserved_data_blocks++;
1478 trace_ext4_da_reserve_space(inode);
1479 spin_unlock(&ei->i_block_reservation_lock);
1480
1481 return 0; /* success */
1482 }
1483
ext4_da_release_space(struct inode * inode,int to_free)1484 void ext4_da_release_space(struct inode *inode, int to_free)
1485 {
1486 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1487 struct ext4_inode_info *ei = EXT4_I(inode);
1488
1489 if (!to_free)
1490 return; /* Nothing to release, exit */
1491
1492 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1493
1494 trace_ext4_da_release_space(inode, to_free);
1495 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1496 /*
1497 * if there aren't enough reserved blocks, then the
1498 * counter is messed up somewhere. Since this
1499 * function is called from invalidate page, it's
1500 * harmless to return without any action.
1501 */
1502 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1503 "ino %lu, to_free %d with only %d reserved "
1504 "data blocks", inode->i_ino, to_free,
1505 ei->i_reserved_data_blocks);
1506 WARN_ON(1);
1507 to_free = ei->i_reserved_data_blocks;
1508 }
1509 ei->i_reserved_data_blocks -= to_free;
1510
1511 /* update fs dirty data blocks counter */
1512 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1513
1514 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1515
1516 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1517 }
1518
1519 /*
1520 * Delayed allocation stuff
1521 */
1522
1523 struct mpage_da_data {
1524 struct inode *inode;
1525 struct writeback_control *wbc;
1526
1527 pgoff_t first_page; /* The first page to write */
1528 pgoff_t next_page; /* Current page to examine */
1529 pgoff_t last_page; /* Last page to examine */
1530 /*
1531 * Extent to map - this can be after first_page because that can be
1532 * fully mapped. We somewhat abuse m_flags to store whether the extent
1533 * is delalloc or unwritten.
1534 */
1535 struct ext4_map_blocks map;
1536 struct ext4_io_submit io_submit; /* IO submission data */
1537 unsigned int do_map:1;
1538 unsigned int scanned_until_end:1;
1539 };
1540
mpage_release_unused_pages(struct mpage_da_data * mpd,bool invalidate)1541 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1542 bool invalidate)
1543 {
1544 int nr_pages, i;
1545 pgoff_t index, end;
1546 struct pagevec pvec;
1547 struct inode *inode = mpd->inode;
1548 struct address_space *mapping = inode->i_mapping;
1549
1550 /* This is necessary when next_page == 0. */
1551 if (mpd->first_page >= mpd->next_page)
1552 return;
1553
1554 mpd->scanned_until_end = 0;
1555 index = mpd->first_page;
1556 end = mpd->next_page - 1;
1557 if (invalidate) {
1558 ext4_lblk_t start, last;
1559 start = index << (PAGE_SHIFT - inode->i_blkbits);
1560 last = end << (PAGE_SHIFT - inode->i_blkbits);
1561 ext4_es_remove_extent(inode, start, last - start + 1);
1562 }
1563
1564 pagevec_init(&pvec);
1565 while (index <= end) {
1566 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1567 if (nr_pages == 0)
1568 break;
1569 for (i = 0; i < nr_pages; i++) {
1570 struct page *page = pvec.pages[i];
1571
1572 BUG_ON(!PageLocked(page));
1573 BUG_ON(PageWriteback(page));
1574 if (invalidate) {
1575 if (page_mapped(page))
1576 clear_page_dirty_for_io(page);
1577 block_invalidatepage(page, 0, PAGE_SIZE);
1578 ClearPageUptodate(page);
1579 }
1580 unlock_page(page);
1581 }
1582 pagevec_release(&pvec);
1583 }
1584 }
1585
ext4_print_free_blocks(struct inode * inode)1586 static void ext4_print_free_blocks(struct inode *inode)
1587 {
1588 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1589 struct super_block *sb = inode->i_sb;
1590 struct ext4_inode_info *ei = EXT4_I(inode);
1591
1592 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1593 EXT4_C2B(EXT4_SB(inode->i_sb),
1594 ext4_count_free_clusters(sb)));
1595 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1596 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1597 (long long) EXT4_C2B(EXT4_SB(sb),
1598 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1599 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1600 (long long) EXT4_C2B(EXT4_SB(sb),
1601 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1602 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1603 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1604 ei->i_reserved_data_blocks);
1605 return;
1606 }
1607
ext4_bh_delay_or_unwritten(handle_t * handle,struct buffer_head * bh)1608 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1609 {
1610 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1611 }
1612
1613 /*
1614 * ext4_insert_delayed_block - adds a delayed block to the extents status
1615 * tree, incrementing the reserved cluster/block
1616 * count or making a pending reservation
1617 * where needed
1618 *
1619 * @inode - file containing the newly added block
1620 * @lblk - logical block to be added
1621 *
1622 * Returns 0 on success, negative error code on failure.
1623 */
ext4_insert_delayed_block(struct inode * inode,ext4_lblk_t lblk)1624 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1625 {
1626 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1627 int ret;
1628 bool allocated = false;
1629 bool reserved = false;
1630
1631 /*
1632 * If the cluster containing lblk is shared with a delayed,
1633 * written, or unwritten extent in a bigalloc file system, it's
1634 * already been accounted for and does not need to be reserved.
1635 * A pending reservation must be made for the cluster if it's
1636 * shared with a written or unwritten extent and doesn't already
1637 * have one. Written and unwritten extents can be purged from the
1638 * extents status tree if the system is under memory pressure, so
1639 * it's necessary to examine the extent tree if a search of the
1640 * extents status tree doesn't get a match.
1641 */
1642 if (sbi->s_cluster_ratio == 1) {
1643 ret = ext4_da_reserve_space(inode);
1644 if (ret != 0) /* ENOSPC */
1645 goto errout;
1646 reserved = true;
1647 } else { /* bigalloc */
1648 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1649 if (!ext4_es_scan_clu(inode,
1650 &ext4_es_is_mapped, lblk)) {
1651 ret = ext4_clu_mapped(inode,
1652 EXT4_B2C(sbi, lblk));
1653 if (ret < 0)
1654 goto errout;
1655 if (ret == 0) {
1656 ret = ext4_da_reserve_space(inode);
1657 if (ret != 0) /* ENOSPC */
1658 goto errout;
1659 reserved = true;
1660 } else {
1661 allocated = true;
1662 }
1663 } else {
1664 allocated = true;
1665 }
1666 }
1667 }
1668
1669 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1670 if (ret && reserved)
1671 ext4_da_release_space(inode, 1);
1672
1673 errout:
1674 return ret;
1675 }
1676
1677 /*
1678 * This function is grabs code from the very beginning of
1679 * ext4_map_blocks, but assumes that the caller is from delayed write
1680 * time. This function looks up the requested blocks and sets the
1681 * buffer delay bit under the protection of i_data_sem.
1682 */
ext4_da_map_blocks(struct inode * inode,sector_t iblock,struct ext4_map_blocks * map,struct buffer_head * bh)1683 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1684 struct ext4_map_blocks *map,
1685 struct buffer_head *bh)
1686 {
1687 struct extent_status es;
1688 int retval;
1689 sector_t invalid_block = ~((sector_t) 0xffff);
1690 #ifdef ES_AGGRESSIVE_TEST
1691 struct ext4_map_blocks orig_map;
1692
1693 memcpy(&orig_map, map, sizeof(*map));
1694 #endif
1695
1696 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1697 invalid_block = ~0;
1698
1699 map->m_flags = 0;
1700 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1701 (unsigned long) map->m_lblk);
1702
1703 /* Lookup extent status tree firstly */
1704 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1705 if (ext4_es_is_hole(&es)) {
1706 retval = 0;
1707 down_read(&EXT4_I(inode)->i_data_sem);
1708 goto add_delayed;
1709 }
1710
1711 /*
1712 * Delayed extent could be allocated by fallocate.
1713 * So we need to check it.
1714 */
1715 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1716 map_bh(bh, inode->i_sb, invalid_block);
1717 set_buffer_new(bh);
1718 set_buffer_delay(bh);
1719 return 0;
1720 }
1721
1722 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1723 retval = es.es_len - (iblock - es.es_lblk);
1724 if (retval > map->m_len)
1725 retval = map->m_len;
1726 map->m_len = retval;
1727 if (ext4_es_is_written(&es))
1728 map->m_flags |= EXT4_MAP_MAPPED;
1729 else if (ext4_es_is_unwritten(&es))
1730 map->m_flags |= EXT4_MAP_UNWRITTEN;
1731 else
1732 BUG();
1733
1734 #ifdef ES_AGGRESSIVE_TEST
1735 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1736 #endif
1737 return retval;
1738 }
1739
1740 /*
1741 * Try to see if we can get the block without requesting a new
1742 * file system block.
1743 */
1744 down_read(&EXT4_I(inode)->i_data_sem);
1745 if (ext4_has_inline_data(inode))
1746 retval = 0;
1747 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1748 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1749 else
1750 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1751
1752 add_delayed:
1753 if (retval == 0) {
1754 int ret;
1755
1756 /*
1757 * XXX: __block_prepare_write() unmaps passed block,
1758 * is it OK?
1759 */
1760
1761 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1762 if (ret != 0) {
1763 retval = ret;
1764 goto out_unlock;
1765 }
1766
1767 map_bh(bh, inode->i_sb, invalid_block);
1768 set_buffer_new(bh);
1769 set_buffer_delay(bh);
1770 } else if (retval > 0) {
1771 int ret;
1772 unsigned int status;
1773
1774 if (unlikely(retval != map->m_len)) {
1775 ext4_warning(inode->i_sb,
1776 "ES len assertion failed for inode "
1777 "%lu: retval %d != map->m_len %d",
1778 inode->i_ino, retval, map->m_len);
1779 WARN_ON(1);
1780 }
1781
1782 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1783 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1784 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1785 map->m_pblk, status);
1786 if (ret != 0)
1787 retval = ret;
1788 }
1789
1790 out_unlock:
1791 up_read((&EXT4_I(inode)->i_data_sem));
1792
1793 return retval;
1794 }
1795
1796 /*
1797 * This is a special get_block_t callback which is used by
1798 * ext4_da_write_begin(). It will either return mapped block or
1799 * reserve space for a single block.
1800 *
1801 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1802 * We also have b_blocknr = -1 and b_bdev initialized properly
1803 *
1804 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1805 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1806 * initialized properly.
1807 */
ext4_da_get_block_prep(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)1808 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1809 struct buffer_head *bh, int create)
1810 {
1811 struct ext4_map_blocks map;
1812 int ret = 0;
1813
1814 BUG_ON(create == 0);
1815 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1816
1817 map.m_lblk = iblock;
1818 map.m_len = 1;
1819
1820 /*
1821 * first, we need to know whether the block is allocated already
1822 * preallocated blocks are unmapped but should treated
1823 * the same as allocated blocks.
1824 */
1825 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1826 if (ret <= 0)
1827 return ret;
1828
1829 map_bh(bh, inode->i_sb, map.m_pblk);
1830 ext4_update_bh_state(bh, map.m_flags);
1831
1832 if (buffer_unwritten(bh)) {
1833 /* A delayed write to unwritten bh should be marked
1834 * new and mapped. Mapped ensures that we don't do
1835 * get_block multiple times when we write to the same
1836 * offset and new ensures that we do proper zero out
1837 * for partial write.
1838 */
1839 set_buffer_new(bh);
1840 set_buffer_mapped(bh);
1841 }
1842 return 0;
1843 }
1844
bget_one(handle_t * handle,struct buffer_head * bh)1845 static int bget_one(handle_t *handle, struct buffer_head *bh)
1846 {
1847 get_bh(bh);
1848 return 0;
1849 }
1850
bput_one(handle_t * handle,struct buffer_head * bh)1851 static int bput_one(handle_t *handle, struct buffer_head *bh)
1852 {
1853 put_bh(bh);
1854 return 0;
1855 }
1856
__ext4_journalled_writepage(struct page * page,unsigned int len)1857 static int __ext4_journalled_writepage(struct page *page,
1858 unsigned int len)
1859 {
1860 struct address_space *mapping = page->mapping;
1861 struct inode *inode = mapping->host;
1862 struct buffer_head *page_bufs = NULL;
1863 handle_t *handle = NULL;
1864 int ret = 0, err = 0;
1865 int inline_data = ext4_has_inline_data(inode);
1866 struct buffer_head *inode_bh = NULL;
1867
1868 ClearPageChecked(page);
1869
1870 if (inline_data) {
1871 BUG_ON(page->index != 0);
1872 BUG_ON(len > ext4_get_max_inline_size(inode));
1873 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1874 if (inode_bh == NULL)
1875 goto out;
1876 } else {
1877 page_bufs = page_buffers(page);
1878 if (!page_bufs) {
1879 BUG();
1880 goto out;
1881 }
1882 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1883 NULL, bget_one);
1884 }
1885 /*
1886 * We need to release the page lock before we start the
1887 * journal, so grab a reference so the page won't disappear
1888 * out from under us.
1889 */
1890 get_page(page);
1891 unlock_page(page);
1892
1893 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1894 ext4_writepage_trans_blocks(inode));
1895 if (IS_ERR(handle)) {
1896 ret = PTR_ERR(handle);
1897 put_page(page);
1898 goto out_no_pagelock;
1899 }
1900 BUG_ON(!ext4_handle_valid(handle));
1901
1902 lock_page(page);
1903 put_page(page);
1904 if (page->mapping != mapping) {
1905 /* The page got truncated from under us */
1906 ext4_journal_stop(handle);
1907 ret = 0;
1908 goto out;
1909 }
1910
1911 if (inline_data) {
1912 ret = ext4_mark_inode_dirty(handle, inode);
1913 } else {
1914 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1915 do_journal_get_write_access);
1916
1917 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1918 write_end_fn);
1919 }
1920 if (ret == 0)
1921 ret = err;
1922 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1923 if (ret == 0)
1924 ret = err;
1925 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1926 err = ext4_journal_stop(handle);
1927 if (!ret)
1928 ret = err;
1929
1930 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1931 out:
1932 unlock_page(page);
1933 out_no_pagelock:
1934 if (!inline_data && page_bufs)
1935 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1936 NULL, bput_one);
1937 brelse(inode_bh);
1938 return ret;
1939 }
1940
cancel_page_dirty_status(struct page * page)1941 static void cancel_page_dirty_status(struct page *page)
1942 {
1943 struct address_space *mapping = page_mapping(page);
1944 unsigned long flags;
1945
1946 cancel_dirty_page(page);
1947 xa_lock_irqsave(&mapping->i_pages, flags);
1948 __xa_clear_mark(&mapping->i_pages, page_index(page),
1949 PAGECACHE_TAG_DIRTY);
1950 __xa_clear_mark(&mapping->i_pages, page_index(page),
1951 PAGECACHE_TAG_TOWRITE);
1952 xa_unlock_irqrestore(&mapping->i_pages, flags);
1953 }
1954
1955 /*
1956 * Note that we don't need to start a transaction unless we're journaling data
1957 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1958 * need to file the inode to the transaction's list in ordered mode because if
1959 * we are writing back data added by write(), the inode is already there and if
1960 * we are writing back data modified via mmap(), no one guarantees in which
1961 * transaction the data will hit the disk. In case we are journaling data, we
1962 * cannot start transaction directly because transaction start ranks above page
1963 * lock so we have to do some magic.
1964 *
1965 * This function can get called via...
1966 * - ext4_writepages after taking page lock (have journal handle)
1967 * - journal_submit_inode_data_buffers (no journal handle)
1968 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1969 * - grab_page_cache when doing write_begin (have journal handle)
1970 *
1971 * We don't do any block allocation in this function. If we have page with
1972 * multiple blocks we need to write those buffer_heads that are mapped. This
1973 * is important for mmaped based write. So if we do with blocksize 1K
1974 * truncate(f, 1024);
1975 * a = mmap(f, 0, 4096);
1976 * a[0] = 'a';
1977 * truncate(f, 4096);
1978 * we have in the page first buffer_head mapped via page_mkwrite call back
1979 * but other buffer_heads would be unmapped but dirty (dirty done via the
1980 * do_wp_page). So writepage should write the first block. If we modify
1981 * the mmap area beyond 1024 we will again get a page_fault and the
1982 * page_mkwrite callback will do the block allocation and mark the
1983 * buffer_heads mapped.
1984 *
1985 * We redirty the page if we have any buffer_heads that is either delay or
1986 * unwritten in the page.
1987 *
1988 * We can get recursively called as show below.
1989 *
1990 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1991 * ext4_writepage()
1992 *
1993 * But since we don't do any block allocation we should not deadlock.
1994 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1995 */
ext4_writepage(struct page * page,struct writeback_control * wbc)1996 static int ext4_writepage(struct page *page,
1997 struct writeback_control *wbc)
1998 {
1999 int ret = 0;
2000 loff_t size;
2001 unsigned int len;
2002 struct buffer_head *page_bufs = NULL;
2003 struct inode *inode = page->mapping->host;
2004 struct ext4_io_submit io_submit;
2005 bool keep_towrite = false;
2006
2007 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2008 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2009 unlock_page(page);
2010 return -EIO;
2011 }
2012
2013 if (WARN_ON(!page_has_buffers(page))) {
2014 cancel_page_dirty_status(page);
2015 unlock_page(page);
2016 return 0;
2017 }
2018
2019 trace_ext4_writepage(page);
2020 size = i_size_read(inode);
2021 if (page->index == size >> PAGE_SHIFT &&
2022 !ext4_verity_in_progress(inode))
2023 len = size & ~PAGE_MASK;
2024 else
2025 len = PAGE_SIZE;
2026
2027 page_bufs = page_buffers(page);
2028 /*
2029 * We cannot do block allocation or other extent handling in this
2030 * function. If there are buffers needing that, we have to redirty
2031 * the page. But we may reach here when we do a journal commit via
2032 * journal_submit_inode_data_buffers() and in that case we must write
2033 * allocated buffers to achieve data=ordered mode guarantees.
2034 *
2035 * Also, if there is only one buffer per page (the fs block
2036 * size == the page size), if one buffer needs block
2037 * allocation or needs to modify the extent tree to clear the
2038 * unwritten flag, we know that the page can't be written at
2039 * all, so we might as well refuse the write immediately.
2040 * Unfortunately if the block size != page size, we can't as
2041 * easily detect this case using ext4_walk_page_buffers(), but
2042 * for the extremely common case, this is an optimization that
2043 * skips a useless round trip through ext4_bio_write_page().
2044 */
2045 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2046 ext4_bh_delay_or_unwritten)) {
2047 redirty_page_for_writepage(wbc, page);
2048 if ((current->flags & PF_MEMALLOC) ||
2049 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2050 /*
2051 * For memory cleaning there's no point in writing only
2052 * some buffers. So just bail out. Warn if we came here
2053 * from direct reclaim.
2054 */
2055 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2056 == PF_MEMALLOC);
2057 unlock_page(page);
2058 return 0;
2059 }
2060 keep_towrite = true;
2061 }
2062
2063 if (PageChecked(page) && ext4_should_journal_data(inode))
2064 /*
2065 * It's mmapped pagecache. Add buffers and journal it. There
2066 * doesn't seem much point in redirtying the page here.
2067 */
2068 return __ext4_journalled_writepage(page, len);
2069
2070 ext4_io_submit_init(&io_submit, wbc);
2071 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2072 if (!io_submit.io_end) {
2073 redirty_page_for_writepage(wbc, page);
2074 unlock_page(page);
2075 return -ENOMEM;
2076 }
2077 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2078 ext4_io_submit(&io_submit);
2079 /* Drop io_end reference we got from init */
2080 ext4_put_io_end_defer(io_submit.io_end);
2081 return ret;
2082 }
2083
mpage_submit_page(struct mpage_da_data * mpd,struct page * page)2084 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2085 {
2086 int len;
2087 loff_t size;
2088 int err;
2089
2090 BUG_ON(page->index != mpd->first_page);
2091 clear_page_dirty_for_io(page);
2092 /*
2093 * We have to be very careful here! Nothing protects writeback path
2094 * against i_size changes and the page can be writeably mapped into
2095 * page tables. So an application can be growing i_size and writing
2096 * data through mmap while writeback runs. clear_page_dirty_for_io()
2097 * write-protects our page in page tables and the page cannot get
2098 * written to again until we release page lock. So only after
2099 * clear_page_dirty_for_io() we are safe to sample i_size for
2100 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2101 * on the barrier provided by TestClearPageDirty in
2102 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2103 * after page tables are updated.
2104 */
2105 size = i_size_read(mpd->inode);
2106 if (page->index == size >> PAGE_SHIFT &&
2107 !ext4_verity_in_progress(mpd->inode))
2108 len = size & ~PAGE_MASK;
2109 else
2110 len = PAGE_SIZE;
2111 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2112 if (!err)
2113 mpd->wbc->nr_to_write--;
2114 mpd->first_page++;
2115
2116 return err;
2117 }
2118
2119 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2120
2121 /*
2122 * mballoc gives us at most this number of blocks...
2123 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2124 * The rest of mballoc seems to handle chunks up to full group size.
2125 */
2126 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2127
2128 /*
2129 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2130 *
2131 * @mpd - extent of blocks
2132 * @lblk - logical number of the block in the file
2133 * @bh - buffer head we want to add to the extent
2134 *
2135 * The function is used to collect contig. blocks in the same state. If the
2136 * buffer doesn't require mapping for writeback and we haven't started the
2137 * extent of buffers to map yet, the function returns 'true' immediately - the
2138 * caller can write the buffer right away. Otherwise the function returns true
2139 * if the block has been added to the extent, false if the block couldn't be
2140 * added.
2141 */
mpage_add_bh_to_extent(struct mpage_da_data * mpd,ext4_lblk_t lblk,struct buffer_head * bh)2142 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2143 struct buffer_head *bh)
2144 {
2145 struct ext4_map_blocks *map = &mpd->map;
2146
2147 /* Buffer that doesn't need mapping for writeback? */
2148 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2149 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2150 /* So far no extent to map => we write the buffer right away */
2151 if (map->m_len == 0)
2152 return true;
2153 return false;
2154 }
2155
2156 /* First block in the extent? */
2157 if (map->m_len == 0) {
2158 /* We cannot map unless handle is started... */
2159 if (!mpd->do_map)
2160 return false;
2161 map->m_lblk = lblk;
2162 map->m_len = 1;
2163 map->m_flags = bh->b_state & BH_FLAGS;
2164 return true;
2165 }
2166
2167 /* Don't go larger than mballoc is willing to allocate */
2168 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2169 return false;
2170
2171 /* Can we merge the block to our big extent? */
2172 if (lblk == map->m_lblk + map->m_len &&
2173 (bh->b_state & BH_FLAGS) == map->m_flags) {
2174 map->m_len++;
2175 return true;
2176 }
2177 return false;
2178 }
2179
2180 /*
2181 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2182 *
2183 * @mpd - extent of blocks for mapping
2184 * @head - the first buffer in the page
2185 * @bh - buffer we should start processing from
2186 * @lblk - logical number of the block in the file corresponding to @bh
2187 *
2188 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2189 * the page for IO if all buffers in this page were mapped and there's no
2190 * accumulated extent of buffers to map or add buffers in the page to the
2191 * extent of buffers to map. The function returns 1 if the caller can continue
2192 * by processing the next page, 0 if it should stop adding buffers to the
2193 * extent to map because we cannot extend it anymore. It can also return value
2194 * < 0 in case of error during IO submission.
2195 */
mpage_process_page_bufs(struct mpage_da_data * mpd,struct buffer_head * head,struct buffer_head * bh,ext4_lblk_t lblk)2196 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2197 struct buffer_head *head,
2198 struct buffer_head *bh,
2199 ext4_lblk_t lblk)
2200 {
2201 struct inode *inode = mpd->inode;
2202 int err;
2203 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2204 >> inode->i_blkbits;
2205
2206 if (ext4_verity_in_progress(inode))
2207 blocks = EXT_MAX_BLOCKS;
2208
2209 do {
2210 BUG_ON(buffer_locked(bh));
2211
2212 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2213 /* Found extent to map? */
2214 if (mpd->map.m_len)
2215 return 0;
2216 /* Buffer needs mapping and handle is not started? */
2217 if (!mpd->do_map)
2218 return 0;
2219 /* Everything mapped so far and we hit EOF */
2220 break;
2221 }
2222 } while (lblk++, (bh = bh->b_this_page) != head);
2223 /* So far everything mapped? Submit the page for IO. */
2224 if (mpd->map.m_len == 0) {
2225 err = mpage_submit_page(mpd, head->b_page);
2226 if (err < 0)
2227 return err;
2228 }
2229 if (lblk >= blocks) {
2230 mpd->scanned_until_end = 1;
2231 return 0;
2232 }
2233 return 1;
2234 }
2235
2236 /*
2237 * mpage_process_page - update page buffers corresponding to changed extent and
2238 * may submit fully mapped page for IO
2239 *
2240 * @mpd - description of extent to map, on return next extent to map
2241 * @m_lblk - logical block mapping.
2242 * @m_pblk - corresponding physical mapping.
2243 * @map_bh - determines on return whether this page requires any further
2244 * mapping or not.
2245 * Scan given page buffers corresponding to changed extent and update buffer
2246 * state according to new extent state.
2247 * We map delalloc buffers to their physical location, clear unwritten bits.
2248 * If the given page is not fully mapped, we update @map to the next extent in
2249 * the given page that needs mapping & return @map_bh as true.
2250 */
mpage_process_page(struct mpage_da_data * mpd,struct page * page,ext4_lblk_t * m_lblk,ext4_fsblk_t * m_pblk,bool * map_bh)2251 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2252 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2253 bool *map_bh)
2254 {
2255 struct buffer_head *head, *bh;
2256 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2257 ext4_lblk_t lblk = *m_lblk;
2258 ext4_fsblk_t pblock = *m_pblk;
2259 int err = 0;
2260 int blkbits = mpd->inode->i_blkbits;
2261 ssize_t io_end_size = 0;
2262 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2263
2264 bh = head = page_buffers(page);
2265 do {
2266 if (lblk < mpd->map.m_lblk)
2267 continue;
2268 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2269 /*
2270 * Buffer after end of mapped extent.
2271 * Find next buffer in the page to map.
2272 */
2273 mpd->map.m_len = 0;
2274 mpd->map.m_flags = 0;
2275 io_end_vec->size += io_end_size;
2276 io_end_size = 0;
2277
2278 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2279 if (err > 0)
2280 err = 0;
2281 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2282 io_end_vec = ext4_alloc_io_end_vec(io_end);
2283 if (IS_ERR(io_end_vec)) {
2284 err = PTR_ERR(io_end_vec);
2285 goto out;
2286 }
2287 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2288 }
2289 *map_bh = true;
2290 goto out;
2291 }
2292 if (buffer_delay(bh)) {
2293 clear_buffer_delay(bh);
2294 bh->b_blocknr = pblock++;
2295 }
2296 clear_buffer_unwritten(bh);
2297 io_end_size += (1 << blkbits);
2298 } while (lblk++, (bh = bh->b_this_page) != head);
2299
2300 io_end_vec->size += io_end_size;
2301 io_end_size = 0;
2302 *map_bh = false;
2303 out:
2304 *m_lblk = lblk;
2305 *m_pblk = pblock;
2306 return err;
2307 }
2308
2309 /*
2310 * mpage_map_buffers - update buffers corresponding to changed extent and
2311 * submit fully mapped pages for IO
2312 *
2313 * @mpd - description of extent to map, on return next extent to map
2314 *
2315 * Scan buffers corresponding to changed extent (we expect corresponding pages
2316 * to be already locked) and update buffer state according to new extent state.
2317 * We map delalloc buffers to their physical location, clear unwritten bits,
2318 * and mark buffers as uninit when we perform writes to unwritten extents
2319 * and do extent conversion after IO is finished. If the last page is not fully
2320 * mapped, we update @map to the next extent in the last page that needs
2321 * mapping. Otherwise we submit the page for IO.
2322 */
mpage_map_and_submit_buffers(struct mpage_da_data * mpd)2323 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2324 {
2325 struct pagevec pvec;
2326 int nr_pages, i;
2327 struct inode *inode = mpd->inode;
2328 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2329 pgoff_t start, end;
2330 ext4_lblk_t lblk;
2331 ext4_fsblk_t pblock;
2332 int err;
2333 bool map_bh = false;
2334
2335 start = mpd->map.m_lblk >> bpp_bits;
2336 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2337 lblk = start << bpp_bits;
2338 pblock = mpd->map.m_pblk;
2339
2340 pagevec_init(&pvec);
2341 while (start <= end) {
2342 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2343 &start, end);
2344 if (nr_pages == 0)
2345 break;
2346 for (i = 0; i < nr_pages; i++) {
2347 struct page *page = pvec.pages[i];
2348
2349 err = mpage_process_page(mpd, page, &lblk, &pblock,
2350 &map_bh);
2351 /*
2352 * If map_bh is true, means page may require further bh
2353 * mapping, or maybe the page was submitted for IO.
2354 * So we return to call further extent mapping.
2355 */
2356 if (err < 0 || map_bh)
2357 goto out;
2358 /* Page fully mapped - let IO run! */
2359 err = mpage_submit_page(mpd, page);
2360 if (err < 0)
2361 goto out;
2362 }
2363 pagevec_release(&pvec);
2364 }
2365 /* Extent fully mapped and matches with page boundary. We are done. */
2366 mpd->map.m_len = 0;
2367 mpd->map.m_flags = 0;
2368 return 0;
2369 out:
2370 pagevec_release(&pvec);
2371 return err;
2372 }
2373
mpage_map_one_extent(handle_t * handle,struct mpage_da_data * mpd)2374 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2375 {
2376 struct inode *inode = mpd->inode;
2377 struct ext4_map_blocks *map = &mpd->map;
2378 int get_blocks_flags;
2379 int err, dioread_nolock;
2380
2381 trace_ext4_da_write_pages_extent(inode, map);
2382 /*
2383 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2384 * to convert an unwritten extent to be initialized (in the case
2385 * where we have written into one or more preallocated blocks). It is
2386 * possible that we're going to need more metadata blocks than
2387 * previously reserved. However we must not fail because we're in
2388 * writeback and there is nothing we can do about it so it might result
2389 * in data loss. So use reserved blocks to allocate metadata if
2390 * possible.
2391 *
2392 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2393 * the blocks in question are delalloc blocks. This indicates
2394 * that the blocks and quotas has already been checked when
2395 * the data was copied into the page cache.
2396 */
2397 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2398 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2399 EXT4_GET_BLOCKS_IO_SUBMIT;
2400 dioread_nolock = ext4_should_dioread_nolock(inode);
2401 if (dioread_nolock)
2402 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2403 if (map->m_flags & BIT(BH_Delay))
2404 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2405
2406 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2407 if (err < 0)
2408 return err;
2409 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2410 if (!mpd->io_submit.io_end->handle &&
2411 ext4_handle_valid(handle)) {
2412 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2413 handle->h_rsv_handle = NULL;
2414 }
2415 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2416 }
2417
2418 BUG_ON(map->m_len == 0);
2419 return 0;
2420 }
2421
2422 /*
2423 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2424 * mpd->len and submit pages underlying it for IO
2425 *
2426 * @handle - handle for journal operations
2427 * @mpd - extent to map
2428 * @give_up_on_write - we set this to true iff there is a fatal error and there
2429 * is no hope of writing the data. The caller should discard
2430 * dirty pages to avoid infinite loops.
2431 *
2432 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2433 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2434 * them to initialized or split the described range from larger unwritten
2435 * extent. Note that we need not map all the described range since allocation
2436 * can return less blocks or the range is covered by more unwritten extents. We
2437 * cannot map more because we are limited by reserved transaction credits. On
2438 * the other hand we always make sure that the last touched page is fully
2439 * mapped so that it can be written out (and thus forward progress is
2440 * guaranteed). After mapping we submit all mapped pages for IO.
2441 */
mpage_map_and_submit_extent(handle_t * handle,struct mpage_da_data * mpd,bool * give_up_on_write)2442 static int mpage_map_and_submit_extent(handle_t *handle,
2443 struct mpage_da_data *mpd,
2444 bool *give_up_on_write)
2445 {
2446 struct inode *inode = mpd->inode;
2447 struct ext4_map_blocks *map = &mpd->map;
2448 int err;
2449 loff_t disksize;
2450 int progress = 0;
2451 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2452 struct ext4_io_end_vec *io_end_vec;
2453
2454 io_end_vec = ext4_alloc_io_end_vec(io_end);
2455 if (IS_ERR(io_end_vec))
2456 return PTR_ERR(io_end_vec);
2457 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2458 do {
2459 err = mpage_map_one_extent(handle, mpd);
2460 if (err < 0) {
2461 struct super_block *sb = inode->i_sb;
2462
2463 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2464 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2465 goto invalidate_dirty_pages;
2466 /*
2467 * Let the uper layers retry transient errors.
2468 * In the case of ENOSPC, if ext4_count_free_blocks()
2469 * is non-zero, a commit should free up blocks.
2470 */
2471 if ((err == -ENOMEM) ||
2472 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2473 if (progress)
2474 goto update_disksize;
2475 return err;
2476 }
2477 ext4_msg(sb, KERN_CRIT,
2478 "Delayed block allocation failed for "
2479 "inode %lu at logical offset %llu with"
2480 " max blocks %u with error %d",
2481 inode->i_ino,
2482 (unsigned long long)map->m_lblk,
2483 (unsigned)map->m_len, -err);
2484 ext4_msg(sb, KERN_CRIT,
2485 "This should not happen!! Data will "
2486 "be lost\n");
2487 if (err == -ENOSPC)
2488 ext4_print_free_blocks(inode);
2489 invalidate_dirty_pages:
2490 *give_up_on_write = true;
2491 return err;
2492 }
2493 progress = 1;
2494 /*
2495 * Update buffer state, submit mapped pages, and get us new
2496 * extent to map
2497 */
2498 err = mpage_map_and_submit_buffers(mpd);
2499 if (err < 0)
2500 goto update_disksize;
2501 } while (map->m_len);
2502
2503 update_disksize:
2504 /*
2505 * Update on-disk size after IO is submitted. Races with
2506 * truncate are avoided by checking i_size under i_data_sem.
2507 */
2508 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2509 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2510 int err2;
2511 loff_t i_size;
2512
2513 down_write(&EXT4_I(inode)->i_data_sem);
2514 i_size = i_size_read(inode);
2515 if (disksize > i_size)
2516 disksize = i_size;
2517 if (disksize > EXT4_I(inode)->i_disksize)
2518 EXT4_I(inode)->i_disksize = disksize;
2519 up_write(&EXT4_I(inode)->i_data_sem);
2520 err2 = ext4_mark_inode_dirty(handle, inode);
2521 if (err2) {
2522 ext4_error_err(inode->i_sb, -err2,
2523 "Failed to mark inode %lu dirty",
2524 inode->i_ino);
2525 }
2526 if (!err)
2527 err = err2;
2528 }
2529 return err;
2530 }
2531
2532 /*
2533 * Calculate the total number of credits to reserve for one writepages
2534 * iteration. This is called from ext4_writepages(). We map an extent of
2535 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2536 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2537 * bpp - 1 blocks in bpp different extents.
2538 */
ext4_da_writepages_trans_blocks(struct inode * inode)2539 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2540 {
2541 int bpp = ext4_journal_blocks_per_page(inode);
2542
2543 return ext4_meta_trans_blocks(inode,
2544 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2545 }
2546
2547 /*
2548 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2549 * and underlying extent to map
2550 *
2551 * @mpd - where to look for pages
2552 *
2553 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2554 * IO immediately. When we find a page which isn't mapped we start accumulating
2555 * extent of buffers underlying these pages that needs mapping (formed by
2556 * either delayed or unwritten buffers). We also lock the pages containing
2557 * these buffers. The extent found is returned in @mpd structure (starting at
2558 * mpd->lblk with length mpd->len blocks).
2559 *
2560 * Note that this function can attach bios to one io_end structure which are
2561 * neither logically nor physically contiguous. Although it may seem as an
2562 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2563 * case as we need to track IO to all buffers underlying a page in one io_end.
2564 */
mpage_prepare_extent_to_map(struct mpage_da_data * mpd)2565 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2566 {
2567 struct address_space *mapping = mpd->inode->i_mapping;
2568 struct pagevec pvec;
2569 unsigned int nr_pages;
2570 long left = mpd->wbc->nr_to_write;
2571 pgoff_t index = mpd->first_page;
2572 pgoff_t end = mpd->last_page;
2573 xa_mark_t tag;
2574 int i, err = 0;
2575 int blkbits = mpd->inode->i_blkbits;
2576 ext4_lblk_t lblk;
2577 struct buffer_head *head;
2578
2579 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2580 tag = PAGECACHE_TAG_TOWRITE;
2581 else
2582 tag = PAGECACHE_TAG_DIRTY;
2583
2584 pagevec_init(&pvec);
2585 mpd->map.m_len = 0;
2586 mpd->next_page = index;
2587 while (index <= end) {
2588 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2589 tag);
2590 if (nr_pages == 0)
2591 break;
2592
2593 for (i = 0; i < nr_pages; i++) {
2594 struct page *page = pvec.pages[i];
2595
2596 /*
2597 * Accumulated enough dirty pages? This doesn't apply
2598 * to WB_SYNC_ALL mode. For integrity sync we have to
2599 * keep going because someone may be concurrently
2600 * dirtying pages, and we might have synced a lot of
2601 * newly appeared dirty pages, but have not synced all
2602 * of the old dirty pages.
2603 */
2604 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2605 goto out;
2606
2607 /* If we can't merge this page, we are done. */
2608 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2609 goto out;
2610
2611 lock_page(page);
2612 /*
2613 * If the page is no longer dirty, or its mapping no
2614 * longer corresponds to inode we are writing (which
2615 * means it has been truncated or invalidated), or the
2616 * page is already under writeback and we are not doing
2617 * a data integrity writeback, skip the page
2618 */
2619 if (!PageDirty(page) ||
2620 (PageWriteback(page) &&
2621 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2622 unlikely(page->mapping != mapping)) {
2623 unlock_page(page);
2624 continue;
2625 }
2626
2627 if (WARN_ON(!page_has_buffers(page))) {
2628 cancel_page_dirty_status(page);
2629 unlock_page(page);
2630 continue;
2631 }
2632
2633 wait_on_page_writeback(page);
2634 BUG_ON(PageWriteback(page));
2635
2636 if (mpd->map.m_len == 0)
2637 mpd->first_page = page->index;
2638 mpd->next_page = page->index + 1;
2639 /* Add all dirty buffers to mpd */
2640 lblk = ((ext4_lblk_t)page->index) <<
2641 (PAGE_SHIFT - blkbits);
2642 head = page_buffers(page);
2643 err = mpage_process_page_bufs(mpd, head, head, lblk);
2644 if (err <= 0)
2645 goto out;
2646 err = 0;
2647 left--;
2648 }
2649 pagevec_release(&pvec);
2650 cond_resched();
2651 }
2652 mpd->scanned_until_end = 1;
2653 return 0;
2654 out:
2655 pagevec_release(&pvec);
2656 return err;
2657 }
2658
ext4_writepages(struct address_space * mapping,struct writeback_control * wbc)2659 static int ext4_writepages(struct address_space *mapping,
2660 struct writeback_control *wbc)
2661 {
2662 pgoff_t writeback_index = 0;
2663 long nr_to_write = wbc->nr_to_write;
2664 int range_whole = 0;
2665 int cycled = 1;
2666 handle_t *handle = NULL;
2667 struct mpage_da_data mpd;
2668 struct inode *inode = mapping->host;
2669 int needed_blocks, rsv_blocks = 0, ret = 0;
2670 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2671 struct blk_plug plug;
2672 bool give_up_on_write = false;
2673
2674 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2675 return -EIO;
2676
2677 percpu_down_read(&sbi->s_writepages_rwsem);
2678 trace_ext4_writepages(inode, wbc);
2679
2680 /*
2681 * No pages to write? This is mainly a kludge to avoid starting
2682 * a transaction for special inodes like journal inode on last iput()
2683 * because that could violate lock ordering on umount
2684 */
2685 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2686 goto out_writepages;
2687
2688 if (ext4_should_journal_data(inode)) {
2689 ret = generic_writepages(mapping, wbc);
2690 goto out_writepages;
2691 }
2692
2693 /*
2694 * If the filesystem has aborted, it is read-only, so return
2695 * right away instead of dumping stack traces later on that
2696 * will obscure the real source of the problem. We test
2697 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2698 * the latter could be true if the filesystem is mounted
2699 * read-only, and in that case, ext4_writepages should
2700 * *never* be called, so if that ever happens, we would want
2701 * the stack trace.
2702 */
2703 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2704 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2705 ret = -EROFS;
2706 goto out_writepages;
2707 }
2708
2709 /*
2710 * If we have inline data and arrive here, it means that
2711 * we will soon create the block for the 1st page, so
2712 * we'd better clear the inline data here.
2713 */
2714 if (ext4_has_inline_data(inode)) {
2715 /* Just inode will be modified... */
2716 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2717 if (IS_ERR(handle)) {
2718 ret = PTR_ERR(handle);
2719 goto out_writepages;
2720 }
2721 BUG_ON(ext4_test_inode_state(inode,
2722 EXT4_STATE_MAY_INLINE_DATA));
2723 ext4_destroy_inline_data(handle, inode);
2724 ext4_journal_stop(handle);
2725 }
2726
2727 if (ext4_should_dioread_nolock(inode)) {
2728 /*
2729 * We may need to convert up to one extent per block in
2730 * the page and we may dirty the inode.
2731 */
2732 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2733 PAGE_SIZE >> inode->i_blkbits);
2734 }
2735
2736 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2737 range_whole = 1;
2738
2739 if (wbc->range_cyclic) {
2740 writeback_index = mapping->writeback_index;
2741 if (writeback_index)
2742 cycled = 0;
2743 mpd.first_page = writeback_index;
2744 mpd.last_page = -1;
2745 } else {
2746 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2747 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2748 }
2749
2750 mpd.inode = inode;
2751 mpd.wbc = wbc;
2752 ext4_io_submit_init(&mpd.io_submit, wbc);
2753 retry:
2754 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2755 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2756 blk_start_plug(&plug);
2757
2758 /*
2759 * First writeback pages that don't need mapping - we can avoid
2760 * starting a transaction unnecessarily and also avoid being blocked
2761 * in the block layer on device congestion while having transaction
2762 * started.
2763 */
2764 mpd.do_map = 0;
2765 mpd.scanned_until_end = 0;
2766 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2767 if (!mpd.io_submit.io_end) {
2768 ret = -ENOMEM;
2769 goto unplug;
2770 }
2771 ret = mpage_prepare_extent_to_map(&mpd);
2772 /* Unlock pages we didn't use */
2773 mpage_release_unused_pages(&mpd, false);
2774 /* Submit prepared bio */
2775 ext4_io_submit(&mpd.io_submit);
2776 ext4_put_io_end_defer(mpd.io_submit.io_end);
2777 mpd.io_submit.io_end = NULL;
2778 if (ret < 0)
2779 goto unplug;
2780
2781 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2782 /* For each extent of pages we use new io_end */
2783 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2784 if (!mpd.io_submit.io_end) {
2785 ret = -ENOMEM;
2786 break;
2787 }
2788
2789 /*
2790 * We have two constraints: We find one extent to map and we
2791 * must always write out whole page (makes a difference when
2792 * blocksize < pagesize) so that we don't block on IO when we
2793 * try to write out the rest of the page. Journalled mode is
2794 * not supported by delalloc.
2795 */
2796 BUG_ON(ext4_should_journal_data(inode));
2797 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2798
2799 /* start a new transaction */
2800 handle = ext4_journal_start_with_reserve(inode,
2801 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2802 if (IS_ERR(handle)) {
2803 ret = PTR_ERR(handle);
2804 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2805 "%ld pages, ino %lu; err %d", __func__,
2806 wbc->nr_to_write, inode->i_ino, ret);
2807 /* Release allocated io_end */
2808 ext4_put_io_end(mpd.io_submit.io_end);
2809 mpd.io_submit.io_end = NULL;
2810 break;
2811 }
2812 mpd.do_map = 1;
2813
2814 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2815 ret = mpage_prepare_extent_to_map(&mpd);
2816 if (!ret && mpd.map.m_len)
2817 ret = mpage_map_and_submit_extent(handle, &mpd,
2818 &give_up_on_write);
2819 /*
2820 * Caution: If the handle is synchronous,
2821 * ext4_journal_stop() can wait for transaction commit
2822 * to finish which may depend on writeback of pages to
2823 * complete or on page lock to be released. In that
2824 * case, we have to wait until after we have
2825 * submitted all the IO, released page locks we hold,
2826 * and dropped io_end reference (for extent conversion
2827 * to be able to complete) before stopping the handle.
2828 */
2829 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2830 ext4_journal_stop(handle);
2831 handle = NULL;
2832 mpd.do_map = 0;
2833 }
2834 /* Unlock pages we didn't use */
2835 mpage_release_unused_pages(&mpd, give_up_on_write);
2836 /* Submit prepared bio */
2837 ext4_io_submit(&mpd.io_submit);
2838
2839 /*
2840 * Drop our io_end reference we got from init. We have
2841 * to be careful and use deferred io_end finishing if
2842 * we are still holding the transaction as we can
2843 * release the last reference to io_end which may end
2844 * up doing unwritten extent conversion.
2845 */
2846 if (handle) {
2847 ext4_put_io_end_defer(mpd.io_submit.io_end);
2848 ext4_journal_stop(handle);
2849 } else
2850 ext4_put_io_end(mpd.io_submit.io_end);
2851 mpd.io_submit.io_end = NULL;
2852
2853 if (ret == -ENOSPC && sbi->s_journal) {
2854 /*
2855 * Commit the transaction which would
2856 * free blocks released in the transaction
2857 * and try again
2858 */
2859 jbd2_journal_force_commit_nested(sbi->s_journal);
2860 ret = 0;
2861 continue;
2862 }
2863 /* Fatal error - ENOMEM, EIO... */
2864 if (ret)
2865 break;
2866 }
2867 unplug:
2868 blk_finish_plug(&plug);
2869 if (!ret && !cycled && wbc->nr_to_write > 0) {
2870 cycled = 1;
2871 mpd.last_page = writeback_index - 1;
2872 mpd.first_page = 0;
2873 goto retry;
2874 }
2875
2876 /* Update index */
2877 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2878 /*
2879 * Set the writeback_index so that range_cyclic
2880 * mode will write it back later
2881 */
2882 mapping->writeback_index = mpd.first_page;
2883
2884 out_writepages:
2885 trace_ext4_writepages_result(inode, wbc, ret,
2886 nr_to_write - wbc->nr_to_write);
2887 percpu_up_read(&sbi->s_writepages_rwsem);
2888 return ret;
2889 }
2890
ext4_dax_writepages(struct address_space * mapping,struct writeback_control * wbc)2891 static int ext4_dax_writepages(struct address_space *mapping,
2892 struct writeback_control *wbc)
2893 {
2894 int ret;
2895 long nr_to_write = wbc->nr_to_write;
2896 struct inode *inode = mapping->host;
2897 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2898
2899 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2900 return -EIO;
2901
2902 percpu_down_read(&sbi->s_writepages_rwsem);
2903 trace_ext4_writepages(inode, wbc);
2904
2905 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2906 trace_ext4_writepages_result(inode, wbc, ret,
2907 nr_to_write - wbc->nr_to_write);
2908 percpu_up_read(&sbi->s_writepages_rwsem);
2909 return ret;
2910 }
2911
ext4_nonda_switch(struct super_block * sb)2912 static int ext4_nonda_switch(struct super_block *sb)
2913 {
2914 s64 free_clusters, dirty_clusters;
2915 struct ext4_sb_info *sbi = EXT4_SB(sb);
2916
2917 /*
2918 * switch to non delalloc mode if we are running low
2919 * on free block. The free block accounting via percpu
2920 * counters can get slightly wrong with percpu_counter_batch getting
2921 * accumulated on each CPU without updating global counters
2922 * Delalloc need an accurate free block accounting. So switch
2923 * to non delalloc when we are near to error range.
2924 */
2925 free_clusters =
2926 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2927 dirty_clusters =
2928 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2929 /*
2930 * Start pushing delalloc when 1/2 of free blocks are dirty.
2931 */
2932 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2933 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2934
2935 if (2 * free_clusters < 3 * dirty_clusters ||
2936 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2937 /*
2938 * free block count is less than 150% of dirty blocks
2939 * or free blocks is less than watermark
2940 */
2941 return 1;
2942 }
2943 return 0;
2944 }
2945
ext4_da_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned flags,struct page ** pagep,void ** fsdata)2946 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2947 loff_t pos, unsigned len, unsigned flags,
2948 struct page **pagep, void **fsdata)
2949 {
2950 int ret, retries = 0;
2951 struct page *page;
2952 pgoff_t index;
2953 struct inode *inode = mapping->host;
2954
2955 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2956 return -EIO;
2957
2958 index = pos >> PAGE_SHIFT;
2959
2960 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2961 ext4_verity_in_progress(inode)) {
2962 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2963 return ext4_write_begin(file, mapping, pos,
2964 len, flags, pagep, fsdata);
2965 }
2966 *fsdata = (void *)0;
2967 trace_ext4_da_write_begin(inode, pos, len, flags);
2968
2969 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2970 ret = ext4_da_write_inline_data_begin(mapping, inode,
2971 pos, len, flags,
2972 pagep, fsdata);
2973 if (ret < 0)
2974 return ret;
2975 if (ret == 1)
2976 return 0;
2977 }
2978
2979 retry:
2980 page = grab_cache_page_write_begin(mapping, index, flags);
2981 if (!page)
2982 return -ENOMEM;
2983
2984 /* In case writeback began while the page was unlocked */
2985 wait_for_stable_page(page);
2986
2987 #ifdef CONFIG_FS_ENCRYPTION
2988 ret = ext4_block_write_begin(page, pos, len,
2989 ext4_da_get_block_prep);
2990 #else
2991 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2992 #endif
2993 if (ret < 0) {
2994 unlock_page(page);
2995 put_page(page);
2996 /*
2997 * block_write_begin may have instantiated a few blocks
2998 * outside i_size. Trim these off again. Don't need
2999 * i_size_read because we hold inode lock.
3000 */
3001 if (pos + len > inode->i_size)
3002 ext4_truncate_failed_write(inode);
3003
3004 if (ret == -ENOSPC &&
3005 ext4_should_retry_alloc(inode->i_sb, &retries))
3006 goto retry;
3007 return ret;
3008 }
3009
3010 *pagep = page;
3011 return ret;
3012 }
3013
3014 /*
3015 * Check if we should update i_disksize
3016 * when write to the end of file but not require block allocation
3017 */
ext4_da_should_update_i_disksize(struct page * page,unsigned long offset)3018 static int ext4_da_should_update_i_disksize(struct page *page,
3019 unsigned long offset)
3020 {
3021 struct buffer_head *bh;
3022 struct inode *inode = page->mapping->host;
3023 unsigned int idx;
3024 int i;
3025
3026 bh = page_buffers(page);
3027 idx = offset >> inode->i_blkbits;
3028
3029 for (i = 0; i < idx; i++)
3030 bh = bh->b_this_page;
3031
3032 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3033 return 0;
3034 return 1;
3035 }
3036
ext4_da_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)3037 static int ext4_da_write_end(struct file *file,
3038 struct address_space *mapping,
3039 loff_t pos, unsigned len, unsigned copied,
3040 struct page *page, void *fsdata)
3041 {
3042 struct inode *inode = mapping->host;
3043 loff_t new_i_size;
3044 unsigned long start, end;
3045 int write_mode = (int)(unsigned long)fsdata;
3046
3047 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3048 return ext4_write_end(file, mapping, pos,
3049 len, copied, page, fsdata);
3050
3051 trace_ext4_da_write_end(inode, pos, len, copied);
3052
3053 if (write_mode != CONVERT_INLINE_DATA &&
3054 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3055 ext4_has_inline_data(inode))
3056 return ext4_write_inline_data_end(inode, pos, len, copied, page);
3057
3058 start = pos & (PAGE_SIZE - 1);
3059 end = start + copied - 1;
3060
3061 /*
3062 * Since we are holding inode lock, we are sure i_disksize <=
3063 * i_size. We also know that if i_disksize < i_size, there are
3064 * delalloc writes pending in the range upto i_size. If the end of
3065 * the current write is <= i_size, there's no need to touch
3066 * i_disksize since writeback will push i_disksize upto i_size
3067 * eventually. If the end of the current write is > i_size and
3068 * inside an allocated block (ext4_da_should_update_i_disksize()
3069 * check), we need to update i_disksize here as neither
3070 * ext4_writepage() nor certain ext4_writepages() paths not
3071 * allocating blocks update i_disksize.
3072 *
3073 * Note that we defer inode dirtying to generic_write_end() /
3074 * ext4_da_write_inline_data_end().
3075 */
3076 new_i_size = pos + copied;
3077 if (copied && new_i_size > inode->i_size &&
3078 ext4_da_should_update_i_disksize(page, end))
3079 ext4_update_i_disksize(inode, new_i_size);
3080
3081 return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3082 }
3083
3084 /*
3085 * Force all delayed allocation blocks to be allocated for a given inode.
3086 */
ext4_alloc_da_blocks(struct inode * inode)3087 int ext4_alloc_da_blocks(struct inode *inode)
3088 {
3089 trace_ext4_alloc_da_blocks(inode);
3090
3091 if (!EXT4_I(inode)->i_reserved_data_blocks)
3092 return 0;
3093
3094 /*
3095 * We do something simple for now. The filemap_flush() will
3096 * also start triggering a write of the data blocks, which is
3097 * not strictly speaking necessary (and for users of
3098 * laptop_mode, not even desirable). However, to do otherwise
3099 * would require replicating code paths in:
3100 *
3101 * ext4_writepages() ->
3102 * write_cache_pages() ---> (via passed in callback function)
3103 * __mpage_da_writepage() -->
3104 * mpage_add_bh_to_extent()
3105 * mpage_da_map_blocks()
3106 *
3107 * The problem is that write_cache_pages(), located in
3108 * mm/page-writeback.c, marks pages clean in preparation for
3109 * doing I/O, which is not desirable if we're not planning on
3110 * doing I/O at all.
3111 *
3112 * We could call write_cache_pages(), and then redirty all of
3113 * the pages by calling redirty_page_for_writepage() but that
3114 * would be ugly in the extreme. So instead we would need to
3115 * replicate parts of the code in the above functions,
3116 * simplifying them because we wouldn't actually intend to
3117 * write out the pages, but rather only collect contiguous
3118 * logical block extents, call the multi-block allocator, and
3119 * then update the buffer heads with the block allocations.
3120 *
3121 * For now, though, we'll cheat by calling filemap_flush(),
3122 * which will map the blocks, and start the I/O, but not
3123 * actually wait for the I/O to complete.
3124 */
3125 return filemap_flush(inode->i_mapping);
3126 }
3127
3128 /*
3129 * bmap() is special. It gets used by applications such as lilo and by
3130 * the swapper to find the on-disk block of a specific piece of data.
3131 *
3132 * Naturally, this is dangerous if the block concerned is still in the
3133 * journal. If somebody makes a swapfile on an ext4 data-journaling
3134 * filesystem and enables swap, then they may get a nasty shock when the
3135 * data getting swapped to that swapfile suddenly gets overwritten by
3136 * the original zero's written out previously to the journal and
3137 * awaiting writeback in the kernel's buffer cache.
3138 *
3139 * So, if we see any bmap calls here on a modified, data-journaled file,
3140 * take extra steps to flush any blocks which might be in the cache.
3141 */
ext4_bmap(struct address_space * mapping,sector_t block)3142 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3143 {
3144 struct inode *inode = mapping->host;
3145 journal_t *journal;
3146 int err;
3147
3148 /*
3149 * We can get here for an inline file via the FIBMAP ioctl
3150 */
3151 if (ext4_has_inline_data(inode))
3152 return 0;
3153
3154 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3155 test_opt(inode->i_sb, DELALLOC)) {
3156 /*
3157 * With delalloc we want to sync the file
3158 * so that we can make sure we allocate
3159 * blocks for file
3160 */
3161 filemap_write_and_wait(mapping);
3162 }
3163
3164 if (EXT4_JOURNAL(inode) &&
3165 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3166 /*
3167 * This is a REALLY heavyweight approach, but the use of
3168 * bmap on dirty files is expected to be extremely rare:
3169 * only if we run lilo or swapon on a freshly made file
3170 * do we expect this to happen.
3171 *
3172 * (bmap requires CAP_SYS_RAWIO so this does not
3173 * represent an unprivileged user DOS attack --- we'd be
3174 * in trouble if mortal users could trigger this path at
3175 * will.)
3176 *
3177 * NB. EXT4_STATE_JDATA is not set on files other than
3178 * regular files. If somebody wants to bmap a directory
3179 * or symlink and gets confused because the buffer
3180 * hasn't yet been flushed to disk, they deserve
3181 * everything they get.
3182 */
3183
3184 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3185 journal = EXT4_JOURNAL(inode);
3186 jbd2_journal_lock_updates(journal);
3187 err = jbd2_journal_flush(journal);
3188 jbd2_journal_unlock_updates(journal);
3189
3190 if (err)
3191 return 0;
3192 }
3193
3194 return iomap_bmap(mapping, block, &ext4_iomap_ops);
3195 }
3196
ext4_readpage(struct file * file,struct page * page)3197 static int ext4_readpage(struct file *file, struct page *page)
3198 {
3199 int ret = -EAGAIN;
3200 struct inode *inode = page->mapping->host;
3201
3202 trace_ext4_readpage(page);
3203
3204 if (ext4_has_inline_data(inode))
3205 ret = ext4_readpage_inline(inode, page);
3206
3207 if (ret == -EAGAIN)
3208 return ext4_mpage_readpages(inode, NULL, page);
3209
3210 return ret;
3211 }
3212
ext4_readahead(struct readahead_control * rac)3213 static void ext4_readahead(struct readahead_control *rac)
3214 {
3215 struct inode *inode = rac->mapping->host;
3216
3217 /* If the file has inline data, no need to do readahead. */
3218 if (ext4_has_inline_data(inode))
3219 return;
3220
3221 ext4_mpage_readpages(inode, rac, NULL);
3222 }
3223
ext4_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3224 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3225 unsigned int length)
3226 {
3227 trace_ext4_invalidatepage(page, offset, length);
3228
3229 /* No journalling happens on data buffers when this function is used */
3230 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3231
3232 block_invalidatepage(page, offset, length);
3233 }
3234
__ext4_journalled_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3235 static int __ext4_journalled_invalidatepage(struct page *page,
3236 unsigned int offset,
3237 unsigned int length)
3238 {
3239 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3240
3241 trace_ext4_journalled_invalidatepage(page, offset, length);
3242
3243 /*
3244 * If it's a full truncate we just forget about the pending dirtying
3245 */
3246 if (offset == 0 && length == PAGE_SIZE)
3247 ClearPageChecked(page);
3248
3249 return jbd2_journal_invalidatepage(journal, page, offset, length);
3250 }
3251
3252 /* Wrapper for aops... */
ext4_journalled_invalidatepage(struct page * page,unsigned int offset,unsigned int length)3253 static void ext4_journalled_invalidatepage(struct page *page,
3254 unsigned int offset,
3255 unsigned int length)
3256 {
3257 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3258 }
3259
ext4_releasepage(struct page * page,gfp_t wait)3260 static int ext4_releasepage(struct page *page, gfp_t wait)
3261 {
3262 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3263
3264 trace_ext4_releasepage(page);
3265
3266 /* Page has dirty journalled data -> cannot release */
3267 if (PageChecked(page))
3268 return 0;
3269 if (journal)
3270 return jbd2_journal_try_to_free_buffers(journal, page);
3271 else
3272 return try_to_free_buffers(page);
3273 }
3274
ext4_inode_datasync_dirty(struct inode * inode)3275 static bool ext4_inode_datasync_dirty(struct inode *inode)
3276 {
3277 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3278
3279 if (journal) {
3280 if (jbd2_transaction_committed(journal,
3281 EXT4_I(inode)->i_datasync_tid))
3282 return false;
3283 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3284 return !list_empty(&EXT4_I(inode)->i_fc_list);
3285 return true;
3286 }
3287
3288 /* Any metadata buffers to write? */
3289 if (!list_empty(&inode->i_mapping->private_list))
3290 return true;
3291 return inode->i_state & I_DIRTY_DATASYNC;
3292 }
3293
ext4_set_iomap(struct inode * inode,struct iomap * iomap,struct ext4_map_blocks * map,loff_t offset,loff_t length)3294 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3295 struct ext4_map_blocks *map, loff_t offset,
3296 loff_t length)
3297 {
3298 u8 blkbits = inode->i_blkbits;
3299
3300 /*
3301 * Writes that span EOF might trigger an I/O size update on completion,
3302 * so consider them to be dirty for the purpose of O_DSYNC, even if
3303 * there is no other metadata changes being made or are pending.
3304 */
3305 iomap->flags = 0;
3306 if (ext4_inode_datasync_dirty(inode) ||
3307 offset + length > i_size_read(inode))
3308 iomap->flags |= IOMAP_F_DIRTY;
3309
3310 if (map->m_flags & EXT4_MAP_NEW)
3311 iomap->flags |= IOMAP_F_NEW;
3312
3313 iomap->bdev = inode->i_sb->s_bdev;
3314 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3315 iomap->offset = (u64) map->m_lblk << blkbits;
3316 iomap->length = (u64) map->m_len << blkbits;
3317
3318 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3319 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3320 iomap->flags |= IOMAP_F_MERGED;
3321
3322 /*
3323 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3324 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3325 * set. In order for any allocated unwritten extents to be converted
3326 * into written extents correctly within the ->end_io() handler, we
3327 * need to ensure that the iomap->type is set appropriately. Hence, the
3328 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3329 * been set first.
3330 */
3331 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3332 iomap->type = IOMAP_UNWRITTEN;
3333 iomap->addr = (u64) map->m_pblk << blkbits;
3334 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3335 iomap->type = IOMAP_MAPPED;
3336 iomap->addr = (u64) map->m_pblk << blkbits;
3337 } else {
3338 iomap->type = IOMAP_HOLE;
3339 iomap->addr = IOMAP_NULL_ADDR;
3340 }
3341 }
3342
ext4_iomap_alloc(struct inode * inode,struct ext4_map_blocks * map,unsigned int flags)3343 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3344 unsigned int flags)
3345 {
3346 handle_t *handle;
3347 u8 blkbits = inode->i_blkbits;
3348 int ret, dio_credits, m_flags = 0, retries = 0;
3349
3350 /*
3351 * Trim the mapping request to the maximum value that we can map at
3352 * once for direct I/O.
3353 */
3354 if (map->m_len > DIO_MAX_BLOCKS)
3355 map->m_len = DIO_MAX_BLOCKS;
3356 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3357
3358 retry:
3359 /*
3360 * Either we allocate blocks and then don't get an unwritten extent, so
3361 * in that case we have reserved enough credits. Or, the blocks are
3362 * already allocated and unwritten. In that case, the extent conversion
3363 * fits into the credits as well.
3364 */
3365 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3366 if (IS_ERR(handle))
3367 return PTR_ERR(handle);
3368
3369 /*
3370 * DAX and direct I/O are the only two operations that are currently
3371 * supported with IOMAP_WRITE.
3372 */
3373 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3374 if (IS_DAX(inode))
3375 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3376 /*
3377 * We use i_size instead of i_disksize here because delalloc writeback
3378 * can complete at any point during the I/O and subsequently push the
3379 * i_disksize out to i_size. This could be beyond where direct I/O is
3380 * happening and thus expose allocated blocks to direct I/O reads.
3381 */
3382 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3383 m_flags = EXT4_GET_BLOCKS_CREATE;
3384 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3385 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3386
3387 ret = ext4_map_blocks(handle, inode, map, m_flags);
3388
3389 /*
3390 * We cannot fill holes in indirect tree based inodes as that could
3391 * expose stale data in the case of a crash. Use the magic error code
3392 * to fallback to buffered I/O.
3393 */
3394 if (!m_flags && !ret)
3395 ret = -ENOTBLK;
3396
3397 ext4_journal_stop(handle);
3398 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3399 goto retry;
3400
3401 return ret;
3402 }
3403
3404
ext4_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3405 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3406 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3407 {
3408 int ret;
3409 struct ext4_map_blocks map;
3410 u8 blkbits = inode->i_blkbits;
3411
3412 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3413 return -EINVAL;
3414
3415 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3416 return -ERANGE;
3417
3418 /*
3419 * Calculate the first and last logical blocks respectively.
3420 */
3421 map.m_lblk = offset >> blkbits;
3422 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3423 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3424
3425 if (flags & IOMAP_WRITE) {
3426 /*
3427 * We check here if the blocks are already allocated, then we
3428 * don't need to start a journal txn and we can directly return
3429 * the mapping information. This could boost performance
3430 * especially in multi-threaded overwrite requests.
3431 */
3432 if (offset + length <= i_size_read(inode)) {
3433 ret = ext4_map_blocks(NULL, inode, &map, 0);
3434 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3435 goto out;
3436 }
3437 ret = ext4_iomap_alloc(inode, &map, flags);
3438 } else {
3439 ret = ext4_map_blocks(NULL, inode, &map, 0);
3440 }
3441
3442 if (ret < 0)
3443 return ret;
3444 out:
3445 ext4_set_iomap(inode, iomap, &map, offset, length);
3446
3447 return 0;
3448 }
3449
ext4_iomap_overwrite_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3450 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3451 loff_t length, unsigned flags, struct iomap *iomap,
3452 struct iomap *srcmap)
3453 {
3454 int ret;
3455
3456 /*
3457 * Even for writes we don't need to allocate blocks, so just pretend
3458 * we are reading to save overhead of starting a transaction.
3459 */
3460 flags &= ~IOMAP_WRITE;
3461 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3462 WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3463 return ret;
3464 }
3465
ext4_iomap_end(struct inode * inode,loff_t offset,loff_t length,ssize_t written,unsigned flags,struct iomap * iomap)3466 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3467 ssize_t written, unsigned flags, struct iomap *iomap)
3468 {
3469 /*
3470 * Check to see whether an error occurred while writing out the data to
3471 * the allocated blocks. If so, return the magic error code so that we
3472 * fallback to buffered I/O and attempt to complete the remainder of
3473 * the I/O. Any blocks that may have been allocated in preparation for
3474 * the direct I/O will be reused during buffered I/O.
3475 */
3476 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3477 return -ENOTBLK;
3478
3479 return 0;
3480 }
3481
3482 const struct iomap_ops ext4_iomap_ops = {
3483 .iomap_begin = ext4_iomap_begin,
3484 .iomap_end = ext4_iomap_end,
3485 };
3486
3487 const struct iomap_ops ext4_iomap_overwrite_ops = {
3488 .iomap_begin = ext4_iomap_overwrite_begin,
3489 .iomap_end = ext4_iomap_end,
3490 };
3491
ext4_iomap_is_delalloc(struct inode * inode,struct ext4_map_blocks * map)3492 static bool ext4_iomap_is_delalloc(struct inode *inode,
3493 struct ext4_map_blocks *map)
3494 {
3495 struct extent_status es;
3496 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3497
3498 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3499 map->m_lblk, end, &es);
3500
3501 if (!es.es_len || es.es_lblk > end)
3502 return false;
3503
3504 if (es.es_lblk > map->m_lblk) {
3505 map->m_len = es.es_lblk - map->m_lblk;
3506 return false;
3507 }
3508
3509 offset = map->m_lblk - es.es_lblk;
3510 map->m_len = es.es_len - offset;
3511
3512 return true;
3513 }
3514
ext4_iomap_begin_report(struct inode * inode,loff_t offset,loff_t length,unsigned int flags,struct iomap * iomap,struct iomap * srcmap)3515 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3516 loff_t length, unsigned int flags,
3517 struct iomap *iomap, struct iomap *srcmap)
3518 {
3519 int ret;
3520 bool delalloc = false;
3521 struct ext4_map_blocks map;
3522 u8 blkbits = inode->i_blkbits;
3523
3524 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3525 return -EINVAL;
3526
3527 if (ext4_has_inline_data(inode)) {
3528 ret = ext4_inline_data_iomap(inode, iomap);
3529 if (ret != -EAGAIN) {
3530 if (ret == 0 && offset >= iomap->length)
3531 ret = -ENOENT;
3532 return ret;
3533 }
3534 }
3535
3536 /*
3537 * Calculate the first and last logical block respectively.
3538 */
3539 map.m_lblk = offset >> blkbits;
3540 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3541 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3542
3543 /*
3544 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3545 * So handle it here itself instead of querying ext4_map_blocks().
3546 * Since ext4_map_blocks() will warn about it and will return
3547 * -EIO error.
3548 */
3549 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3550 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3551
3552 if (offset >= sbi->s_bitmap_maxbytes) {
3553 map.m_flags = 0;
3554 goto set_iomap;
3555 }
3556 }
3557
3558 ret = ext4_map_blocks(NULL, inode, &map, 0);
3559 if (ret < 0)
3560 return ret;
3561 if (ret == 0)
3562 delalloc = ext4_iomap_is_delalloc(inode, &map);
3563
3564 set_iomap:
3565 ext4_set_iomap(inode, iomap, &map, offset, length);
3566 if (delalloc && iomap->type == IOMAP_HOLE)
3567 iomap->type = IOMAP_DELALLOC;
3568
3569 return 0;
3570 }
3571
3572 const struct iomap_ops ext4_iomap_report_ops = {
3573 .iomap_begin = ext4_iomap_begin_report,
3574 };
3575
3576 /*
3577 * Pages can be marked dirty completely asynchronously from ext4's journalling
3578 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3579 * much here because ->set_page_dirty is called under VFS locks. The page is
3580 * not necessarily locked.
3581 *
3582 * We cannot just dirty the page and leave attached buffers clean, because the
3583 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3584 * or jbddirty because all the journalling code will explode.
3585 *
3586 * So what we do is to mark the page "pending dirty" and next time writepage
3587 * is called, propagate that into the buffers appropriately.
3588 */
ext4_journalled_set_page_dirty(struct page * page)3589 static int ext4_journalled_set_page_dirty(struct page *page)
3590 {
3591 SetPageChecked(page);
3592 return __set_page_dirty_nobuffers(page);
3593 }
3594
ext4_set_page_dirty(struct page * page)3595 static int ext4_set_page_dirty(struct page *page)
3596 {
3597 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3598 WARN_ON_ONCE(!page_has_buffers(page));
3599 return __set_page_dirty_buffers(page);
3600 }
3601
ext4_iomap_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)3602 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3603 struct file *file, sector_t *span)
3604 {
3605 return iomap_swapfile_activate(sis, file, span,
3606 &ext4_iomap_report_ops);
3607 }
3608
3609 static const struct address_space_operations ext4_aops = {
3610 .readpage = ext4_readpage,
3611 .readahead = ext4_readahead,
3612 .writepage = ext4_writepage,
3613 .writepages = ext4_writepages,
3614 .write_begin = ext4_write_begin,
3615 .write_end = ext4_write_end,
3616 .set_page_dirty = ext4_set_page_dirty,
3617 .bmap = ext4_bmap,
3618 .invalidatepage = ext4_invalidatepage,
3619 .releasepage = ext4_releasepage,
3620 .direct_IO = noop_direct_IO,
3621 .migratepage = buffer_migrate_page,
3622 .is_partially_uptodate = block_is_partially_uptodate,
3623 .error_remove_page = generic_error_remove_page,
3624 .swap_activate = ext4_iomap_swap_activate,
3625 };
3626
3627 static const struct address_space_operations ext4_journalled_aops = {
3628 .readpage = ext4_readpage,
3629 .readahead = ext4_readahead,
3630 .writepage = ext4_writepage,
3631 .writepages = ext4_writepages,
3632 .write_begin = ext4_write_begin,
3633 .write_end = ext4_journalled_write_end,
3634 .set_page_dirty = ext4_journalled_set_page_dirty,
3635 .bmap = ext4_bmap,
3636 .invalidatepage = ext4_journalled_invalidatepage,
3637 .releasepage = ext4_releasepage,
3638 .direct_IO = noop_direct_IO,
3639 .is_partially_uptodate = block_is_partially_uptodate,
3640 .error_remove_page = generic_error_remove_page,
3641 .swap_activate = ext4_iomap_swap_activate,
3642 };
3643
3644 static const struct address_space_operations ext4_da_aops = {
3645 .readpage = ext4_readpage,
3646 .readahead = ext4_readahead,
3647 .writepage = ext4_writepage,
3648 .writepages = ext4_writepages,
3649 .write_begin = ext4_da_write_begin,
3650 .write_end = ext4_da_write_end,
3651 .set_page_dirty = ext4_set_page_dirty,
3652 .bmap = ext4_bmap,
3653 .invalidatepage = ext4_invalidatepage,
3654 .releasepage = ext4_releasepage,
3655 .direct_IO = noop_direct_IO,
3656 .migratepage = buffer_migrate_page,
3657 .is_partially_uptodate = block_is_partially_uptodate,
3658 .error_remove_page = generic_error_remove_page,
3659 .swap_activate = ext4_iomap_swap_activate,
3660 };
3661
3662 static const struct address_space_operations ext4_dax_aops = {
3663 .writepages = ext4_dax_writepages,
3664 .direct_IO = noop_direct_IO,
3665 .set_page_dirty = noop_set_page_dirty,
3666 .bmap = ext4_bmap,
3667 .invalidatepage = noop_invalidatepage,
3668 .swap_activate = ext4_iomap_swap_activate,
3669 };
3670
ext4_set_aops(struct inode * inode)3671 void ext4_set_aops(struct inode *inode)
3672 {
3673 switch (ext4_inode_journal_mode(inode)) {
3674 case EXT4_INODE_ORDERED_DATA_MODE:
3675 case EXT4_INODE_WRITEBACK_DATA_MODE:
3676 break;
3677 case EXT4_INODE_JOURNAL_DATA_MODE:
3678 inode->i_mapping->a_ops = &ext4_journalled_aops;
3679 return;
3680 default:
3681 BUG();
3682 }
3683 if (IS_DAX(inode))
3684 inode->i_mapping->a_ops = &ext4_dax_aops;
3685 else if (test_opt(inode->i_sb, DELALLOC))
3686 inode->i_mapping->a_ops = &ext4_da_aops;
3687 else
3688 inode->i_mapping->a_ops = &ext4_aops;
3689 }
3690
__ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3691 static int __ext4_block_zero_page_range(handle_t *handle,
3692 struct address_space *mapping, loff_t from, loff_t length)
3693 {
3694 ext4_fsblk_t index = from >> PAGE_SHIFT;
3695 unsigned offset = from & (PAGE_SIZE-1);
3696 unsigned blocksize, pos;
3697 ext4_lblk_t iblock;
3698 struct inode *inode = mapping->host;
3699 struct buffer_head *bh;
3700 struct page *page;
3701 int err = 0;
3702
3703 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3704 mapping_gfp_constraint(mapping, ~__GFP_FS));
3705 if (!page)
3706 return -ENOMEM;
3707
3708 blocksize = inode->i_sb->s_blocksize;
3709
3710 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3711
3712 if (!page_has_buffers(page))
3713 create_empty_buffers(page, blocksize, 0);
3714
3715 /* Find the buffer that contains "offset" */
3716 bh = page_buffers(page);
3717 pos = blocksize;
3718 while (offset >= pos) {
3719 bh = bh->b_this_page;
3720 iblock++;
3721 pos += blocksize;
3722 }
3723 if (buffer_freed(bh)) {
3724 BUFFER_TRACE(bh, "freed: skip");
3725 goto unlock;
3726 }
3727 if (!buffer_mapped(bh)) {
3728 BUFFER_TRACE(bh, "unmapped");
3729 ext4_get_block(inode, iblock, bh, 0);
3730 /* unmapped? It's a hole - nothing to do */
3731 if (!buffer_mapped(bh)) {
3732 BUFFER_TRACE(bh, "still unmapped");
3733 goto unlock;
3734 }
3735 }
3736
3737 /* Ok, it's mapped. Make sure it's up-to-date */
3738 if (PageUptodate(page))
3739 set_buffer_uptodate(bh);
3740
3741 if (!buffer_uptodate(bh)) {
3742 err = ext4_read_bh_lock(bh, 0, true);
3743 if (err)
3744 goto unlock;
3745 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3746 /* We expect the key to be set. */
3747 BUG_ON(!fscrypt_has_encryption_key(inode));
3748 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3749 bh_offset(bh));
3750 if (err) {
3751 clear_buffer_uptodate(bh);
3752 goto unlock;
3753 }
3754 }
3755 }
3756 if (ext4_should_journal_data(inode)) {
3757 BUFFER_TRACE(bh, "get write access");
3758 err = ext4_journal_get_write_access(handle, bh);
3759 if (err)
3760 goto unlock;
3761 }
3762 zero_user(page, offset, length);
3763 BUFFER_TRACE(bh, "zeroed end of block");
3764
3765 if (ext4_should_journal_data(inode)) {
3766 err = ext4_handle_dirty_metadata(handle, inode, bh);
3767 } else {
3768 err = 0;
3769 mark_buffer_dirty(bh);
3770 if (ext4_should_order_data(inode))
3771 err = ext4_jbd2_inode_add_write(handle, inode, from,
3772 length);
3773 }
3774
3775 unlock:
3776 unlock_page(page);
3777 put_page(page);
3778 return err;
3779 }
3780
3781 /*
3782 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3783 * starting from file offset 'from'. The range to be zero'd must
3784 * be contained with in one block. If the specified range exceeds
3785 * the end of the block it will be shortened to end of the block
3786 * that cooresponds to 'from'
3787 */
ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3788 static int ext4_block_zero_page_range(handle_t *handle,
3789 struct address_space *mapping, loff_t from, loff_t length)
3790 {
3791 struct inode *inode = mapping->host;
3792 unsigned offset = from & (PAGE_SIZE-1);
3793 unsigned blocksize = inode->i_sb->s_blocksize;
3794 unsigned max = blocksize - (offset & (blocksize - 1));
3795
3796 /*
3797 * correct length if it does not fall between
3798 * 'from' and the end of the block
3799 */
3800 if (length > max || length < 0)
3801 length = max;
3802
3803 if (IS_DAX(inode)) {
3804 return iomap_zero_range(inode, from, length, NULL,
3805 &ext4_iomap_ops);
3806 }
3807 return __ext4_block_zero_page_range(handle, mapping, from, length);
3808 }
3809
3810 /*
3811 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3812 * up to the end of the block which corresponds to `from'.
3813 * This required during truncate. We need to physically zero the tail end
3814 * of that block so it doesn't yield old data if the file is later grown.
3815 */
ext4_block_truncate_page(handle_t * handle,struct address_space * mapping,loff_t from)3816 static int ext4_block_truncate_page(handle_t *handle,
3817 struct address_space *mapping, loff_t from)
3818 {
3819 unsigned offset = from & (PAGE_SIZE-1);
3820 unsigned length;
3821 unsigned blocksize;
3822 struct inode *inode = mapping->host;
3823
3824 /* If we are processing an encrypted inode during orphan list handling */
3825 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3826 return 0;
3827
3828 blocksize = inode->i_sb->s_blocksize;
3829 length = blocksize - (offset & (blocksize - 1));
3830
3831 return ext4_block_zero_page_range(handle, mapping, from, length);
3832 }
3833
ext4_zero_partial_blocks(handle_t * handle,struct inode * inode,loff_t lstart,loff_t length)3834 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3835 loff_t lstart, loff_t length)
3836 {
3837 struct super_block *sb = inode->i_sb;
3838 struct address_space *mapping = inode->i_mapping;
3839 unsigned partial_start, partial_end;
3840 ext4_fsblk_t start, end;
3841 loff_t byte_end = (lstart + length - 1);
3842 int err = 0;
3843
3844 partial_start = lstart & (sb->s_blocksize - 1);
3845 partial_end = byte_end & (sb->s_blocksize - 1);
3846
3847 start = lstart >> sb->s_blocksize_bits;
3848 end = byte_end >> sb->s_blocksize_bits;
3849
3850 /* Handle partial zero within the single block */
3851 if (start == end &&
3852 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3853 err = ext4_block_zero_page_range(handle, mapping,
3854 lstart, length);
3855 return err;
3856 }
3857 /* Handle partial zero out on the start of the range */
3858 if (partial_start) {
3859 err = ext4_block_zero_page_range(handle, mapping,
3860 lstart, sb->s_blocksize);
3861 if (err)
3862 return err;
3863 }
3864 /* Handle partial zero out on the end of the range */
3865 if (partial_end != sb->s_blocksize - 1)
3866 err = ext4_block_zero_page_range(handle, mapping,
3867 byte_end - partial_end,
3868 partial_end + 1);
3869 return err;
3870 }
3871
ext4_can_truncate(struct inode * inode)3872 int ext4_can_truncate(struct inode *inode)
3873 {
3874 if (S_ISREG(inode->i_mode))
3875 return 1;
3876 if (S_ISDIR(inode->i_mode))
3877 return 1;
3878 if (S_ISLNK(inode->i_mode))
3879 return !ext4_inode_is_fast_symlink(inode);
3880 return 0;
3881 }
3882
3883 /*
3884 * We have to make sure i_disksize gets properly updated before we truncate
3885 * page cache due to hole punching or zero range. Otherwise i_disksize update
3886 * can get lost as it may have been postponed to submission of writeback but
3887 * that will never happen after we truncate page cache.
3888 */
ext4_update_disksize_before_punch(struct inode * inode,loff_t offset,loff_t len)3889 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3890 loff_t len)
3891 {
3892 handle_t *handle;
3893 int ret;
3894
3895 loff_t size = i_size_read(inode);
3896
3897 WARN_ON(!inode_is_locked(inode));
3898 if (offset > size || offset + len < size)
3899 return 0;
3900
3901 if (EXT4_I(inode)->i_disksize >= size)
3902 return 0;
3903
3904 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3905 if (IS_ERR(handle))
3906 return PTR_ERR(handle);
3907 ext4_update_i_disksize(inode, size);
3908 ret = ext4_mark_inode_dirty(handle, inode);
3909 ext4_journal_stop(handle);
3910
3911 return ret;
3912 }
3913
ext4_wait_dax_page(struct ext4_inode_info * ei)3914 static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3915 {
3916 up_write(&ei->i_mmap_sem);
3917 schedule();
3918 down_write(&ei->i_mmap_sem);
3919 }
3920
ext4_break_layouts(struct inode * inode)3921 int ext4_break_layouts(struct inode *inode)
3922 {
3923 struct ext4_inode_info *ei = EXT4_I(inode);
3924 struct page *page;
3925 int error;
3926
3927 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3928 return -EINVAL;
3929
3930 do {
3931 page = dax_layout_busy_page(inode->i_mapping);
3932 if (!page)
3933 return 0;
3934
3935 error = ___wait_var_event(&page->_refcount,
3936 atomic_read(&page->_refcount) == 1,
3937 TASK_INTERRUPTIBLE, 0, 0,
3938 ext4_wait_dax_page(ei));
3939 } while (error == 0);
3940
3941 return error;
3942 }
3943
3944 /*
3945 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3946 * associated with the given offset and length
3947 *
3948 * @inode: File inode
3949 * @offset: The offset where the hole will begin
3950 * @len: The length of the hole
3951 *
3952 * Returns: 0 on success or negative on failure
3953 */
3954
ext4_punch_hole(struct inode * inode,loff_t offset,loff_t length)3955 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3956 {
3957 struct super_block *sb = inode->i_sb;
3958 ext4_lblk_t first_block, stop_block;
3959 struct address_space *mapping = inode->i_mapping;
3960 loff_t first_block_offset, last_block_offset;
3961 handle_t *handle;
3962 unsigned int credits;
3963 int ret = 0, ret2 = 0;
3964
3965 trace_ext4_punch_hole(inode, offset, length, 0);
3966
3967 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
3968 if (ext4_has_inline_data(inode)) {
3969 down_write(&EXT4_I(inode)->i_mmap_sem);
3970 ret = ext4_convert_inline_data(inode);
3971 up_write(&EXT4_I(inode)->i_mmap_sem);
3972 if (ret)
3973 return ret;
3974 }
3975
3976 /*
3977 * Write out all dirty pages to avoid race conditions
3978 * Then release them.
3979 */
3980 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3981 ret = filemap_write_and_wait_range(mapping, offset,
3982 offset + length - 1);
3983 if (ret)
3984 return ret;
3985 }
3986
3987 inode_lock(inode);
3988
3989 /* No need to punch hole beyond i_size */
3990 if (offset >= inode->i_size)
3991 goto out_mutex;
3992
3993 /*
3994 * If the hole extends beyond i_size, set the hole
3995 * to end after the page that contains i_size
3996 */
3997 if (offset + length > inode->i_size) {
3998 length = inode->i_size +
3999 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4000 offset;
4001 }
4002
4003 if (offset & (sb->s_blocksize - 1) ||
4004 (offset + length) & (sb->s_blocksize - 1)) {
4005 /*
4006 * Attach jinode to inode for jbd2 if we do any zeroing of
4007 * partial block
4008 */
4009 ret = ext4_inode_attach_jinode(inode);
4010 if (ret < 0)
4011 goto out_mutex;
4012
4013 }
4014
4015 /* Wait all existing dio workers, newcomers will block on i_mutex */
4016 inode_dio_wait(inode);
4017
4018 /*
4019 * Prevent page faults from reinstantiating pages we have released from
4020 * page cache.
4021 */
4022 down_write(&EXT4_I(inode)->i_mmap_sem);
4023
4024 ret = ext4_break_layouts(inode);
4025 if (ret)
4026 goto out_dio;
4027
4028 first_block_offset = round_up(offset, sb->s_blocksize);
4029 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4030
4031 /* Now release the pages and zero block aligned part of pages*/
4032 if (last_block_offset > first_block_offset) {
4033 ret = ext4_update_disksize_before_punch(inode, offset, length);
4034 if (ret)
4035 goto out_dio;
4036 truncate_pagecache_range(inode, first_block_offset,
4037 last_block_offset);
4038 }
4039
4040 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4041 credits = ext4_writepage_trans_blocks(inode);
4042 else
4043 credits = ext4_blocks_for_truncate(inode);
4044 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4045 if (IS_ERR(handle)) {
4046 ret = PTR_ERR(handle);
4047 ext4_std_error(sb, ret);
4048 goto out_dio;
4049 }
4050
4051 ret = ext4_zero_partial_blocks(handle, inode, offset,
4052 length);
4053 if (ret)
4054 goto out_stop;
4055
4056 first_block = (offset + sb->s_blocksize - 1) >>
4057 EXT4_BLOCK_SIZE_BITS(sb);
4058 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4059
4060 /* If there are blocks to remove, do it */
4061 if (stop_block > first_block) {
4062
4063 down_write(&EXT4_I(inode)->i_data_sem);
4064 ext4_discard_preallocations(inode, 0);
4065
4066 ret = ext4_es_remove_extent(inode, first_block,
4067 stop_block - first_block);
4068 if (ret) {
4069 up_write(&EXT4_I(inode)->i_data_sem);
4070 goto out_stop;
4071 }
4072
4073 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4074 ret = ext4_ext_remove_space(inode, first_block,
4075 stop_block - 1);
4076 else
4077 ret = ext4_ind_remove_space(handle, inode, first_block,
4078 stop_block);
4079
4080 up_write(&EXT4_I(inode)->i_data_sem);
4081 }
4082 ext4_fc_track_range(handle, inode, first_block, stop_block);
4083 if (IS_SYNC(inode))
4084 ext4_handle_sync(handle);
4085
4086 inode->i_mtime = inode->i_ctime = current_time(inode);
4087 ret2 = ext4_mark_inode_dirty(handle, inode);
4088 if (unlikely(ret2))
4089 ret = ret2;
4090 if (ret >= 0)
4091 ext4_update_inode_fsync_trans(handle, inode, 1);
4092 out_stop:
4093 ext4_journal_stop(handle);
4094 out_dio:
4095 up_write(&EXT4_I(inode)->i_mmap_sem);
4096 out_mutex:
4097 inode_unlock(inode);
4098 return ret;
4099 }
4100
ext4_inode_attach_jinode(struct inode * inode)4101 int ext4_inode_attach_jinode(struct inode *inode)
4102 {
4103 struct ext4_inode_info *ei = EXT4_I(inode);
4104 struct jbd2_inode *jinode;
4105
4106 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4107 return 0;
4108
4109 jinode = jbd2_alloc_inode(GFP_KERNEL);
4110 spin_lock(&inode->i_lock);
4111 if (!ei->jinode) {
4112 if (!jinode) {
4113 spin_unlock(&inode->i_lock);
4114 return -ENOMEM;
4115 }
4116 ei->jinode = jinode;
4117 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4118 jinode = NULL;
4119 }
4120 spin_unlock(&inode->i_lock);
4121 if (unlikely(jinode != NULL))
4122 jbd2_free_inode(jinode);
4123 return 0;
4124 }
4125
4126 /*
4127 * ext4_truncate()
4128 *
4129 * We block out ext4_get_block() block instantiations across the entire
4130 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4131 * simultaneously on behalf of the same inode.
4132 *
4133 * As we work through the truncate and commit bits of it to the journal there
4134 * is one core, guiding principle: the file's tree must always be consistent on
4135 * disk. We must be able to restart the truncate after a crash.
4136 *
4137 * The file's tree may be transiently inconsistent in memory (although it
4138 * probably isn't), but whenever we close off and commit a journal transaction,
4139 * the contents of (the filesystem + the journal) must be consistent and
4140 * restartable. It's pretty simple, really: bottom up, right to left (although
4141 * left-to-right works OK too).
4142 *
4143 * Note that at recovery time, journal replay occurs *before* the restart of
4144 * truncate against the orphan inode list.
4145 *
4146 * The committed inode has the new, desired i_size (which is the same as
4147 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4148 * that this inode's truncate did not complete and it will again call
4149 * ext4_truncate() to have another go. So there will be instantiated blocks
4150 * to the right of the truncation point in a crashed ext4 filesystem. But
4151 * that's fine - as long as they are linked from the inode, the post-crash
4152 * ext4_truncate() run will find them and release them.
4153 */
ext4_truncate(struct inode * inode)4154 int ext4_truncate(struct inode *inode)
4155 {
4156 struct ext4_inode_info *ei = EXT4_I(inode);
4157 unsigned int credits;
4158 int err = 0, err2;
4159 handle_t *handle;
4160 struct address_space *mapping = inode->i_mapping;
4161
4162 /*
4163 * There is a possibility that we're either freeing the inode
4164 * or it's a completely new inode. In those cases we might not
4165 * have i_mutex locked because it's not necessary.
4166 */
4167 if (!(inode->i_state & (I_NEW|I_FREEING)))
4168 WARN_ON(!inode_is_locked(inode));
4169 trace_ext4_truncate_enter(inode);
4170
4171 if (!ext4_can_truncate(inode))
4172 goto out_trace;
4173
4174 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4175 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4176
4177 if (ext4_has_inline_data(inode)) {
4178 int has_inline = 1;
4179
4180 err = ext4_inline_data_truncate(inode, &has_inline);
4181 if (err || has_inline)
4182 goto out_trace;
4183 }
4184
4185 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4186 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4187 if (ext4_inode_attach_jinode(inode) < 0)
4188 goto out_trace;
4189 }
4190
4191 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4192 credits = ext4_writepage_trans_blocks(inode);
4193 else
4194 credits = ext4_blocks_for_truncate(inode);
4195
4196 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4197 if (IS_ERR(handle)) {
4198 err = PTR_ERR(handle);
4199 goto out_trace;
4200 }
4201
4202 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4203 ext4_block_truncate_page(handle, mapping, inode->i_size);
4204
4205 /*
4206 * We add the inode to the orphan list, so that if this
4207 * truncate spans multiple transactions, and we crash, we will
4208 * resume the truncate when the filesystem recovers. It also
4209 * marks the inode dirty, to catch the new size.
4210 *
4211 * Implication: the file must always be in a sane, consistent
4212 * truncatable state while each transaction commits.
4213 */
4214 err = ext4_orphan_add(handle, inode);
4215 if (err)
4216 goto out_stop;
4217
4218 down_write(&EXT4_I(inode)->i_data_sem);
4219
4220 ext4_discard_preallocations(inode, 0);
4221
4222 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4223 err = ext4_ext_truncate(handle, inode);
4224 else
4225 ext4_ind_truncate(handle, inode);
4226
4227 up_write(&ei->i_data_sem);
4228 if (err)
4229 goto out_stop;
4230
4231 if (IS_SYNC(inode))
4232 ext4_handle_sync(handle);
4233
4234 out_stop:
4235 /*
4236 * If this was a simple ftruncate() and the file will remain alive,
4237 * then we need to clear up the orphan record which we created above.
4238 * However, if this was a real unlink then we were called by
4239 * ext4_evict_inode(), and we allow that function to clean up the
4240 * orphan info for us.
4241 */
4242 if (inode->i_nlink)
4243 ext4_orphan_del(handle, inode);
4244
4245 inode->i_mtime = inode->i_ctime = current_time(inode);
4246 err2 = ext4_mark_inode_dirty(handle, inode);
4247 if (unlikely(err2 && !err))
4248 err = err2;
4249 ext4_journal_stop(handle);
4250
4251 out_trace:
4252 trace_ext4_truncate_exit(inode);
4253 return err;
4254 }
4255
ext4_inode_peek_iversion(const struct inode * inode)4256 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4257 {
4258 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4259 return inode_peek_iversion_raw(inode);
4260 else
4261 return inode_peek_iversion(inode);
4262 }
4263
ext4_inode_blocks_set(struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4264 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4265 struct ext4_inode_info *ei)
4266 {
4267 struct inode *inode = &(ei->vfs_inode);
4268 u64 i_blocks = READ_ONCE(inode->i_blocks);
4269 struct super_block *sb = inode->i_sb;
4270
4271 if (i_blocks <= ~0U) {
4272 /*
4273 * i_blocks can be represented in a 32 bit variable
4274 * as multiple of 512 bytes
4275 */
4276 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4277 raw_inode->i_blocks_high = 0;
4278 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4279 return 0;
4280 }
4281
4282 /*
4283 * This should never happen since sb->s_maxbytes should not have
4284 * allowed this, sb->s_maxbytes was set according to the huge_file
4285 * feature in ext4_fill_super().
4286 */
4287 if (!ext4_has_feature_huge_file(sb))
4288 return -EFSCORRUPTED;
4289
4290 if (i_blocks <= 0xffffffffffffULL) {
4291 /*
4292 * i_blocks can be represented in a 48 bit variable
4293 * as multiple of 512 bytes
4294 */
4295 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4296 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4297 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4298 } else {
4299 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4300 /* i_block is stored in file system block size */
4301 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4302 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4303 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4304 }
4305 return 0;
4306 }
4307
ext4_fill_raw_inode(struct inode * inode,struct ext4_inode * raw_inode)4308 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4309 {
4310 struct ext4_inode_info *ei = EXT4_I(inode);
4311 uid_t i_uid;
4312 gid_t i_gid;
4313 projid_t i_projid;
4314 int block;
4315 int err;
4316
4317 err = ext4_inode_blocks_set(raw_inode, ei);
4318
4319 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4320 i_uid = i_uid_read(inode);
4321 i_gid = i_gid_read(inode);
4322 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4323 if (!(test_opt(inode->i_sb, NO_UID32))) {
4324 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4325 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4326 /*
4327 * Fix up interoperability with old kernels. Otherwise,
4328 * old inodes get re-used with the upper 16 bits of the
4329 * uid/gid intact.
4330 */
4331 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4332 raw_inode->i_uid_high = 0;
4333 raw_inode->i_gid_high = 0;
4334 } else {
4335 raw_inode->i_uid_high =
4336 cpu_to_le16(high_16_bits(i_uid));
4337 raw_inode->i_gid_high =
4338 cpu_to_le16(high_16_bits(i_gid));
4339 }
4340 } else {
4341 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4342 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4343 raw_inode->i_uid_high = 0;
4344 raw_inode->i_gid_high = 0;
4345 }
4346 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4347
4348 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4349 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4350 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4351 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4352
4353 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4354 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4355 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4356 raw_inode->i_file_acl_high =
4357 cpu_to_le16(ei->i_file_acl >> 32);
4358 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4359 ext4_isize_set(raw_inode, ei->i_disksize);
4360
4361 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4362 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4363 if (old_valid_dev(inode->i_rdev)) {
4364 raw_inode->i_block[0] =
4365 cpu_to_le32(old_encode_dev(inode->i_rdev));
4366 raw_inode->i_block[1] = 0;
4367 } else {
4368 raw_inode->i_block[0] = 0;
4369 raw_inode->i_block[1] =
4370 cpu_to_le32(new_encode_dev(inode->i_rdev));
4371 raw_inode->i_block[2] = 0;
4372 }
4373 } else if (!ext4_has_inline_data(inode)) {
4374 for (block = 0; block < EXT4_N_BLOCKS; block++)
4375 raw_inode->i_block[block] = ei->i_data[block];
4376 }
4377
4378 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4379 u64 ivers = ext4_inode_peek_iversion(inode);
4380
4381 raw_inode->i_disk_version = cpu_to_le32(ivers);
4382 if (ei->i_extra_isize) {
4383 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4384 raw_inode->i_version_hi =
4385 cpu_to_le32(ivers >> 32);
4386 raw_inode->i_extra_isize =
4387 cpu_to_le16(ei->i_extra_isize);
4388 }
4389 }
4390
4391 if (i_projid != EXT4_DEF_PROJID &&
4392 !ext4_has_feature_project(inode->i_sb))
4393 err = err ?: -EFSCORRUPTED;
4394
4395 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4396 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4397 raw_inode->i_projid = cpu_to_le32(i_projid);
4398
4399 ext4_inode_csum_set(inode, raw_inode, ei);
4400 return err;
4401 }
4402
4403 /*
4404 * ext4_get_inode_loc returns with an extra refcount against the inode's
4405 * underlying buffer_head on success. If we pass 'inode' and it does not
4406 * have in-inode xattr, we have all inode data in memory that is needed
4407 * to recreate the on-disk version of this inode.
4408 */
__ext4_get_inode_loc(struct super_block * sb,unsigned long ino,struct inode * inode,struct ext4_iloc * iloc,ext4_fsblk_t * ret_block)4409 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4410 struct inode *inode, struct ext4_iloc *iloc,
4411 ext4_fsblk_t *ret_block)
4412 {
4413 struct ext4_group_desc *gdp;
4414 struct buffer_head *bh;
4415 ext4_fsblk_t block;
4416 struct blk_plug plug;
4417 int inodes_per_block, inode_offset;
4418
4419 iloc->bh = NULL;
4420 if (ino < EXT4_ROOT_INO ||
4421 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4422 return -EFSCORRUPTED;
4423
4424 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4425 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4426 if (!gdp)
4427 return -EIO;
4428
4429 /*
4430 * Figure out the offset within the block group inode table
4431 */
4432 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4433 inode_offset = ((ino - 1) %
4434 EXT4_INODES_PER_GROUP(sb));
4435 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4436 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4437
4438 bh = sb_getblk(sb, block);
4439 if (unlikely(!bh))
4440 return -ENOMEM;
4441 if (!buffer_uptodate(bh)) {
4442 lock_buffer(bh);
4443
4444 if (ext4_buffer_uptodate(bh)) {
4445 /* someone brought it uptodate while we waited */
4446 unlock_buffer(bh);
4447 goto has_buffer;
4448 }
4449
4450 /*
4451 * If we have all information of the inode in memory and this
4452 * is the only valid inode in the block, we need not read the
4453 * block.
4454 */
4455 if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4456 struct buffer_head *bitmap_bh;
4457 int i, start;
4458
4459 start = inode_offset & ~(inodes_per_block - 1);
4460
4461 /* Is the inode bitmap in cache? */
4462 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4463 if (unlikely(!bitmap_bh))
4464 goto make_io;
4465
4466 /*
4467 * If the inode bitmap isn't in cache then the
4468 * optimisation may end up performing two reads instead
4469 * of one, so skip it.
4470 */
4471 if (!buffer_uptodate(bitmap_bh)) {
4472 brelse(bitmap_bh);
4473 goto make_io;
4474 }
4475 for (i = start; i < start + inodes_per_block; i++) {
4476 if (i == inode_offset)
4477 continue;
4478 if (ext4_test_bit(i, bitmap_bh->b_data))
4479 break;
4480 }
4481 brelse(bitmap_bh);
4482 if (i == start + inodes_per_block) {
4483 struct ext4_inode *raw_inode =
4484 (struct ext4_inode *) (bh->b_data + iloc->offset);
4485
4486 /* all other inodes are free, so skip I/O */
4487 memset(bh->b_data, 0, bh->b_size);
4488 if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4489 ext4_fill_raw_inode(inode, raw_inode);
4490 set_buffer_uptodate(bh);
4491 unlock_buffer(bh);
4492 goto has_buffer;
4493 }
4494 }
4495
4496 make_io:
4497 /*
4498 * If we need to do any I/O, try to pre-readahead extra
4499 * blocks from the inode table.
4500 */
4501 blk_start_plug(&plug);
4502 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4503 ext4_fsblk_t b, end, table;
4504 unsigned num;
4505 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4506
4507 table = ext4_inode_table(sb, gdp);
4508 /* s_inode_readahead_blks is always a power of 2 */
4509 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4510 if (table > b)
4511 b = table;
4512 end = b + ra_blks;
4513 num = EXT4_INODES_PER_GROUP(sb);
4514 if (ext4_has_group_desc_csum(sb))
4515 num -= ext4_itable_unused_count(sb, gdp);
4516 table += num / inodes_per_block;
4517 if (end > table)
4518 end = table;
4519 while (b <= end)
4520 ext4_sb_breadahead_unmovable(sb, b++);
4521 }
4522
4523 /*
4524 * There are other valid inodes in the buffer, this inode
4525 * has in-inode xattrs, or we don't have this inode in memory.
4526 * Read the block from disk.
4527 */
4528 trace_ext4_load_inode(sb, ino);
4529 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4530 blk_finish_plug(&plug);
4531 wait_on_buffer(bh);
4532 ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4533 if (!buffer_uptodate(bh)) {
4534 if (ret_block)
4535 *ret_block = block;
4536 brelse(bh);
4537 return -EIO;
4538 }
4539 }
4540 has_buffer:
4541 iloc->bh = bh;
4542 return 0;
4543 }
4544
__ext4_get_inode_loc_noinmem(struct inode * inode,struct ext4_iloc * iloc)4545 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4546 struct ext4_iloc *iloc)
4547 {
4548 ext4_fsblk_t err_blk = 0;
4549 int ret;
4550
4551 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4552 &err_blk);
4553
4554 if (ret == -EIO)
4555 ext4_error_inode_block(inode, err_blk, EIO,
4556 "unable to read itable block");
4557
4558 return ret;
4559 }
4560
ext4_get_inode_loc(struct inode * inode,struct ext4_iloc * iloc)4561 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4562 {
4563 ext4_fsblk_t err_blk = 0;
4564 int ret;
4565
4566 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4567 &err_blk);
4568
4569 if (ret == -EIO)
4570 ext4_error_inode_block(inode, err_blk, EIO,
4571 "unable to read itable block");
4572
4573 return ret;
4574 }
4575
4576
ext4_get_fc_inode_loc(struct super_block * sb,unsigned long ino,struct ext4_iloc * iloc)4577 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4578 struct ext4_iloc *iloc)
4579 {
4580 return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4581 }
4582
ext4_should_enable_dax(struct inode * inode)4583 static bool ext4_should_enable_dax(struct inode *inode)
4584 {
4585 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4586
4587 if (test_opt2(inode->i_sb, DAX_NEVER))
4588 return false;
4589 if (!S_ISREG(inode->i_mode))
4590 return false;
4591 if (ext4_should_journal_data(inode))
4592 return false;
4593 if (ext4_has_inline_data(inode))
4594 return false;
4595 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4596 return false;
4597 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4598 return false;
4599 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4600 return false;
4601 if (test_opt(inode->i_sb, DAX_ALWAYS))
4602 return true;
4603
4604 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4605 }
4606
ext4_set_inode_flags(struct inode * inode,bool init)4607 void ext4_set_inode_flags(struct inode *inode, bool init)
4608 {
4609 unsigned int flags = EXT4_I(inode)->i_flags;
4610 unsigned int new_fl = 0;
4611
4612 WARN_ON_ONCE(IS_DAX(inode) && init);
4613
4614 if (flags & EXT4_SYNC_FL)
4615 new_fl |= S_SYNC;
4616 if (flags & EXT4_APPEND_FL)
4617 new_fl |= S_APPEND;
4618 if (flags & EXT4_IMMUTABLE_FL)
4619 new_fl |= S_IMMUTABLE;
4620 if (flags & EXT4_NOATIME_FL)
4621 new_fl |= S_NOATIME;
4622 if (flags & EXT4_DIRSYNC_FL)
4623 new_fl |= S_DIRSYNC;
4624
4625 /* Because of the way inode_set_flags() works we must preserve S_DAX
4626 * here if already set. */
4627 new_fl |= (inode->i_flags & S_DAX);
4628 if (init && ext4_should_enable_dax(inode))
4629 new_fl |= S_DAX;
4630
4631 if (flags & EXT4_ENCRYPT_FL)
4632 new_fl |= S_ENCRYPTED;
4633 if (flags & EXT4_CASEFOLD_FL)
4634 new_fl |= S_CASEFOLD;
4635 if (flags & EXT4_VERITY_FL)
4636 new_fl |= S_VERITY;
4637 inode_set_flags(inode, new_fl,
4638 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4639 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4640 }
4641
ext4_inode_blocks(struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4642 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4643 struct ext4_inode_info *ei)
4644 {
4645 blkcnt_t i_blocks ;
4646 struct inode *inode = &(ei->vfs_inode);
4647 struct super_block *sb = inode->i_sb;
4648
4649 if (ext4_has_feature_huge_file(sb)) {
4650 /* we are using combined 48 bit field */
4651 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4652 le32_to_cpu(raw_inode->i_blocks_lo);
4653 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4654 /* i_blocks represent file system block size */
4655 return i_blocks << (inode->i_blkbits - 9);
4656 } else {
4657 return i_blocks;
4658 }
4659 } else {
4660 return le32_to_cpu(raw_inode->i_blocks_lo);
4661 }
4662 }
4663
ext4_iget_extra_inode(struct inode * inode,struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4664 static inline int ext4_iget_extra_inode(struct inode *inode,
4665 struct ext4_inode *raw_inode,
4666 struct ext4_inode_info *ei)
4667 {
4668 __le32 *magic = (void *)raw_inode +
4669 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4670
4671 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
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 EXT_MAX_BLOCKS - 1);
5448 else
5449 ext4_fc_track_range(
5450 handle, inode,
5451 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5452 inode->i_sb->s_blocksize_bits,
5453 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5454 inode->i_sb->s_blocksize_bits);
5455
5456 down_write(&EXT4_I(inode)->i_data_sem);
5457 EXT4_I(inode)->i_disksize = attr->ia_size;
5458 rc = ext4_mark_inode_dirty(handle, inode);
5459 if (!error)
5460 error = rc;
5461 /*
5462 * We have to update i_size under i_data_sem together
5463 * with i_disksize to avoid races with writeback code
5464 * running ext4_wb_update_i_disksize().
5465 */
5466 if (!error)
5467 i_size_write(inode, attr->ia_size);
5468 up_write(&EXT4_I(inode)->i_data_sem);
5469 ext4_journal_stop(handle);
5470 if (error)
5471 goto out_mmap_sem;
5472 if (!shrink) {
5473 pagecache_isize_extended(inode, oldsize,
5474 inode->i_size);
5475 } else if (ext4_should_journal_data(inode)) {
5476 ext4_wait_for_tail_page_commit(inode);
5477 }
5478 }
5479
5480 /*
5481 * Truncate pagecache after we've waited for commit
5482 * in data=journal mode to make pages freeable.
5483 */
5484 truncate_pagecache(inode, inode->i_size);
5485 /*
5486 * Call ext4_truncate() even if i_size didn't change to
5487 * truncate possible preallocated blocks.
5488 */
5489 if (attr->ia_size <= oldsize) {
5490 rc = ext4_truncate(inode);
5491 if (rc)
5492 error = rc;
5493 }
5494 out_mmap_sem:
5495 up_write(&EXT4_I(inode)->i_mmap_sem);
5496 }
5497
5498 if (!error) {
5499 setattr_copy(inode, attr);
5500 mark_inode_dirty(inode);
5501 }
5502
5503 /*
5504 * If the call to ext4_truncate failed to get a transaction handle at
5505 * all, we need to clean up the in-core orphan list manually.
5506 */
5507 if (orphan && inode->i_nlink)
5508 ext4_orphan_del(NULL, inode);
5509
5510 if (!error && (ia_valid & ATTR_MODE))
5511 rc = posix_acl_chmod(inode, inode->i_mode);
5512
5513 err_out:
5514 if (error)
5515 ext4_std_error(inode->i_sb, error);
5516 if (!error)
5517 error = rc;
5518 ext4_fc_stop_update(inode);
5519 return error;
5520 }
5521
ext4_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5522 int ext4_getattr(const struct path *path, struct kstat *stat,
5523 u32 request_mask, unsigned int query_flags)
5524 {
5525 struct inode *inode = d_inode(path->dentry);
5526 struct ext4_inode *raw_inode;
5527 struct ext4_inode_info *ei = EXT4_I(inode);
5528 unsigned int flags;
5529
5530 if ((request_mask & STATX_BTIME) &&
5531 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5532 stat->result_mask |= STATX_BTIME;
5533 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5534 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5535 }
5536
5537 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5538 if (flags & EXT4_APPEND_FL)
5539 stat->attributes |= STATX_ATTR_APPEND;
5540 if (flags & EXT4_COMPR_FL)
5541 stat->attributes |= STATX_ATTR_COMPRESSED;
5542 if (flags & EXT4_ENCRYPT_FL)
5543 stat->attributes |= STATX_ATTR_ENCRYPTED;
5544 if (flags & EXT4_IMMUTABLE_FL)
5545 stat->attributes |= STATX_ATTR_IMMUTABLE;
5546 if (flags & EXT4_NODUMP_FL)
5547 stat->attributes |= STATX_ATTR_NODUMP;
5548 if (flags & EXT4_VERITY_FL)
5549 stat->attributes |= STATX_ATTR_VERITY;
5550
5551 stat->attributes_mask |= (STATX_ATTR_APPEND |
5552 STATX_ATTR_COMPRESSED |
5553 STATX_ATTR_ENCRYPTED |
5554 STATX_ATTR_IMMUTABLE |
5555 STATX_ATTR_NODUMP |
5556 STATX_ATTR_VERITY);
5557
5558 generic_fillattr(inode, stat);
5559 return 0;
5560 }
5561
ext4_file_getattr(const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5562 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5563 u32 request_mask, unsigned int query_flags)
5564 {
5565 struct inode *inode = d_inode(path->dentry);
5566 u64 delalloc_blocks;
5567
5568 ext4_getattr(path, stat, request_mask, query_flags);
5569
5570 /*
5571 * If there is inline data in the inode, the inode will normally not
5572 * have data blocks allocated (it may have an external xattr block).
5573 * Report at least one sector for such files, so tools like tar, rsync,
5574 * others don't incorrectly think the file is completely sparse.
5575 */
5576 if (unlikely(ext4_has_inline_data(inode)))
5577 stat->blocks += (stat->size + 511) >> 9;
5578
5579 /*
5580 * We can't update i_blocks if the block allocation is delayed
5581 * otherwise in the case of system crash before the real block
5582 * allocation is done, we will have i_blocks inconsistent with
5583 * on-disk file blocks.
5584 * We always keep i_blocks updated together with real
5585 * allocation. But to not confuse with user, stat
5586 * will return the blocks that include the delayed allocation
5587 * blocks for this file.
5588 */
5589 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5590 EXT4_I(inode)->i_reserved_data_blocks);
5591 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5592 return 0;
5593 }
5594
ext4_index_trans_blocks(struct inode * inode,int lblocks,int pextents)5595 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5596 int pextents)
5597 {
5598 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5599 return ext4_ind_trans_blocks(inode, lblocks);
5600 return ext4_ext_index_trans_blocks(inode, pextents);
5601 }
5602
5603 /*
5604 * Account for index blocks, block groups bitmaps and block group
5605 * descriptor blocks if modify datablocks and index blocks
5606 * worse case, the indexs blocks spread over different block groups
5607 *
5608 * If datablocks are discontiguous, they are possible to spread over
5609 * different block groups too. If they are contiguous, with flexbg,
5610 * they could still across block group boundary.
5611 *
5612 * Also account for superblock, inode, quota and xattr blocks
5613 */
ext4_meta_trans_blocks(struct inode * inode,int lblocks,int pextents)5614 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5615 int pextents)
5616 {
5617 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5618 int gdpblocks;
5619 int idxblocks;
5620 int ret = 0;
5621
5622 /*
5623 * How many index blocks need to touch to map @lblocks logical blocks
5624 * to @pextents physical extents?
5625 */
5626 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5627
5628 ret = idxblocks;
5629
5630 /*
5631 * Now let's see how many group bitmaps and group descriptors need
5632 * to account
5633 */
5634 groups = idxblocks + pextents;
5635 gdpblocks = groups;
5636 if (groups > ngroups)
5637 groups = ngroups;
5638 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5639 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5640
5641 /* bitmaps and block group descriptor blocks */
5642 ret += groups + gdpblocks;
5643
5644 /* Blocks for super block, inode, quota and xattr blocks */
5645 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5646
5647 return ret;
5648 }
5649
5650 /*
5651 * Calculate the total number of credits to reserve to fit
5652 * the modification of a single pages into a single transaction,
5653 * which may include multiple chunks of block allocations.
5654 *
5655 * This could be called via ext4_write_begin()
5656 *
5657 * We need to consider the worse case, when
5658 * one new block per extent.
5659 */
ext4_writepage_trans_blocks(struct inode * inode)5660 int ext4_writepage_trans_blocks(struct inode *inode)
5661 {
5662 int bpp = ext4_journal_blocks_per_page(inode);
5663 int ret;
5664
5665 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5666
5667 /* Account for data blocks for journalled mode */
5668 if (ext4_should_journal_data(inode))
5669 ret += bpp;
5670 return ret;
5671 }
5672
5673 /*
5674 * Calculate the journal credits for a chunk of data modification.
5675 *
5676 * This is called from DIO, fallocate or whoever calling
5677 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5678 *
5679 * journal buffers for data blocks are not included here, as DIO
5680 * and fallocate do no need to journal data buffers.
5681 */
ext4_chunk_trans_blocks(struct inode * inode,int nrblocks)5682 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5683 {
5684 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5685 }
5686
5687 /*
5688 * The caller must have previously called ext4_reserve_inode_write().
5689 * Give this, we know that the caller already has write access to iloc->bh.
5690 */
ext4_mark_iloc_dirty(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5691 int ext4_mark_iloc_dirty(handle_t *handle,
5692 struct inode *inode, struct ext4_iloc *iloc)
5693 {
5694 int err = 0;
5695
5696 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5697 put_bh(iloc->bh);
5698 return -EIO;
5699 }
5700 ext4_fc_track_inode(handle, inode);
5701
5702 if (IS_I_VERSION(inode))
5703 inode_inc_iversion(inode);
5704
5705 /* the do_update_inode consumes one bh->b_count */
5706 get_bh(iloc->bh);
5707
5708 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5709 err = ext4_do_update_inode(handle, inode, iloc);
5710 put_bh(iloc->bh);
5711 return err;
5712 }
5713
5714 /*
5715 * On success, We end up with an outstanding reference count against
5716 * iloc->bh. This _must_ be cleaned up later.
5717 */
5718
5719 int
ext4_reserve_inode_write(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5720 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5721 struct ext4_iloc *iloc)
5722 {
5723 int err;
5724
5725 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5726 return -EIO;
5727
5728 err = ext4_get_inode_loc(inode, iloc);
5729 if (!err) {
5730 BUFFER_TRACE(iloc->bh, "get_write_access");
5731 err = ext4_journal_get_write_access(handle, iloc->bh);
5732 if (err) {
5733 brelse(iloc->bh);
5734 iloc->bh = NULL;
5735 }
5736 }
5737 ext4_std_error(inode->i_sb, err);
5738 return err;
5739 }
5740
__ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc,handle_t * handle,int * no_expand)5741 static int __ext4_expand_extra_isize(struct inode *inode,
5742 unsigned int new_extra_isize,
5743 struct ext4_iloc *iloc,
5744 handle_t *handle, int *no_expand)
5745 {
5746 struct ext4_inode *raw_inode;
5747 struct ext4_xattr_ibody_header *header;
5748 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5749 struct ext4_inode_info *ei = EXT4_I(inode);
5750 int error;
5751
5752 /* this was checked at iget time, but double check for good measure */
5753 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5754 (ei->i_extra_isize & 3)) {
5755 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5756 ei->i_extra_isize,
5757 EXT4_INODE_SIZE(inode->i_sb));
5758 return -EFSCORRUPTED;
5759 }
5760 if ((new_extra_isize < ei->i_extra_isize) ||
5761 (new_extra_isize < 4) ||
5762 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5763 return -EINVAL; /* Should never happen */
5764
5765 raw_inode = ext4_raw_inode(iloc);
5766
5767 header = IHDR(inode, raw_inode);
5768
5769 /* No extended attributes present */
5770 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5771 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5772 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5773 EXT4_I(inode)->i_extra_isize, 0,
5774 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5775 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5776 return 0;
5777 }
5778
5779 /* try to expand with EAs present */
5780 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5781 raw_inode, handle);
5782 if (error) {
5783 /*
5784 * Inode size expansion failed; don't try again
5785 */
5786 *no_expand = 1;
5787 }
5788
5789 return error;
5790 }
5791
5792 /*
5793 * Expand an inode by new_extra_isize bytes.
5794 * Returns 0 on success or negative error number on failure.
5795 */
ext4_try_to_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc iloc,handle_t * handle)5796 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5797 unsigned int new_extra_isize,
5798 struct ext4_iloc iloc,
5799 handle_t *handle)
5800 {
5801 int no_expand;
5802 int error;
5803
5804 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5805 return -EOVERFLOW;
5806
5807 /*
5808 * In nojournal mode, we can immediately attempt to expand
5809 * the inode. When journaled, we first need to obtain extra
5810 * buffer credits since we may write into the EA block
5811 * with this same handle. If journal_extend fails, then it will
5812 * only result in a minor loss of functionality for that inode.
5813 * If this is felt to be critical, then e2fsck should be run to
5814 * force a large enough s_min_extra_isize.
5815 */
5816 if (ext4_journal_extend(handle,
5817 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5818 return -ENOSPC;
5819
5820 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5821 return -EBUSY;
5822
5823 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5824 handle, &no_expand);
5825 ext4_write_unlock_xattr(inode, &no_expand);
5826
5827 return error;
5828 }
5829
ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc)5830 int ext4_expand_extra_isize(struct inode *inode,
5831 unsigned int new_extra_isize,
5832 struct ext4_iloc *iloc)
5833 {
5834 handle_t *handle;
5835 int no_expand;
5836 int error, rc;
5837
5838 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5839 brelse(iloc->bh);
5840 return -EOVERFLOW;
5841 }
5842
5843 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5844 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5845 if (IS_ERR(handle)) {
5846 error = PTR_ERR(handle);
5847 brelse(iloc->bh);
5848 return error;
5849 }
5850
5851 ext4_write_lock_xattr(inode, &no_expand);
5852
5853 BUFFER_TRACE(iloc->bh, "get_write_access");
5854 error = ext4_journal_get_write_access(handle, iloc->bh);
5855 if (error) {
5856 brelse(iloc->bh);
5857 goto out_unlock;
5858 }
5859
5860 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5861 handle, &no_expand);
5862
5863 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5864 if (!error)
5865 error = rc;
5866
5867 out_unlock:
5868 ext4_write_unlock_xattr(inode, &no_expand);
5869 ext4_journal_stop(handle);
5870 return error;
5871 }
5872
5873 /*
5874 * What we do here is to mark the in-core inode as clean with respect to inode
5875 * dirtiness (it may still be data-dirty).
5876 * This means that the in-core inode may be reaped by prune_icache
5877 * without having to perform any I/O. This is a very good thing,
5878 * because *any* task may call prune_icache - even ones which
5879 * have a transaction open against a different journal.
5880 *
5881 * Is this cheating? Not really. Sure, we haven't written the
5882 * inode out, but prune_icache isn't a user-visible syncing function.
5883 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5884 * we start and wait on commits.
5885 */
__ext4_mark_inode_dirty(handle_t * handle,struct inode * inode,const char * func,unsigned int line)5886 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5887 const char *func, unsigned int line)
5888 {
5889 struct ext4_iloc iloc;
5890 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5891 int err;
5892
5893 might_sleep();
5894 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5895 err = ext4_reserve_inode_write(handle, inode, &iloc);
5896 if (err)
5897 goto out;
5898
5899 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5900 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5901 iloc, handle);
5902
5903 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5904 out:
5905 if (unlikely(err))
5906 ext4_error_inode_err(inode, func, line, 0, err,
5907 "mark_inode_dirty error");
5908 return err;
5909 }
5910
5911 /*
5912 * ext4_dirty_inode() is called from __mark_inode_dirty()
5913 *
5914 * We're really interested in the case where a file is being extended.
5915 * i_size has been changed by generic_commit_write() and we thus need
5916 * to include the updated inode in the current transaction.
5917 *
5918 * Also, dquot_alloc_block() will always dirty the inode when blocks
5919 * are allocated to the file.
5920 *
5921 * If the inode is marked synchronous, we don't honour that here - doing
5922 * so would cause a commit on atime updates, which we don't bother doing.
5923 * We handle synchronous inodes at the highest possible level.
5924 *
5925 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5926 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5927 * to copy into the on-disk inode structure are the timestamp files.
5928 */
ext4_dirty_inode(struct inode * inode,int flags)5929 void ext4_dirty_inode(struct inode *inode, int flags)
5930 {
5931 handle_t *handle;
5932
5933 if (flags == I_DIRTY_TIME)
5934 return;
5935 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5936 if (IS_ERR(handle))
5937 goto out;
5938
5939 ext4_mark_inode_dirty(handle, inode);
5940
5941 ext4_journal_stop(handle);
5942 out:
5943 return;
5944 }
5945
ext4_change_inode_journal_flag(struct inode * inode,int val)5946 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5947 {
5948 journal_t *journal;
5949 handle_t *handle;
5950 int err;
5951 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5952
5953 /*
5954 * We have to be very careful here: changing a data block's
5955 * journaling status dynamically is dangerous. If we write a
5956 * data block to the journal, change the status and then delete
5957 * that block, we risk forgetting to revoke the old log record
5958 * from the journal and so a subsequent replay can corrupt data.
5959 * So, first we make sure that the journal is empty and that
5960 * nobody is changing anything.
5961 */
5962
5963 journal = EXT4_JOURNAL(inode);
5964 if (!journal)
5965 return 0;
5966 if (is_journal_aborted(journal))
5967 return -EROFS;
5968
5969 /* Wait for all existing dio workers */
5970 inode_dio_wait(inode);
5971
5972 /*
5973 * Before flushing the journal and switching inode's aops, we have
5974 * to flush all dirty data the inode has. There can be outstanding
5975 * delayed allocations, there can be unwritten extents created by
5976 * fallocate or buffered writes in dioread_nolock mode covered by
5977 * dirty data which can be converted only after flushing the dirty
5978 * data (and journalled aops don't know how to handle these cases).
5979 */
5980 if (val) {
5981 down_write(&EXT4_I(inode)->i_mmap_sem);
5982 err = filemap_write_and_wait(inode->i_mapping);
5983 if (err < 0) {
5984 up_write(&EXT4_I(inode)->i_mmap_sem);
5985 return err;
5986 }
5987 }
5988
5989 percpu_down_write(&sbi->s_writepages_rwsem);
5990 jbd2_journal_lock_updates(journal);
5991
5992 /*
5993 * OK, there are no updates running now, and all cached data is
5994 * synced to disk. We are now in a completely consistent state
5995 * which doesn't have anything in the journal, and we know that
5996 * no filesystem updates are running, so it is safe to modify
5997 * the inode's in-core data-journaling state flag now.
5998 */
5999
6000 if (val)
6001 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6002 else {
6003 err = jbd2_journal_flush(journal);
6004 if (err < 0) {
6005 jbd2_journal_unlock_updates(journal);
6006 percpu_up_write(&sbi->s_writepages_rwsem);
6007 return err;
6008 }
6009 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6010 }
6011 ext4_set_aops(inode);
6012
6013 jbd2_journal_unlock_updates(journal);
6014 percpu_up_write(&sbi->s_writepages_rwsem);
6015
6016 if (val)
6017 up_write(&EXT4_I(inode)->i_mmap_sem);
6018
6019 /* Finally we can mark the inode as dirty. */
6020
6021 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6022 if (IS_ERR(handle))
6023 return PTR_ERR(handle);
6024
6025 ext4_fc_mark_ineligible(inode->i_sb,
6026 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
6027 err = ext4_mark_inode_dirty(handle, inode);
6028 ext4_handle_sync(handle);
6029 ext4_journal_stop(handle);
6030 ext4_std_error(inode->i_sb, err);
6031
6032 return err;
6033 }
6034
ext4_bh_unmapped(handle_t * handle,struct buffer_head * bh)6035 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6036 {
6037 return !buffer_mapped(bh);
6038 }
6039
ext4_page_mkwrite(struct vm_fault * vmf)6040 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6041 {
6042 struct vm_area_struct *vma = vmf->vma;
6043 struct page *page = vmf->page;
6044 loff_t size;
6045 unsigned long len;
6046 int err;
6047 vm_fault_t ret;
6048 struct file *file = vma->vm_file;
6049 struct inode *inode = file_inode(file);
6050 struct address_space *mapping = inode->i_mapping;
6051 handle_t *handle;
6052 get_block_t *get_block;
6053 int retries = 0;
6054
6055 if (unlikely(IS_IMMUTABLE(inode)))
6056 return VM_FAULT_SIGBUS;
6057
6058 sb_start_pagefault(inode->i_sb);
6059 file_update_time(vma->vm_file);
6060
6061 down_read(&EXT4_I(inode)->i_mmap_sem);
6062
6063 err = ext4_convert_inline_data(inode);
6064 if (err)
6065 goto out_ret;
6066
6067 /*
6068 * On data journalling we skip straight to the transaction handle:
6069 * there's no delalloc; page truncated will be checked later; the
6070 * early return w/ all buffers mapped (calculates size/len) can't
6071 * be used; and there's no dioread_nolock, so only ext4_get_block.
6072 */
6073 if (ext4_should_journal_data(inode))
6074 goto retry_alloc;
6075
6076 /* Delalloc case is easy... */
6077 if (test_opt(inode->i_sb, DELALLOC) &&
6078 !ext4_nonda_switch(inode->i_sb)) {
6079 do {
6080 err = block_page_mkwrite(vma, vmf,
6081 ext4_da_get_block_prep);
6082 } while (err == -ENOSPC &&
6083 ext4_should_retry_alloc(inode->i_sb, &retries));
6084 goto out_ret;
6085 }
6086
6087 lock_page(page);
6088 size = i_size_read(inode);
6089 /* Page got truncated from under us? */
6090 if (page->mapping != mapping || page_offset(page) > size) {
6091 unlock_page(page);
6092 ret = VM_FAULT_NOPAGE;
6093 goto out;
6094 }
6095
6096 if (page->index == size >> PAGE_SHIFT)
6097 len = size & ~PAGE_MASK;
6098 else
6099 len = PAGE_SIZE;
6100 /*
6101 * Return if we have all the buffers mapped. This avoids the need to do
6102 * journal_start/journal_stop which can block and take a long time
6103 *
6104 * This cannot be done for data journalling, as we have to add the
6105 * inode to the transaction's list to writeprotect pages on commit.
6106 */
6107 if (page_has_buffers(page)) {
6108 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6109 0, len, NULL,
6110 ext4_bh_unmapped)) {
6111 /* Wait so that we don't change page under IO */
6112 wait_for_stable_page(page);
6113 ret = VM_FAULT_LOCKED;
6114 goto out;
6115 }
6116 }
6117 unlock_page(page);
6118 /* OK, we need to fill the hole... */
6119 if (ext4_should_dioread_nolock(inode))
6120 get_block = ext4_get_block_unwritten;
6121 else
6122 get_block = ext4_get_block;
6123 retry_alloc:
6124 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6125 ext4_writepage_trans_blocks(inode));
6126 if (IS_ERR(handle)) {
6127 ret = VM_FAULT_SIGBUS;
6128 goto out;
6129 }
6130 /*
6131 * Data journalling can't use block_page_mkwrite() because it
6132 * will set_buffer_dirty() before do_journal_get_write_access()
6133 * thus might hit warning messages for dirty metadata buffers.
6134 */
6135 if (!ext4_should_journal_data(inode)) {
6136 err = block_page_mkwrite(vma, vmf, get_block);
6137 } else {
6138 lock_page(page);
6139 size = i_size_read(inode);
6140 /* Page got truncated from under us? */
6141 if (page->mapping != mapping || page_offset(page) > size) {
6142 ret = VM_FAULT_NOPAGE;
6143 goto out_error;
6144 }
6145
6146 if (page->index == size >> PAGE_SHIFT)
6147 len = size & ~PAGE_MASK;
6148 else
6149 len = PAGE_SIZE;
6150
6151 err = __block_write_begin(page, 0, len, ext4_get_block);
6152 if (!err) {
6153 ret = VM_FAULT_SIGBUS;
6154 if (ext4_walk_page_buffers(handle, page_buffers(page),
6155 0, len, NULL, do_journal_get_write_access))
6156 goto out_error;
6157 if (ext4_walk_page_buffers(handle, page_buffers(page),
6158 0, len, NULL, write_end_fn))
6159 goto out_error;
6160 if (ext4_jbd2_inode_add_write(handle, inode,
6161 page_offset(page), len))
6162 goto out_error;
6163 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6164 } else {
6165 unlock_page(page);
6166 }
6167 }
6168 ext4_journal_stop(handle);
6169 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6170 goto retry_alloc;
6171 out_ret:
6172 ret = block_page_mkwrite_return(err);
6173 out:
6174 up_read(&EXT4_I(inode)->i_mmap_sem);
6175 sb_end_pagefault(inode->i_sb);
6176 return ret;
6177 out_error:
6178 unlock_page(page);
6179 ext4_journal_stop(handle);
6180 goto out;
6181 }
6182
ext4_filemap_fault(struct vm_fault * vmf)6183 vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6184 {
6185 struct inode *inode = file_inode(vmf->vma->vm_file);
6186 vm_fault_t ret;
6187
6188 down_read(&EXT4_I(inode)->i_mmap_sem);
6189 ret = filemap_fault(vmf);
6190 up_read(&EXT4_I(inode)->i_mmap_sem);
6191
6192 return ret;
6193 }
6194