1 // SPDX-License-Identifier: GPL-2.0
3 * linux/fs/ext4/inode.c
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)
12 * linux/fs/minix/inode.c
14 * Copyright (C) 1991, 1992 Linus Torvalds
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
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>
43 #include "ext4_jbd2.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
58 int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 unsigned int csum_size = sizeof(dummy_csum);
61 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
64 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 EXT4_GOOD_OLD_INODE_SIZE - offset);
67 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 offset = offsetof(struct ext4_inode, i_checksum_hi);
69 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 EXT4_GOOD_OLD_INODE_SIZE,
71 offset - EXT4_GOOD_OLD_INODE_SIZE);
72 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
77 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 EXT4_INODE_SIZE(inode->i_sb) - offset);
84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 struct ext4_inode_info *ei)
87 __u32 provided, calculated;
89 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 cpu_to_le32(EXT4_OS_LINUX) ||
91 !ext4_has_metadata_csum(inode->i_sb))
94 provided = le16_to_cpu(raw->i_checksum_lo);
95 calculated = ext4_inode_csum(inode, raw, ei);
96 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 calculated &= 0xFFFF;
102 return provided == calculated;
105 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 struct ext4_inode_info *ei)
110 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 cpu_to_le32(EXT4_OS_LINUX) ||
112 !ext4_has_metadata_csum(inode->i_sb))
115 csum = ext4_inode_csum(inode, raw, ei);
116 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
125 trace_ext4_begin_ordered_truncate(inode, new_size);
127 * If jinode is zero, then we never opened the file for
128 * writing, so there's no need to call
129 * jbd2_journal_begin_ordered_truncate() since there's no
130 * outstanding writes we need to flush.
132 if (!EXT4_I(inode)->jinode)
134 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 EXT4_I(inode)->jinode,
139 static void ext4_invalidatepage(struct page *page, unsigned int offset,
140 unsigned int length);
141 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
142 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
143 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
147 * Test whether an inode is a fast symlink.
148 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
150 int ext4_inode_is_fast_symlink(struct inode *inode)
152 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
153 int ea_blocks = EXT4_I(inode)->i_file_acl ?
154 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
156 if (ext4_has_inline_data(inode))
159 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
161 return S_ISLNK(inode->i_mode) && inode->i_size &&
162 (inode->i_size < EXT4_N_BLOCKS * 4);
166 * Restart the transaction associated with *handle. This does a commit,
167 * so before we call here everything must be consistently dirtied against
170 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
176 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
177 * moment, get_block can be called only for blocks inside i_size since
178 * page cache has been already dropped and writes are blocked by
179 * i_mutex. So we can safely drop the i_data_sem here.
181 BUG_ON(EXT4_JOURNAL(inode) == NULL);
182 jbd_debug(2, "restarting handle %p\n", handle);
183 up_write(&EXT4_I(inode)->i_data_sem);
184 ret = ext4_journal_restart(handle, nblocks);
185 down_write(&EXT4_I(inode)->i_data_sem);
186 ext4_discard_preallocations(inode);
192 * Called at the last iput() if i_nlink is zero.
194 void ext4_evict_inode(struct inode *inode)
199 * Credits for final inode cleanup and freeing:
200 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
201 * (xattr block freeing), bitmap, group descriptor (inode freeing)
203 int extra_credits = 6;
204 struct ext4_xattr_inode_array *ea_inode_array = NULL;
205 bool freeze_protected = false;
207 trace_ext4_evict_inode(inode);
209 if (inode->i_nlink) {
211 * When journalling data dirty buffers are tracked only in the
212 * journal. So although mm thinks everything is clean and
213 * ready for reaping the inode might still have some pages to
214 * write in the running transaction or waiting to be
215 * checkpointed. Thus calling jbd2_journal_invalidatepage()
216 * (via truncate_inode_pages()) to discard these buffers can
217 * cause data loss. Also even if we did not discard these
218 * buffers, we would have no way to find them after the inode
219 * is reaped and thus user could see stale data if he tries to
220 * read them before the transaction is checkpointed. So be
221 * careful and force everything to disk here... We use
222 * ei->i_datasync_tid to store the newest transaction
223 * containing inode's data.
225 * Note that directories do not have this problem because they
226 * don't use page cache.
228 if (inode->i_ino != EXT4_JOURNAL_INO &&
229 ext4_should_journal_data(inode) &&
230 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
231 inode->i_data.nrpages) {
232 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
233 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
235 jbd2_complete_transaction(journal, commit_tid);
236 filemap_write_and_wait(&inode->i_data);
238 truncate_inode_pages_final(&inode->i_data);
243 if (is_bad_inode(inode))
245 dquot_initialize(inode);
247 if (ext4_should_order_data(inode))
248 ext4_begin_ordered_truncate(inode, 0);
249 truncate_inode_pages_final(&inode->i_data);
252 * Protect us against freezing - iput() caller didn't have to have any
253 * protection against it. When we are in a running transaction though,
254 * we are already protected against freezing and we cannot grab further
255 * protection due to lock ordering constraints.
257 if (!ext4_journal_current_handle()) {
258 sb_start_intwrite(inode->i_sb);
259 freeze_protected = true;
262 if (!IS_NOQUOTA(inode))
263 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
266 * Block bitmap, group descriptor, and inode are accounted in both
267 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
269 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
270 ext4_blocks_for_truncate(inode) + extra_credits - 3);
271 if (IS_ERR(handle)) {
272 ext4_std_error(inode->i_sb, PTR_ERR(handle));
274 * If we're going to skip the normal cleanup, we still need to
275 * make sure that the in-core orphan linked list is properly
278 ext4_orphan_del(NULL, inode);
279 if (freeze_protected)
280 sb_end_intwrite(inode->i_sb);
285 ext4_handle_sync(handle);
288 * Set inode->i_size to 0 before calling ext4_truncate(). We need
289 * special handling of symlinks here because i_size is used to
290 * determine whether ext4_inode_info->i_data contains symlink data or
291 * block mappings. Setting i_size to 0 will remove its fast symlink
292 * status. Erase i_data so that it becomes a valid empty block map.
294 if (ext4_inode_is_fast_symlink(inode))
295 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
297 err = ext4_mark_inode_dirty(handle, inode);
299 ext4_warning(inode->i_sb,
300 "couldn't mark inode dirty (err %d)", err);
303 if (inode->i_blocks) {
304 err = ext4_truncate(inode);
306 ext4_error(inode->i_sb,
307 "couldn't truncate inode %lu (err %d)",
313 /* Remove xattr references. */
314 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
317 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
319 ext4_journal_stop(handle);
320 ext4_orphan_del(NULL, inode);
321 if (freeze_protected)
322 sb_end_intwrite(inode->i_sb);
323 ext4_xattr_inode_array_free(ea_inode_array);
328 * Kill off the orphan record which ext4_truncate created.
329 * AKPM: I think this can be inside the above `if'.
330 * Note that ext4_orphan_del() has to be able to cope with the
331 * deletion of a non-existent orphan - this is because we don't
332 * know if ext4_truncate() actually created an orphan record.
333 * (Well, we could do this if we need to, but heck - it works)
335 ext4_orphan_del(handle, inode);
336 EXT4_I(inode)->i_dtime = get_seconds();
339 * One subtle ordering requirement: if anything has gone wrong
340 * (transaction abort, IO errors, whatever), then we can still
341 * do these next steps (the fs will already have been marked as
342 * having errors), but we can't free the inode if the mark_dirty
345 if (ext4_mark_inode_dirty(handle, inode))
346 /* If that failed, just do the required in-core inode clear. */
347 ext4_clear_inode(inode);
349 ext4_free_inode(handle, inode);
350 ext4_journal_stop(handle);
351 if (freeze_protected)
352 sb_end_intwrite(inode->i_sb);
353 ext4_xattr_inode_array_free(ea_inode_array);
356 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
360 qsize_t *ext4_get_reserved_space(struct inode *inode)
362 return &EXT4_I(inode)->i_reserved_quota;
367 * Called with i_data_sem down, which is important since we can call
368 * ext4_discard_preallocations() from here.
370 void ext4_da_update_reserve_space(struct inode *inode,
371 int used, int quota_claim)
373 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
374 struct ext4_inode_info *ei = EXT4_I(inode);
376 spin_lock(&ei->i_block_reservation_lock);
377 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
378 if (unlikely(used > ei->i_reserved_data_blocks)) {
379 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
380 "with only %d reserved data blocks",
381 __func__, inode->i_ino, used,
382 ei->i_reserved_data_blocks);
384 used = ei->i_reserved_data_blocks;
387 /* Update per-inode reservations */
388 ei->i_reserved_data_blocks -= used;
389 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
391 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
393 /* Update quota subsystem for data blocks */
395 dquot_claim_block(inode, EXT4_C2B(sbi, used));
398 * We did fallocate with an offset that is already delayed
399 * allocated. So on delayed allocated writeback we should
400 * not re-claim the quota for fallocated blocks.
402 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
406 * If we have done all the pending block allocations and if
407 * there aren't any writers on the inode, we can discard the
408 * inode's preallocations.
410 if ((ei->i_reserved_data_blocks == 0) &&
411 (atomic_read(&inode->i_writecount) == 0))
412 ext4_discard_preallocations(inode);
415 static int __check_block_validity(struct inode *inode, const char *func,
417 struct ext4_map_blocks *map)
419 if (ext4_has_feature_journal(inode->i_sb) &&
421 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
423 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
424 ext4_error_inode(inode, func, line, map->m_pblk,
425 "lblock %lu mapped to illegal pblock %llu "
426 "(length %d)", (unsigned long) map->m_lblk,
427 map->m_pblk, map->m_len);
428 return -EFSCORRUPTED;
433 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
438 if (ext4_encrypted_inode(inode))
439 return fscrypt_zeroout_range(inode, lblk, pblk, len);
441 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
448 #define check_block_validity(inode, map) \
449 __check_block_validity((inode), __func__, __LINE__, (map))
451 #ifdef ES_AGGRESSIVE_TEST
452 static void ext4_map_blocks_es_recheck(handle_t *handle,
454 struct ext4_map_blocks *es_map,
455 struct ext4_map_blocks *map,
462 * There is a race window that the result is not the same.
463 * e.g. xfstests #223 when dioread_nolock enables. The reason
464 * is that we lookup a block mapping in extent status tree with
465 * out taking i_data_sem. So at the time the unwritten extent
466 * could be converted.
468 down_read(&EXT4_I(inode)->i_data_sem);
469 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
470 retval = ext4_ext_map_blocks(handle, inode, map, flags &
471 EXT4_GET_BLOCKS_KEEP_SIZE);
473 retval = ext4_ind_map_blocks(handle, inode, map, flags &
474 EXT4_GET_BLOCKS_KEEP_SIZE);
476 up_read((&EXT4_I(inode)->i_data_sem));
479 * We don't check m_len because extent will be collpased in status
480 * tree. So the m_len might not equal.
482 if (es_map->m_lblk != map->m_lblk ||
483 es_map->m_flags != map->m_flags ||
484 es_map->m_pblk != map->m_pblk) {
485 printk("ES cache assertion failed for inode: %lu "
486 "es_cached ex [%d/%d/%llu/%x] != "
487 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
488 inode->i_ino, es_map->m_lblk, es_map->m_len,
489 es_map->m_pblk, es_map->m_flags, map->m_lblk,
490 map->m_len, map->m_pblk, map->m_flags,
494 #endif /* ES_AGGRESSIVE_TEST */
497 * The ext4_map_blocks() function tries to look up the requested blocks,
498 * and returns if the blocks are already mapped.
500 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
501 * and store the allocated blocks in the result buffer head and mark it
504 * If file type is extents based, it will call ext4_ext_map_blocks(),
505 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
508 * On success, it returns the number of blocks being mapped or allocated. if
509 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
510 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
512 * It returns 0 if plain look up failed (blocks have not been allocated), in
513 * that case, @map is returned as unmapped but we still do fill map->m_len to
514 * indicate the length of a hole starting at map->m_lblk.
516 * It returns the error in case of allocation failure.
518 int ext4_map_blocks(handle_t *handle, struct inode *inode,
519 struct ext4_map_blocks *map, int flags)
521 struct extent_status es;
524 #ifdef ES_AGGRESSIVE_TEST
525 struct ext4_map_blocks orig_map;
527 memcpy(&orig_map, map, sizeof(*map));
531 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
532 "logical block %lu\n", inode->i_ino, flags, map->m_len,
533 (unsigned long) map->m_lblk);
536 * ext4_map_blocks returns an int, and m_len is an unsigned int
538 if (unlikely(map->m_len > INT_MAX))
539 map->m_len = INT_MAX;
541 /* We can handle the block number less than EXT_MAX_BLOCKS */
542 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
543 return -EFSCORRUPTED;
545 /* Lookup extent status tree firstly */
546 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
547 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
548 map->m_pblk = ext4_es_pblock(&es) +
549 map->m_lblk - es.es_lblk;
550 map->m_flags |= ext4_es_is_written(&es) ?
551 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
552 retval = es.es_len - (map->m_lblk - es.es_lblk);
553 if (retval > map->m_len)
556 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
558 retval = es.es_len - (map->m_lblk - es.es_lblk);
559 if (retval > map->m_len)
566 #ifdef ES_AGGRESSIVE_TEST
567 ext4_map_blocks_es_recheck(handle, inode, map,
574 * Try to see if we can get the block without requesting a new
577 down_read(&EXT4_I(inode)->i_data_sem);
578 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
579 retval = ext4_ext_map_blocks(handle, inode, map, flags &
580 EXT4_GET_BLOCKS_KEEP_SIZE);
582 retval = ext4_ind_map_blocks(handle, inode, map, flags &
583 EXT4_GET_BLOCKS_KEEP_SIZE);
588 if (unlikely(retval != map->m_len)) {
589 ext4_warning(inode->i_sb,
590 "ES len assertion failed for inode "
591 "%lu: retval %d != map->m_len %d",
592 inode->i_ino, retval, map->m_len);
596 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
597 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
598 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
599 !(status & EXTENT_STATUS_WRITTEN) &&
600 ext4_find_delalloc_range(inode, map->m_lblk,
601 map->m_lblk + map->m_len - 1))
602 status |= EXTENT_STATUS_DELAYED;
603 ret = ext4_es_insert_extent(inode, map->m_lblk,
604 map->m_len, map->m_pblk, status);
608 up_read((&EXT4_I(inode)->i_data_sem));
611 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
612 ret = check_block_validity(inode, map);
617 /* If it is only a block(s) look up */
618 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
622 * Returns if the blocks have already allocated
624 * Note that if blocks have been preallocated
625 * ext4_ext_get_block() returns the create = 0
626 * with buffer head unmapped.
628 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
630 * If we need to convert extent to unwritten
631 * we continue and do the actual work in
632 * ext4_ext_map_blocks()
634 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
638 * Here we clear m_flags because after allocating an new extent,
639 * it will be set again.
641 map->m_flags &= ~EXT4_MAP_FLAGS;
644 * New blocks allocate and/or writing to unwritten extent
645 * will possibly result in updating i_data, so we take
646 * the write lock of i_data_sem, and call get_block()
647 * with create == 1 flag.
649 down_write(&EXT4_I(inode)->i_data_sem);
652 * We need to check for EXT4 here because migrate
653 * could have changed the inode type in between
655 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
656 retval = ext4_ext_map_blocks(handle, inode, map, flags);
658 retval = ext4_ind_map_blocks(handle, inode, map, flags);
660 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
662 * We allocated new blocks which will result in
663 * i_data's format changing. Force the migrate
664 * to fail by clearing migrate flags
666 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
670 * Update reserved blocks/metadata blocks after successful
671 * block allocation which had been deferred till now. We don't
672 * support fallocate for non extent files. So we can update
673 * reserve space here.
676 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
677 ext4_da_update_reserve_space(inode, retval, 1);
683 if (unlikely(retval != map->m_len)) {
684 ext4_warning(inode->i_sb,
685 "ES len assertion failed for inode "
686 "%lu: retval %d != map->m_len %d",
687 inode->i_ino, retval, map->m_len);
692 * We have to zeroout blocks before inserting them into extent
693 * status tree. Otherwise someone could look them up there and
694 * use them before they are really zeroed. We also have to
695 * unmap metadata before zeroing as otherwise writeback can
696 * overwrite zeros with stale data from block device.
698 if (flags & EXT4_GET_BLOCKS_ZERO &&
699 map->m_flags & EXT4_MAP_MAPPED &&
700 map->m_flags & EXT4_MAP_NEW) {
701 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
703 ret = ext4_issue_zeroout(inode, map->m_lblk,
704 map->m_pblk, map->m_len);
712 * If the extent has been zeroed out, we don't need to update
713 * extent status tree.
715 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
716 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
717 if (ext4_es_is_written(&es))
720 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
721 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
722 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
723 !(status & EXTENT_STATUS_WRITTEN) &&
724 ext4_find_delalloc_range(inode, map->m_lblk,
725 map->m_lblk + map->m_len - 1))
726 status |= EXTENT_STATUS_DELAYED;
727 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
728 map->m_pblk, status);
736 up_write((&EXT4_I(inode)->i_data_sem));
737 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
738 ret = check_block_validity(inode, map);
743 * Inodes with freshly allocated blocks where contents will be
744 * visible after transaction commit must be on transaction's
747 if (map->m_flags & EXT4_MAP_NEW &&
748 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
749 !(flags & EXT4_GET_BLOCKS_ZERO) &&
750 !ext4_is_quota_file(inode) &&
751 ext4_should_order_data(inode)) {
753 (loff_t)map->m_lblk << inode->i_blkbits;
754 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
756 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
757 ret = ext4_jbd2_inode_add_wait(handle, inode,
760 ret = ext4_jbd2_inode_add_write(handle, inode,
770 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
771 * we have to be careful as someone else may be manipulating b_state as well.
773 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
775 unsigned long old_state;
776 unsigned long new_state;
778 flags &= EXT4_MAP_FLAGS;
780 /* Dummy buffer_head? Set non-atomically. */
782 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
786 * Someone else may be modifying b_state. Be careful! This is ugly but
787 * once we get rid of using bh as a container for mapping information
788 * to pass to / from get_block functions, this can go away.
791 old_state = READ_ONCE(bh->b_state);
792 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
794 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
797 static int _ext4_get_block(struct inode *inode, sector_t iblock,
798 struct buffer_head *bh, int flags)
800 struct ext4_map_blocks map;
803 if (ext4_has_inline_data(inode))
807 map.m_len = bh->b_size >> inode->i_blkbits;
809 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
812 map_bh(bh, inode->i_sb, map.m_pblk);
813 ext4_update_bh_state(bh, map.m_flags);
814 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
816 } else if (ret == 0) {
817 /* hole case, need to fill in bh->b_size */
818 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
823 int ext4_get_block(struct inode *inode, sector_t iblock,
824 struct buffer_head *bh, int create)
826 return _ext4_get_block(inode, iblock, bh,
827 create ? EXT4_GET_BLOCKS_CREATE : 0);
831 * Get block function used when preparing for buffered write if we require
832 * creating an unwritten extent if blocks haven't been allocated. The extent
833 * will be converted to written after the IO is complete.
835 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
836 struct buffer_head *bh_result, int create)
838 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
839 inode->i_ino, create);
840 return _ext4_get_block(inode, iblock, bh_result,
841 EXT4_GET_BLOCKS_IO_CREATE_EXT);
844 /* Maximum number of blocks we map for direct IO at once. */
845 #define DIO_MAX_BLOCKS 4096
848 * Get blocks function for the cases that need to start a transaction -
849 * generally difference cases of direct IO and DAX IO. It also handles retries
852 static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
853 struct buffer_head *bh_result, int flags)
860 /* Trim mapping request to maximum we can map at once for DIO */
861 if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
862 bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
863 dio_credits = ext4_chunk_trans_blocks(inode,
864 bh_result->b_size >> inode->i_blkbits);
866 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
868 return PTR_ERR(handle);
870 ret = _ext4_get_block(inode, iblock, bh_result, flags);
871 ext4_journal_stop(handle);
873 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
878 /* Get block function for DIO reads and writes to inodes without extents */
879 int ext4_dio_get_block(struct inode *inode, sector_t iblock,
880 struct buffer_head *bh, int create)
882 /* We don't expect handle for direct IO */
883 WARN_ON_ONCE(ext4_journal_current_handle());
886 return _ext4_get_block(inode, iblock, bh, 0);
887 return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
891 * Get block function for AIO DIO writes when we create unwritten extent if
892 * blocks are not allocated yet. The extent will be converted to written
893 * after IO is complete.
895 static int ext4_dio_get_block_unwritten_async(struct inode *inode,
896 sector_t iblock, struct buffer_head *bh_result, int create)
900 /* We don't expect handle for direct IO */
901 WARN_ON_ONCE(ext4_journal_current_handle());
903 ret = ext4_get_block_trans(inode, iblock, bh_result,
904 EXT4_GET_BLOCKS_IO_CREATE_EXT);
907 * When doing DIO using unwritten extents, we need io_end to convert
908 * unwritten extents to written on IO completion. We allocate io_end
909 * once we spot unwritten extent and store it in b_private. Generic
910 * DIO code keeps b_private set and furthermore passes the value to
911 * our completion callback in 'private' argument.
913 if (!ret && buffer_unwritten(bh_result)) {
914 if (!bh_result->b_private) {
915 ext4_io_end_t *io_end;
917 io_end = ext4_init_io_end(inode, GFP_KERNEL);
920 bh_result->b_private = io_end;
921 ext4_set_io_unwritten_flag(inode, io_end);
923 set_buffer_defer_completion(bh_result);
930 * Get block function for non-AIO DIO writes when we create unwritten extent if
931 * blocks are not allocated yet. The extent will be converted to written
932 * after IO is complete by ext4_direct_IO_write().
934 static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
935 sector_t iblock, struct buffer_head *bh_result, int create)
939 /* We don't expect handle for direct IO */
940 WARN_ON_ONCE(ext4_journal_current_handle());
942 ret = ext4_get_block_trans(inode, iblock, bh_result,
943 EXT4_GET_BLOCKS_IO_CREATE_EXT);
946 * Mark inode as having pending DIO writes to unwritten extents.
947 * ext4_direct_IO_write() checks this flag and converts extents to
950 if (!ret && buffer_unwritten(bh_result))
951 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
956 static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
957 struct buffer_head *bh_result, int create)
961 ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
962 inode->i_ino, create);
963 /* We don't expect handle for direct IO */
964 WARN_ON_ONCE(ext4_journal_current_handle());
966 ret = _ext4_get_block(inode, iblock, bh_result, 0);
968 * Blocks should have been preallocated! ext4_file_write_iter() checks
971 WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
978 * `handle' can be NULL if create is zero
980 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
981 ext4_lblk_t block, int map_flags)
983 struct ext4_map_blocks map;
984 struct buffer_head *bh;
985 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
988 J_ASSERT(handle != NULL || create == 0);
992 err = ext4_map_blocks(handle, inode, &map, map_flags);
995 return create ? ERR_PTR(-ENOSPC) : NULL;
999 bh = sb_getblk(inode->i_sb, map.m_pblk);
1001 return ERR_PTR(-ENOMEM);
1002 if (map.m_flags & EXT4_MAP_NEW) {
1003 J_ASSERT(create != 0);
1004 J_ASSERT(handle != NULL);
1007 * Now that we do not always journal data, we should
1008 * keep in mind whether this should always journal the
1009 * new buffer as metadata. For now, regular file
1010 * writes use ext4_get_block instead, so it's not a
1014 BUFFER_TRACE(bh, "call get_create_access");
1015 err = ext4_journal_get_create_access(handle, bh);
1016 if (unlikely(err)) {
1020 if (!buffer_uptodate(bh)) {
1021 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1022 set_buffer_uptodate(bh);
1025 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1026 err = ext4_handle_dirty_metadata(handle, inode, bh);
1030 BUFFER_TRACE(bh, "not a new buffer");
1034 return ERR_PTR(err);
1037 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1038 ext4_lblk_t block, int map_flags)
1040 struct buffer_head *bh;
1042 bh = ext4_getblk(handle, inode, block, map_flags);
1045 if (!bh || buffer_uptodate(bh))
1047 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
1049 if (buffer_uptodate(bh))
1052 return ERR_PTR(-EIO);
1055 /* Read a contiguous batch of blocks. */
1056 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1057 bool wait, struct buffer_head **bhs)
1061 for (i = 0; i < bh_count; i++) {
1062 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1063 if (IS_ERR(bhs[i])) {
1064 err = PTR_ERR(bhs[i]);
1070 for (i = 0; i < bh_count; i++)
1071 /* Note that NULL bhs[i] is valid because of holes. */
1072 if (bhs[i] && !buffer_uptodate(bhs[i]))
1073 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
1079 for (i = 0; i < bh_count; i++)
1081 wait_on_buffer(bhs[i]);
1083 for (i = 0; i < bh_count; i++) {
1084 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1092 for (i = 0; i < bh_count; i++) {
1099 int ext4_walk_page_buffers(handle_t *handle,
1100 struct buffer_head *head,
1104 int (*fn)(handle_t *handle,
1105 struct buffer_head *bh))
1107 struct buffer_head *bh;
1108 unsigned block_start, block_end;
1109 unsigned blocksize = head->b_size;
1111 struct buffer_head *next;
1113 for (bh = head, block_start = 0;
1114 ret == 0 && (bh != head || !block_start);
1115 block_start = block_end, bh = next) {
1116 next = bh->b_this_page;
1117 block_end = block_start + blocksize;
1118 if (block_end <= from || block_start >= to) {
1119 if (partial && !buffer_uptodate(bh))
1123 err = (*fn)(handle, bh);
1131 * To preserve ordering, it is essential that the hole instantiation and
1132 * the data write be encapsulated in a single transaction. We cannot
1133 * close off a transaction and start a new one between the ext4_get_block()
1134 * and the commit_write(). So doing the jbd2_journal_start at the start of
1135 * prepare_write() is the right place.
1137 * Also, this function can nest inside ext4_writepage(). In that case, we
1138 * *know* that ext4_writepage() has generated enough buffer credits to do the
1139 * whole page. So we won't block on the journal in that case, which is good,
1140 * because the caller may be PF_MEMALLOC.
1142 * By accident, ext4 can be reentered when a transaction is open via
1143 * quota file writes. If we were to commit the transaction while thus
1144 * reentered, there can be a deadlock - we would be holding a quota
1145 * lock, and the commit would never complete if another thread had a
1146 * transaction open and was blocking on the quota lock - a ranking
1149 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1150 * will _not_ run commit under these circumstances because handle->h_ref
1151 * is elevated. We'll still have enough credits for the tiny quotafile
1154 int do_journal_get_write_access(handle_t *handle,
1155 struct buffer_head *bh)
1157 int dirty = buffer_dirty(bh);
1160 if (!buffer_mapped(bh) || buffer_freed(bh))
1163 * __block_write_begin() could have dirtied some buffers. Clean
1164 * the dirty bit as jbd2_journal_get_write_access() could complain
1165 * otherwise about fs integrity issues. Setting of the dirty bit
1166 * by __block_write_begin() isn't a real problem here as we clear
1167 * the bit before releasing a page lock and thus writeback cannot
1168 * ever write the buffer.
1171 clear_buffer_dirty(bh);
1172 BUFFER_TRACE(bh, "get write access");
1173 ret = ext4_journal_get_write_access(handle, bh);
1175 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1179 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1180 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1181 get_block_t *get_block)
1183 unsigned from = pos & (PAGE_SIZE - 1);
1184 unsigned to = from + len;
1185 struct inode *inode = page->mapping->host;
1186 unsigned block_start, block_end;
1189 unsigned blocksize = inode->i_sb->s_blocksize;
1191 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1192 bool decrypt = false;
1194 BUG_ON(!PageLocked(page));
1195 BUG_ON(from > PAGE_SIZE);
1196 BUG_ON(to > PAGE_SIZE);
1199 if (!page_has_buffers(page))
1200 create_empty_buffers(page, blocksize, 0);
1201 head = page_buffers(page);
1202 bbits = ilog2(blocksize);
1203 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1205 for (bh = head, block_start = 0; bh != head || !block_start;
1206 block++, block_start = block_end, bh = bh->b_this_page) {
1207 block_end = block_start + blocksize;
1208 if (block_end <= from || block_start >= to) {
1209 if (PageUptodate(page)) {
1210 if (!buffer_uptodate(bh))
1211 set_buffer_uptodate(bh);
1216 clear_buffer_new(bh);
1217 if (!buffer_mapped(bh)) {
1218 WARN_ON(bh->b_size != blocksize);
1219 err = get_block(inode, block, bh, 1);
1222 if (buffer_new(bh)) {
1223 clean_bdev_bh_alias(bh);
1224 if (PageUptodate(page)) {
1225 clear_buffer_new(bh);
1226 set_buffer_uptodate(bh);
1227 mark_buffer_dirty(bh);
1230 if (block_end > to || block_start < from)
1231 zero_user_segments(page, to, block_end,
1236 if (PageUptodate(page)) {
1237 if (!buffer_uptodate(bh))
1238 set_buffer_uptodate(bh);
1241 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1242 !buffer_unwritten(bh) &&
1243 (block_start < from || block_end > to)) {
1244 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1246 decrypt = ext4_encrypted_inode(inode) &&
1247 S_ISREG(inode->i_mode);
1251 * If we issued read requests, let them complete.
1253 while (wait_bh > wait) {
1254 wait_on_buffer(*--wait_bh);
1255 if (!buffer_uptodate(*wait_bh))
1259 page_zero_new_buffers(page, from, to);
1261 err = fscrypt_decrypt_page(page->mapping->host, page,
1262 PAGE_SIZE, 0, page->index);
1267 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1268 loff_t pos, unsigned len, unsigned flags,
1269 struct page **pagep, void **fsdata)
1271 struct inode *inode = mapping->host;
1272 int ret, needed_blocks;
1279 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1282 trace_ext4_write_begin(inode, pos, len, flags);
1284 * Reserve one block more for addition to orphan list in case
1285 * we allocate blocks but write fails for some reason
1287 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1288 index = pos >> PAGE_SHIFT;
1289 from = pos & (PAGE_SIZE - 1);
1292 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1293 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1302 * grab_cache_page_write_begin() can take a long time if the
1303 * system is thrashing due to memory pressure, or if the page
1304 * is being written back. So grab it first before we start
1305 * the transaction handle. This also allows us to allocate
1306 * the page (if needed) without using GFP_NOFS.
1309 page = grab_cache_page_write_begin(mapping, index, flags);
1313 * The same as page allocation, we prealloc buffer heads before
1314 * starting the handle.
1316 if (!page_has_buffers(page))
1317 create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1322 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1323 if (IS_ERR(handle)) {
1325 return PTR_ERR(handle);
1329 if (page->mapping != mapping) {
1330 /* The page got truncated from under us */
1333 ext4_journal_stop(handle);
1336 /* In case writeback began while the page was unlocked */
1337 wait_for_stable_page(page);
1339 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1340 if (ext4_should_dioread_nolock(inode))
1341 ret = ext4_block_write_begin(page, pos, len,
1342 ext4_get_block_unwritten);
1344 ret = ext4_block_write_begin(page, pos, len,
1347 if (ext4_should_dioread_nolock(inode))
1348 ret = __block_write_begin(page, pos, len,
1349 ext4_get_block_unwritten);
1351 ret = __block_write_begin(page, pos, len, ext4_get_block);
1353 if (!ret && ext4_should_journal_data(inode)) {
1354 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1356 do_journal_get_write_access);
1362 * __block_write_begin may have instantiated a few blocks
1363 * outside i_size. Trim these off again. Don't need
1364 * i_size_read because we hold i_mutex.
1366 * Add inode to orphan list in case we crash before
1369 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1370 ext4_orphan_add(handle, inode);
1372 ext4_journal_stop(handle);
1373 if (pos + len > inode->i_size) {
1374 ext4_truncate_failed_write(inode);
1376 * If truncate failed early the inode might
1377 * still be on the orphan list; we need to
1378 * make sure the inode is removed from the
1379 * orphan list in that case.
1382 ext4_orphan_del(NULL, inode);
1385 if (ret == -ENOSPC &&
1386 ext4_should_retry_alloc(inode->i_sb, &retries))
1395 /* For write_end() in data=journal mode */
1396 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1399 if (!buffer_mapped(bh) || buffer_freed(bh))
1401 set_buffer_uptodate(bh);
1402 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1403 clear_buffer_meta(bh);
1404 clear_buffer_prio(bh);
1409 * We need to pick up the new inode size which generic_commit_write gave us
1410 * `file' can be NULL - eg, when called from page_symlink().
1412 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1413 * buffers are managed internally.
1415 static int ext4_write_end(struct file *file,
1416 struct address_space *mapping,
1417 loff_t pos, unsigned len, unsigned copied,
1418 struct page *page, void *fsdata)
1420 handle_t *handle = ext4_journal_current_handle();
1421 struct inode *inode = mapping->host;
1422 loff_t old_size = inode->i_size;
1424 int i_size_changed = 0;
1425 int inline_data = ext4_has_inline_data(inode);
1427 trace_ext4_write_end(inode, pos, len, copied);
1429 ret = ext4_write_inline_data_end(inode, pos, len,
1438 copied = block_write_end(file, mapping, pos,
1439 len, copied, page, fsdata);
1441 * it's important to update i_size while still holding page lock:
1442 * page writeout could otherwise come in and zero beyond i_size.
1444 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1449 pagecache_isize_extended(inode, old_size, pos);
1451 * Don't mark the inode dirty under page lock. First, it unnecessarily
1452 * makes the holding time of page lock longer. Second, it forces lock
1453 * ordering of page lock and transaction start for journaling
1456 if (i_size_changed || inline_data)
1457 ext4_mark_inode_dirty(handle, inode);
1459 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1460 /* if we have allocated more blocks and copied
1461 * less. We will have blocks allocated outside
1462 * inode->i_size. So truncate them
1464 ext4_orphan_add(handle, inode);
1466 ret2 = ext4_journal_stop(handle);
1470 if (pos + len > inode->i_size) {
1471 ext4_truncate_failed_write(inode);
1473 * If truncate failed early the inode might still be
1474 * on the orphan list; we need to make sure the inode
1475 * is removed from the orphan list in that case.
1478 ext4_orphan_del(NULL, inode);
1481 return ret ? ret : copied;
1485 * This is a private version of page_zero_new_buffers() which doesn't
1486 * set the buffer to be dirty, since in data=journalled mode we need
1487 * to call ext4_handle_dirty_metadata() instead.
1489 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1491 unsigned from, unsigned to)
1493 unsigned int block_start = 0, block_end;
1494 struct buffer_head *head, *bh;
1496 bh = head = page_buffers(page);
1498 block_end = block_start + bh->b_size;
1499 if (buffer_new(bh)) {
1500 if (block_end > from && block_start < to) {
1501 if (!PageUptodate(page)) {
1502 unsigned start, size;
1504 start = max(from, block_start);
1505 size = min(to, block_end) - start;
1507 zero_user(page, start, size);
1508 write_end_fn(handle, bh);
1510 clear_buffer_new(bh);
1513 block_start = block_end;
1514 bh = bh->b_this_page;
1515 } while (bh != head);
1518 static int ext4_journalled_write_end(struct file *file,
1519 struct address_space *mapping,
1520 loff_t pos, unsigned len, unsigned copied,
1521 struct page *page, void *fsdata)
1523 handle_t *handle = ext4_journal_current_handle();
1524 struct inode *inode = mapping->host;
1525 loff_t old_size = inode->i_size;
1529 int size_changed = 0;
1530 int inline_data = ext4_has_inline_data(inode);
1532 trace_ext4_journalled_write_end(inode, pos, len, copied);
1533 from = pos & (PAGE_SIZE - 1);
1536 BUG_ON(!ext4_handle_valid(handle));
1539 ret = ext4_write_inline_data_end(inode, pos, len,
1547 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1549 ext4_journalled_zero_new_buffers(handle, page, from, to);
1551 if (unlikely(copied < len))
1552 ext4_journalled_zero_new_buffers(handle, page,
1554 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1555 from + copied, &partial,
1558 SetPageUptodate(page);
1560 size_changed = ext4_update_inode_size(inode, pos + copied);
1561 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1562 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1567 pagecache_isize_extended(inode, old_size, pos);
1569 if (size_changed || inline_data) {
1570 ret2 = ext4_mark_inode_dirty(handle, inode);
1575 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1576 /* if we have allocated more blocks and copied
1577 * less. We will have blocks allocated outside
1578 * inode->i_size. So truncate them
1580 ext4_orphan_add(handle, inode);
1583 ret2 = ext4_journal_stop(handle);
1586 if (pos + len > inode->i_size) {
1587 ext4_truncate_failed_write(inode);
1589 * If truncate failed early the inode might still be
1590 * on the orphan list; we need to make sure the inode
1591 * is removed from the orphan list in that case.
1594 ext4_orphan_del(NULL, inode);
1597 return ret ? ret : copied;
1601 * Reserve space for a single cluster
1603 static int ext4_da_reserve_space(struct inode *inode)
1605 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1606 struct ext4_inode_info *ei = EXT4_I(inode);
1610 * We will charge metadata quota at writeout time; this saves
1611 * us from metadata over-estimation, though we may go over by
1612 * a small amount in the end. Here we just reserve for data.
1614 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1618 spin_lock(&ei->i_block_reservation_lock);
1619 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1620 spin_unlock(&ei->i_block_reservation_lock);
1621 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1624 ei->i_reserved_data_blocks++;
1625 trace_ext4_da_reserve_space(inode);
1626 spin_unlock(&ei->i_block_reservation_lock);
1628 return 0; /* success */
1631 static void ext4_da_release_space(struct inode *inode, int to_free)
1633 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1634 struct ext4_inode_info *ei = EXT4_I(inode);
1637 return; /* Nothing to release, exit */
1639 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1641 trace_ext4_da_release_space(inode, to_free);
1642 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1644 * if there aren't enough reserved blocks, then the
1645 * counter is messed up somewhere. Since this
1646 * function is called from invalidate page, it's
1647 * harmless to return without any action.
1649 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1650 "ino %lu, to_free %d with only %d reserved "
1651 "data blocks", inode->i_ino, to_free,
1652 ei->i_reserved_data_blocks);
1654 to_free = ei->i_reserved_data_blocks;
1656 ei->i_reserved_data_blocks -= to_free;
1658 /* update fs dirty data blocks counter */
1659 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1661 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1663 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1666 static void ext4_da_page_release_reservation(struct page *page,
1667 unsigned int offset,
1668 unsigned int length)
1670 int to_release = 0, contiguous_blks = 0;
1671 struct buffer_head *head, *bh;
1672 unsigned int curr_off = 0;
1673 struct inode *inode = page->mapping->host;
1674 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1675 unsigned int stop = offset + length;
1679 BUG_ON(stop > PAGE_SIZE || stop < length);
1681 head = page_buffers(page);
1684 unsigned int next_off = curr_off + bh->b_size;
1686 if (next_off > stop)
1689 if ((offset <= curr_off) && (buffer_delay(bh))) {
1692 clear_buffer_delay(bh);
1693 } else if (contiguous_blks) {
1694 lblk = page->index <<
1695 (PAGE_SHIFT - inode->i_blkbits);
1696 lblk += (curr_off >> inode->i_blkbits) -
1698 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1699 contiguous_blks = 0;
1701 curr_off = next_off;
1702 } while ((bh = bh->b_this_page) != head);
1704 if (contiguous_blks) {
1705 lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
1706 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1707 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1710 /* If we have released all the blocks belonging to a cluster, then we
1711 * need to release the reserved space for that cluster. */
1712 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1713 while (num_clusters > 0) {
1714 lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
1715 ((num_clusters - 1) << sbi->s_cluster_bits);
1716 if (sbi->s_cluster_ratio == 1 ||
1717 !ext4_find_delalloc_cluster(inode, lblk))
1718 ext4_da_release_space(inode, 1);
1725 * Delayed allocation stuff
1728 struct mpage_da_data {
1729 struct inode *inode;
1730 struct writeback_control *wbc;
1732 pgoff_t first_page; /* The first page to write */
1733 pgoff_t next_page; /* Current page to examine */
1734 pgoff_t last_page; /* Last page to examine */
1736 * Extent to map - this can be after first_page because that can be
1737 * fully mapped. We somewhat abuse m_flags to store whether the extent
1738 * is delalloc or unwritten.
1740 struct ext4_map_blocks map;
1741 struct ext4_io_submit io_submit; /* IO submission data */
1742 unsigned int do_map:1;
1745 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1750 struct pagevec pvec;
1751 struct inode *inode = mpd->inode;
1752 struct address_space *mapping = inode->i_mapping;
1754 /* This is necessary when next_page == 0. */
1755 if (mpd->first_page >= mpd->next_page)
1758 index = mpd->first_page;
1759 end = mpd->next_page - 1;
1761 ext4_lblk_t start, last;
1762 start = index << (PAGE_SHIFT - inode->i_blkbits);
1763 last = end << (PAGE_SHIFT - inode->i_blkbits);
1766 * avoid racing with extent status tree scans made by
1767 * ext4_insert_delayed_block()
1769 down_write(&EXT4_I(inode)->i_data_sem);
1770 ext4_es_remove_extent(inode, start, last - start + 1);
1771 up_write(&EXT4_I(inode)->i_data_sem);
1774 pagevec_init(&pvec, 0);
1775 while (index <= end) {
1776 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1779 for (i = 0; i < nr_pages; i++) {
1780 struct page *page = pvec.pages[i];
1782 BUG_ON(!PageLocked(page));
1783 BUG_ON(PageWriteback(page));
1785 if (page_mapped(page))
1786 clear_page_dirty_for_io(page);
1787 block_invalidatepage(page, 0, PAGE_SIZE);
1788 ClearPageUptodate(page);
1792 pagevec_release(&pvec);
1796 static void ext4_print_free_blocks(struct inode *inode)
1798 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1799 struct super_block *sb = inode->i_sb;
1800 struct ext4_inode_info *ei = EXT4_I(inode);
1802 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1803 EXT4_C2B(EXT4_SB(inode->i_sb),
1804 ext4_count_free_clusters(sb)));
1805 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1806 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1807 (long long) EXT4_C2B(EXT4_SB(sb),
1808 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1809 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1810 (long long) EXT4_C2B(EXT4_SB(sb),
1811 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1812 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1813 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1814 ei->i_reserved_data_blocks);
1818 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1820 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1824 * This function is grabs code from the very beginning of
1825 * ext4_map_blocks, but assumes that the caller is from delayed write
1826 * time. This function looks up the requested blocks and sets the
1827 * buffer delay bit under the protection of i_data_sem.
1829 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1830 struct ext4_map_blocks *map,
1831 struct buffer_head *bh)
1833 struct extent_status es;
1835 sector_t invalid_block = ~((sector_t) 0xffff);
1836 #ifdef ES_AGGRESSIVE_TEST
1837 struct ext4_map_blocks orig_map;
1839 memcpy(&orig_map, map, sizeof(*map));
1842 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1846 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1847 "logical block %lu\n", inode->i_ino, map->m_len,
1848 (unsigned long) map->m_lblk);
1850 /* Lookup extent status tree firstly */
1851 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1852 if (ext4_es_is_hole(&es)) {
1854 down_read(&EXT4_I(inode)->i_data_sem);
1859 * Delayed extent could be allocated by fallocate.
1860 * So we need to check it.
1862 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1863 map_bh(bh, inode->i_sb, invalid_block);
1865 set_buffer_delay(bh);
1869 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1870 retval = es.es_len - (iblock - es.es_lblk);
1871 if (retval > map->m_len)
1872 retval = map->m_len;
1873 map->m_len = retval;
1874 if (ext4_es_is_written(&es))
1875 map->m_flags |= EXT4_MAP_MAPPED;
1876 else if (ext4_es_is_unwritten(&es))
1877 map->m_flags |= EXT4_MAP_UNWRITTEN;
1881 #ifdef ES_AGGRESSIVE_TEST
1882 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1888 * Try to see if we can get the block without requesting a new
1889 * file system block.
1891 down_read(&EXT4_I(inode)->i_data_sem);
1892 if (ext4_has_inline_data(inode))
1894 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1895 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1897 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1903 * XXX: __block_prepare_write() unmaps passed block,
1907 * If the block was allocated from previously allocated cluster,
1908 * then we don't need to reserve it again. However we still need
1909 * to reserve metadata for every block we're going to write.
1911 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1912 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1913 ret = ext4_da_reserve_space(inode);
1915 /* not enough space to reserve */
1921 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1922 ~0, EXTENT_STATUS_DELAYED);
1928 map_bh(bh, inode->i_sb, invalid_block);
1930 set_buffer_delay(bh);
1931 } else if (retval > 0) {
1933 unsigned int status;
1935 if (unlikely(retval != map->m_len)) {
1936 ext4_warning(inode->i_sb,
1937 "ES len assertion failed for inode "
1938 "%lu: retval %d != map->m_len %d",
1939 inode->i_ino, retval, map->m_len);
1943 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1944 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1945 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1946 map->m_pblk, status);
1952 up_read((&EXT4_I(inode)->i_data_sem));
1958 * This is a special get_block_t callback which is used by
1959 * ext4_da_write_begin(). It will either return mapped block or
1960 * reserve space for a single block.
1962 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1963 * We also have b_blocknr = -1 and b_bdev initialized properly
1965 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1966 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1967 * initialized properly.
1969 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1970 struct buffer_head *bh, int create)
1972 struct ext4_map_blocks map;
1975 BUG_ON(create == 0);
1976 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1978 map.m_lblk = iblock;
1982 * first, we need to know whether the block is allocated already
1983 * preallocated blocks are unmapped but should treated
1984 * the same as allocated blocks.
1986 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1990 map_bh(bh, inode->i_sb, map.m_pblk);
1991 ext4_update_bh_state(bh, map.m_flags);
1993 if (buffer_unwritten(bh)) {
1994 /* A delayed write to unwritten bh should be marked
1995 * new and mapped. Mapped ensures that we don't do
1996 * get_block multiple times when we write to the same
1997 * offset and new ensures that we do proper zero out
1998 * for partial write.
2001 set_buffer_mapped(bh);
2006 static int bget_one(handle_t *handle, struct buffer_head *bh)
2012 static int bput_one(handle_t *handle, struct buffer_head *bh)
2018 static int __ext4_journalled_writepage(struct page *page,
2021 struct address_space *mapping = page->mapping;
2022 struct inode *inode = mapping->host;
2023 struct buffer_head *page_bufs = NULL;
2024 handle_t *handle = NULL;
2025 int ret = 0, err = 0;
2026 int inline_data = ext4_has_inline_data(inode);
2027 struct buffer_head *inode_bh = NULL;
2029 ClearPageChecked(page);
2032 BUG_ON(page->index != 0);
2033 BUG_ON(len > ext4_get_max_inline_size(inode));
2034 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2035 if (inode_bh == NULL)
2038 page_bufs = page_buffers(page);
2043 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2047 * We need to release the page lock before we start the
2048 * journal, so grab a reference so the page won't disappear
2049 * out from under us.
2054 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2055 ext4_writepage_trans_blocks(inode));
2056 if (IS_ERR(handle)) {
2057 ret = PTR_ERR(handle);
2059 goto out_no_pagelock;
2061 BUG_ON(!ext4_handle_valid(handle));
2065 if (page->mapping != mapping) {
2066 /* The page got truncated from under us */
2067 ext4_journal_stop(handle);
2073 ret = ext4_mark_inode_dirty(handle, inode);
2075 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2076 do_journal_get_write_access);
2078 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2083 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2084 err = ext4_journal_stop(handle);
2088 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2092 if (!inline_data && page_bufs)
2093 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
2100 * Note that we don't need to start a transaction unless we're journaling data
2101 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2102 * need to file the inode to the transaction's list in ordered mode because if
2103 * we are writing back data added by write(), the inode is already there and if
2104 * we are writing back data modified via mmap(), no one guarantees in which
2105 * transaction the data will hit the disk. In case we are journaling data, we
2106 * cannot start transaction directly because transaction start ranks above page
2107 * lock so we have to do some magic.
2109 * This function can get called via...
2110 * - ext4_writepages after taking page lock (have journal handle)
2111 * - journal_submit_inode_data_buffers (no journal handle)
2112 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2113 * - grab_page_cache when doing write_begin (have journal handle)
2115 * We don't do any block allocation in this function. If we have page with
2116 * multiple blocks we need to write those buffer_heads that are mapped. This
2117 * is important for mmaped based write. So if we do with blocksize 1K
2118 * truncate(f, 1024);
2119 * a = mmap(f, 0, 4096);
2121 * truncate(f, 4096);
2122 * we have in the page first buffer_head mapped via page_mkwrite call back
2123 * but other buffer_heads would be unmapped but dirty (dirty done via the
2124 * do_wp_page). So writepage should write the first block. If we modify
2125 * the mmap area beyond 1024 we will again get a page_fault and the
2126 * page_mkwrite callback will do the block allocation and mark the
2127 * buffer_heads mapped.
2129 * We redirty the page if we have any buffer_heads that is either delay or
2130 * unwritten in the page.
2132 * We can get recursively called as show below.
2134 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2137 * But since we don't do any block allocation we should not deadlock.
2138 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2140 static int ext4_writepage(struct page *page,
2141 struct writeback_control *wbc)
2146 struct buffer_head *page_bufs = NULL;
2147 struct inode *inode = page->mapping->host;
2148 struct ext4_io_submit io_submit;
2149 bool keep_towrite = false;
2151 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2152 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2157 trace_ext4_writepage(page);
2158 size = i_size_read(inode);
2159 if (page->index == size >> PAGE_SHIFT)
2160 len = size & ~PAGE_MASK;
2164 /* Should never happen but for bugs in other kernel subsystems */
2165 if (!page_has_buffers(page)) {
2166 ext4_warning_inode(inode,
2167 "page %lu does not have buffers attached", page->index);
2168 ClearPageDirty(page);
2173 page_bufs = page_buffers(page);
2175 * We cannot do block allocation or other extent handling in this
2176 * function. If there are buffers needing that, we have to redirty
2177 * the page. But we may reach here when we do a journal commit via
2178 * journal_submit_inode_data_buffers() and in that case we must write
2179 * allocated buffers to achieve data=ordered mode guarantees.
2181 * Also, if there is only one buffer per page (the fs block
2182 * size == the page size), if one buffer needs block
2183 * allocation or needs to modify the extent tree to clear the
2184 * unwritten flag, we know that the page can't be written at
2185 * all, so we might as well refuse the write immediately.
2186 * Unfortunately if the block size != page size, we can't as
2187 * easily detect this case using ext4_walk_page_buffers(), but
2188 * for the extremely common case, this is an optimization that
2189 * skips a useless round trip through ext4_bio_write_page().
2191 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2192 ext4_bh_delay_or_unwritten)) {
2193 redirty_page_for_writepage(wbc, page);
2194 if ((current->flags & PF_MEMALLOC) ||
2195 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2197 * For memory cleaning there's no point in writing only
2198 * some buffers. So just bail out. Warn if we came here
2199 * from direct reclaim.
2201 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2206 keep_towrite = true;
2209 if (PageChecked(page) && ext4_should_journal_data(inode))
2211 * It's mmapped pagecache. Add buffers and journal it. There
2212 * doesn't seem much point in redirtying the page here.
2214 return __ext4_journalled_writepage(page, len);
2216 ext4_io_submit_init(&io_submit, wbc);
2217 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2218 if (!io_submit.io_end) {
2219 redirty_page_for_writepage(wbc, page);
2223 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2224 ext4_io_submit(&io_submit);
2225 /* Drop io_end reference we got from init */
2226 ext4_put_io_end_defer(io_submit.io_end);
2230 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2236 BUG_ON(page->index != mpd->first_page);
2237 clear_page_dirty_for_io(page);
2239 * We have to be very careful here! Nothing protects writeback path
2240 * against i_size changes and the page can be writeably mapped into
2241 * page tables. So an application can be growing i_size and writing
2242 * data through mmap while writeback runs. clear_page_dirty_for_io()
2243 * write-protects our page in page tables and the page cannot get
2244 * written to again until we release page lock. So only after
2245 * clear_page_dirty_for_io() we are safe to sample i_size for
2246 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2247 * on the barrier provided by TestClearPageDirty in
2248 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2249 * after page tables are updated.
2251 size = i_size_read(mpd->inode);
2252 if (page->index == size >> PAGE_SHIFT)
2253 len = size & ~PAGE_MASK;
2256 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2258 mpd->wbc->nr_to_write--;
2264 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2267 * mballoc gives us at most this number of blocks...
2268 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2269 * The rest of mballoc seems to handle chunks up to full group size.
2271 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2274 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2276 * @mpd - extent of blocks
2277 * @lblk - logical number of the block in the file
2278 * @bh - buffer head we want to add to the extent
2280 * The function is used to collect contig. blocks in the same state. If the
2281 * buffer doesn't require mapping for writeback and we haven't started the
2282 * extent of buffers to map yet, the function returns 'true' immediately - the
2283 * caller can write the buffer right away. Otherwise the function returns true
2284 * if the block has been added to the extent, false if the block couldn't be
2287 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2288 struct buffer_head *bh)
2290 struct ext4_map_blocks *map = &mpd->map;
2292 /* Buffer that doesn't need mapping for writeback? */
2293 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2294 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2295 /* So far no extent to map => we write the buffer right away */
2296 if (map->m_len == 0)
2301 /* First block in the extent? */
2302 if (map->m_len == 0) {
2303 /* We cannot map unless handle is started... */
2308 map->m_flags = bh->b_state & BH_FLAGS;
2312 /* Don't go larger than mballoc is willing to allocate */
2313 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2316 /* Can we merge the block to our big extent? */
2317 if (lblk == map->m_lblk + map->m_len &&
2318 (bh->b_state & BH_FLAGS) == map->m_flags) {
2326 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2328 * @mpd - extent of blocks for mapping
2329 * @head - the first buffer in the page
2330 * @bh - buffer we should start processing from
2331 * @lblk - logical number of the block in the file corresponding to @bh
2333 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2334 * the page for IO if all buffers in this page were mapped and there's no
2335 * accumulated extent of buffers to map or add buffers in the page to the
2336 * extent of buffers to map. The function returns 1 if the caller can continue
2337 * by processing the next page, 0 if it should stop adding buffers to the
2338 * extent to map because we cannot extend it anymore. It can also return value
2339 * < 0 in case of error during IO submission.
2341 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2342 struct buffer_head *head,
2343 struct buffer_head *bh,
2346 struct inode *inode = mpd->inode;
2348 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2349 >> inode->i_blkbits;
2352 BUG_ON(buffer_locked(bh));
2354 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2355 /* Found extent to map? */
2358 /* Buffer needs mapping and handle is not started? */
2361 /* Everything mapped so far and we hit EOF */
2364 } while (lblk++, (bh = bh->b_this_page) != head);
2365 /* So far everything mapped? Submit the page for IO. */
2366 if (mpd->map.m_len == 0) {
2367 err = mpage_submit_page(mpd, head->b_page);
2371 return lblk < blocks;
2375 * mpage_map_buffers - update buffers corresponding to changed extent and
2376 * submit fully mapped pages for IO
2378 * @mpd - description of extent to map, on return next extent to map
2380 * Scan buffers corresponding to changed extent (we expect corresponding pages
2381 * to be already locked) and update buffer state according to new extent state.
2382 * We map delalloc buffers to their physical location, clear unwritten bits,
2383 * and mark buffers as uninit when we perform writes to unwritten extents
2384 * and do extent conversion after IO is finished. If the last page is not fully
2385 * mapped, we update @map to the next extent in the last page that needs
2386 * mapping. Otherwise we submit the page for IO.
2388 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2390 struct pagevec pvec;
2392 struct inode *inode = mpd->inode;
2393 struct buffer_head *head, *bh;
2394 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2400 start = mpd->map.m_lblk >> bpp_bits;
2401 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2402 lblk = start << bpp_bits;
2403 pblock = mpd->map.m_pblk;
2405 pagevec_init(&pvec, 0);
2406 while (start <= end) {
2407 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2411 for (i = 0; i < nr_pages; i++) {
2412 struct page *page = pvec.pages[i];
2414 bh = head = page_buffers(page);
2416 if (lblk < mpd->map.m_lblk)
2418 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2420 * Buffer after end of mapped extent.
2421 * Find next buffer in the page to map.
2424 mpd->map.m_flags = 0;
2426 * FIXME: If dioread_nolock supports
2427 * blocksize < pagesize, we need to make
2428 * sure we add size mapped so far to
2429 * io_end->size as the following call
2430 * can submit the page for IO.
2432 err = mpage_process_page_bufs(mpd, head,
2434 pagevec_release(&pvec);
2439 if (buffer_delay(bh)) {
2440 clear_buffer_delay(bh);
2441 bh->b_blocknr = pblock++;
2443 clear_buffer_unwritten(bh);
2444 } while (lblk++, (bh = bh->b_this_page) != head);
2447 * FIXME: This is going to break if dioread_nolock
2448 * supports blocksize < pagesize as we will try to
2449 * convert potentially unmapped parts of inode.
2451 mpd->io_submit.io_end->size += PAGE_SIZE;
2452 /* Page fully mapped - let IO run! */
2453 err = mpage_submit_page(mpd, page);
2455 pagevec_release(&pvec);
2459 pagevec_release(&pvec);
2461 /* Extent fully mapped and matches with page boundary. We are done. */
2463 mpd->map.m_flags = 0;
2467 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2469 struct inode *inode = mpd->inode;
2470 struct ext4_map_blocks *map = &mpd->map;
2471 int get_blocks_flags;
2472 int err, dioread_nolock;
2474 trace_ext4_da_write_pages_extent(inode, map);
2476 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2477 * to convert an unwritten extent to be initialized (in the case
2478 * where we have written into one or more preallocated blocks). It is
2479 * possible that we're going to need more metadata blocks than
2480 * previously reserved. However we must not fail because we're in
2481 * writeback and there is nothing we can do about it so it might result
2482 * in data loss. So use reserved blocks to allocate metadata if
2485 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2486 * the blocks in question are delalloc blocks. This indicates
2487 * that the blocks and quotas has already been checked when
2488 * the data was copied into the page cache.
2490 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2491 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2492 EXT4_GET_BLOCKS_IO_SUBMIT;
2493 dioread_nolock = ext4_should_dioread_nolock(inode);
2495 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2496 if (map->m_flags & (1 << BH_Delay))
2497 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2499 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2502 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2503 if (!mpd->io_submit.io_end->handle &&
2504 ext4_handle_valid(handle)) {
2505 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2506 handle->h_rsv_handle = NULL;
2508 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2511 BUG_ON(map->m_len == 0);
2512 if (map->m_flags & EXT4_MAP_NEW) {
2513 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
2520 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2521 * mpd->len and submit pages underlying it for IO
2523 * @handle - handle for journal operations
2524 * @mpd - extent to map
2525 * @give_up_on_write - we set this to true iff there is a fatal error and there
2526 * is no hope of writing the data. The caller should discard
2527 * dirty pages to avoid infinite loops.
2529 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2530 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2531 * them to initialized or split the described range from larger unwritten
2532 * extent. Note that we need not map all the described range since allocation
2533 * can return less blocks or the range is covered by more unwritten extents. We
2534 * cannot map more because we are limited by reserved transaction credits. On
2535 * the other hand we always make sure that the last touched page is fully
2536 * mapped so that it can be written out (and thus forward progress is
2537 * guaranteed). After mapping we submit all mapped pages for IO.
2539 static int mpage_map_and_submit_extent(handle_t *handle,
2540 struct mpage_da_data *mpd,
2541 bool *give_up_on_write)
2543 struct inode *inode = mpd->inode;
2544 struct ext4_map_blocks *map = &mpd->map;
2549 mpd->io_submit.io_end->offset =
2550 ((loff_t)map->m_lblk) << inode->i_blkbits;
2552 err = mpage_map_one_extent(handle, mpd);
2554 struct super_block *sb = inode->i_sb;
2556 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2557 EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2558 goto invalidate_dirty_pages;
2560 * Let the uper layers retry transient errors.
2561 * In the case of ENOSPC, if ext4_count_free_blocks()
2562 * is non-zero, a commit should free up blocks.
2564 if ((err == -ENOMEM) ||
2565 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2567 goto update_disksize;
2570 ext4_msg(sb, KERN_CRIT,
2571 "Delayed block allocation failed for "
2572 "inode %lu at logical offset %llu with"
2573 " max blocks %u with error %d",
2575 (unsigned long long)map->m_lblk,
2576 (unsigned)map->m_len, -err);
2577 ext4_msg(sb, KERN_CRIT,
2578 "This should not happen!! Data will "
2581 ext4_print_free_blocks(inode);
2582 invalidate_dirty_pages:
2583 *give_up_on_write = true;
2588 * Update buffer state, submit mapped pages, and get us new
2591 err = mpage_map_and_submit_buffers(mpd);
2593 goto update_disksize;
2594 } while (map->m_len);
2598 * Update on-disk size after IO is submitted. Races with
2599 * truncate are avoided by checking i_size under i_data_sem.
2601 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2602 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2606 down_write(&EXT4_I(inode)->i_data_sem);
2607 i_size = i_size_read(inode);
2608 if (disksize > i_size)
2610 if (disksize > EXT4_I(inode)->i_disksize)
2611 EXT4_I(inode)->i_disksize = disksize;
2612 up_write(&EXT4_I(inode)->i_data_sem);
2613 err2 = ext4_mark_inode_dirty(handle, inode);
2615 ext4_error(inode->i_sb,
2616 "Failed to mark inode %lu dirty",
2625 * Calculate the total number of credits to reserve for one writepages
2626 * iteration. This is called from ext4_writepages(). We map an extent of
2627 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2628 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2629 * bpp - 1 blocks in bpp different extents.
2631 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2633 int bpp = ext4_journal_blocks_per_page(inode);
2635 return ext4_meta_trans_blocks(inode,
2636 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2640 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2641 * and underlying extent to map
2643 * @mpd - where to look for pages
2645 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2646 * IO immediately. When we find a page which isn't mapped we start accumulating
2647 * extent of buffers underlying these pages that needs mapping (formed by
2648 * either delayed or unwritten buffers). We also lock the pages containing
2649 * these buffers. The extent found is returned in @mpd structure (starting at
2650 * mpd->lblk with length mpd->len blocks).
2652 * Note that this function can attach bios to one io_end structure which are
2653 * neither logically nor physically contiguous. Although it may seem as an
2654 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2655 * case as we need to track IO to all buffers underlying a page in one io_end.
2657 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2659 struct address_space *mapping = mpd->inode->i_mapping;
2660 struct pagevec pvec;
2661 unsigned int nr_pages;
2662 long left = mpd->wbc->nr_to_write;
2663 pgoff_t index = mpd->first_page;
2664 pgoff_t end = mpd->last_page;
2667 int blkbits = mpd->inode->i_blkbits;
2669 struct buffer_head *head;
2671 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2672 tag = PAGECACHE_TAG_TOWRITE;
2674 tag = PAGECACHE_TAG_DIRTY;
2676 pagevec_init(&pvec, 0);
2678 mpd->next_page = index;
2679 while (index <= end) {
2680 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2681 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2685 for (i = 0; i < nr_pages; i++) {
2686 struct page *page = pvec.pages[i];
2689 * At this point, the page may be truncated or
2690 * invalidated (changing page->mapping to NULL), or
2691 * even swizzled back from swapper_space to tmpfs file
2692 * mapping. However, page->index will not change
2693 * because we have a reference on the page.
2695 if (page->index > end)
2699 * Accumulated enough dirty pages? This doesn't apply
2700 * to WB_SYNC_ALL mode. For integrity sync we have to
2701 * keep going because someone may be concurrently
2702 * dirtying pages, and we might have synced a lot of
2703 * newly appeared dirty pages, but have not synced all
2704 * of the old dirty pages.
2706 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2709 /* If we can't merge this page, we are done. */
2710 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2715 * If the page is no longer dirty, or its mapping no
2716 * longer corresponds to inode we are writing (which
2717 * means it has been truncated or invalidated), or the
2718 * page is already under writeback and we are not doing
2719 * a data integrity writeback, skip the page
2721 if (!PageDirty(page) ||
2722 (PageWriteback(page) &&
2723 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2724 unlikely(page->mapping != mapping)) {
2729 wait_on_page_writeback(page);
2730 BUG_ON(PageWriteback(page));
2733 * Should never happen but for buggy code in
2734 * other subsystems that call
2735 * set_page_dirty() without properly warning
2736 * the file system first. See [1] for more
2739 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2741 if (!page_has_buffers(page)) {
2742 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2743 ClearPageDirty(page);
2748 if (mpd->map.m_len == 0)
2749 mpd->first_page = page->index;
2750 mpd->next_page = page->index + 1;
2751 /* Add all dirty buffers to mpd */
2752 lblk = ((ext4_lblk_t)page->index) <<
2753 (PAGE_SHIFT - blkbits);
2754 head = page_buffers(page);
2755 err = mpage_process_page_bufs(mpd, head, head, lblk);
2761 pagevec_release(&pvec);
2766 pagevec_release(&pvec);
2770 static int __writepage(struct page *page, struct writeback_control *wbc,
2773 struct address_space *mapping = data;
2774 int ret = ext4_writepage(page, wbc);
2775 mapping_set_error(mapping, ret);
2779 static int ext4_writepages(struct address_space *mapping,
2780 struct writeback_control *wbc)
2782 pgoff_t writeback_index = 0;
2783 long nr_to_write = wbc->nr_to_write;
2784 int range_whole = 0;
2786 handle_t *handle = NULL;
2787 struct mpage_da_data mpd;
2788 struct inode *inode = mapping->host;
2789 int needed_blocks, rsv_blocks = 0, ret = 0;
2790 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2792 struct blk_plug plug;
2793 bool give_up_on_write = false;
2795 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2798 percpu_down_read(&sbi->s_writepages_rwsem);
2799 trace_ext4_writepages(inode, wbc);
2801 if (dax_mapping(mapping)) {
2802 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
2804 goto out_writepages;
2808 * No pages to write? This is mainly a kludge to avoid starting
2809 * a transaction for special inodes like journal inode on last iput()
2810 * because that could violate lock ordering on umount
2812 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2813 goto out_writepages;
2815 if (ext4_should_journal_data(inode)) {
2816 struct blk_plug plug;
2818 blk_start_plug(&plug);
2819 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2820 blk_finish_plug(&plug);
2821 goto out_writepages;
2825 * If the filesystem has aborted, it is read-only, so return
2826 * right away instead of dumping stack traces later on that
2827 * will obscure the real source of the problem. We test
2828 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2829 * the latter could be true if the filesystem is mounted
2830 * read-only, and in that case, ext4_writepages should
2831 * *never* be called, so if that ever happens, we would want
2834 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2835 sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2837 goto out_writepages;
2840 if (ext4_should_dioread_nolock(inode)) {
2842 * We may need to convert up to one extent per block in
2843 * the page and we may dirty the inode.
2845 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2846 PAGE_SIZE >> inode->i_blkbits);
2850 * If we have inline data and arrive here, it means that
2851 * we will soon create the block for the 1st page, so
2852 * we'd better clear the inline data here.
2854 if (ext4_has_inline_data(inode)) {
2855 /* Just inode will be modified... */
2856 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2857 if (IS_ERR(handle)) {
2858 ret = PTR_ERR(handle);
2859 goto out_writepages;
2861 BUG_ON(ext4_test_inode_state(inode,
2862 EXT4_STATE_MAY_INLINE_DATA));
2863 ext4_destroy_inline_data(handle, inode);
2864 ext4_journal_stop(handle);
2867 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2870 if (wbc->range_cyclic) {
2871 writeback_index = mapping->writeback_index;
2872 if (writeback_index)
2874 mpd.first_page = writeback_index;
2877 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2878 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2883 ext4_io_submit_init(&mpd.io_submit, wbc);
2885 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2886 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2888 blk_start_plug(&plug);
2891 * First writeback pages that don't need mapping - we can avoid
2892 * starting a transaction unnecessarily and also avoid being blocked
2893 * in the block layer on device congestion while having transaction
2897 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2898 if (!mpd.io_submit.io_end) {
2902 ret = mpage_prepare_extent_to_map(&mpd);
2903 /* Submit prepared bio */
2904 ext4_io_submit(&mpd.io_submit);
2905 ext4_put_io_end_defer(mpd.io_submit.io_end);
2906 mpd.io_submit.io_end = NULL;
2907 /* Unlock pages we didn't use */
2908 mpage_release_unused_pages(&mpd, false);
2912 while (!done && mpd.first_page <= mpd.last_page) {
2913 /* For each extent of pages we use new io_end */
2914 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2915 if (!mpd.io_submit.io_end) {
2921 * We have two constraints: We find one extent to map and we
2922 * must always write out whole page (makes a difference when
2923 * blocksize < pagesize) so that we don't block on IO when we
2924 * try to write out the rest of the page. Journalled mode is
2925 * not supported by delalloc.
2927 BUG_ON(ext4_should_journal_data(inode));
2928 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2930 /* start a new transaction */
2931 handle = ext4_journal_start_with_reserve(inode,
2932 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2933 if (IS_ERR(handle)) {
2934 ret = PTR_ERR(handle);
2935 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2936 "%ld pages, ino %lu; err %d", __func__,
2937 wbc->nr_to_write, inode->i_ino, ret);
2938 /* Release allocated io_end */
2939 ext4_put_io_end(mpd.io_submit.io_end);
2940 mpd.io_submit.io_end = NULL;
2945 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2946 ret = mpage_prepare_extent_to_map(&mpd);
2949 ret = mpage_map_and_submit_extent(handle, &mpd,
2953 * We scanned the whole range (or exhausted
2954 * nr_to_write), submitted what was mapped and
2955 * didn't find anything needing mapping. We are
2962 * Caution: If the handle is synchronous,
2963 * ext4_journal_stop() can wait for transaction commit
2964 * to finish which may depend on writeback of pages to
2965 * complete or on page lock to be released. In that
2966 * case, we have to wait until after after we have
2967 * submitted all the IO, released page locks we hold,
2968 * and dropped io_end reference (for extent conversion
2969 * to be able to complete) before stopping the handle.
2971 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2972 ext4_journal_stop(handle);
2976 /* Submit prepared bio */
2977 ext4_io_submit(&mpd.io_submit);
2978 /* Unlock pages we didn't use */
2979 mpage_release_unused_pages(&mpd, give_up_on_write);
2981 * Drop our io_end reference we got from init. We have
2982 * to be careful and use deferred io_end finishing if
2983 * we are still holding the transaction as we can
2984 * release the last reference to io_end which may end
2985 * up doing unwritten extent conversion.
2988 ext4_put_io_end_defer(mpd.io_submit.io_end);
2989 ext4_journal_stop(handle);
2991 ext4_put_io_end(mpd.io_submit.io_end);
2992 mpd.io_submit.io_end = NULL;
2994 if (ret == -ENOSPC && sbi->s_journal) {
2996 * Commit the transaction which would
2997 * free blocks released in the transaction
3000 jbd2_journal_force_commit_nested(sbi->s_journal);
3004 /* Fatal error - ENOMEM, EIO... */
3009 blk_finish_plug(&plug);
3010 if (!ret && !cycled && wbc->nr_to_write > 0) {
3012 mpd.last_page = writeback_index - 1;
3018 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3020 * Set the writeback_index so that range_cyclic
3021 * mode will write it back later
3023 mapping->writeback_index = mpd.first_page;
3026 trace_ext4_writepages_result(inode, wbc, ret,
3027 nr_to_write - wbc->nr_to_write);
3028 percpu_up_read(&sbi->s_writepages_rwsem);
3032 static int ext4_nonda_switch(struct super_block *sb)
3034 s64 free_clusters, dirty_clusters;
3035 struct ext4_sb_info *sbi = EXT4_SB(sb);
3038 * switch to non delalloc mode if we are running low
3039 * on free block. The free block accounting via percpu
3040 * counters can get slightly wrong with percpu_counter_batch getting
3041 * accumulated on each CPU without updating global counters
3042 * Delalloc need an accurate free block accounting. So switch
3043 * to non delalloc when we are near to error range.
3046 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3048 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
3050 * Start pushing delalloc when 1/2 of free blocks are dirty.
3052 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
3053 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
3055 if (2 * free_clusters < 3 * dirty_clusters ||
3056 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
3058 * free block count is less than 150% of dirty blocks
3059 * or free blocks is less than watermark
3066 /* We always reserve for an inode update; the superblock could be there too */
3067 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
3069 if (likely(ext4_has_feature_large_file(inode->i_sb)))
3072 if (pos + len <= 0x7fffffffULL)
3075 /* We might need to update the superblock to set LARGE_FILE */
3079 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3080 loff_t pos, unsigned len, unsigned flags,
3081 struct page **pagep, void **fsdata)
3083 int ret, retries = 0;
3086 struct inode *inode = mapping->host;
3089 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3092 index = pos >> PAGE_SHIFT;
3094 if (ext4_nonda_switch(inode->i_sb) ||
3095 S_ISLNK(inode->i_mode)) {
3096 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3097 return ext4_write_begin(file, mapping, pos,
3098 len, flags, pagep, fsdata);
3100 *fsdata = (void *)0;
3101 trace_ext4_da_write_begin(inode, pos, len, flags);
3103 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3104 ret = ext4_da_write_inline_data_begin(mapping, inode,
3114 * grab_cache_page_write_begin() can take a long time if the
3115 * system is thrashing due to memory pressure, or if the page
3116 * is being written back. So grab it first before we start
3117 * the transaction handle. This also allows us to allocate
3118 * the page (if needed) without using GFP_NOFS.
3121 page = grab_cache_page_write_begin(mapping, index, flags);
3127 * With delayed allocation, we don't log the i_disksize update
3128 * if there is delayed block allocation. But we still need
3129 * to journalling the i_disksize update if writes to the end
3130 * of file which has an already mapped buffer.
3133 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3134 ext4_da_write_credits(inode, pos, len));
3135 if (IS_ERR(handle)) {
3137 return PTR_ERR(handle);
3141 if (page->mapping != mapping) {
3142 /* The page got truncated from under us */
3145 ext4_journal_stop(handle);
3148 /* In case writeback began while the page was unlocked */
3149 wait_for_stable_page(page);
3151 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3152 ret = ext4_block_write_begin(page, pos, len,
3153 ext4_da_get_block_prep);
3155 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3159 ext4_journal_stop(handle);
3161 * block_write_begin may have instantiated a few blocks
3162 * outside i_size. Trim these off again. Don't need
3163 * i_size_read because we hold i_mutex.
3165 if (pos + len > inode->i_size)
3166 ext4_truncate_failed_write(inode);
3168 if (ret == -ENOSPC &&
3169 ext4_should_retry_alloc(inode->i_sb, &retries))
3181 * Check if we should update i_disksize
3182 * when write to the end of file but not require block allocation
3184 static int ext4_da_should_update_i_disksize(struct page *page,
3185 unsigned long offset)
3187 struct buffer_head *bh;
3188 struct inode *inode = page->mapping->host;
3192 bh = page_buffers(page);
3193 idx = offset >> inode->i_blkbits;
3195 for (i = 0; i < idx; i++)
3196 bh = bh->b_this_page;
3198 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3203 static int ext4_da_write_end(struct file *file,
3204 struct address_space *mapping,
3205 loff_t pos, unsigned len, unsigned copied,
3206 struct page *page, void *fsdata)
3208 struct inode *inode = mapping->host;
3210 handle_t *handle = ext4_journal_current_handle();
3212 unsigned long start, end;
3213 int write_mode = (int)(unsigned long)fsdata;
3215 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3216 return ext4_write_end(file, mapping, pos,
3217 len, copied, page, fsdata);
3219 trace_ext4_da_write_end(inode, pos, len, copied);
3220 start = pos & (PAGE_SIZE - 1);
3221 end = start + copied - 1;
3224 * generic_write_end() will run mark_inode_dirty() if i_size
3225 * changes. So let's piggyback the i_disksize mark_inode_dirty
3228 new_i_size = pos + copied;
3229 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3230 if (ext4_has_inline_data(inode) ||
3231 ext4_da_should_update_i_disksize(page, end)) {
3232 ext4_update_i_disksize(inode, new_i_size);
3233 /* We need to mark inode dirty even if
3234 * new_i_size is less that inode->i_size
3235 * bu greater than i_disksize.(hint delalloc)
3237 ext4_mark_inode_dirty(handle, inode);
3241 if (write_mode != CONVERT_INLINE_DATA &&
3242 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3243 ext4_has_inline_data(inode))
3244 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3247 ret2 = generic_write_end(file, mapping, pos, len, copied,
3253 ret2 = ext4_journal_stop(handle);
3257 return ret ? ret : copied;
3260 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
3261 unsigned int length)
3264 * Drop reserved blocks
3266 BUG_ON(!PageLocked(page));
3267 if (!page_has_buffers(page))
3270 ext4_da_page_release_reservation(page, offset, length);
3273 ext4_invalidatepage(page, offset, length);
3279 * Force all delayed allocation blocks to be allocated for a given inode.
3281 int ext4_alloc_da_blocks(struct inode *inode)
3283 trace_ext4_alloc_da_blocks(inode);
3285 if (!EXT4_I(inode)->i_reserved_data_blocks)
3289 * We do something simple for now. The filemap_flush() will
3290 * also start triggering a write of the data blocks, which is
3291 * not strictly speaking necessary (and for users of
3292 * laptop_mode, not even desirable). However, to do otherwise
3293 * would require replicating code paths in:
3295 * ext4_writepages() ->
3296 * write_cache_pages() ---> (via passed in callback function)
3297 * __mpage_da_writepage() -->
3298 * mpage_add_bh_to_extent()
3299 * mpage_da_map_blocks()
3301 * The problem is that write_cache_pages(), located in
3302 * mm/page-writeback.c, marks pages clean in preparation for
3303 * doing I/O, which is not desirable if we're not planning on
3306 * We could call write_cache_pages(), and then redirty all of
3307 * the pages by calling redirty_page_for_writepage() but that
3308 * would be ugly in the extreme. So instead we would need to
3309 * replicate parts of the code in the above functions,
3310 * simplifying them because we wouldn't actually intend to
3311 * write out the pages, but rather only collect contiguous
3312 * logical block extents, call the multi-block allocator, and
3313 * then update the buffer heads with the block allocations.
3315 * For now, though, we'll cheat by calling filemap_flush(),
3316 * which will map the blocks, and start the I/O, but not
3317 * actually wait for the I/O to complete.
3319 return filemap_flush(inode->i_mapping);
3323 * bmap() is special. It gets used by applications such as lilo and by
3324 * the swapper to find the on-disk block of a specific piece of data.
3326 * Naturally, this is dangerous if the block concerned is still in the
3327 * journal. If somebody makes a swapfile on an ext4 data-journaling
3328 * filesystem and enables swap, then they may get a nasty shock when the
3329 * data getting swapped to that swapfile suddenly gets overwritten by
3330 * the original zero's written out previously to the journal and
3331 * awaiting writeback in the kernel's buffer cache.
3333 * So, if we see any bmap calls here on a modified, data-journaled file,
3334 * take extra steps to flush any blocks which might be in the cache.
3336 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3338 struct inode *inode = mapping->host;
3343 * We can get here for an inline file via the FIBMAP ioctl
3345 if (ext4_has_inline_data(inode))
3348 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3349 test_opt(inode->i_sb, DELALLOC)) {
3351 * With delalloc we want to sync the file
3352 * so that we can make sure we allocate
3355 filemap_write_and_wait(mapping);
3358 if (EXT4_JOURNAL(inode) &&
3359 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3361 * This is a REALLY heavyweight approach, but the use of
3362 * bmap on dirty files is expected to be extremely rare:
3363 * only if we run lilo or swapon on a freshly made file
3364 * do we expect this to happen.
3366 * (bmap requires CAP_SYS_RAWIO so this does not
3367 * represent an unprivileged user DOS attack --- we'd be
3368 * in trouble if mortal users could trigger this path at
3371 * NB. EXT4_STATE_JDATA is not set on files other than
3372 * regular files. If somebody wants to bmap a directory
3373 * or symlink and gets confused because the buffer
3374 * hasn't yet been flushed to disk, they deserve
3375 * everything they get.
3378 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3379 journal = EXT4_JOURNAL(inode);
3380 jbd2_journal_lock_updates(journal);
3381 err = jbd2_journal_flush(journal);
3382 jbd2_journal_unlock_updates(journal);
3388 return generic_block_bmap(mapping, block, ext4_get_block);
3391 static int ext4_readpage(struct file *file, struct page *page)
3394 struct inode *inode = page->mapping->host;
3396 trace_ext4_readpage(page);
3398 if (ext4_has_inline_data(inode))
3399 ret = ext4_readpage_inline(inode, page);
3402 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3408 ext4_readpages(struct file *file, struct address_space *mapping,
3409 struct list_head *pages, unsigned nr_pages)
3411 struct inode *inode = mapping->host;
3413 /* If the file has inline data, no need to do readpages. */
3414 if (ext4_has_inline_data(inode))
3417 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3420 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3421 unsigned int length)
3423 trace_ext4_invalidatepage(page, offset, length);
3425 /* No journalling happens on data buffers when this function is used */
3426 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3428 block_invalidatepage(page, offset, length);
3431 static int __ext4_journalled_invalidatepage(struct page *page,
3432 unsigned int offset,
3433 unsigned int length)
3435 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3437 trace_ext4_journalled_invalidatepage(page, offset, length);
3440 * If it's a full truncate we just forget about the pending dirtying
3442 if (offset == 0 && length == PAGE_SIZE)
3443 ClearPageChecked(page);
3445 return jbd2_journal_invalidatepage(journal, page, offset, length);
3448 /* Wrapper for aops... */
3449 static void ext4_journalled_invalidatepage(struct page *page,
3450 unsigned int offset,
3451 unsigned int length)
3453 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3456 static int ext4_releasepage(struct page *page, gfp_t wait)
3458 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3460 trace_ext4_releasepage(page);
3462 /* Page has dirty journalled data -> cannot release */
3463 if (PageChecked(page))
3466 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3468 return try_to_free_buffers(page);
3471 #ifdef CONFIG_FS_DAX
3472 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3473 unsigned flags, struct iomap *iomap)
3475 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3476 unsigned int blkbits = inode->i_blkbits;
3477 unsigned long first_block, last_block;
3478 struct ext4_map_blocks map;
3481 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3483 first_block = offset >> blkbits;
3484 last_block = min_t(loff_t, (offset + length - 1) >> blkbits,
3485 EXT4_MAX_LOGICAL_BLOCK);
3487 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3490 map.m_lblk = first_block;
3491 map.m_len = last_block - first_block + 1;
3493 if (!(flags & IOMAP_WRITE)) {
3494 ret = ext4_map_blocks(NULL, inode, &map, 0);
3500 /* Trim mapping request to maximum we can map at once for DIO */
3501 if (map.m_len > DIO_MAX_BLOCKS)
3502 map.m_len = DIO_MAX_BLOCKS;
3503 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3506 * Either we allocate blocks and then we don't get unwritten
3507 * extent so we have reserved enough credits, or the blocks
3508 * are already allocated and unwritten and in that case
3509 * extent conversion fits in the credits as well.
3511 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3514 return PTR_ERR(handle);
3516 ret = ext4_map_blocks(handle, inode, &map,
3517 EXT4_GET_BLOCKS_CREATE_ZERO);
3519 ext4_journal_stop(handle);
3520 if (ret == -ENOSPC &&
3521 ext4_should_retry_alloc(inode->i_sb, &retries))
3527 * If we added blocks beyond i_size, we need to make sure they
3528 * will get truncated if we crash before updating i_size in
3529 * ext4_iomap_end(). For faults we don't need to do that (and
3530 * even cannot because for orphan list operations inode_lock is
3531 * required) - if we happen to instantiate block beyond i_size,
3532 * it is because we race with truncate which has already added
3533 * the inode to the orphan list.
3535 if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3536 (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
3539 err = ext4_orphan_add(handle, inode);
3541 ext4_journal_stop(handle);
3545 ext4_journal_stop(handle);
3549 iomap->bdev = inode->i_sb->s_bdev;
3550 iomap->dax_dev = sbi->s_daxdev;
3551 iomap->offset = first_block << blkbits;
3554 iomap->type = IOMAP_HOLE;
3555 iomap->blkno = IOMAP_NULL_BLOCK;
3556 iomap->length = (u64)map.m_len << blkbits;
3558 if (map.m_flags & EXT4_MAP_MAPPED) {
3559 iomap->type = IOMAP_MAPPED;
3560 } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3561 iomap->type = IOMAP_UNWRITTEN;
3566 iomap->blkno = (sector_t)map.m_pblk << (blkbits - 9);
3567 iomap->length = (u64)map.m_len << blkbits;
3570 if (map.m_flags & EXT4_MAP_NEW)
3571 iomap->flags |= IOMAP_F_NEW;
3575 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3576 ssize_t written, unsigned flags, struct iomap *iomap)
3580 int blkbits = inode->i_blkbits;
3581 bool truncate = false;
3583 if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
3586 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3587 if (IS_ERR(handle)) {
3588 ret = PTR_ERR(handle);
3591 if (ext4_update_inode_size(inode, offset + written))
3592 ext4_mark_inode_dirty(handle, inode);
3594 * We may need to truncate allocated but not written blocks beyond EOF.
3596 if (iomap->offset + iomap->length >
3597 ALIGN(inode->i_size, 1 << blkbits)) {
3598 ext4_lblk_t written_blk, end_blk;
3600 written_blk = (offset + written) >> blkbits;
3601 end_blk = (offset + length) >> blkbits;
3602 if (written_blk < end_blk && ext4_can_truncate(inode))
3606 * Remove inode from orphan list if we were extending a inode and
3607 * everything went fine.
3609 if (!truncate && inode->i_nlink &&
3610 !list_empty(&EXT4_I(inode)->i_orphan))
3611 ext4_orphan_del(handle, inode);
3612 ext4_journal_stop(handle);
3614 ext4_truncate_failed_write(inode);
3617 * If truncate failed early the inode might still be on the
3618 * orphan list; we need to make sure the inode is removed from
3619 * the orphan list in that case.
3622 ext4_orphan_del(NULL, inode);
3627 const struct iomap_ops ext4_iomap_ops = {
3628 .iomap_begin = ext4_iomap_begin,
3629 .iomap_end = ext4_iomap_end,
3634 static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3635 ssize_t size, void *private)
3637 ext4_io_end_t *io_end = private;
3639 /* if not async direct IO just return */
3643 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3644 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3645 io_end, io_end->inode->i_ino, iocb, offset, size);
3648 * Error during AIO DIO. We cannot convert unwritten extents as the
3649 * data was not written. Just clear the unwritten flag and drop io_end.
3652 ext4_clear_io_unwritten_flag(io_end);
3655 io_end->offset = offset;
3656 io_end->size = size;
3657 ext4_put_io_end(io_end);
3663 * Handling of direct IO writes.
3665 * For ext4 extent files, ext4 will do direct-io write even to holes,
3666 * preallocated extents, and those write extend the file, no need to
3667 * fall back to buffered IO.
3669 * For holes, we fallocate those blocks, mark them as unwritten
3670 * If those blocks were preallocated, we mark sure they are split, but
3671 * still keep the range to write as unwritten.
3673 * The unwritten extents will be converted to written when DIO is completed.
3674 * For async direct IO, since the IO may still pending when return, we
3675 * set up an end_io call back function, which will do the conversion
3676 * when async direct IO completed.
3678 * If the O_DIRECT write will extend the file then add this inode to the
3679 * orphan list. So recovery will truncate it back to the original size
3680 * if the machine crashes during the write.
3683 static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
3685 struct file *file = iocb->ki_filp;
3686 struct inode *inode = file->f_mapping->host;
3688 loff_t offset = iocb->ki_pos;
3689 size_t count = iov_iter_count(iter);
3691 get_block_t *get_block_func = NULL;
3693 loff_t final_size = offset + count;
3697 if (final_size > inode->i_size) {
3698 /* Credits for sb + inode write */
3699 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3700 if (IS_ERR(handle)) {
3701 ret = PTR_ERR(handle);
3704 ret = ext4_orphan_add(handle, inode);
3706 ext4_journal_stop(handle);
3710 ext4_update_i_disksize(inode, inode->i_size);
3711 ext4_journal_stop(handle);
3714 BUG_ON(iocb->private == NULL);
3717 * Make all waiters for direct IO properly wait also for extent
3718 * conversion. This also disallows race between truncate() and
3719 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3721 inode_dio_begin(inode);
3723 /* If we do a overwrite dio, i_mutex locking can be released */
3724 overwrite = *((int *)iocb->private);
3727 inode_unlock(inode);
3730 * For extent mapped files we could direct write to holes and fallocate.
3732 * Allocated blocks to fill the hole are marked as unwritten to prevent
3733 * parallel buffered read to expose the stale data before DIO complete
3736 * As to previously fallocated extents, ext4 get_block will just simply
3737 * mark the buffer mapped but still keep the extents unwritten.
3739 * For non AIO case, we will convert those unwritten extents to written
3740 * after return back from blockdev_direct_IO. That way we save us from
3741 * allocating io_end structure and also the overhead of offloading
3742 * the extent convertion to a workqueue.
3744 * For async DIO, the conversion needs to be deferred when the
3745 * IO is completed. The ext4 end_io callback function will be
3746 * called to take care of the conversion work. Here for async
3747 * case, we allocate an io_end structure to hook to the iocb.
3749 iocb->private = NULL;
3751 get_block_func = ext4_dio_get_block_overwrite;
3752 else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
3753 round_down(offset, i_blocksize(inode)) >= inode->i_size) {
3754 get_block_func = ext4_dio_get_block;
3755 dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3756 } else if (is_sync_kiocb(iocb)) {
3757 get_block_func = ext4_dio_get_block_unwritten_sync;
3758 dio_flags = DIO_LOCKING;
3760 get_block_func = ext4_dio_get_block_unwritten_async;
3761 dio_flags = DIO_LOCKING;
3763 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3764 get_block_func, ext4_end_io_dio, NULL,
3767 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3768 EXT4_STATE_DIO_UNWRITTEN)) {
3771 * for non AIO case, since the IO is already
3772 * completed, we could do the conversion right here
3774 err = ext4_convert_unwritten_extents(NULL, inode,
3778 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3781 inode_dio_end(inode);
3782 /* take i_mutex locking again if we do a ovewrite dio */
3786 if (ret < 0 && final_size > inode->i_size)
3787 ext4_truncate_failed_write(inode);
3789 /* Handle extending of i_size after direct IO write */
3793 /* Credits for sb + inode write */
3794 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3795 if (IS_ERR(handle)) {
3797 * We wrote the data but cannot extend
3798 * i_size. Bail out. In async io case, we do
3799 * not return error here because we have
3800 * already submmitted the corresponding
3801 * bio. Returning error here makes the caller
3802 * think that this IO is done and failed
3803 * resulting in race with bio's completion
3807 ret = PTR_ERR(handle);
3809 ext4_orphan_del(NULL, inode);
3814 ext4_orphan_del(handle, inode);
3816 loff_t end = offset + ret;
3817 if (end > inode->i_size) {
3818 ext4_update_i_disksize(inode, end);
3819 i_size_write(inode, end);
3821 * We're going to return a positive `ret'
3822 * here due to non-zero-length I/O, so there's
3823 * no way of reporting error returns from
3824 * ext4_mark_inode_dirty() to userspace. So
3827 ext4_mark_inode_dirty(handle, inode);
3830 err = ext4_journal_stop(handle);
3838 static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
3840 struct address_space *mapping = iocb->ki_filp->f_mapping;
3841 struct inode *inode = mapping->host;
3842 size_t count = iov_iter_count(iter);
3844 loff_t offset = iocb->ki_pos;
3845 loff_t size = i_size_read(inode);
3851 * Shared inode_lock is enough for us - it protects against concurrent
3852 * writes & truncates and since we take care of writing back page cache,
3853 * we are protected against page writeback as well.
3855 if (iocb->ki_flags & IOCB_NOWAIT) {
3856 if (!inode_trylock_shared(inode))
3859 inode_lock_shared(inode);
3862 ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
3863 iocb->ki_pos + count - 1);
3866 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
3867 iter, ext4_dio_get_block, NULL, NULL, 0);
3869 inode_unlock_shared(inode);
3873 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
3875 struct file *file = iocb->ki_filp;
3876 struct inode *inode = file->f_mapping->host;
3877 size_t count = iov_iter_count(iter);
3878 loff_t offset = iocb->ki_pos;
3881 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3882 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3887 * If we are doing data journalling we don't support O_DIRECT
3889 if (ext4_should_journal_data(inode))
3892 /* Let buffer I/O handle the inline data case. */
3893 if (ext4_has_inline_data(inode))
3896 /* DAX uses iomap path now */
3897 if (WARN_ON_ONCE(IS_DAX(inode)))
3900 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3901 if (iov_iter_rw(iter) == READ)
3902 ret = ext4_direct_IO_read(iocb, iter);
3904 ret = ext4_direct_IO_write(iocb, iter);
3905 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3910 * Pages can be marked dirty completely asynchronously from ext4's journalling
3911 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3912 * much here because ->set_page_dirty is called under VFS locks. The page is
3913 * not necessarily locked.
3915 * We cannot just dirty the page and leave attached buffers clean, because the
3916 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3917 * or jbddirty because all the journalling code will explode.
3919 * So what we do is to mark the page "pending dirty" and next time writepage
3920 * is called, propagate that into the buffers appropriately.
3922 static int ext4_journalled_set_page_dirty(struct page *page)
3924 SetPageChecked(page);
3925 return __set_page_dirty_nobuffers(page);
3928 static int ext4_set_page_dirty(struct page *page)
3930 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3931 WARN_ON_ONCE(!page_has_buffers(page));
3932 return __set_page_dirty_buffers(page);
3935 static const struct address_space_operations ext4_aops = {
3936 .readpage = ext4_readpage,
3937 .readpages = ext4_readpages,
3938 .writepage = ext4_writepage,
3939 .writepages = ext4_writepages,
3940 .write_begin = ext4_write_begin,
3941 .write_end = ext4_write_end,
3942 .set_page_dirty = ext4_set_page_dirty,
3944 .invalidatepage = ext4_invalidatepage,
3945 .releasepage = ext4_releasepage,
3946 .direct_IO = ext4_direct_IO,
3947 .migratepage = buffer_migrate_page,
3948 .is_partially_uptodate = block_is_partially_uptodate,
3949 .error_remove_page = generic_error_remove_page,
3952 static const struct address_space_operations ext4_journalled_aops = {
3953 .readpage = ext4_readpage,
3954 .readpages = ext4_readpages,
3955 .writepage = ext4_writepage,
3956 .writepages = ext4_writepages,
3957 .write_begin = ext4_write_begin,
3958 .write_end = ext4_journalled_write_end,
3959 .set_page_dirty = ext4_journalled_set_page_dirty,
3961 .invalidatepage = ext4_journalled_invalidatepage,
3962 .releasepage = ext4_releasepage,
3963 .direct_IO = ext4_direct_IO,
3964 .is_partially_uptodate = block_is_partially_uptodate,
3965 .error_remove_page = generic_error_remove_page,
3968 static const struct address_space_operations ext4_da_aops = {
3969 .readpage = ext4_readpage,
3970 .readpages = ext4_readpages,
3971 .writepage = ext4_writepage,
3972 .writepages = ext4_writepages,
3973 .write_begin = ext4_da_write_begin,
3974 .write_end = ext4_da_write_end,
3975 .set_page_dirty = ext4_set_page_dirty,
3977 .invalidatepage = ext4_da_invalidatepage,
3978 .releasepage = ext4_releasepage,
3979 .direct_IO = ext4_direct_IO,
3980 .migratepage = buffer_migrate_page,
3981 .is_partially_uptodate = block_is_partially_uptodate,
3982 .error_remove_page = generic_error_remove_page,
3985 void ext4_set_aops(struct inode *inode)
3987 switch (ext4_inode_journal_mode(inode)) {
3988 case EXT4_INODE_ORDERED_DATA_MODE:
3989 case EXT4_INODE_WRITEBACK_DATA_MODE:
3991 case EXT4_INODE_JOURNAL_DATA_MODE:
3992 inode->i_mapping->a_ops = &ext4_journalled_aops;
3997 if (test_opt(inode->i_sb, DELALLOC))
3998 inode->i_mapping->a_ops = &ext4_da_aops;
4000 inode->i_mapping->a_ops = &ext4_aops;
4003 static int __ext4_block_zero_page_range(handle_t *handle,
4004 struct address_space *mapping, loff_t from, loff_t length)
4006 ext4_fsblk_t index = from >> PAGE_SHIFT;
4007 unsigned offset = from & (PAGE_SIZE-1);
4008 unsigned blocksize, pos;
4010 struct inode *inode = mapping->host;
4011 struct buffer_head *bh;
4015 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
4016 mapping_gfp_constraint(mapping, ~__GFP_FS));
4020 blocksize = inode->i_sb->s_blocksize;
4022 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
4024 if (!page_has_buffers(page))
4025 create_empty_buffers(page, blocksize, 0);
4027 /* Find the buffer that contains "offset" */
4028 bh = page_buffers(page);
4030 while (offset >= pos) {
4031 bh = bh->b_this_page;
4035 if (buffer_freed(bh)) {
4036 BUFFER_TRACE(bh, "freed: skip");
4039 if (!buffer_mapped(bh)) {
4040 BUFFER_TRACE(bh, "unmapped");
4041 ext4_get_block(inode, iblock, bh, 0);
4042 /* unmapped? It's a hole - nothing to do */
4043 if (!buffer_mapped(bh)) {
4044 BUFFER_TRACE(bh, "still unmapped");
4049 /* Ok, it's mapped. Make sure it's up-to-date */
4050 if (PageUptodate(page))
4051 set_buffer_uptodate(bh);
4053 if (!buffer_uptodate(bh)) {
4055 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
4057 /* Uhhuh. Read error. Complain and punt. */
4058 if (!buffer_uptodate(bh))
4060 if (S_ISREG(inode->i_mode) &&
4061 ext4_encrypted_inode(inode)) {
4062 /* We expect the key to be set. */
4063 BUG_ON(!fscrypt_has_encryption_key(inode));
4064 BUG_ON(blocksize != PAGE_SIZE);
4065 WARN_ON_ONCE(fscrypt_decrypt_page(page->mapping->host,
4066 page, PAGE_SIZE, 0, page->index));
4069 if (ext4_should_journal_data(inode)) {
4070 BUFFER_TRACE(bh, "get write access");
4071 err = ext4_journal_get_write_access(handle, bh);
4075 zero_user(page, offset, length);
4076 BUFFER_TRACE(bh, "zeroed end of block");
4078 if (ext4_should_journal_data(inode)) {
4079 err = ext4_handle_dirty_metadata(handle, inode, bh);
4082 mark_buffer_dirty(bh);
4083 if (ext4_should_order_data(inode))
4084 err = ext4_jbd2_inode_add_write(handle, inode, from,
4095 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4096 * starting from file offset 'from'. The range to be zero'd must
4097 * be contained with in one block. If the specified range exceeds
4098 * the end of the block it will be shortened to end of the block
4099 * that cooresponds to 'from'
4101 static int ext4_block_zero_page_range(handle_t *handle,
4102 struct address_space *mapping, loff_t from, loff_t length)
4104 struct inode *inode = mapping->host;
4105 unsigned offset = from & (PAGE_SIZE-1);
4106 unsigned blocksize = inode->i_sb->s_blocksize;
4107 unsigned max = blocksize - (offset & (blocksize - 1));
4110 * correct length if it does not fall between
4111 * 'from' and the end of the block
4113 if (length > max || length < 0)
4116 if (IS_DAX(inode)) {
4117 return iomap_zero_range(inode, from, length, NULL,
4120 return __ext4_block_zero_page_range(handle, mapping, from, length);
4124 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4125 * up to the end of the block which corresponds to `from'.
4126 * This required during truncate. We need to physically zero the tail end
4127 * of that block so it doesn't yield old data if the file is later grown.
4129 static int ext4_block_truncate_page(handle_t *handle,
4130 struct address_space *mapping, loff_t from)
4132 unsigned offset = from & (PAGE_SIZE-1);
4135 struct inode *inode = mapping->host;
4137 /* If we are processing an encrypted inode during orphan list handling */
4138 if (ext4_encrypted_inode(inode) && !fscrypt_has_encryption_key(inode))
4141 blocksize = inode->i_sb->s_blocksize;
4142 length = blocksize - (offset & (blocksize - 1));
4144 return ext4_block_zero_page_range(handle, mapping, from, length);
4147 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4148 loff_t lstart, loff_t length)
4150 struct super_block *sb = inode->i_sb;
4151 struct address_space *mapping = inode->i_mapping;
4152 unsigned partial_start, partial_end;
4153 ext4_fsblk_t start, end;
4154 loff_t byte_end = (lstart + length - 1);
4157 partial_start = lstart & (sb->s_blocksize - 1);
4158 partial_end = byte_end & (sb->s_blocksize - 1);
4160 start = lstart >> sb->s_blocksize_bits;
4161 end = byte_end >> sb->s_blocksize_bits;
4163 /* Handle partial zero within the single block */
4165 (partial_start || (partial_end != sb->s_blocksize - 1))) {
4166 err = ext4_block_zero_page_range(handle, mapping,
4170 /* Handle partial zero out on the start of the range */
4171 if (partial_start) {
4172 err = ext4_block_zero_page_range(handle, mapping,
4173 lstart, sb->s_blocksize);
4177 /* Handle partial zero out on the end of the range */
4178 if (partial_end != sb->s_blocksize - 1)
4179 err = ext4_block_zero_page_range(handle, mapping,
4180 byte_end - partial_end,
4185 int ext4_can_truncate(struct inode *inode)
4187 if (S_ISREG(inode->i_mode))
4189 if (S_ISDIR(inode->i_mode))
4191 if (S_ISLNK(inode->i_mode))
4192 return !ext4_inode_is_fast_symlink(inode);
4197 * We have to make sure i_disksize gets properly updated before we truncate
4198 * page cache due to hole punching or zero range. Otherwise i_disksize update
4199 * can get lost as it may have been postponed to submission of writeback but
4200 * that will never happen after we truncate page cache.
4202 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4206 loff_t size = i_size_read(inode);
4208 WARN_ON(!inode_is_locked(inode));
4209 if (offset > size || offset + len < size)
4212 if (EXT4_I(inode)->i_disksize >= size)
4215 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4217 return PTR_ERR(handle);
4218 ext4_update_i_disksize(inode, size);
4219 ext4_mark_inode_dirty(handle, inode);
4220 ext4_journal_stop(handle);
4226 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4227 * associated with the given offset and length
4229 * @inode: File inode
4230 * @offset: The offset where the hole will begin
4231 * @len: The length of the hole
4233 * Returns: 0 on success or negative on failure
4236 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4238 struct super_block *sb = inode->i_sb;
4239 ext4_lblk_t first_block, stop_block;
4240 struct address_space *mapping = inode->i_mapping;
4241 loff_t first_block_offset, last_block_offset, max_length;
4242 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4244 unsigned int credits;
4247 if (!S_ISREG(inode->i_mode))
4250 trace_ext4_punch_hole(inode, offset, length, 0);
4252 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4253 if (ext4_has_inline_data(inode)) {
4254 down_write(&EXT4_I(inode)->i_mmap_sem);
4255 ret = ext4_convert_inline_data(inode);
4256 up_write(&EXT4_I(inode)->i_mmap_sem);
4262 * Write out all dirty pages to avoid race conditions
4263 * Then release them.
4265 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4266 ret = filemap_write_and_wait_range(mapping, offset,
4267 offset + length - 1);
4274 /* No need to punch hole beyond i_size */
4275 if (offset >= inode->i_size)
4279 * If the hole extends beyond i_size, set the hole
4280 * to end after the page that contains i_size
4282 if (offset + length > inode->i_size) {
4283 length = inode->i_size +
4284 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4289 * For punch hole the length + offset needs to be within one block
4290 * before last range. Adjust the length if it goes beyond that limit.
4292 max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
4293 if (offset + length > max_length)
4294 length = max_length - offset;
4296 if (offset & (sb->s_blocksize - 1) ||
4297 (offset + length) & (sb->s_blocksize - 1)) {
4299 * Attach jinode to inode for jbd2 if we do any zeroing of
4302 ret = ext4_inode_attach_jinode(inode);
4308 /* Wait all existing dio workers, newcomers will block on i_mutex */
4309 ext4_inode_block_unlocked_dio(inode);
4310 inode_dio_wait(inode);
4313 * Prevent page faults from reinstantiating pages we have released from
4316 down_write(&EXT4_I(inode)->i_mmap_sem);
4317 first_block_offset = round_up(offset, sb->s_blocksize);
4318 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4320 /* Now release the pages and zero block aligned part of pages*/
4321 if (last_block_offset > first_block_offset) {
4322 ret = ext4_update_disksize_before_punch(inode, offset, length);
4325 truncate_pagecache_range(inode, first_block_offset,
4329 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4330 credits = ext4_writepage_trans_blocks(inode);
4332 credits = ext4_blocks_for_truncate(inode);
4333 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4334 if (IS_ERR(handle)) {
4335 ret = PTR_ERR(handle);
4336 ext4_std_error(sb, ret);
4340 ret = ext4_zero_partial_blocks(handle, inode, offset,
4345 first_block = (offset + sb->s_blocksize - 1) >>
4346 EXT4_BLOCK_SIZE_BITS(sb);
4347 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4349 /* If there are blocks to remove, do it */
4350 if (stop_block > first_block) {
4352 down_write(&EXT4_I(inode)->i_data_sem);
4353 ext4_discard_preallocations(inode);
4355 ret = ext4_es_remove_extent(inode, first_block,
4356 stop_block - first_block);
4358 up_write(&EXT4_I(inode)->i_data_sem);
4362 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4363 ret = ext4_ext_remove_space(inode, first_block,
4366 ret = ext4_ind_remove_space(handle, inode, first_block,
4369 up_write(&EXT4_I(inode)->i_data_sem);
4372 ext4_handle_sync(handle);
4374 inode->i_mtime = inode->i_ctime = current_time(inode);
4375 ext4_mark_inode_dirty(handle, inode);
4377 ext4_update_inode_fsync_trans(handle, inode, 1);
4379 ext4_journal_stop(handle);
4381 up_write(&EXT4_I(inode)->i_mmap_sem);
4382 ext4_inode_resume_unlocked_dio(inode);
4384 inode_unlock(inode);
4388 int ext4_inode_attach_jinode(struct inode *inode)
4390 struct ext4_inode_info *ei = EXT4_I(inode);
4391 struct jbd2_inode *jinode;
4393 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4396 jinode = jbd2_alloc_inode(GFP_KERNEL);
4397 spin_lock(&inode->i_lock);
4400 spin_unlock(&inode->i_lock);
4403 ei->jinode = jinode;
4404 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4407 spin_unlock(&inode->i_lock);
4408 if (unlikely(jinode != NULL))
4409 jbd2_free_inode(jinode);
4416 * We block out ext4_get_block() block instantiations across the entire
4417 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4418 * simultaneously on behalf of the same inode.
4420 * As we work through the truncate and commit bits of it to the journal there
4421 * is one core, guiding principle: the file's tree must always be consistent on
4422 * disk. We must be able to restart the truncate after a crash.
4424 * The file's tree may be transiently inconsistent in memory (although it
4425 * probably isn't), but whenever we close off and commit a journal transaction,
4426 * the contents of (the filesystem + the journal) must be consistent and
4427 * restartable. It's pretty simple, really: bottom up, right to left (although
4428 * left-to-right works OK too).
4430 * Note that at recovery time, journal replay occurs *before* the restart of
4431 * truncate against the orphan inode list.
4433 * The committed inode has the new, desired i_size (which is the same as
4434 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4435 * that this inode's truncate did not complete and it will again call
4436 * ext4_truncate() to have another go. So there will be instantiated blocks
4437 * to the right of the truncation point in a crashed ext4 filesystem. But
4438 * that's fine - as long as they are linked from the inode, the post-crash
4439 * ext4_truncate() run will find them and release them.
4441 int ext4_truncate(struct inode *inode)
4443 struct ext4_inode_info *ei = EXT4_I(inode);
4444 unsigned int credits;
4447 struct address_space *mapping = inode->i_mapping;
4450 * There is a possibility that we're either freeing the inode
4451 * or it's a completely new inode. In those cases we might not
4452 * have i_mutex locked because it's not necessary.
4454 if (!(inode->i_state & (I_NEW|I_FREEING)))
4455 WARN_ON(!inode_is_locked(inode));
4456 trace_ext4_truncate_enter(inode);
4458 if (!ext4_can_truncate(inode))
4461 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4463 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4464 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4466 if (ext4_has_inline_data(inode)) {
4469 err = ext4_inline_data_truncate(inode, &has_inline);
4476 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4477 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4478 if (ext4_inode_attach_jinode(inode) < 0)
4482 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4483 credits = ext4_writepage_trans_blocks(inode);
4485 credits = ext4_blocks_for_truncate(inode);
4487 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4489 return PTR_ERR(handle);
4491 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4492 ext4_block_truncate_page(handle, mapping, inode->i_size);
4495 * We add the inode to the orphan list, so that if this
4496 * truncate spans multiple transactions, and we crash, we will
4497 * resume the truncate when the filesystem recovers. It also
4498 * marks the inode dirty, to catch the new size.
4500 * Implication: the file must always be in a sane, consistent
4501 * truncatable state while each transaction commits.
4503 err = ext4_orphan_add(handle, inode);
4507 down_write(&EXT4_I(inode)->i_data_sem);
4509 ext4_discard_preallocations(inode);
4511 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4512 err = ext4_ext_truncate(handle, inode);
4514 ext4_ind_truncate(handle, inode);
4516 up_write(&ei->i_data_sem);
4521 ext4_handle_sync(handle);
4525 * If this was a simple ftruncate() and the file will remain alive,
4526 * then we need to clear up the orphan record which we created above.
4527 * However, if this was a real unlink then we were called by
4528 * ext4_evict_inode(), and we allow that function to clean up the
4529 * orphan info for us.
4532 ext4_orphan_del(handle, inode);
4534 inode->i_mtime = inode->i_ctime = current_time(inode);
4535 ext4_mark_inode_dirty(handle, inode);
4536 ext4_journal_stop(handle);
4538 trace_ext4_truncate_exit(inode);
4543 * ext4_get_inode_loc returns with an extra refcount against the inode's
4544 * underlying buffer_head on success. If 'in_mem' is true, we have all
4545 * data in memory that is needed to recreate the on-disk version of this
4548 static int __ext4_get_inode_loc(struct inode *inode,
4549 struct ext4_iloc *iloc, int in_mem)
4551 struct ext4_group_desc *gdp;
4552 struct buffer_head *bh;
4553 struct super_block *sb = inode->i_sb;
4555 int inodes_per_block, inode_offset;
4558 if (inode->i_ino < EXT4_ROOT_INO ||
4559 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4560 return -EFSCORRUPTED;
4562 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4563 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4568 * Figure out the offset within the block group inode table
4570 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4571 inode_offset = ((inode->i_ino - 1) %
4572 EXT4_INODES_PER_GROUP(sb));
4573 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4574 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4576 bh = sb_getblk(sb, block);
4579 if (!buffer_uptodate(bh)) {
4583 * If the buffer has the write error flag, we have failed
4584 * to write out another inode in the same block. In this
4585 * case, we don't have to read the block because we may
4586 * read the old inode data successfully.
4588 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4589 set_buffer_uptodate(bh);
4591 if (buffer_uptodate(bh)) {
4592 /* someone brought it uptodate while we waited */
4598 * If we have all information of the inode in memory and this
4599 * is the only valid inode in the block, we need not read the
4603 struct buffer_head *bitmap_bh;
4606 start = inode_offset & ~(inodes_per_block - 1);
4608 /* Is the inode bitmap in cache? */
4609 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4610 if (unlikely(!bitmap_bh))
4614 * If the inode bitmap isn't in cache then the
4615 * optimisation may end up performing two reads instead
4616 * of one, so skip it.
4618 if (!buffer_uptodate(bitmap_bh)) {
4622 for (i = start; i < start + inodes_per_block; i++) {
4623 if (i == inode_offset)
4625 if (ext4_test_bit(i, bitmap_bh->b_data))
4629 if (i == start + inodes_per_block) {
4630 /* all other inodes are free, so skip I/O */
4631 memset(bh->b_data, 0, bh->b_size);
4632 set_buffer_uptodate(bh);
4640 * If we need to do any I/O, try to pre-readahead extra
4641 * blocks from the inode table.
4643 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4644 ext4_fsblk_t b, end, table;
4646 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4648 table = ext4_inode_table(sb, gdp);
4649 /* s_inode_readahead_blks is always a power of 2 */
4650 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4654 num = EXT4_INODES_PER_GROUP(sb);
4655 if (ext4_has_group_desc_csum(sb))
4656 num -= ext4_itable_unused_count(sb, gdp);
4657 table += num / inodes_per_block;
4661 sb_breadahead_unmovable(sb, b++);
4665 * There are other valid inodes in the buffer, this inode
4666 * has in-inode xattrs, or we don't have this inode in memory.
4667 * Read the block from disk.
4669 trace_ext4_load_inode(inode);
4671 bh->b_end_io = end_buffer_read_sync;
4672 submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
4674 if (!buffer_uptodate(bh)) {
4675 EXT4_ERROR_INODE_BLOCK(inode, block,
4676 "unable to read itable block");
4686 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4688 /* We have all inode data except xattrs in memory here. */
4689 return __ext4_get_inode_loc(inode, iloc,
4690 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4693 void ext4_set_inode_flags(struct inode *inode)
4695 unsigned int flags = EXT4_I(inode)->i_flags;
4696 unsigned int new_fl = 0;
4698 if (flags & EXT4_SYNC_FL)
4700 if (flags & EXT4_APPEND_FL)
4702 if (flags & EXT4_IMMUTABLE_FL)
4703 new_fl |= S_IMMUTABLE;
4704 if (flags & EXT4_NOATIME_FL)
4705 new_fl |= S_NOATIME;
4706 if (flags & EXT4_DIRSYNC_FL)
4707 new_fl |= S_DIRSYNC;
4708 if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode) &&
4709 !ext4_should_journal_data(inode) && !ext4_has_inline_data(inode) &&
4710 !ext4_encrypted_inode(inode))
4712 inode_set_flags(inode, new_fl,
4713 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4716 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4717 struct ext4_inode_info *ei)
4720 struct inode *inode = &(ei->vfs_inode);
4721 struct super_block *sb = inode->i_sb;
4723 if (ext4_has_feature_huge_file(sb)) {
4724 /* we are using combined 48 bit field */
4725 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4726 le32_to_cpu(raw_inode->i_blocks_lo);
4727 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4728 /* i_blocks represent file system block size */
4729 return i_blocks << (inode->i_blkbits - 9);
4734 return le32_to_cpu(raw_inode->i_blocks_lo);
4738 static inline int ext4_iget_extra_inode(struct inode *inode,
4739 struct ext4_inode *raw_inode,
4740 struct ext4_inode_info *ei)
4742 __le32 *magic = (void *)raw_inode +
4743 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4745 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
4746 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4747 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4748 return ext4_find_inline_data_nolock(inode);
4750 EXT4_I(inode)->i_inline_off = 0;
4754 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4756 if (!ext4_has_feature_project(inode->i_sb))
4758 *projid = EXT4_I(inode)->i_projid;
4762 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4763 ext4_iget_flags flags, const char *function,
4766 struct ext4_iloc iloc;
4767 struct ext4_inode *raw_inode;
4768 struct ext4_inode_info *ei;
4769 struct inode *inode;
4770 journal_t *journal = EXT4_SB(sb)->s_journal;
4778 if ((!(flags & EXT4_IGET_SPECIAL) &&
4779 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4780 (ino < EXT4_ROOT_INO) ||
4781 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4782 if (flags & EXT4_IGET_HANDLE)
4783 return ERR_PTR(-ESTALE);
4784 __ext4_error(sb, function, line,
4785 "inode #%lu: comm %s: iget: illegal inode #",
4786 ino, current->comm);
4787 return ERR_PTR(-EFSCORRUPTED);
4790 inode = iget_locked(sb, ino);
4792 return ERR_PTR(-ENOMEM);
4793 if (!(inode->i_state & I_NEW))
4799 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4802 raw_inode = ext4_raw_inode(&iloc);
4804 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4805 ext4_error_inode(inode, function, line, 0,
4806 "iget: root inode unallocated");
4807 ret = -EFSCORRUPTED;
4811 if ((flags & EXT4_IGET_HANDLE) &&
4812 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4817 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4818 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4819 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4820 EXT4_INODE_SIZE(inode->i_sb) ||
4821 (ei->i_extra_isize & 3)) {
4822 ext4_error_inode(inode, function, line, 0,
4823 "iget: bad extra_isize %u "
4826 EXT4_INODE_SIZE(inode->i_sb));
4827 ret = -EFSCORRUPTED;
4831 ei->i_extra_isize = 0;
4833 /* Precompute checksum seed for inode metadata */
4834 if (ext4_has_metadata_csum(sb)) {
4835 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4837 __le32 inum = cpu_to_le32(inode->i_ino);
4838 __le32 gen = raw_inode->i_generation;
4839 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4841 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4845 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4846 ext4_error_inode(inode, function, line, 0,
4847 "iget: checksum invalid");
4852 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4853 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4854 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4855 if (ext4_has_feature_project(sb) &&
4856 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4857 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4858 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4860 i_projid = EXT4_DEF_PROJID;
4862 if (!(test_opt(inode->i_sb, NO_UID32))) {
4863 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4864 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4866 i_uid_write(inode, i_uid);
4867 i_gid_write(inode, i_gid);
4868 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4869 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4871 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4872 ei->i_inline_off = 0;
4873 ei->i_dir_start_lookup = 0;
4874 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4875 /* We now have enough fields to check if the inode was active or not.
4876 * This is needed because nfsd might try to access dead inodes
4877 * the test is that same one that e2fsck uses
4878 * NeilBrown 1999oct15
4880 if (inode->i_nlink == 0) {
4881 if ((inode->i_mode == 0 ||
4882 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4883 ino != EXT4_BOOT_LOADER_INO) {
4884 /* this inode is deleted */
4888 /* The only unlinked inodes we let through here have
4889 * valid i_mode and are being read by the orphan
4890 * recovery code: that's fine, we're about to complete
4891 * the process of deleting those.
4892 * OR it is the EXT4_BOOT_LOADER_INO which is
4893 * not initialized on a new filesystem. */
4895 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4896 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4897 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4898 if (ext4_has_feature_64bit(sb))
4900 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4901 inode->i_size = ext4_isize(sb, raw_inode);
4902 if ((size = i_size_read(inode)) < 0) {
4903 ext4_error_inode(inode, function, line, 0,
4904 "iget: bad i_size value: %lld", size);
4905 ret = -EFSCORRUPTED;
4909 * If dir_index is not enabled but there's dir with INDEX flag set,
4910 * we'd normally treat htree data as empty space. But with metadata
4911 * checksumming that corrupts checksums so forbid that.
4913 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4914 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4915 EXT4_ERROR_INODE(inode,
4916 "iget: Dir with htree data on filesystem without dir_index feature.");
4917 ret = -EFSCORRUPTED;
4920 ei->i_disksize = inode->i_size;
4922 ei->i_reserved_quota = 0;
4924 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4925 ei->i_block_group = iloc.block_group;
4926 ei->i_last_alloc_group = ~0;
4928 * NOTE! The in-memory inode i_data array is in little-endian order
4929 * even on big-endian machines: we do NOT byteswap the block numbers!
4931 for (block = 0; block < EXT4_N_BLOCKS; block++)
4932 ei->i_data[block] = raw_inode->i_block[block];
4933 INIT_LIST_HEAD(&ei->i_orphan);
4936 * Set transaction id's of transactions that have to be committed
4937 * to finish f[data]sync. We set them to currently running transaction
4938 * as we cannot be sure that the inode or some of its metadata isn't
4939 * part of the transaction - the inode could have been reclaimed and
4940 * now it is reread from disk.
4943 transaction_t *transaction;
4946 read_lock(&journal->j_state_lock);
4947 if (journal->j_running_transaction)
4948 transaction = journal->j_running_transaction;
4950 transaction = journal->j_committing_transaction;
4952 tid = transaction->t_tid;
4954 tid = journal->j_commit_sequence;
4955 read_unlock(&journal->j_state_lock);
4956 ei->i_sync_tid = tid;
4957 ei->i_datasync_tid = tid;
4960 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4961 if (ei->i_extra_isize == 0) {
4962 /* The extra space is currently unused. Use it. */
4963 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4964 ei->i_extra_isize = sizeof(struct ext4_inode) -
4965 EXT4_GOOD_OLD_INODE_SIZE;
4967 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4973 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4974 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4975 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4976 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4978 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4979 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4980 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4981 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4983 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4988 if (ei->i_file_acl &&
4989 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4990 ext4_error_inode(inode, function, line, 0,
4991 "iget: bad extended attribute block %llu",
4993 ret = -EFSCORRUPTED;
4995 } else if (!ext4_has_inline_data(inode)) {
4996 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4997 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4998 (S_ISLNK(inode->i_mode) &&
4999 !ext4_inode_is_fast_symlink(inode))))
5000 /* Validate extent which is part of inode */
5001 ret = ext4_ext_check_inode(inode);
5002 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5003 (S_ISLNK(inode->i_mode) &&
5004 !ext4_inode_is_fast_symlink(inode))) {
5005 /* Validate block references which are part of inode */
5006 ret = ext4_ind_check_inode(inode);
5012 if (S_ISREG(inode->i_mode)) {
5013 inode->i_op = &ext4_file_inode_operations;
5014 inode->i_fop = &ext4_file_operations;
5015 ext4_set_aops(inode);
5016 } else if (S_ISDIR(inode->i_mode)) {
5017 inode->i_op = &ext4_dir_inode_operations;
5018 inode->i_fop = &ext4_dir_operations;
5019 } else if (S_ISLNK(inode->i_mode)) {
5020 if (ext4_encrypted_inode(inode)) {
5021 inode->i_op = &ext4_encrypted_symlink_inode_operations;
5022 ext4_set_aops(inode);
5023 } else if (ext4_inode_is_fast_symlink(inode)) {
5024 inode->i_link = (char *)ei->i_data;
5025 inode->i_op = &ext4_fast_symlink_inode_operations;
5026 nd_terminate_link(ei->i_data, inode->i_size,
5027 sizeof(ei->i_data) - 1);
5029 inode->i_op = &ext4_symlink_inode_operations;
5030 ext4_set_aops(inode);
5032 inode_nohighmem(inode);
5033 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5034 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5035 inode->i_op = &ext4_special_inode_operations;
5036 if (raw_inode->i_block[0])
5037 init_special_inode(inode, inode->i_mode,
5038 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5040 init_special_inode(inode, inode->i_mode,
5041 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5042 } else if (ino == EXT4_BOOT_LOADER_INO) {
5043 make_bad_inode(inode);
5045 ret = -EFSCORRUPTED;
5046 ext4_error_inode(inode, function, line, 0,
5047 "iget: bogus i_mode (%o)", inode->i_mode);
5051 ext4_set_inode_flags(inode);
5053 unlock_new_inode(inode);
5059 return ERR_PTR(ret);
5062 static int ext4_inode_blocks_set(handle_t *handle,
5063 struct ext4_inode *raw_inode,
5064 struct ext4_inode_info *ei)
5066 struct inode *inode = &(ei->vfs_inode);
5067 u64 i_blocks = READ_ONCE(inode->i_blocks);
5068 struct super_block *sb = inode->i_sb;
5070 if (i_blocks <= ~0U) {
5072 * i_blocks can be represented in a 32 bit variable
5073 * as multiple of 512 bytes
5075 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5076 raw_inode->i_blocks_high = 0;
5077 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5080 if (!ext4_has_feature_huge_file(sb))
5083 if (i_blocks <= 0xffffffffffffULL) {
5085 * i_blocks can be represented in a 48 bit variable
5086 * as multiple of 512 bytes
5088 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5089 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5090 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5092 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5093 /* i_block is stored in file system block size */
5094 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5095 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5096 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5101 struct other_inode {
5102 unsigned long orig_ino;
5103 struct ext4_inode *raw_inode;
5106 static int other_inode_match(struct inode * inode, unsigned long ino,
5109 struct other_inode *oi = (struct other_inode *) data;
5111 if ((inode->i_ino != ino) ||
5112 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5114 ((inode->i_state & I_DIRTY_TIME) == 0))
5116 spin_lock(&inode->i_lock);
5117 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5118 I_DIRTY_INODE)) == 0) &&
5119 (inode->i_state & I_DIRTY_TIME)) {
5120 struct ext4_inode_info *ei = EXT4_I(inode);
5122 inode->i_state &= ~I_DIRTY_TIME;
5123 spin_unlock(&inode->i_lock);
5125 spin_lock(&ei->i_raw_lock);
5126 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
5127 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
5128 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
5129 ext4_inode_csum_set(inode, oi->raw_inode, ei);
5130 spin_unlock(&ei->i_raw_lock);
5131 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
5134 spin_unlock(&inode->i_lock);
5139 * Opportunistically update the other time fields for other inodes in
5140 * the same inode table block.
5142 static void ext4_update_other_inodes_time(struct super_block *sb,
5143 unsigned long orig_ino, char *buf)
5145 struct other_inode oi;
5147 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5148 int inode_size = EXT4_INODE_SIZE(sb);
5150 oi.orig_ino = orig_ino;
5152 * Calculate the first inode in the inode table block. Inode
5153 * numbers are one-based. That is, the first inode in a block
5154 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5156 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5157 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5158 if (ino == orig_ino)
5160 oi.raw_inode = (struct ext4_inode *) buf;
5161 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
5166 * Post the struct inode info into an on-disk inode location in the
5167 * buffer-cache. This gobbles the caller's reference to the
5168 * buffer_head in the inode location struct.
5170 * The caller must have write access to iloc->bh.
5172 static int ext4_do_update_inode(handle_t *handle,
5173 struct inode *inode,
5174 struct ext4_iloc *iloc)
5176 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5177 struct ext4_inode_info *ei = EXT4_I(inode);
5178 struct buffer_head *bh = iloc->bh;
5179 struct super_block *sb = inode->i_sb;
5181 int need_datasync = 0, set_large_file = 0;
5186 spin_lock(&ei->i_raw_lock);
5188 /* For fields not tracked in the in-memory inode,
5189 * initialise them to zero for new inodes. */
5190 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5191 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5193 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5195 spin_unlock(&ei->i_raw_lock);
5199 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5200 i_uid = i_uid_read(inode);
5201 i_gid = i_gid_read(inode);
5202 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5203 if (!(test_opt(inode->i_sb, NO_UID32))) {
5204 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5205 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5207 * Fix up interoperability with old kernels. Otherwise, old inodes get
5208 * re-used with the upper 16 bits of the uid/gid intact
5210 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5211 raw_inode->i_uid_high = 0;
5212 raw_inode->i_gid_high = 0;
5214 raw_inode->i_uid_high =
5215 cpu_to_le16(high_16_bits(i_uid));
5216 raw_inode->i_gid_high =
5217 cpu_to_le16(high_16_bits(i_gid));
5220 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5221 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5222 raw_inode->i_uid_high = 0;
5223 raw_inode->i_gid_high = 0;
5225 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5227 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5228 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5229 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5230 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5232 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5233 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5234 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5235 raw_inode->i_file_acl_high =
5236 cpu_to_le16(ei->i_file_acl >> 32);
5237 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5238 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5239 ext4_isize_set(raw_inode, ei->i_disksize);
5242 if (ei->i_disksize > 0x7fffffffULL) {
5243 if (!ext4_has_feature_large_file(sb) ||
5244 EXT4_SB(sb)->s_es->s_rev_level ==
5245 cpu_to_le32(EXT4_GOOD_OLD_REV))
5248 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5249 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5250 if (old_valid_dev(inode->i_rdev)) {
5251 raw_inode->i_block[0] =
5252 cpu_to_le32(old_encode_dev(inode->i_rdev));
5253 raw_inode->i_block[1] = 0;
5255 raw_inode->i_block[0] = 0;
5256 raw_inode->i_block[1] =
5257 cpu_to_le32(new_encode_dev(inode->i_rdev));
5258 raw_inode->i_block[2] = 0;
5260 } else if (!ext4_has_inline_data(inode)) {
5261 for (block = 0; block < EXT4_N_BLOCKS; block++)
5262 raw_inode->i_block[block] = ei->i_data[block];
5265 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5266 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5267 if (ei->i_extra_isize) {
5268 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5269 raw_inode->i_version_hi =
5270 cpu_to_le32(inode->i_version >> 32);
5271 raw_inode->i_extra_isize =
5272 cpu_to_le16(ei->i_extra_isize);
5276 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5277 i_projid != EXT4_DEF_PROJID);
5279 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5280 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5281 raw_inode->i_projid = cpu_to_le32(i_projid);
5283 ext4_inode_csum_set(inode, raw_inode, ei);
5284 spin_unlock(&ei->i_raw_lock);
5285 if (inode->i_sb->s_flags & MS_LAZYTIME)
5286 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5289 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5290 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5293 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5294 if (set_large_file) {
5295 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5296 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5299 ext4_update_dynamic_rev(sb);
5300 ext4_set_feature_large_file(sb);
5301 ext4_handle_sync(handle);
5302 err = ext4_handle_dirty_super(handle, sb);
5304 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5307 ext4_std_error(inode->i_sb, err);
5312 * ext4_write_inode()
5314 * We are called from a few places:
5316 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5317 * Here, there will be no transaction running. We wait for any running
5318 * transaction to commit.
5320 * - Within flush work (sys_sync(), kupdate and such).
5321 * We wait on commit, if told to.
5323 * - Within iput_final() -> write_inode_now()
5324 * We wait on commit, if told to.
5326 * In all cases it is actually safe for us to return without doing anything,
5327 * because the inode has been copied into a raw inode buffer in
5328 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5331 * Note that we are absolutely dependent upon all inode dirtiers doing the
5332 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5333 * which we are interested.
5335 * It would be a bug for them to not do this. The code:
5337 * mark_inode_dirty(inode)
5339 * inode->i_size = expr;
5341 * is in error because write_inode() could occur while `stuff()' is running,
5342 * and the new i_size will be lost. Plus the inode will no longer be on the
5343 * superblock's dirty inode list.
5345 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5349 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5350 sb_rdonly(inode->i_sb))
5353 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5356 if (EXT4_SB(inode->i_sb)->s_journal) {
5357 if (ext4_journal_current_handle()) {
5358 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5364 * No need to force transaction in WB_SYNC_NONE mode. Also
5365 * ext4_sync_fs() will force the commit after everything is
5368 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5371 err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5372 EXT4_I(inode)->i_sync_tid);
5374 struct ext4_iloc iloc;
5376 err = __ext4_get_inode_loc(inode, &iloc, 0);
5380 * sync(2) will flush the whole buffer cache. No need to do
5381 * it here separately for each inode.
5383 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5384 sync_dirty_buffer(iloc.bh);
5385 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5386 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5387 "IO error syncing inode");
5396 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5397 * buffers that are attached to a page stradding i_size and are undergoing
5398 * commit. In that case we have to wait for commit to finish and try again.
5400 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5404 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5405 tid_t commit_tid = 0;
5408 offset = inode->i_size & (PAGE_SIZE - 1);
5410 * If the page is fully truncated, we don't need to wait for any commit
5411 * (and we even should not as __ext4_journalled_invalidatepage() may
5412 * strip all buffers from the page but keep the page dirty which can then
5413 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5414 * buffers). Also we don't need to wait for any commit if all buffers in
5415 * the page remain valid. This is most beneficial for the common case of
5416 * blocksize == PAGESIZE.
5418 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5421 page = find_lock_page(inode->i_mapping,
5422 inode->i_size >> PAGE_SHIFT);
5425 ret = __ext4_journalled_invalidatepage(page, offset,
5426 PAGE_SIZE - offset);
5432 read_lock(&journal->j_state_lock);
5433 if (journal->j_committing_transaction)
5434 commit_tid = journal->j_committing_transaction->t_tid;
5435 read_unlock(&journal->j_state_lock);
5437 jbd2_log_wait_commit(journal, commit_tid);
5444 * Called from notify_change.
5446 * We want to trap VFS attempts to truncate the file as soon as
5447 * possible. In particular, we want to make sure that when the VFS
5448 * shrinks i_size, we put the inode on the orphan list and modify
5449 * i_disksize immediately, so that during the subsequent flushing of
5450 * dirty pages and freeing of disk blocks, we can guarantee that any
5451 * commit will leave the blocks being flushed in an unused state on
5452 * disk. (On recovery, the inode will get truncated and the blocks will
5453 * be freed, so we have a strong guarantee that no future commit will
5454 * leave these blocks visible to the user.)
5456 * Another thing we have to assure is that if we are in ordered mode
5457 * and inode is still attached to the committing transaction, we must
5458 * we start writeout of all the dirty pages which are being truncated.
5459 * This way we are sure that all the data written in the previous
5460 * transaction are already on disk (truncate waits for pages under
5463 * Called with inode->i_mutex down.
5465 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5467 struct inode *inode = d_inode(dentry);
5470 const unsigned int ia_valid = attr->ia_valid;
5472 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5475 if (unlikely(IS_IMMUTABLE(inode)))
5478 if (unlikely(IS_APPEND(inode) &&
5479 (ia_valid & (ATTR_MODE | ATTR_UID |
5480 ATTR_GID | ATTR_TIMES_SET))))
5483 error = setattr_prepare(dentry, attr);
5487 if (is_quota_modification(inode, attr)) {
5488 error = dquot_initialize(inode);
5492 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5493 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5496 /* (user+group)*(old+new) structure, inode write (sb,
5497 * inode block, ? - but truncate inode update has it) */
5498 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5499 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5500 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5501 if (IS_ERR(handle)) {
5502 error = PTR_ERR(handle);
5506 /* dquot_transfer() calls back ext4_get_inode_usage() which
5507 * counts xattr inode references.
5509 down_read(&EXT4_I(inode)->xattr_sem);
5510 error = dquot_transfer(inode, attr);
5511 up_read(&EXT4_I(inode)->xattr_sem);
5514 ext4_journal_stop(handle);
5517 /* Update corresponding info in inode so that everything is in
5518 * one transaction */
5519 if (attr->ia_valid & ATTR_UID)
5520 inode->i_uid = attr->ia_uid;
5521 if (attr->ia_valid & ATTR_GID)
5522 inode->i_gid = attr->ia_gid;
5523 error = ext4_mark_inode_dirty(handle, inode);
5524 ext4_journal_stop(handle);
5527 if (attr->ia_valid & ATTR_SIZE) {
5529 loff_t oldsize = inode->i_size;
5530 int shrink = (attr->ia_size <= inode->i_size);
5532 if (ext4_encrypted_inode(inode)) {
5533 error = fscrypt_get_encryption_info(inode);
5536 if (!fscrypt_has_encryption_key(inode))
5540 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5541 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5543 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5546 if (!S_ISREG(inode->i_mode))
5549 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5550 inode_inc_iversion(inode);
5552 if (ext4_should_order_data(inode) &&
5553 (attr->ia_size < inode->i_size)) {
5554 error = ext4_begin_ordered_truncate(inode,
5559 if (attr->ia_size != inode->i_size) {
5560 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5561 if (IS_ERR(handle)) {
5562 error = PTR_ERR(handle);
5565 if (ext4_handle_valid(handle) && shrink) {
5566 error = ext4_orphan_add(handle, inode);
5570 * Update c/mtime on truncate up, ext4_truncate() will
5571 * update c/mtime in shrink case below
5574 inode->i_mtime = current_time(inode);
5575 inode->i_ctime = inode->i_mtime;
5577 down_write(&EXT4_I(inode)->i_data_sem);
5578 EXT4_I(inode)->i_disksize = attr->ia_size;
5579 rc = ext4_mark_inode_dirty(handle, inode);
5583 * We have to update i_size under i_data_sem together
5584 * with i_disksize to avoid races with writeback code
5585 * running ext4_wb_update_i_disksize().
5588 i_size_write(inode, attr->ia_size);
5589 up_write(&EXT4_I(inode)->i_data_sem);
5590 ext4_journal_stop(handle);
5592 if (orphan && inode->i_nlink)
5593 ext4_orphan_del(NULL, inode);
5598 pagecache_isize_extended(inode, oldsize, inode->i_size);
5601 * Blocks are going to be removed from the inode. Wait
5602 * for dio in flight. Temporarily disable
5603 * dioread_nolock to prevent livelock.
5606 if (!ext4_should_journal_data(inode)) {
5607 ext4_inode_block_unlocked_dio(inode);
5608 inode_dio_wait(inode);
5609 ext4_inode_resume_unlocked_dio(inode);
5611 ext4_wait_for_tail_page_commit(inode);
5613 down_write(&EXT4_I(inode)->i_mmap_sem);
5615 * Truncate pagecache after we've waited for commit
5616 * in data=journal mode to make pages freeable.
5618 truncate_pagecache(inode, inode->i_size);
5620 rc = ext4_truncate(inode);
5624 up_write(&EXT4_I(inode)->i_mmap_sem);
5628 setattr_copy(inode, attr);
5629 mark_inode_dirty(inode);
5633 * If the call to ext4_truncate failed to get a transaction handle at
5634 * all, we need to clean up the in-core orphan list manually.
5636 if (orphan && inode->i_nlink)
5637 ext4_orphan_del(NULL, inode);
5639 if (!error && (ia_valid & ATTR_MODE))
5640 rc = posix_acl_chmod(inode, inode->i_mode);
5643 ext4_std_error(inode->i_sb, error);
5649 int ext4_getattr(const struct path *path, struct kstat *stat,
5650 u32 request_mask, unsigned int query_flags)
5652 struct inode *inode = d_inode(path->dentry);
5653 struct ext4_inode *raw_inode;
5654 struct ext4_inode_info *ei = EXT4_I(inode);
5657 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5658 stat->result_mask |= STATX_BTIME;
5659 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5660 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5663 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5664 if (flags & EXT4_APPEND_FL)
5665 stat->attributes |= STATX_ATTR_APPEND;
5666 if (flags & EXT4_COMPR_FL)
5667 stat->attributes |= STATX_ATTR_COMPRESSED;
5668 if (flags & EXT4_ENCRYPT_FL)
5669 stat->attributes |= STATX_ATTR_ENCRYPTED;
5670 if (flags & EXT4_IMMUTABLE_FL)
5671 stat->attributes |= STATX_ATTR_IMMUTABLE;
5672 if (flags & EXT4_NODUMP_FL)
5673 stat->attributes |= STATX_ATTR_NODUMP;
5675 stat->attributes_mask |= (STATX_ATTR_APPEND |
5676 STATX_ATTR_COMPRESSED |
5677 STATX_ATTR_ENCRYPTED |
5678 STATX_ATTR_IMMUTABLE |
5681 generic_fillattr(inode, stat);
5685 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5686 u32 request_mask, unsigned int query_flags)
5688 struct inode *inode = d_inode(path->dentry);
5689 u64 delalloc_blocks;
5691 ext4_getattr(path, stat, request_mask, query_flags);
5694 * If there is inline data in the inode, the inode will normally not
5695 * have data blocks allocated (it may have an external xattr block).
5696 * Report at least one sector for such files, so tools like tar, rsync,
5697 * others don't incorrectly think the file is completely sparse.
5699 if (unlikely(ext4_has_inline_data(inode)))
5700 stat->blocks += (stat->size + 511) >> 9;
5703 * We can't update i_blocks if the block allocation is delayed
5704 * otherwise in the case of system crash before the real block
5705 * allocation is done, we will have i_blocks inconsistent with
5706 * on-disk file blocks.
5707 * We always keep i_blocks updated together with real
5708 * allocation. But to not confuse with user, stat
5709 * will return the blocks that include the delayed allocation
5710 * blocks for this file.
5712 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5713 EXT4_I(inode)->i_reserved_data_blocks);
5714 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5718 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5721 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5722 return ext4_ind_trans_blocks(inode, lblocks);
5723 return ext4_ext_index_trans_blocks(inode, pextents);
5727 * Account for index blocks, block groups bitmaps and block group
5728 * descriptor blocks if modify datablocks and index blocks
5729 * worse case, the indexs blocks spread over different block groups
5731 * If datablocks are discontiguous, they are possible to spread over
5732 * different block groups too. If they are contiguous, with flexbg,
5733 * they could still across block group boundary.
5735 * Also account for superblock, inode, quota and xattr blocks
5737 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5740 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5746 * How many index blocks need to touch to map @lblocks logical blocks
5747 * to @pextents physical extents?
5749 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5754 * Now let's see how many group bitmaps and group descriptors need
5757 groups = idxblocks + pextents;
5759 if (groups > ngroups)
5761 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5762 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5764 /* bitmaps and block group descriptor blocks */
5765 ret += groups + gdpblocks;
5767 /* Blocks for super block, inode, quota and xattr blocks */
5768 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5774 * Calculate the total number of credits to reserve to fit
5775 * the modification of a single pages into a single transaction,
5776 * which may include multiple chunks of block allocations.
5778 * This could be called via ext4_write_begin()
5780 * We need to consider the worse case, when
5781 * one new block per extent.
5783 int ext4_writepage_trans_blocks(struct inode *inode)
5785 int bpp = ext4_journal_blocks_per_page(inode);
5788 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5790 /* Account for data blocks for journalled mode */
5791 if (ext4_should_journal_data(inode))
5797 * Calculate the journal credits for a chunk of data modification.
5799 * This is called from DIO, fallocate or whoever calling
5800 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5802 * journal buffers for data blocks are not included here, as DIO
5803 * and fallocate do no need to journal data buffers.
5805 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5807 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5811 * The caller must have previously called ext4_reserve_inode_write().
5812 * Give this, we know that the caller already has write access to iloc->bh.
5814 int ext4_mark_iloc_dirty(handle_t *handle,
5815 struct inode *inode, struct ext4_iloc *iloc)
5819 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5823 if (IS_I_VERSION(inode))
5824 inode_inc_iversion(inode);
5826 /* the do_update_inode consumes one bh->b_count */
5829 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5830 err = ext4_do_update_inode(handle, inode, iloc);
5836 * On success, We end up with an outstanding reference count against
5837 * iloc->bh. This _must_ be cleaned up later.
5841 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5842 struct ext4_iloc *iloc)
5846 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5849 err = ext4_get_inode_loc(inode, iloc);
5851 BUFFER_TRACE(iloc->bh, "get_write_access");
5852 err = ext4_journal_get_write_access(handle, iloc->bh);
5858 ext4_std_error(inode->i_sb, err);
5862 static int __ext4_expand_extra_isize(struct inode *inode,
5863 unsigned int new_extra_isize,
5864 struct ext4_iloc *iloc,
5865 handle_t *handle, int *no_expand)
5867 struct ext4_inode *raw_inode;
5868 struct ext4_xattr_ibody_header *header;
5869 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5870 struct ext4_inode_info *ei = EXT4_I(inode);
5873 /* this was checked at iget time, but double check for good measure */
5874 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5875 (ei->i_extra_isize & 3)) {
5876 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5878 EXT4_INODE_SIZE(inode->i_sb));
5879 return -EFSCORRUPTED;
5881 if ((new_extra_isize < ei->i_extra_isize) ||
5882 (new_extra_isize < 4) ||
5883 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5884 return -EINVAL; /* Should never happen */
5886 raw_inode = ext4_raw_inode(iloc);
5888 header = IHDR(inode, raw_inode);
5890 /* No extended attributes present */
5891 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5892 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5893 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5894 EXT4_I(inode)->i_extra_isize, 0,
5895 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5896 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5900 /* try to expand with EAs present */
5901 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5905 * Inode size expansion failed; don't try again
5914 * Expand an inode by new_extra_isize bytes.
5915 * Returns 0 on success or negative error number on failure.
5917 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5918 unsigned int new_extra_isize,
5919 struct ext4_iloc iloc,
5925 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5929 * In nojournal mode, we can immediately attempt to expand
5930 * the inode. When journaled, we first need to obtain extra
5931 * buffer credits since we may write into the EA block
5932 * with this same handle. If journal_extend fails, then it will
5933 * only result in a minor loss of functionality for that inode.
5934 * If this is felt to be critical, then e2fsck should be run to
5935 * force a large enough s_min_extra_isize.
5937 if (ext4_handle_valid(handle) &&
5938 jbd2_journal_extend(handle,
5939 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
5942 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5945 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5946 handle, &no_expand);
5947 ext4_write_unlock_xattr(inode, &no_expand);
5952 int ext4_expand_extra_isize(struct inode *inode,
5953 unsigned int new_extra_isize,
5954 struct ext4_iloc *iloc)
5960 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5965 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5966 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5967 if (IS_ERR(handle)) {
5968 error = PTR_ERR(handle);
5973 ext4_write_lock_xattr(inode, &no_expand);
5975 BUFFER_TRACE(iloc->bh, "get_write_access");
5976 error = ext4_journal_get_write_access(handle, iloc->bh);
5982 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5983 handle, &no_expand);
5985 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5990 ext4_write_unlock_xattr(inode, &no_expand);
5991 ext4_journal_stop(handle);
5996 * What we do here is to mark the in-core inode as clean with respect to inode
5997 * dirtiness (it may still be data-dirty).
5998 * This means that the in-core inode may be reaped by prune_icache
5999 * without having to perform any I/O. This is a very good thing,
6000 * because *any* task may call prune_icache - even ones which
6001 * have a transaction open against a different journal.
6003 * Is this cheating? Not really. Sure, we haven't written the
6004 * inode out, but prune_icache isn't a user-visible syncing function.
6005 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6006 * we start and wait on commits.
6008 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
6010 struct ext4_iloc iloc;
6011 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6015 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6016 err = ext4_reserve_inode_write(handle, inode, &iloc);
6020 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6021 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6024 return ext4_mark_iloc_dirty(handle, inode, &iloc);
6028 * ext4_dirty_inode() is called from __mark_inode_dirty()
6030 * We're really interested in the case where a file is being extended.
6031 * i_size has been changed by generic_commit_write() and we thus need
6032 * to include the updated inode in the current transaction.
6034 * Also, dquot_alloc_block() will always dirty the inode when blocks
6035 * are allocated to the file.
6037 * If the inode is marked synchronous, we don't honour that here - doing
6038 * so would cause a commit on atime updates, which we don't bother doing.
6039 * We handle synchronous inodes at the highest possible level.
6041 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
6042 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
6043 * to copy into the on-disk inode structure are the timestamp files.
6045 void ext4_dirty_inode(struct inode *inode, int flags)
6049 if (flags == I_DIRTY_TIME)
6051 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6055 ext4_mark_inode_dirty(handle, inode);
6057 ext4_journal_stop(handle);
6064 * Bind an inode's backing buffer_head into this transaction, to prevent
6065 * it from being flushed to disk early. Unlike
6066 * ext4_reserve_inode_write, this leaves behind no bh reference and
6067 * returns no iloc structure, so the caller needs to repeat the iloc
6068 * lookup to mark the inode dirty later.
6070 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
6072 struct ext4_iloc iloc;
6076 err = ext4_get_inode_loc(inode, &iloc);
6078 BUFFER_TRACE(iloc.bh, "get_write_access");
6079 err = jbd2_journal_get_write_access(handle, iloc.bh);
6081 err = ext4_handle_dirty_metadata(handle,
6087 ext4_std_error(inode->i_sb, err);
6092 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6097 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6100 * We have to be very careful here: changing a data block's
6101 * journaling status dynamically is dangerous. If we write a
6102 * data block to the journal, change the status and then delete
6103 * that block, we risk forgetting to revoke the old log record
6104 * from the journal and so a subsequent replay can corrupt data.
6105 * So, first we make sure that the journal is empty and that
6106 * nobody is changing anything.
6109 journal = EXT4_JOURNAL(inode);
6112 if (is_journal_aborted(journal))
6115 /* Wait for all existing dio workers */
6116 ext4_inode_block_unlocked_dio(inode);
6117 inode_dio_wait(inode);
6120 * Before flushing the journal and switching inode's aops, we have
6121 * to flush all dirty data the inode has. There can be outstanding
6122 * delayed allocations, there can be unwritten extents created by
6123 * fallocate or buffered writes in dioread_nolock mode covered by
6124 * dirty data which can be converted only after flushing the dirty
6125 * data (and journalled aops don't know how to handle these cases).
6128 down_write(&EXT4_I(inode)->i_mmap_sem);
6129 err = filemap_write_and_wait(inode->i_mapping);
6131 up_write(&EXT4_I(inode)->i_mmap_sem);
6132 ext4_inode_resume_unlocked_dio(inode);
6137 percpu_down_write(&sbi->s_writepages_rwsem);
6138 jbd2_journal_lock_updates(journal);
6141 * OK, there are no updates running now, and all cached data is
6142 * synced to disk. We are now in a completely consistent state
6143 * which doesn't have anything in the journal, and we know that
6144 * no filesystem updates are running, so it is safe to modify
6145 * the inode's in-core data-journaling state flag now.
6149 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6151 err = jbd2_journal_flush(journal);
6153 jbd2_journal_unlock_updates(journal);
6154 percpu_up_write(&sbi->s_writepages_rwsem);
6155 ext4_inode_resume_unlocked_dio(inode);
6158 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6160 ext4_set_aops(inode);
6162 jbd2_journal_unlock_updates(journal);
6163 percpu_up_write(&sbi->s_writepages_rwsem);
6166 up_write(&EXT4_I(inode)->i_mmap_sem);
6167 ext4_inode_resume_unlocked_dio(inode);
6169 /* Finally we can mark the inode as dirty. */
6171 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6173 return PTR_ERR(handle);
6175 err = ext4_mark_inode_dirty(handle, inode);
6176 ext4_handle_sync(handle);
6177 ext4_journal_stop(handle);
6178 ext4_std_error(inode->i_sb, err);
6183 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6185 return !buffer_mapped(bh);
6188 int ext4_page_mkwrite(struct vm_fault *vmf)
6190 struct vm_area_struct *vma = vmf->vma;
6191 struct page *page = vmf->page;
6195 struct file *file = vma->vm_file;
6196 struct inode *inode = file_inode(file);
6197 struct address_space *mapping = inode->i_mapping;
6199 get_block_t *get_block;
6202 if (unlikely(IS_IMMUTABLE(inode)))
6203 return VM_FAULT_SIGBUS;
6205 sb_start_pagefault(inode->i_sb);
6206 file_update_time(vma->vm_file);
6208 down_read(&EXT4_I(inode)->i_mmap_sem);
6210 ret = ext4_convert_inline_data(inode);
6214 /* Delalloc case is easy... */
6215 if (test_opt(inode->i_sb, DELALLOC) &&
6216 !ext4_should_journal_data(inode) &&
6217 !ext4_nonda_switch(inode->i_sb)) {
6219 ret = block_page_mkwrite(vma, vmf,
6220 ext4_da_get_block_prep);
6221 } while (ret == -ENOSPC &&
6222 ext4_should_retry_alloc(inode->i_sb, &retries));
6227 size = i_size_read(inode);
6228 /* Page got truncated from under us? */
6229 if (page->mapping != mapping || page_offset(page) > size) {
6231 ret = VM_FAULT_NOPAGE;
6235 if (page->index == size >> PAGE_SHIFT)
6236 len = size & ~PAGE_MASK;
6240 * Return if we have all the buffers mapped. This avoids the need to do
6241 * journal_start/journal_stop which can block and take a long time
6243 if (page_has_buffers(page)) {
6244 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6246 ext4_bh_unmapped)) {
6247 /* Wait so that we don't change page under IO */
6248 wait_for_stable_page(page);
6249 ret = VM_FAULT_LOCKED;
6254 /* OK, we need to fill the hole... */
6255 if (ext4_should_dioread_nolock(inode))
6256 get_block = ext4_get_block_unwritten;
6258 get_block = ext4_get_block;
6260 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6261 ext4_writepage_trans_blocks(inode));
6262 if (IS_ERR(handle)) {
6263 ret = VM_FAULT_SIGBUS;
6266 ret = block_page_mkwrite(vma, vmf, get_block);
6267 if (!ret && ext4_should_journal_data(inode)) {
6268 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
6269 PAGE_SIZE, NULL, do_journal_get_write_access)) {
6271 ret = VM_FAULT_SIGBUS;
6272 ext4_journal_stop(handle);
6275 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6277 ext4_journal_stop(handle);
6278 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6281 ret = block_page_mkwrite_return(ret);
6283 up_read(&EXT4_I(inode)->i_mmap_sem);
6284 sb_end_pagefault(inode->i_sb);
6288 int ext4_filemap_fault(struct vm_fault *vmf)
6290 struct inode *inode = file_inode(vmf->vma->vm_file);
6293 down_read(&EXT4_I(inode)->i_mmap_sem);
6294 err = filemap_fault(vmf);
6295 up_read(&EXT4_I(inode)->i_mmap_sem);
6301 * Find the first extent at or after @lblk in an inode that is not a hole.
6302 * Search for @map_len blocks at most. The extent is returned in @result.
6304 * The function returns 1 if we found an extent. The function returns 0 in
6305 * case there is no extent at or after @lblk and in that case also sets
6306 * @result->es_len to 0. In case of error, the error code is returned.
6308 int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
6309 unsigned int map_len, struct extent_status *result)
6311 struct ext4_map_blocks map;
6312 struct extent_status es = {};
6316 map.m_len = map_len;
6319 * For non-extent based files this loop may iterate several times since
6320 * we do not determine full hole size.
6322 while (map.m_len > 0) {
6323 ret = ext4_map_blocks(NULL, inode, &map, 0);
6326 /* There's extent covering m_lblk? Just return it. */
6330 ext4_es_store_pblock(result, map.m_pblk);
6331 result->es_lblk = map.m_lblk;
6332 result->es_len = map.m_len;
6333 if (map.m_flags & EXT4_MAP_UNWRITTEN)
6334 status = EXTENT_STATUS_UNWRITTEN;
6336 status = EXTENT_STATUS_WRITTEN;
6337 ext4_es_store_status(result, status);
6340 ext4_es_find_delayed_extent_range(inode, map.m_lblk,
6341 map.m_lblk + map.m_len - 1,
6343 /* Is delalloc data before next block in extent tree? */
6344 if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
6345 ext4_lblk_t offset = 0;
6347 if (es.es_lblk < lblk)
6348 offset = lblk - es.es_lblk;
6349 result->es_lblk = es.es_lblk + offset;
6350 ext4_es_store_pblock(result,
6351 ext4_es_pblock(&es) + offset);
6352 result->es_len = es.es_len - offset;
6353 ext4_es_store_status(result, ext4_es_status(&es));
6357 /* There's a hole at m_lblk, advance us after it */
6358 map.m_lblk += map.m_len;
6359 map_len -= map.m_len;
6360 map.m_len = map_len;