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);
1315 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1316 if (IS_ERR(handle)) {
1318 return PTR_ERR(handle);
1322 if (page->mapping != mapping) {
1323 /* The page got truncated from under us */
1326 ext4_journal_stop(handle);
1329 /* In case writeback began while the page was unlocked */
1330 wait_for_stable_page(page);
1332 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1333 if (ext4_should_dioread_nolock(inode))
1334 ret = ext4_block_write_begin(page, pos, len,
1335 ext4_get_block_unwritten);
1337 ret = ext4_block_write_begin(page, pos, len,
1340 if (ext4_should_dioread_nolock(inode))
1341 ret = __block_write_begin(page, pos, len,
1342 ext4_get_block_unwritten);
1344 ret = __block_write_begin(page, pos, len, ext4_get_block);
1346 if (!ret && ext4_should_journal_data(inode)) {
1347 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1349 do_journal_get_write_access);
1355 * __block_write_begin may have instantiated a few blocks
1356 * outside i_size. Trim these off again. Don't need
1357 * i_size_read because we hold i_mutex.
1359 * Add inode to orphan list in case we crash before
1362 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1363 ext4_orphan_add(handle, inode);
1365 ext4_journal_stop(handle);
1366 if (pos + len > inode->i_size) {
1367 ext4_truncate_failed_write(inode);
1369 * If truncate failed early the inode might
1370 * still be on the orphan list; we need to
1371 * make sure the inode is removed from the
1372 * orphan list in that case.
1375 ext4_orphan_del(NULL, inode);
1378 if (ret == -ENOSPC &&
1379 ext4_should_retry_alloc(inode->i_sb, &retries))
1388 /* For write_end() in data=journal mode */
1389 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1392 if (!buffer_mapped(bh) || buffer_freed(bh))
1394 set_buffer_uptodate(bh);
1395 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1396 clear_buffer_meta(bh);
1397 clear_buffer_prio(bh);
1402 * We need to pick up the new inode size which generic_commit_write gave us
1403 * `file' can be NULL - eg, when called from page_symlink().
1405 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1406 * buffers are managed internally.
1408 static int ext4_write_end(struct file *file,
1409 struct address_space *mapping,
1410 loff_t pos, unsigned len, unsigned copied,
1411 struct page *page, void *fsdata)
1413 handle_t *handle = ext4_journal_current_handle();
1414 struct inode *inode = mapping->host;
1415 loff_t old_size = inode->i_size;
1417 int i_size_changed = 0;
1418 int inline_data = ext4_has_inline_data(inode);
1420 trace_ext4_write_end(inode, pos, len, copied);
1422 ret = ext4_write_inline_data_end(inode, pos, len,
1431 copied = block_write_end(file, mapping, pos,
1432 len, copied, page, fsdata);
1434 * it's important to update i_size while still holding page lock:
1435 * page writeout could otherwise come in and zero beyond i_size.
1437 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1442 pagecache_isize_extended(inode, old_size, pos);
1444 * Don't mark the inode dirty under page lock. First, it unnecessarily
1445 * makes the holding time of page lock longer. Second, it forces lock
1446 * ordering of page lock and transaction start for journaling
1449 if (i_size_changed || inline_data)
1450 ext4_mark_inode_dirty(handle, inode);
1452 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1453 /* if we have allocated more blocks and copied
1454 * less. We will have blocks allocated outside
1455 * inode->i_size. So truncate them
1457 ext4_orphan_add(handle, inode);
1459 ret2 = ext4_journal_stop(handle);
1463 if (pos + len > inode->i_size) {
1464 ext4_truncate_failed_write(inode);
1466 * If truncate failed early the inode might still be
1467 * on the orphan list; we need to make sure the inode
1468 * is removed from the orphan list in that case.
1471 ext4_orphan_del(NULL, inode);
1474 return ret ? ret : copied;
1478 * This is a private version of page_zero_new_buffers() which doesn't
1479 * set the buffer to be dirty, since in data=journalled mode we need
1480 * to call ext4_handle_dirty_metadata() instead.
1482 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1484 unsigned from, unsigned to)
1486 unsigned int block_start = 0, block_end;
1487 struct buffer_head *head, *bh;
1489 bh = head = page_buffers(page);
1491 block_end = block_start + bh->b_size;
1492 if (buffer_new(bh)) {
1493 if (block_end > from && block_start < to) {
1494 if (!PageUptodate(page)) {
1495 unsigned start, size;
1497 start = max(from, block_start);
1498 size = min(to, block_end) - start;
1500 zero_user(page, start, size);
1501 write_end_fn(handle, bh);
1503 clear_buffer_new(bh);
1506 block_start = block_end;
1507 bh = bh->b_this_page;
1508 } while (bh != head);
1511 static int ext4_journalled_write_end(struct file *file,
1512 struct address_space *mapping,
1513 loff_t pos, unsigned len, unsigned copied,
1514 struct page *page, void *fsdata)
1516 handle_t *handle = ext4_journal_current_handle();
1517 struct inode *inode = mapping->host;
1518 loff_t old_size = inode->i_size;
1522 int size_changed = 0;
1523 int inline_data = ext4_has_inline_data(inode);
1525 trace_ext4_journalled_write_end(inode, pos, len, copied);
1526 from = pos & (PAGE_SIZE - 1);
1529 BUG_ON(!ext4_handle_valid(handle));
1532 ret = ext4_write_inline_data_end(inode, pos, len,
1540 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1542 ext4_journalled_zero_new_buffers(handle, page, from, to);
1544 if (unlikely(copied < len))
1545 ext4_journalled_zero_new_buffers(handle, page,
1547 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1548 from + copied, &partial,
1551 SetPageUptodate(page);
1553 size_changed = ext4_update_inode_size(inode, pos + copied);
1554 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1555 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1560 pagecache_isize_extended(inode, old_size, pos);
1562 if (size_changed || inline_data) {
1563 ret2 = ext4_mark_inode_dirty(handle, inode);
1568 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1569 /* if we have allocated more blocks and copied
1570 * less. We will have blocks allocated outside
1571 * inode->i_size. So truncate them
1573 ext4_orphan_add(handle, inode);
1576 ret2 = ext4_journal_stop(handle);
1579 if (pos + len > inode->i_size) {
1580 ext4_truncate_failed_write(inode);
1582 * If truncate failed early the inode might still be
1583 * on the orphan list; we need to make sure the inode
1584 * is removed from the orphan list in that case.
1587 ext4_orphan_del(NULL, inode);
1590 return ret ? ret : copied;
1594 * Reserve space for a single cluster
1596 static int ext4_da_reserve_space(struct inode *inode)
1598 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1599 struct ext4_inode_info *ei = EXT4_I(inode);
1603 * We will charge metadata quota at writeout time; this saves
1604 * us from metadata over-estimation, though we may go over by
1605 * a small amount in the end. Here we just reserve for data.
1607 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1611 spin_lock(&ei->i_block_reservation_lock);
1612 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1613 spin_unlock(&ei->i_block_reservation_lock);
1614 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1617 ei->i_reserved_data_blocks++;
1618 trace_ext4_da_reserve_space(inode);
1619 spin_unlock(&ei->i_block_reservation_lock);
1621 return 0; /* success */
1624 static void ext4_da_release_space(struct inode *inode, int to_free)
1626 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1627 struct ext4_inode_info *ei = EXT4_I(inode);
1630 return; /* Nothing to release, exit */
1632 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1634 trace_ext4_da_release_space(inode, to_free);
1635 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1637 * if there aren't enough reserved blocks, then the
1638 * counter is messed up somewhere. Since this
1639 * function is called from invalidate page, it's
1640 * harmless to return without any action.
1642 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1643 "ino %lu, to_free %d with only %d reserved "
1644 "data blocks", inode->i_ino, to_free,
1645 ei->i_reserved_data_blocks);
1647 to_free = ei->i_reserved_data_blocks;
1649 ei->i_reserved_data_blocks -= to_free;
1651 /* update fs dirty data blocks counter */
1652 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1654 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1656 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1659 static void ext4_da_page_release_reservation(struct page *page,
1660 unsigned int offset,
1661 unsigned int length)
1663 int to_release = 0, contiguous_blks = 0;
1664 struct buffer_head *head, *bh;
1665 unsigned int curr_off = 0;
1666 struct inode *inode = page->mapping->host;
1667 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1668 unsigned int stop = offset + length;
1672 BUG_ON(stop > PAGE_SIZE || stop < length);
1674 head = page_buffers(page);
1677 unsigned int next_off = curr_off + bh->b_size;
1679 if (next_off > stop)
1682 if ((offset <= curr_off) && (buffer_delay(bh))) {
1685 clear_buffer_delay(bh);
1686 } else if (contiguous_blks) {
1687 lblk = page->index <<
1688 (PAGE_SHIFT - inode->i_blkbits);
1689 lblk += (curr_off >> inode->i_blkbits) -
1691 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1692 contiguous_blks = 0;
1694 curr_off = next_off;
1695 } while ((bh = bh->b_this_page) != head);
1697 if (contiguous_blks) {
1698 lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
1699 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1700 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1703 /* If we have released all the blocks belonging to a cluster, then we
1704 * need to release the reserved space for that cluster. */
1705 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1706 while (num_clusters > 0) {
1707 lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
1708 ((num_clusters - 1) << sbi->s_cluster_bits);
1709 if (sbi->s_cluster_ratio == 1 ||
1710 !ext4_find_delalloc_cluster(inode, lblk))
1711 ext4_da_release_space(inode, 1);
1718 * Delayed allocation stuff
1721 struct mpage_da_data {
1722 struct inode *inode;
1723 struct writeback_control *wbc;
1725 pgoff_t first_page; /* The first page to write */
1726 pgoff_t next_page; /* Current page to examine */
1727 pgoff_t last_page; /* Last page to examine */
1729 * Extent to map - this can be after first_page because that can be
1730 * fully mapped. We somewhat abuse m_flags to store whether the extent
1731 * is delalloc or unwritten.
1733 struct ext4_map_blocks map;
1734 struct ext4_io_submit io_submit; /* IO submission data */
1735 unsigned int do_map:1;
1738 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1743 struct pagevec pvec;
1744 struct inode *inode = mpd->inode;
1745 struct address_space *mapping = inode->i_mapping;
1747 /* This is necessary when next_page == 0. */
1748 if (mpd->first_page >= mpd->next_page)
1751 index = mpd->first_page;
1752 end = mpd->next_page - 1;
1754 ext4_lblk_t start, last;
1755 start = index << (PAGE_SHIFT - inode->i_blkbits);
1756 last = end << (PAGE_SHIFT - inode->i_blkbits);
1757 ext4_es_remove_extent(inode, start, last - start + 1);
1760 pagevec_init(&pvec, 0);
1761 while (index <= end) {
1762 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1765 for (i = 0; i < nr_pages; i++) {
1766 struct page *page = pvec.pages[i];
1768 BUG_ON(!PageLocked(page));
1769 BUG_ON(PageWriteback(page));
1771 if (page_mapped(page))
1772 clear_page_dirty_for_io(page);
1773 block_invalidatepage(page, 0, PAGE_SIZE);
1774 ClearPageUptodate(page);
1778 pagevec_release(&pvec);
1782 static void ext4_print_free_blocks(struct inode *inode)
1784 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1785 struct super_block *sb = inode->i_sb;
1786 struct ext4_inode_info *ei = EXT4_I(inode);
1788 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1789 EXT4_C2B(EXT4_SB(inode->i_sb),
1790 ext4_count_free_clusters(sb)));
1791 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1792 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1793 (long long) EXT4_C2B(EXT4_SB(sb),
1794 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1795 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1796 (long long) EXT4_C2B(EXT4_SB(sb),
1797 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1798 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1799 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1800 ei->i_reserved_data_blocks);
1804 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1806 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1810 * This function is grabs code from the very beginning of
1811 * ext4_map_blocks, but assumes that the caller is from delayed write
1812 * time. This function looks up the requested blocks and sets the
1813 * buffer delay bit under the protection of i_data_sem.
1815 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1816 struct ext4_map_blocks *map,
1817 struct buffer_head *bh)
1819 struct extent_status es;
1821 sector_t invalid_block = ~((sector_t) 0xffff);
1822 #ifdef ES_AGGRESSIVE_TEST
1823 struct ext4_map_blocks orig_map;
1825 memcpy(&orig_map, map, sizeof(*map));
1828 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1832 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1833 "logical block %lu\n", inode->i_ino, map->m_len,
1834 (unsigned long) map->m_lblk);
1836 /* Lookup extent status tree firstly */
1837 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1838 if (ext4_es_is_hole(&es)) {
1840 down_read(&EXT4_I(inode)->i_data_sem);
1845 * Delayed extent could be allocated by fallocate.
1846 * So we need to check it.
1848 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1849 map_bh(bh, inode->i_sb, invalid_block);
1851 set_buffer_delay(bh);
1855 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1856 retval = es.es_len - (iblock - es.es_lblk);
1857 if (retval > map->m_len)
1858 retval = map->m_len;
1859 map->m_len = retval;
1860 if (ext4_es_is_written(&es))
1861 map->m_flags |= EXT4_MAP_MAPPED;
1862 else if (ext4_es_is_unwritten(&es))
1863 map->m_flags |= EXT4_MAP_UNWRITTEN;
1867 #ifdef ES_AGGRESSIVE_TEST
1868 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1874 * Try to see if we can get the block without requesting a new
1875 * file system block.
1877 down_read(&EXT4_I(inode)->i_data_sem);
1878 if (ext4_has_inline_data(inode))
1880 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1881 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1883 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1889 * XXX: __block_prepare_write() unmaps passed block,
1893 * If the block was allocated from previously allocated cluster,
1894 * then we don't need to reserve it again. However we still need
1895 * to reserve metadata for every block we're going to write.
1897 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1898 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1899 ret = ext4_da_reserve_space(inode);
1901 /* not enough space to reserve */
1907 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1908 ~0, EXTENT_STATUS_DELAYED);
1914 map_bh(bh, inode->i_sb, invalid_block);
1916 set_buffer_delay(bh);
1917 } else if (retval > 0) {
1919 unsigned int status;
1921 if (unlikely(retval != map->m_len)) {
1922 ext4_warning(inode->i_sb,
1923 "ES len assertion failed for inode "
1924 "%lu: retval %d != map->m_len %d",
1925 inode->i_ino, retval, map->m_len);
1929 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1930 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1931 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1932 map->m_pblk, status);
1938 up_read((&EXT4_I(inode)->i_data_sem));
1944 * This is a special get_block_t callback which is used by
1945 * ext4_da_write_begin(). It will either return mapped block or
1946 * reserve space for a single block.
1948 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1949 * We also have b_blocknr = -1 and b_bdev initialized properly
1951 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1952 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1953 * initialized properly.
1955 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1956 struct buffer_head *bh, int create)
1958 struct ext4_map_blocks map;
1961 BUG_ON(create == 0);
1962 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1964 map.m_lblk = iblock;
1968 * first, we need to know whether the block is allocated already
1969 * preallocated blocks are unmapped but should treated
1970 * the same as allocated blocks.
1972 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1976 map_bh(bh, inode->i_sb, map.m_pblk);
1977 ext4_update_bh_state(bh, map.m_flags);
1979 if (buffer_unwritten(bh)) {
1980 /* A delayed write to unwritten bh should be marked
1981 * new and mapped. Mapped ensures that we don't do
1982 * get_block multiple times when we write to the same
1983 * offset and new ensures that we do proper zero out
1984 * for partial write.
1987 set_buffer_mapped(bh);
1992 static int bget_one(handle_t *handle, struct buffer_head *bh)
1998 static int bput_one(handle_t *handle, struct buffer_head *bh)
2004 static int __ext4_journalled_writepage(struct page *page,
2007 struct address_space *mapping = page->mapping;
2008 struct inode *inode = mapping->host;
2009 struct buffer_head *page_bufs = NULL;
2010 handle_t *handle = NULL;
2011 int ret = 0, err = 0;
2012 int inline_data = ext4_has_inline_data(inode);
2013 struct buffer_head *inode_bh = NULL;
2015 ClearPageChecked(page);
2018 BUG_ON(page->index != 0);
2019 BUG_ON(len > ext4_get_max_inline_size(inode));
2020 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2021 if (inode_bh == NULL)
2024 page_bufs = page_buffers(page);
2029 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2033 * We need to release the page lock before we start the
2034 * journal, so grab a reference so the page won't disappear
2035 * out from under us.
2040 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2041 ext4_writepage_trans_blocks(inode));
2042 if (IS_ERR(handle)) {
2043 ret = PTR_ERR(handle);
2045 goto out_no_pagelock;
2047 BUG_ON(!ext4_handle_valid(handle));
2051 if (page->mapping != mapping) {
2052 /* The page got truncated from under us */
2053 ext4_journal_stop(handle);
2059 ret = ext4_mark_inode_dirty(handle, inode);
2061 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2062 do_journal_get_write_access);
2064 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2069 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2070 err = ext4_journal_stop(handle);
2074 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2078 if (!inline_data && page_bufs)
2079 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
2086 * Note that we don't need to start a transaction unless we're journaling data
2087 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2088 * need to file the inode to the transaction's list in ordered mode because if
2089 * we are writing back data added by write(), the inode is already there and if
2090 * we are writing back data modified via mmap(), no one guarantees in which
2091 * transaction the data will hit the disk. In case we are journaling data, we
2092 * cannot start transaction directly because transaction start ranks above page
2093 * lock so we have to do some magic.
2095 * This function can get called via...
2096 * - ext4_writepages after taking page lock (have journal handle)
2097 * - journal_submit_inode_data_buffers (no journal handle)
2098 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2099 * - grab_page_cache when doing write_begin (have journal handle)
2101 * We don't do any block allocation in this function. If we have page with
2102 * multiple blocks we need to write those buffer_heads that are mapped. This
2103 * is important for mmaped based write. So if we do with blocksize 1K
2104 * truncate(f, 1024);
2105 * a = mmap(f, 0, 4096);
2107 * truncate(f, 4096);
2108 * we have in the page first buffer_head mapped via page_mkwrite call back
2109 * but other buffer_heads would be unmapped but dirty (dirty done via the
2110 * do_wp_page). So writepage should write the first block. If we modify
2111 * the mmap area beyond 1024 we will again get a page_fault and the
2112 * page_mkwrite callback will do the block allocation and mark the
2113 * buffer_heads mapped.
2115 * We redirty the page if we have any buffer_heads that is either delay or
2116 * unwritten in the page.
2118 * We can get recursively called as show below.
2120 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2123 * But since we don't do any block allocation we should not deadlock.
2124 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2126 static int ext4_writepage(struct page *page,
2127 struct writeback_control *wbc)
2132 struct buffer_head *page_bufs = NULL;
2133 struct inode *inode = page->mapping->host;
2134 struct ext4_io_submit io_submit;
2135 bool keep_towrite = false;
2137 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2138 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2143 trace_ext4_writepage(page);
2144 size = i_size_read(inode);
2145 if (page->index == size >> PAGE_SHIFT)
2146 len = size & ~PAGE_MASK;
2150 page_bufs = page_buffers(page);
2152 * We cannot do block allocation or other extent handling in this
2153 * function. If there are buffers needing that, we have to redirty
2154 * the page. But we may reach here when we do a journal commit via
2155 * journal_submit_inode_data_buffers() and in that case we must write
2156 * allocated buffers to achieve data=ordered mode guarantees.
2158 * Also, if there is only one buffer per page (the fs block
2159 * size == the page size), if one buffer needs block
2160 * allocation or needs to modify the extent tree to clear the
2161 * unwritten flag, we know that the page can't be written at
2162 * all, so we might as well refuse the write immediately.
2163 * Unfortunately if the block size != page size, we can't as
2164 * easily detect this case using ext4_walk_page_buffers(), but
2165 * for the extremely common case, this is an optimization that
2166 * skips a useless round trip through ext4_bio_write_page().
2168 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2169 ext4_bh_delay_or_unwritten)) {
2170 redirty_page_for_writepage(wbc, page);
2171 if ((current->flags & PF_MEMALLOC) ||
2172 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2174 * For memory cleaning there's no point in writing only
2175 * some buffers. So just bail out. Warn if we came here
2176 * from direct reclaim.
2178 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2183 keep_towrite = true;
2186 if (PageChecked(page) && ext4_should_journal_data(inode))
2188 * It's mmapped pagecache. Add buffers and journal it. There
2189 * doesn't seem much point in redirtying the page here.
2191 return __ext4_journalled_writepage(page, len);
2193 ext4_io_submit_init(&io_submit, wbc);
2194 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2195 if (!io_submit.io_end) {
2196 redirty_page_for_writepage(wbc, page);
2200 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2201 ext4_io_submit(&io_submit);
2202 /* Drop io_end reference we got from init */
2203 ext4_put_io_end_defer(io_submit.io_end);
2207 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2213 BUG_ON(page->index != mpd->first_page);
2214 clear_page_dirty_for_io(page);
2216 * We have to be very careful here! Nothing protects writeback path
2217 * against i_size changes and the page can be writeably mapped into
2218 * page tables. So an application can be growing i_size and writing
2219 * data through mmap while writeback runs. clear_page_dirty_for_io()
2220 * write-protects our page in page tables and the page cannot get
2221 * written to again until we release page lock. So only after
2222 * clear_page_dirty_for_io() we are safe to sample i_size for
2223 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2224 * on the barrier provided by TestClearPageDirty in
2225 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2226 * after page tables are updated.
2228 size = i_size_read(mpd->inode);
2229 if (page->index == size >> PAGE_SHIFT)
2230 len = size & ~PAGE_MASK;
2233 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2235 mpd->wbc->nr_to_write--;
2241 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2244 * mballoc gives us at most this number of blocks...
2245 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2246 * The rest of mballoc seems to handle chunks up to full group size.
2248 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2251 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2253 * @mpd - extent of blocks
2254 * @lblk - logical number of the block in the file
2255 * @bh - buffer head we want to add to the extent
2257 * The function is used to collect contig. blocks in the same state. If the
2258 * buffer doesn't require mapping for writeback and we haven't started the
2259 * extent of buffers to map yet, the function returns 'true' immediately - the
2260 * caller can write the buffer right away. Otherwise the function returns true
2261 * if the block has been added to the extent, false if the block couldn't be
2264 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2265 struct buffer_head *bh)
2267 struct ext4_map_blocks *map = &mpd->map;
2269 /* Buffer that doesn't need mapping for writeback? */
2270 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2271 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2272 /* So far no extent to map => we write the buffer right away */
2273 if (map->m_len == 0)
2278 /* First block in the extent? */
2279 if (map->m_len == 0) {
2280 /* We cannot map unless handle is started... */
2285 map->m_flags = bh->b_state & BH_FLAGS;
2289 /* Don't go larger than mballoc is willing to allocate */
2290 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2293 /* Can we merge the block to our big extent? */
2294 if (lblk == map->m_lblk + map->m_len &&
2295 (bh->b_state & BH_FLAGS) == map->m_flags) {
2303 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2305 * @mpd - extent of blocks for mapping
2306 * @head - the first buffer in the page
2307 * @bh - buffer we should start processing from
2308 * @lblk - logical number of the block in the file corresponding to @bh
2310 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2311 * the page for IO if all buffers in this page were mapped and there's no
2312 * accumulated extent of buffers to map or add buffers in the page to the
2313 * extent of buffers to map. The function returns 1 if the caller can continue
2314 * by processing the next page, 0 if it should stop adding buffers to the
2315 * extent to map because we cannot extend it anymore. It can also return value
2316 * < 0 in case of error during IO submission.
2318 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2319 struct buffer_head *head,
2320 struct buffer_head *bh,
2323 struct inode *inode = mpd->inode;
2325 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2326 >> inode->i_blkbits;
2329 BUG_ON(buffer_locked(bh));
2331 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2332 /* Found extent to map? */
2335 /* Buffer needs mapping and handle is not started? */
2338 /* Everything mapped so far and we hit EOF */
2341 } while (lblk++, (bh = bh->b_this_page) != head);
2342 /* So far everything mapped? Submit the page for IO. */
2343 if (mpd->map.m_len == 0) {
2344 err = mpage_submit_page(mpd, head->b_page);
2348 return lblk < blocks;
2352 * mpage_map_buffers - update buffers corresponding to changed extent and
2353 * submit fully mapped pages for IO
2355 * @mpd - description of extent to map, on return next extent to map
2357 * Scan buffers corresponding to changed extent (we expect corresponding pages
2358 * to be already locked) and update buffer state according to new extent state.
2359 * We map delalloc buffers to their physical location, clear unwritten bits,
2360 * and mark buffers as uninit when we perform writes to unwritten extents
2361 * and do extent conversion after IO is finished. If the last page is not fully
2362 * mapped, we update @map to the next extent in the last page that needs
2363 * mapping. Otherwise we submit the page for IO.
2365 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2367 struct pagevec pvec;
2369 struct inode *inode = mpd->inode;
2370 struct buffer_head *head, *bh;
2371 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2377 start = mpd->map.m_lblk >> bpp_bits;
2378 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2379 lblk = start << bpp_bits;
2380 pblock = mpd->map.m_pblk;
2382 pagevec_init(&pvec, 0);
2383 while (start <= end) {
2384 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2388 for (i = 0; i < nr_pages; i++) {
2389 struct page *page = pvec.pages[i];
2391 bh = head = page_buffers(page);
2393 if (lblk < mpd->map.m_lblk)
2395 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2397 * Buffer after end of mapped extent.
2398 * Find next buffer in the page to map.
2401 mpd->map.m_flags = 0;
2403 * FIXME: If dioread_nolock supports
2404 * blocksize < pagesize, we need to make
2405 * sure we add size mapped so far to
2406 * io_end->size as the following call
2407 * can submit the page for IO.
2409 err = mpage_process_page_bufs(mpd, head,
2411 pagevec_release(&pvec);
2416 if (buffer_delay(bh)) {
2417 clear_buffer_delay(bh);
2418 bh->b_blocknr = pblock++;
2420 clear_buffer_unwritten(bh);
2421 } while (lblk++, (bh = bh->b_this_page) != head);
2424 * FIXME: This is going to break if dioread_nolock
2425 * supports blocksize < pagesize as we will try to
2426 * convert potentially unmapped parts of inode.
2428 mpd->io_submit.io_end->size += PAGE_SIZE;
2429 /* Page fully mapped - let IO run! */
2430 err = mpage_submit_page(mpd, page);
2432 pagevec_release(&pvec);
2436 pagevec_release(&pvec);
2438 /* Extent fully mapped and matches with page boundary. We are done. */
2440 mpd->map.m_flags = 0;
2444 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2446 struct inode *inode = mpd->inode;
2447 struct ext4_map_blocks *map = &mpd->map;
2448 int get_blocks_flags;
2449 int err, dioread_nolock;
2451 trace_ext4_da_write_pages_extent(inode, map);
2453 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2454 * to convert an unwritten extent to be initialized (in the case
2455 * where we have written into one or more preallocated blocks). It is
2456 * possible that we're going to need more metadata blocks than
2457 * previously reserved. However we must not fail because we're in
2458 * writeback and there is nothing we can do about it so it might result
2459 * in data loss. So use reserved blocks to allocate metadata if
2462 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2463 * the blocks in question are delalloc blocks. This indicates
2464 * that the blocks and quotas has already been checked when
2465 * the data was copied into the page cache.
2467 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2468 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2469 EXT4_GET_BLOCKS_IO_SUBMIT;
2470 dioread_nolock = ext4_should_dioread_nolock(inode);
2472 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2473 if (map->m_flags & (1 << BH_Delay))
2474 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2476 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2479 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2480 if (!mpd->io_submit.io_end->handle &&
2481 ext4_handle_valid(handle)) {
2482 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2483 handle->h_rsv_handle = NULL;
2485 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2488 BUG_ON(map->m_len == 0);
2489 if (map->m_flags & EXT4_MAP_NEW) {
2490 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
2497 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2498 * mpd->len and submit pages underlying it for IO
2500 * @handle - handle for journal operations
2501 * @mpd - extent to map
2502 * @give_up_on_write - we set this to true iff there is a fatal error and there
2503 * is no hope of writing the data. The caller should discard
2504 * dirty pages to avoid infinite loops.
2506 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2507 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2508 * them to initialized or split the described range from larger unwritten
2509 * extent. Note that we need not map all the described range since allocation
2510 * can return less blocks or the range is covered by more unwritten extents. We
2511 * cannot map more because we are limited by reserved transaction credits. On
2512 * the other hand we always make sure that the last touched page is fully
2513 * mapped so that it can be written out (and thus forward progress is
2514 * guaranteed). After mapping we submit all mapped pages for IO.
2516 static int mpage_map_and_submit_extent(handle_t *handle,
2517 struct mpage_da_data *mpd,
2518 bool *give_up_on_write)
2520 struct inode *inode = mpd->inode;
2521 struct ext4_map_blocks *map = &mpd->map;
2526 mpd->io_submit.io_end->offset =
2527 ((loff_t)map->m_lblk) << inode->i_blkbits;
2529 err = mpage_map_one_extent(handle, mpd);
2531 struct super_block *sb = inode->i_sb;
2533 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2534 EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2535 goto invalidate_dirty_pages;
2537 * Let the uper layers retry transient errors.
2538 * In the case of ENOSPC, if ext4_count_free_blocks()
2539 * is non-zero, a commit should free up blocks.
2541 if ((err == -ENOMEM) ||
2542 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2544 goto update_disksize;
2547 ext4_msg(sb, KERN_CRIT,
2548 "Delayed block allocation failed for "
2549 "inode %lu at logical offset %llu with"
2550 " max blocks %u with error %d",
2552 (unsigned long long)map->m_lblk,
2553 (unsigned)map->m_len, -err);
2554 ext4_msg(sb, KERN_CRIT,
2555 "This should not happen!! Data will "
2558 ext4_print_free_blocks(inode);
2559 invalidate_dirty_pages:
2560 *give_up_on_write = true;
2565 * Update buffer state, submit mapped pages, and get us new
2568 err = mpage_map_and_submit_buffers(mpd);
2570 goto update_disksize;
2571 } while (map->m_len);
2575 * Update on-disk size after IO is submitted. Races with
2576 * truncate are avoided by checking i_size under i_data_sem.
2578 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2579 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2583 down_write(&EXT4_I(inode)->i_data_sem);
2584 i_size = i_size_read(inode);
2585 if (disksize > i_size)
2587 if (disksize > EXT4_I(inode)->i_disksize)
2588 EXT4_I(inode)->i_disksize = disksize;
2589 up_write(&EXT4_I(inode)->i_data_sem);
2590 err2 = ext4_mark_inode_dirty(handle, inode);
2592 ext4_error(inode->i_sb,
2593 "Failed to mark inode %lu dirty",
2602 * Calculate the total number of credits to reserve for one writepages
2603 * iteration. This is called from ext4_writepages(). We map an extent of
2604 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2605 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2606 * bpp - 1 blocks in bpp different extents.
2608 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2610 int bpp = ext4_journal_blocks_per_page(inode);
2612 return ext4_meta_trans_blocks(inode,
2613 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2617 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2618 * and underlying extent to map
2620 * @mpd - where to look for pages
2622 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2623 * IO immediately. When we find a page which isn't mapped we start accumulating
2624 * extent of buffers underlying these pages that needs mapping (formed by
2625 * either delayed or unwritten buffers). We also lock the pages containing
2626 * these buffers. The extent found is returned in @mpd structure (starting at
2627 * mpd->lblk with length mpd->len blocks).
2629 * Note that this function can attach bios to one io_end structure which are
2630 * neither logically nor physically contiguous. Although it may seem as an
2631 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2632 * case as we need to track IO to all buffers underlying a page in one io_end.
2634 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2636 struct address_space *mapping = mpd->inode->i_mapping;
2637 struct pagevec pvec;
2638 unsigned int nr_pages;
2639 long left = mpd->wbc->nr_to_write;
2640 pgoff_t index = mpd->first_page;
2641 pgoff_t end = mpd->last_page;
2644 int blkbits = mpd->inode->i_blkbits;
2646 struct buffer_head *head;
2648 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2649 tag = PAGECACHE_TAG_TOWRITE;
2651 tag = PAGECACHE_TAG_DIRTY;
2653 pagevec_init(&pvec, 0);
2655 mpd->next_page = index;
2656 while (index <= end) {
2657 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2658 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2662 for (i = 0; i < nr_pages; i++) {
2663 struct page *page = pvec.pages[i];
2666 * At this point, the page may be truncated or
2667 * invalidated (changing page->mapping to NULL), or
2668 * even swizzled back from swapper_space to tmpfs file
2669 * mapping. However, page->index will not change
2670 * because we have a reference on the page.
2672 if (page->index > end)
2676 * Accumulated enough dirty pages? This doesn't apply
2677 * to WB_SYNC_ALL mode. For integrity sync we have to
2678 * keep going because someone may be concurrently
2679 * dirtying pages, and we might have synced a lot of
2680 * newly appeared dirty pages, but have not synced all
2681 * of the old dirty pages.
2683 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2686 /* If we can't merge this page, we are done. */
2687 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2692 * If the page is no longer dirty, or its mapping no
2693 * longer corresponds to inode we are writing (which
2694 * means it has been truncated or invalidated), or the
2695 * page is already under writeback and we are not doing
2696 * a data integrity writeback, skip the page
2698 if (!PageDirty(page) ||
2699 (PageWriteback(page) &&
2700 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2701 unlikely(page->mapping != mapping)) {
2706 wait_on_page_writeback(page);
2707 BUG_ON(PageWriteback(page));
2709 if (mpd->map.m_len == 0)
2710 mpd->first_page = page->index;
2711 mpd->next_page = page->index + 1;
2712 /* Add all dirty buffers to mpd */
2713 lblk = ((ext4_lblk_t)page->index) <<
2714 (PAGE_SHIFT - blkbits);
2715 head = page_buffers(page);
2716 err = mpage_process_page_bufs(mpd, head, head, lblk);
2722 pagevec_release(&pvec);
2727 pagevec_release(&pvec);
2731 static int __writepage(struct page *page, struct writeback_control *wbc,
2734 struct address_space *mapping = data;
2735 int ret = ext4_writepage(page, wbc);
2736 mapping_set_error(mapping, ret);
2740 static int ext4_writepages(struct address_space *mapping,
2741 struct writeback_control *wbc)
2743 pgoff_t writeback_index = 0;
2744 long nr_to_write = wbc->nr_to_write;
2745 int range_whole = 0;
2747 handle_t *handle = NULL;
2748 struct mpage_da_data mpd;
2749 struct inode *inode = mapping->host;
2750 int needed_blocks, rsv_blocks = 0, ret = 0;
2751 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2753 struct blk_plug plug;
2754 bool give_up_on_write = false;
2756 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2759 percpu_down_read(&sbi->s_writepages_rwsem);
2760 trace_ext4_writepages(inode, wbc);
2762 if (dax_mapping(mapping)) {
2763 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
2765 goto out_writepages;
2769 * No pages to write? This is mainly a kludge to avoid starting
2770 * a transaction for special inodes like journal inode on last iput()
2771 * because that could violate lock ordering on umount
2773 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2774 goto out_writepages;
2776 if (ext4_should_journal_data(inode)) {
2777 struct blk_plug plug;
2779 blk_start_plug(&plug);
2780 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2781 blk_finish_plug(&plug);
2782 goto out_writepages;
2786 * If the filesystem has aborted, it is read-only, so return
2787 * right away instead of dumping stack traces later on that
2788 * will obscure the real source of the problem. We test
2789 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2790 * the latter could be true if the filesystem is mounted
2791 * read-only, and in that case, ext4_writepages should
2792 * *never* be called, so if that ever happens, we would want
2795 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2796 sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2798 goto out_writepages;
2801 if (ext4_should_dioread_nolock(inode)) {
2803 * We may need to convert up to one extent per block in
2804 * the page and we may dirty the inode.
2806 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2807 PAGE_SIZE >> inode->i_blkbits);
2811 * If we have inline data and arrive here, it means that
2812 * we will soon create the block for the 1st page, so
2813 * we'd better clear the inline data here.
2815 if (ext4_has_inline_data(inode)) {
2816 /* Just inode will be modified... */
2817 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2818 if (IS_ERR(handle)) {
2819 ret = PTR_ERR(handle);
2820 goto out_writepages;
2822 BUG_ON(ext4_test_inode_state(inode,
2823 EXT4_STATE_MAY_INLINE_DATA));
2824 ext4_destroy_inline_data(handle, inode);
2825 ext4_journal_stop(handle);
2828 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2831 if (wbc->range_cyclic) {
2832 writeback_index = mapping->writeback_index;
2833 if (writeback_index)
2835 mpd.first_page = writeback_index;
2838 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2839 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2844 ext4_io_submit_init(&mpd.io_submit, wbc);
2846 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2847 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2849 blk_start_plug(&plug);
2852 * First writeback pages that don't need mapping - we can avoid
2853 * starting a transaction unnecessarily and also avoid being blocked
2854 * in the block layer on device congestion while having transaction
2858 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2859 if (!mpd.io_submit.io_end) {
2863 ret = mpage_prepare_extent_to_map(&mpd);
2864 /* Submit prepared bio */
2865 ext4_io_submit(&mpd.io_submit);
2866 ext4_put_io_end_defer(mpd.io_submit.io_end);
2867 mpd.io_submit.io_end = NULL;
2868 /* Unlock pages we didn't use */
2869 mpage_release_unused_pages(&mpd, false);
2873 while (!done && mpd.first_page <= mpd.last_page) {
2874 /* For each extent of pages we use new io_end */
2875 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2876 if (!mpd.io_submit.io_end) {
2882 * We have two constraints: We find one extent to map and we
2883 * must always write out whole page (makes a difference when
2884 * blocksize < pagesize) so that we don't block on IO when we
2885 * try to write out the rest of the page. Journalled mode is
2886 * not supported by delalloc.
2888 BUG_ON(ext4_should_journal_data(inode));
2889 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2891 /* start a new transaction */
2892 handle = ext4_journal_start_with_reserve(inode,
2893 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2894 if (IS_ERR(handle)) {
2895 ret = PTR_ERR(handle);
2896 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2897 "%ld pages, ino %lu; err %d", __func__,
2898 wbc->nr_to_write, inode->i_ino, ret);
2899 /* Release allocated io_end */
2900 ext4_put_io_end(mpd.io_submit.io_end);
2901 mpd.io_submit.io_end = NULL;
2906 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2907 ret = mpage_prepare_extent_to_map(&mpd);
2910 ret = mpage_map_and_submit_extent(handle, &mpd,
2914 * We scanned the whole range (or exhausted
2915 * nr_to_write), submitted what was mapped and
2916 * didn't find anything needing mapping. We are
2923 * Caution: If the handle is synchronous,
2924 * ext4_journal_stop() can wait for transaction commit
2925 * to finish which may depend on writeback of pages to
2926 * complete or on page lock to be released. In that
2927 * case, we have to wait until after after we have
2928 * submitted all the IO, released page locks we hold,
2929 * and dropped io_end reference (for extent conversion
2930 * to be able to complete) before stopping the handle.
2932 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2933 ext4_journal_stop(handle);
2937 /* Submit prepared bio */
2938 ext4_io_submit(&mpd.io_submit);
2939 /* Unlock pages we didn't use */
2940 mpage_release_unused_pages(&mpd, give_up_on_write);
2942 * Drop our io_end reference we got from init. We have
2943 * to be careful and use deferred io_end finishing if
2944 * we are still holding the transaction as we can
2945 * release the last reference to io_end which may end
2946 * up doing unwritten extent conversion.
2949 ext4_put_io_end_defer(mpd.io_submit.io_end);
2950 ext4_journal_stop(handle);
2952 ext4_put_io_end(mpd.io_submit.io_end);
2953 mpd.io_submit.io_end = NULL;
2955 if (ret == -ENOSPC && sbi->s_journal) {
2957 * Commit the transaction which would
2958 * free blocks released in the transaction
2961 jbd2_journal_force_commit_nested(sbi->s_journal);
2965 /* Fatal error - ENOMEM, EIO... */
2970 blk_finish_plug(&plug);
2971 if (!ret && !cycled && wbc->nr_to_write > 0) {
2973 mpd.last_page = writeback_index - 1;
2979 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2981 * Set the writeback_index so that range_cyclic
2982 * mode will write it back later
2984 mapping->writeback_index = mpd.first_page;
2987 trace_ext4_writepages_result(inode, wbc, ret,
2988 nr_to_write - wbc->nr_to_write);
2989 percpu_up_read(&sbi->s_writepages_rwsem);
2993 static int ext4_nonda_switch(struct super_block *sb)
2995 s64 free_clusters, dirty_clusters;
2996 struct ext4_sb_info *sbi = EXT4_SB(sb);
2999 * switch to non delalloc mode if we are running low
3000 * on free block. The free block accounting via percpu
3001 * counters can get slightly wrong with percpu_counter_batch getting
3002 * accumulated on each CPU without updating global counters
3003 * Delalloc need an accurate free block accounting. So switch
3004 * to non delalloc when we are near to error range.
3007 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
3009 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
3011 * Start pushing delalloc when 1/2 of free blocks are dirty.
3013 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
3014 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
3016 if (2 * free_clusters < 3 * dirty_clusters ||
3017 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
3019 * free block count is less than 150% of dirty blocks
3020 * or free blocks is less than watermark
3027 /* We always reserve for an inode update; the superblock could be there too */
3028 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
3030 if (likely(ext4_has_feature_large_file(inode->i_sb)))
3033 if (pos + len <= 0x7fffffffULL)
3036 /* We might need to update the superblock to set LARGE_FILE */
3040 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3041 loff_t pos, unsigned len, unsigned flags,
3042 struct page **pagep, void **fsdata)
3044 int ret, retries = 0;
3047 struct inode *inode = mapping->host;
3050 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3053 index = pos >> PAGE_SHIFT;
3055 if (ext4_nonda_switch(inode->i_sb) ||
3056 S_ISLNK(inode->i_mode)) {
3057 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3058 return ext4_write_begin(file, mapping, pos,
3059 len, flags, pagep, fsdata);
3061 *fsdata = (void *)0;
3062 trace_ext4_da_write_begin(inode, pos, len, flags);
3064 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3065 ret = ext4_da_write_inline_data_begin(mapping, inode,
3075 * grab_cache_page_write_begin() can take a long time if the
3076 * system is thrashing due to memory pressure, or if the page
3077 * is being written back. So grab it first before we start
3078 * the transaction handle. This also allows us to allocate
3079 * the page (if needed) without using GFP_NOFS.
3082 page = grab_cache_page_write_begin(mapping, index, flags);
3088 * With delayed allocation, we don't log the i_disksize update
3089 * if there is delayed block allocation. But we still need
3090 * to journalling the i_disksize update if writes to the end
3091 * of file which has an already mapped buffer.
3094 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3095 ext4_da_write_credits(inode, pos, len));
3096 if (IS_ERR(handle)) {
3098 return PTR_ERR(handle);
3102 if (page->mapping != mapping) {
3103 /* The page got truncated from under us */
3106 ext4_journal_stop(handle);
3109 /* In case writeback began while the page was unlocked */
3110 wait_for_stable_page(page);
3112 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3113 ret = ext4_block_write_begin(page, pos, len,
3114 ext4_da_get_block_prep);
3116 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3120 ext4_journal_stop(handle);
3122 * block_write_begin may have instantiated a few blocks
3123 * outside i_size. Trim these off again. Don't need
3124 * i_size_read because we hold i_mutex.
3126 if (pos + len > inode->i_size)
3127 ext4_truncate_failed_write(inode);
3129 if (ret == -ENOSPC &&
3130 ext4_should_retry_alloc(inode->i_sb, &retries))
3142 * Check if we should update i_disksize
3143 * when write to the end of file but not require block allocation
3145 static int ext4_da_should_update_i_disksize(struct page *page,
3146 unsigned long offset)
3148 struct buffer_head *bh;
3149 struct inode *inode = page->mapping->host;
3153 bh = page_buffers(page);
3154 idx = offset >> inode->i_blkbits;
3156 for (i = 0; i < idx; i++)
3157 bh = bh->b_this_page;
3159 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3164 static int ext4_da_write_end(struct file *file,
3165 struct address_space *mapping,
3166 loff_t pos, unsigned len, unsigned copied,
3167 struct page *page, void *fsdata)
3169 struct inode *inode = mapping->host;
3171 handle_t *handle = ext4_journal_current_handle();
3173 unsigned long start, end;
3174 int write_mode = (int)(unsigned long)fsdata;
3176 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3177 return ext4_write_end(file, mapping, pos,
3178 len, copied, page, fsdata);
3180 trace_ext4_da_write_end(inode, pos, len, copied);
3181 start = pos & (PAGE_SIZE - 1);
3182 end = start + copied - 1;
3185 * generic_write_end() will run mark_inode_dirty() if i_size
3186 * changes. So let's piggyback the i_disksize mark_inode_dirty
3189 new_i_size = pos + copied;
3190 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3191 if (ext4_has_inline_data(inode) ||
3192 ext4_da_should_update_i_disksize(page, end)) {
3193 ext4_update_i_disksize(inode, new_i_size);
3194 /* We need to mark inode dirty even if
3195 * new_i_size is less that inode->i_size
3196 * bu greater than i_disksize.(hint delalloc)
3198 ext4_mark_inode_dirty(handle, inode);
3202 if (write_mode != CONVERT_INLINE_DATA &&
3203 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3204 ext4_has_inline_data(inode))
3205 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3208 ret2 = generic_write_end(file, mapping, pos, len, copied,
3214 ret2 = ext4_journal_stop(handle);
3218 return ret ? ret : copied;
3221 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
3222 unsigned int length)
3225 * Drop reserved blocks
3227 BUG_ON(!PageLocked(page));
3228 if (!page_has_buffers(page))
3231 ext4_da_page_release_reservation(page, offset, length);
3234 ext4_invalidatepage(page, offset, length);
3240 * Force all delayed allocation blocks to be allocated for a given inode.
3242 int ext4_alloc_da_blocks(struct inode *inode)
3244 trace_ext4_alloc_da_blocks(inode);
3246 if (!EXT4_I(inode)->i_reserved_data_blocks)
3250 * We do something simple for now. The filemap_flush() will
3251 * also start triggering a write of the data blocks, which is
3252 * not strictly speaking necessary (and for users of
3253 * laptop_mode, not even desirable). However, to do otherwise
3254 * would require replicating code paths in:
3256 * ext4_writepages() ->
3257 * write_cache_pages() ---> (via passed in callback function)
3258 * __mpage_da_writepage() -->
3259 * mpage_add_bh_to_extent()
3260 * mpage_da_map_blocks()
3262 * The problem is that write_cache_pages(), located in
3263 * mm/page-writeback.c, marks pages clean in preparation for
3264 * doing I/O, which is not desirable if we're not planning on
3267 * We could call write_cache_pages(), and then redirty all of
3268 * the pages by calling redirty_page_for_writepage() but that
3269 * would be ugly in the extreme. So instead we would need to
3270 * replicate parts of the code in the above functions,
3271 * simplifying them because we wouldn't actually intend to
3272 * write out the pages, but rather only collect contiguous
3273 * logical block extents, call the multi-block allocator, and
3274 * then update the buffer heads with the block allocations.
3276 * For now, though, we'll cheat by calling filemap_flush(),
3277 * which will map the blocks, and start the I/O, but not
3278 * actually wait for the I/O to complete.
3280 return filemap_flush(inode->i_mapping);
3284 * bmap() is special. It gets used by applications such as lilo and by
3285 * the swapper to find the on-disk block of a specific piece of data.
3287 * Naturally, this is dangerous if the block concerned is still in the
3288 * journal. If somebody makes a swapfile on an ext4 data-journaling
3289 * filesystem and enables swap, then they may get a nasty shock when the
3290 * data getting swapped to that swapfile suddenly gets overwritten by
3291 * the original zero's written out previously to the journal and
3292 * awaiting writeback in the kernel's buffer cache.
3294 * So, if we see any bmap calls here on a modified, data-journaled file,
3295 * take extra steps to flush any blocks which might be in the cache.
3297 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3299 struct inode *inode = mapping->host;
3304 * We can get here for an inline file via the FIBMAP ioctl
3306 if (ext4_has_inline_data(inode))
3309 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3310 test_opt(inode->i_sb, DELALLOC)) {
3312 * With delalloc we want to sync the file
3313 * so that we can make sure we allocate
3316 filemap_write_and_wait(mapping);
3319 if (EXT4_JOURNAL(inode) &&
3320 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3322 * This is a REALLY heavyweight approach, but the use of
3323 * bmap on dirty files is expected to be extremely rare:
3324 * only if we run lilo or swapon on a freshly made file
3325 * do we expect this to happen.
3327 * (bmap requires CAP_SYS_RAWIO so this does not
3328 * represent an unprivileged user DOS attack --- we'd be
3329 * in trouble if mortal users could trigger this path at
3332 * NB. EXT4_STATE_JDATA is not set on files other than
3333 * regular files. If somebody wants to bmap a directory
3334 * or symlink and gets confused because the buffer
3335 * hasn't yet been flushed to disk, they deserve
3336 * everything they get.
3339 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3340 journal = EXT4_JOURNAL(inode);
3341 jbd2_journal_lock_updates(journal);
3342 err = jbd2_journal_flush(journal);
3343 jbd2_journal_unlock_updates(journal);
3349 return generic_block_bmap(mapping, block, ext4_get_block);
3352 static int ext4_readpage(struct file *file, struct page *page)
3355 struct inode *inode = page->mapping->host;
3357 trace_ext4_readpage(page);
3359 if (ext4_has_inline_data(inode))
3360 ret = ext4_readpage_inline(inode, page);
3363 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3369 ext4_readpages(struct file *file, struct address_space *mapping,
3370 struct list_head *pages, unsigned nr_pages)
3372 struct inode *inode = mapping->host;
3374 /* If the file has inline data, no need to do readpages. */
3375 if (ext4_has_inline_data(inode))
3378 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3381 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3382 unsigned int length)
3384 trace_ext4_invalidatepage(page, offset, length);
3386 /* No journalling happens on data buffers when this function is used */
3387 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3389 block_invalidatepage(page, offset, length);
3392 static int __ext4_journalled_invalidatepage(struct page *page,
3393 unsigned int offset,
3394 unsigned int length)
3396 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3398 trace_ext4_journalled_invalidatepage(page, offset, length);
3401 * If it's a full truncate we just forget about the pending dirtying
3403 if (offset == 0 && length == PAGE_SIZE)
3404 ClearPageChecked(page);
3406 return jbd2_journal_invalidatepage(journal, page, offset, length);
3409 /* Wrapper for aops... */
3410 static void ext4_journalled_invalidatepage(struct page *page,
3411 unsigned int offset,
3412 unsigned int length)
3414 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3417 static int ext4_releasepage(struct page *page, gfp_t wait)
3419 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3421 trace_ext4_releasepage(page);
3423 /* Page has dirty journalled data -> cannot release */
3424 if (PageChecked(page))
3427 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3429 return try_to_free_buffers(page);
3432 #ifdef CONFIG_FS_DAX
3433 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3434 unsigned flags, struct iomap *iomap)
3436 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3437 unsigned int blkbits = inode->i_blkbits;
3438 unsigned long first_block, last_block;
3439 struct ext4_map_blocks map;
3442 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3444 first_block = offset >> blkbits;
3445 last_block = min_t(loff_t, (offset + length - 1) >> blkbits,
3446 EXT4_MAX_LOGICAL_BLOCK);
3448 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3451 map.m_lblk = first_block;
3452 map.m_len = last_block - first_block + 1;
3454 if (!(flags & IOMAP_WRITE)) {
3455 ret = ext4_map_blocks(NULL, inode, &map, 0);
3461 /* Trim mapping request to maximum we can map at once for DIO */
3462 if (map.m_len > DIO_MAX_BLOCKS)
3463 map.m_len = DIO_MAX_BLOCKS;
3464 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3467 * Either we allocate blocks and then we don't get unwritten
3468 * extent so we have reserved enough credits, or the blocks
3469 * are already allocated and unwritten and in that case
3470 * extent conversion fits in the credits as well.
3472 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3475 return PTR_ERR(handle);
3477 ret = ext4_map_blocks(handle, inode, &map,
3478 EXT4_GET_BLOCKS_CREATE_ZERO);
3480 ext4_journal_stop(handle);
3481 if (ret == -ENOSPC &&
3482 ext4_should_retry_alloc(inode->i_sb, &retries))
3488 * If we added blocks beyond i_size, we need to make sure they
3489 * will get truncated if we crash before updating i_size in
3490 * ext4_iomap_end(). For faults we don't need to do that (and
3491 * even cannot because for orphan list operations inode_lock is
3492 * required) - if we happen to instantiate block beyond i_size,
3493 * it is because we race with truncate which has already added
3494 * the inode to the orphan list.
3496 if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3497 (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
3500 err = ext4_orphan_add(handle, inode);
3502 ext4_journal_stop(handle);
3506 ext4_journal_stop(handle);
3510 iomap->bdev = inode->i_sb->s_bdev;
3511 iomap->dax_dev = sbi->s_daxdev;
3512 iomap->offset = first_block << blkbits;
3515 iomap->type = IOMAP_HOLE;
3516 iomap->blkno = IOMAP_NULL_BLOCK;
3517 iomap->length = (u64)map.m_len << blkbits;
3519 if (map.m_flags & EXT4_MAP_MAPPED) {
3520 iomap->type = IOMAP_MAPPED;
3521 } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3522 iomap->type = IOMAP_UNWRITTEN;
3527 iomap->blkno = (sector_t)map.m_pblk << (blkbits - 9);
3528 iomap->length = (u64)map.m_len << blkbits;
3531 if (map.m_flags & EXT4_MAP_NEW)
3532 iomap->flags |= IOMAP_F_NEW;
3536 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3537 ssize_t written, unsigned flags, struct iomap *iomap)
3541 int blkbits = inode->i_blkbits;
3542 bool truncate = false;
3544 if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
3547 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3548 if (IS_ERR(handle)) {
3549 ret = PTR_ERR(handle);
3552 if (ext4_update_inode_size(inode, offset + written))
3553 ext4_mark_inode_dirty(handle, inode);
3555 * We may need to truncate allocated but not written blocks beyond EOF.
3557 if (iomap->offset + iomap->length >
3558 ALIGN(inode->i_size, 1 << blkbits)) {
3559 ext4_lblk_t written_blk, end_blk;
3561 written_blk = (offset + written) >> blkbits;
3562 end_blk = (offset + length) >> blkbits;
3563 if (written_blk < end_blk && ext4_can_truncate(inode))
3567 * Remove inode from orphan list if we were extending a inode and
3568 * everything went fine.
3570 if (!truncate && inode->i_nlink &&
3571 !list_empty(&EXT4_I(inode)->i_orphan))
3572 ext4_orphan_del(handle, inode);
3573 ext4_journal_stop(handle);
3575 ext4_truncate_failed_write(inode);
3578 * If truncate failed early the inode might still be on the
3579 * orphan list; we need to make sure the inode is removed from
3580 * the orphan list in that case.
3583 ext4_orphan_del(NULL, inode);
3588 const struct iomap_ops ext4_iomap_ops = {
3589 .iomap_begin = ext4_iomap_begin,
3590 .iomap_end = ext4_iomap_end,
3595 static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3596 ssize_t size, void *private)
3598 ext4_io_end_t *io_end = private;
3600 /* if not async direct IO just return */
3604 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3605 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3606 io_end, io_end->inode->i_ino, iocb, offset, size);
3609 * Error during AIO DIO. We cannot convert unwritten extents as the
3610 * data was not written. Just clear the unwritten flag and drop io_end.
3613 ext4_clear_io_unwritten_flag(io_end);
3616 io_end->offset = offset;
3617 io_end->size = size;
3618 ext4_put_io_end(io_end);
3624 * Handling of direct IO writes.
3626 * For ext4 extent files, ext4 will do direct-io write even to holes,
3627 * preallocated extents, and those write extend the file, no need to
3628 * fall back to buffered IO.
3630 * For holes, we fallocate those blocks, mark them as unwritten
3631 * If those blocks were preallocated, we mark sure they are split, but
3632 * still keep the range to write as unwritten.
3634 * The unwritten extents will be converted to written when DIO is completed.
3635 * For async direct IO, since the IO may still pending when return, we
3636 * set up an end_io call back function, which will do the conversion
3637 * when async direct IO completed.
3639 * If the O_DIRECT write will extend the file then add this inode to the
3640 * orphan list. So recovery will truncate it back to the original size
3641 * if the machine crashes during the write.
3644 static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
3646 struct file *file = iocb->ki_filp;
3647 struct inode *inode = file->f_mapping->host;
3649 loff_t offset = iocb->ki_pos;
3650 size_t count = iov_iter_count(iter);
3652 get_block_t *get_block_func = NULL;
3654 loff_t final_size = offset + count;
3658 if (final_size > inode->i_size) {
3659 /* Credits for sb + inode write */
3660 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3661 if (IS_ERR(handle)) {
3662 ret = PTR_ERR(handle);
3665 ret = ext4_orphan_add(handle, inode);
3667 ext4_journal_stop(handle);
3671 ext4_update_i_disksize(inode, inode->i_size);
3672 ext4_journal_stop(handle);
3675 BUG_ON(iocb->private == NULL);
3678 * Make all waiters for direct IO properly wait also for extent
3679 * conversion. This also disallows race between truncate() and
3680 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3682 inode_dio_begin(inode);
3684 /* If we do a overwrite dio, i_mutex locking can be released */
3685 overwrite = *((int *)iocb->private);
3688 inode_unlock(inode);
3691 * For extent mapped files we could direct write to holes and fallocate.
3693 * Allocated blocks to fill the hole are marked as unwritten to prevent
3694 * parallel buffered read to expose the stale data before DIO complete
3697 * As to previously fallocated extents, ext4 get_block will just simply
3698 * mark the buffer mapped but still keep the extents unwritten.
3700 * For non AIO case, we will convert those unwritten extents to written
3701 * after return back from blockdev_direct_IO. That way we save us from
3702 * allocating io_end structure and also the overhead of offloading
3703 * the extent convertion to a workqueue.
3705 * For async DIO, the conversion needs to be deferred when the
3706 * IO is completed. The ext4 end_io callback function will be
3707 * called to take care of the conversion work. Here for async
3708 * case, we allocate an io_end structure to hook to the iocb.
3710 iocb->private = NULL;
3712 get_block_func = ext4_dio_get_block_overwrite;
3713 else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
3714 round_down(offset, i_blocksize(inode)) >= inode->i_size) {
3715 get_block_func = ext4_dio_get_block;
3716 dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3717 } else if (is_sync_kiocb(iocb)) {
3718 get_block_func = ext4_dio_get_block_unwritten_sync;
3719 dio_flags = DIO_LOCKING;
3721 get_block_func = ext4_dio_get_block_unwritten_async;
3722 dio_flags = DIO_LOCKING;
3724 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3725 get_block_func, ext4_end_io_dio, NULL,
3728 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3729 EXT4_STATE_DIO_UNWRITTEN)) {
3732 * for non AIO case, since the IO is already
3733 * completed, we could do the conversion right here
3735 err = ext4_convert_unwritten_extents(NULL, inode,
3739 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3742 inode_dio_end(inode);
3743 /* take i_mutex locking again if we do a ovewrite dio */
3747 if (ret < 0 && final_size > inode->i_size)
3748 ext4_truncate_failed_write(inode);
3750 /* Handle extending of i_size after direct IO write */
3754 /* Credits for sb + inode write */
3755 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3756 if (IS_ERR(handle)) {
3758 * We wrote the data but cannot extend
3759 * i_size. Bail out. In async io case, we do
3760 * not return error here because we have
3761 * already submmitted the corresponding
3762 * bio. Returning error here makes the caller
3763 * think that this IO is done and failed
3764 * resulting in race with bio's completion
3768 ret = PTR_ERR(handle);
3770 ext4_orphan_del(NULL, inode);
3775 ext4_orphan_del(handle, inode);
3777 loff_t end = offset + ret;
3778 if (end > inode->i_size) {
3779 ext4_update_i_disksize(inode, end);
3780 i_size_write(inode, end);
3782 * We're going to return a positive `ret'
3783 * here due to non-zero-length I/O, so there's
3784 * no way of reporting error returns from
3785 * ext4_mark_inode_dirty() to userspace. So
3788 ext4_mark_inode_dirty(handle, inode);
3791 err = ext4_journal_stop(handle);
3799 static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
3801 struct address_space *mapping = iocb->ki_filp->f_mapping;
3802 struct inode *inode = mapping->host;
3803 size_t count = iov_iter_count(iter);
3805 loff_t offset = iocb->ki_pos;
3806 loff_t size = i_size_read(inode);
3812 * Shared inode_lock is enough for us - it protects against concurrent
3813 * writes & truncates and since we take care of writing back page cache,
3814 * we are protected against page writeback as well.
3816 if (iocb->ki_flags & IOCB_NOWAIT) {
3817 if (!inode_trylock_shared(inode))
3820 inode_lock_shared(inode);
3823 ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
3824 iocb->ki_pos + count - 1);
3827 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
3828 iter, ext4_dio_get_block, NULL, NULL, 0);
3830 inode_unlock_shared(inode);
3834 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
3836 struct file *file = iocb->ki_filp;
3837 struct inode *inode = file->f_mapping->host;
3838 size_t count = iov_iter_count(iter);
3839 loff_t offset = iocb->ki_pos;
3842 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3843 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3848 * If we are doing data journalling we don't support O_DIRECT
3850 if (ext4_should_journal_data(inode))
3853 /* Let buffer I/O handle the inline data case. */
3854 if (ext4_has_inline_data(inode))
3857 /* DAX uses iomap path now */
3858 if (WARN_ON_ONCE(IS_DAX(inode)))
3861 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3862 if (iov_iter_rw(iter) == READ)
3863 ret = ext4_direct_IO_read(iocb, iter);
3865 ret = ext4_direct_IO_write(iocb, iter);
3866 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3871 * Pages can be marked dirty completely asynchronously from ext4's journalling
3872 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3873 * much here because ->set_page_dirty is called under VFS locks. The page is
3874 * not necessarily locked.
3876 * We cannot just dirty the page and leave attached buffers clean, because the
3877 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3878 * or jbddirty because all the journalling code will explode.
3880 * So what we do is to mark the page "pending dirty" and next time writepage
3881 * is called, propagate that into the buffers appropriately.
3883 static int ext4_journalled_set_page_dirty(struct page *page)
3885 SetPageChecked(page);
3886 return __set_page_dirty_nobuffers(page);
3889 static int ext4_set_page_dirty(struct page *page)
3891 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3892 WARN_ON_ONCE(!page_has_buffers(page));
3893 return __set_page_dirty_buffers(page);
3896 static const struct address_space_operations ext4_aops = {
3897 .readpage = ext4_readpage,
3898 .readpages = ext4_readpages,
3899 .writepage = ext4_writepage,
3900 .writepages = ext4_writepages,
3901 .write_begin = ext4_write_begin,
3902 .write_end = ext4_write_end,
3903 .set_page_dirty = ext4_set_page_dirty,
3905 .invalidatepage = ext4_invalidatepage,
3906 .releasepage = ext4_releasepage,
3907 .direct_IO = ext4_direct_IO,
3908 .migratepage = buffer_migrate_page,
3909 .is_partially_uptodate = block_is_partially_uptodate,
3910 .error_remove_page = generic_error_remove_page,
3913 static const struct address_space_operations ext4_journalled_aops = {
3914 .readpage = ext4_readpage,
3915 .readpages = ext4_readpages,
3916 .writepage = ext4_writepage,
3917 .writepages = ext4_writepages,
3918 .write_begin = ext4_write_begin,
3919 .write_end = ext4_journalled_write_end,
3920 .set_page_dirty = ext4_journalled_set_page_dirty,
3922 .invalidatepage = ext4_journalled_invalidatepage,
3923 .releasepage = ext4_releasepage,
3924 .direct_IO = ext4_direct_IO,
3925 .is_partially_uptodate = block_is_partially_uptodate,
3926 .error_remove_page = generic_error_remove_page,
3929 static const struct address_space_operations ext4_da_aops = {
3930 .readpage = ext4_readpage,
3931 .readpages = ext4_readpages,
3932 .writepage = ext4_writepage,
3933 .writepages = ext4_writepages,
3934 .write_begin = ext4_da_write_begin,
3935 .write_end = ext4_da_write_end,
3936 .set_page_dirty = ext4_set_page_dirty,
3938 .invalidatepage = ext4_da_invalidatepage,
3939 .releasepage = ext4_releasepage,
3940 .direct_IO = ext4_direct_IO,
3941 .migratepage = buffer_migrate_page,
3942 .is_partially_uptodate = block_is_partially_uptodate,
3943 .error_remove_page = generic_error_remove_page,
3946 void ext4_set_aops(struct inode *inode)
3948 switch (ext4_inode_journal_mode(inode)) {
3949 case EXT4_INODE_ORDERED_DATA_MODE:
3950 case EXT4_INODE_WRITEBACK_DATA_MODE:
3952 case EXT4_INODE_JOURNAL_DATA_MODE:
3953 inode->i_mapping->a_ops = &ext4_journalled_aops;
3958 if (test_opt(inode->i_sb, DELALLOC))
3959 inode->i_mapping->a_ops = &ext4_da_aops;
3961 inode->i_mapping->a_ops = &ext4_aops;
3964 static int __ext4_block_zero_page_range(handle_t *handle,
3965 struct address_space *mapping, loff_t from, loff_t length)
3967 ext4_fsblk_t index = from >> PAGE_SHIFT;
3968 unsigned offset = from & (PAGE_SIZE-1);
3969 unsigned blocksize, pos;
3971 struct inode *inode = mapping->host;
3972 struct buffer_head *bh;
3976 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3977 mapping_gfp_constraint(mapping, ~__GFP_FS));
3981 blocksize = inode->i_sb->s_blocksize;
3983 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3985 if (!page_has_buffers(page))
3986 create_empty_buffers(page, blocksize, 0);
3988 /* Find the buffer that contains "offset" */
3989 bh = page_buffers(page);
3991 while (offset >= pos) {
3992 bh = bh->b_this_page;
3996 if (buffer_freed(bh)) {
3997 BUFFER_TRACE(bh, "freed: skip");
4000 if (!buffer_mapped(bh)) {
4001 BUFFER_TRACE(bh, "unmapped");
4002 ext4_get_block(inode, iblock, bh, 0);
4003 /* unmapped? It's a hole - nothing to do */
4004 if (!buffer_mapped(bh)) {
4005 BUFFER_TRACE(bh, "still unmapped");
4010 /* Ok, it's mapped. Make sure it's up-to-date */
4011 if (PageUptodate(page))
4012 set_buffer_uptodate(bh);
4014 if (!buffer_uptodate(bh)) {
4016 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
4018 /* Uhhuh. Read error. Complain and punt. */
4019 if (!buffer_uptodate(bh))
4021 if (S_ISREG(inode->i_mode) &&
4022 ext4_encrypted_inode(inode)) {
4023 /* We expect the key to be set. */
4024 BUG_ON(!fscrypt_has_encryption_key(inode));
4025 BUG_ON(blocksize != PAGE_SIZE);
4026 WARN_ON_ONCE(fscrypt_decrypt_page(page->mapping->host,
4027 page, PAGE_SIZE, 0, page->index));
4030 if (ext4_should_journal_data(inode)) {
4031 BUFFER_TRACE(bh, "get write access");
4032 err = ext4_journal_get_write_access(handle, bh);
4036 zero_user(page, offset, length);
4037 BUFFER_TRACE(bh, "zeroed end of block");
4039 if (ext4_should_journal_data(inode)) {
4040 err = ext4_handle_dirty_metadata(handle, inode, bh);
4043 mark_buffer_dirty(bh);
4044 if (ext4_should_order_data(inode))
4045 err = ext4_jbd2_inode_add_write(handle, inode, from,
4056 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4057 * starting from file offset 'from'. The range to be zero'd must
4058 * be contained with in one block. If the specified range exceeds
4059 * the end of the block it will be shortened to end of the block
4060 * that cooresponds to 'from'
4062 static int ext4_block_zero_page_range(handle_t *handle,
4063 struct address_space *mapping, loff_t from, loff_t length)
4065 struct inode *inode = mapping->host;
4066 unsigned offset = from & (PAGE_SIZE-1);
4067 unsigned blocksize = inode->i_sb->s_blocksize;
4068 unsigned max = blocksize - (offset & (blocksize - 1));
4071 * correct length if it does not fall between
4072 * 'from' and the end of the block
4074 if (length > max || length < 0)
4077 if (IS_DAX(inode)) {
4078 return iomap_zero_range(inode, from, length, NULL,
4081 return __ext4_block_zero_page_range(handle, mapping, from, length);
4085 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4086 * up to the end of the block which corresponds to `from'.
4087 * This required during truncate. We need to physically zero the tail end
4088 * of that block so it doesn't yield old data if the file is later grown.
4090 static int ext4_block_truncate_page(handle_t *handle,
4091 struct address_space *mapping, loff_t from)
4093 unsigned offset = from & (PAGE_SIZE-1);
4096 struct inode *inode = mapping->host;
4098 /* If we are processing an encrypted inode during orphan list handling */
4099 if (ext4_encrypted_inode(inode) && !fscrypt_has_encryption_key(inode))
4102 blocksize = inode->i_sb->s_blocksize;
4103 length = blocksize - (offset & (blocksize - 1));
4105 return ext4_block_zero_page_range(handle, mapping, from, length);
4108 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4109 loff_t lstart, loff_t length)
4111 struct super_block *sb = inode->i_sb;
4112 struct address_space *mapping = inode->i_mapping;
4113 unsigned partial_start, partial_end;
4114 ext4_fsblk_t start, end;
4115 loff_t byte_end = (lstart + length - 1);
4118 partial_start = lstart & (sb->s_blocksize - 1);
4119 partial_end = byte_end & (sb->s_blocksize - 1);
4121 start = lstart >> sb->s_blocksize_bits;
4122 end = byte_end >> sb->s_blocksize_bits;
4124 /* Handle partial zero within the single block */
4126 (partial_start || (partial_end != sb->s_blocksize - 1))) {
4127 err = ext4_block_zero_page_range(handle, mapping,
4131 /* Handle partial zero out on the start of the range */
4132 if (partial_start) {
4133 err = ext4_block_zero_page_range(handle, mapping,
4134 lstart, sb->s_blocksize);
4138 /* Handle partial zero out on the end of the range */
4139 if (partial_end != sb->s_blocksize - 1)
4140 err = ext4_block_zero_page_range(handle, mapping,
4141 byte_end - partial_end,
4146 int ext4_can_truncate(struct inode *inode)
4148 if (S_ISREG(inode->i_mode))
4150 if (S_ISDIR(inode->i_mode))
4152 if (S_ISLNK(inode->i_mode))
4153 return !ext4_inode_is_fast_symlink(inode);
4158 * We have to make sure i_disksize gets properly updated before we truncate
4159 * page cache due to hole punching or zero range. Otherwise i_disksize update
4160 * can get lost as it may have been postponed to submission of writeback but
4161 * that will never happen after we truncate page cache.
4163 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4167 loff_t size = i_size_read(inode);
4169 WARN_ON(!inode_is_locked(inode));
4170 if (offset > size || offset + len < size)
4173 if (EXT4_I(inode)->i_disksize >= size)
4176 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4178 return PTR_ERR(handle);
4179 ext4_update_i_disksize(inode, size);
4180 ext4_mark_inode_dirty(handle, inode);
4181 ext4_journal_stop(handle);
4187 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4188 * associated with the given offset and length
4190 * @inode: File inode
4191 * @offset: The offset where the hole will begin
4192 * @len: The length of the hole
4194 * Returns: 0 on success or negative on failure
4197 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4199 struct super_block *sb = inode->i_sb;
4200 ext4_lblk_t first_block, stop_block;
4201 struct address_space *mapping = inode->i_mapping;
4202 loff_t first_block_offset, last_block_offset;
4204 unsigned int credits;
4207 if (!S_ISREG(inode->i_mode))
4210 trace_ext4_punch_hole(inode, offset, length, 0);
4212 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4213 if (ext4_has_inline_data(inode)) {
4214 down_write(&EXT4_I(inode)->i_mmap_sem);
4215 ret = ext4_convert_inline_data(inode);
4216 up_write(&EXT4_I(inode)->i_mmap_sem);
4222 * Write out all dirty pages to avoid race conditions
4223 * Then release them.
4225 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4226 ret = filemap_write_and_wait_range(mapping, offset,
4227 offset + length - 1);
4234 /* No need to punch hole beyond i_size */
4235 if (offset >= inode->i_size)
4239 * If the hole extends beyond i_size, set the hole
4240 * to end after the page that contains i_size
4242 if (offset + length > inode->i_size) {
4243 length = inode->i_size +
4244 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4248 if (offset & (sb->s_blocksize - 1) ||
4249 (offset + length) & (sb->s_blocksize - 1)) {
4251 * Attach jinode to inode for jbd2 if we do any zeroing of
4254 ret = ext4_inode_attach_jinode(inode);
4260 /* Wait all existing dio workers, newcomers will block on i_mutex */
4261 ext4_inode_block_unlocked_dio(inode);
4262 inode_dio_wait(inode);
4265 * Prevent page faults from reinstantiating pages we have released from
4268 down_write(&EXT4_I(inode)->i_mmap_sem);
4269 first_block_offset = round_up(offset, sb->s_blocksize);
4270 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4272 /* Now release the pages and zero block aligned part of pages*/
4273 if (last_block_offset > first_block_offset) {
4274 ret = ext4_update_disksize_before_punch(inode, offset, length);
4277 truncate_pagecache_range(inode, first_block_offset,
4281 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4282 credits = ext4_writepage_trans_blocks(inode);
4284 credits = ext4_blocks_for_truncate(inode);
4285 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4286 if (IS_ERR(handle)) {
4287 ret = PTR_ERR(handle);
4288 ext4_std_error(sb, ret);
4292 ret = ext4_zero_partial_blocks(handle, inode, offset,
4297 first_block = (offset + sb->s_blocksize - 1) >>
4298 EXT4_BLOCK_SIZE_BITS(sb);
4299 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4301 /* If there are blocks to remove, do it */
4302 if (stop_block > first_block) {
4304 down_write(&EXT4_I(inode)->i_data_sem);
4305 ext4_discard_preallocations(inode);
4307 ret = ext4_es_remove_extent(inode, first_block,
4308 stop_block - first_block);
4310 up_write(&EXT4_I(inode)->i_data_sem);
4314 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4315 ret = ext4_ext_remove_space(inode, first_block,
4318 ret = ext4_ind_remove_space(handle, inode, first_block,
4321 up_write(&EXT4_I(inode)->i_data_sem);
4324 ext4_handle_sync(handle);
4326 inode->i_mtime = inode->i_ctime = current_time(inode);
4327 ext4_mark_inode_dirty(handle, inode);
4329 ext4_update_inode_fsync_trans(handle, inode, 1);
4331 ext4_journal_stop(handle);
4333 up_write(&EXT4_I(inode)->i_mmap_sem);
4334 ext4_inode_resume_unlocked_dio(inode);
4336 inode_unlock(inode);
4340 int ext4_inode_attach_jinode(struct inode *inode)
4342 struct ext4_inode_info *ei = EXT4_I(inode);
4343 struct jbd2_inode *jinode;
4345 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4348 jinode = jbd2_alloc_inode(GFP_KERNEL);
4349 spin_lock(&inode->i_lock);
4352 spin_unlock(&inode->i_lock);
4355 ei->jinode = jinode;
4356 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4359 spin_unlock(&inode->i_lock);
4360 if (unlikely(jinode != NULL))
4361 jbd2_free_inode(jinode);
4368 * We block out ext4_get_block() block instantiations across the entire
4369 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4370 * simultaneously on behalf of the same inode.
4372 * As we work through the truncate and commit bits of it to the journal there
4373 * is one core, guiding principle: the file's tree must always be consistent on
4374 * disk. We must be able to restart the truncate after a crash.
4376 * The file's tree may be transiently inconsistent in memory (although it
4377 * probably isn't), but whenever we close off and commit a journal transaction,
4378 * the contents of (the filesystem + the journal) must be consistent and
4379 * restartable. It's pretty simple, really: bottom up, right to left (although
4380 * left-to-right works OK too).
4382 * Note that at recovery time, journal replay occurs *before* the restart of
4383 * truncate against the orphan inode list.
4385 * The committed inode has the new, desired i_size (which is the same as
4386 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4387 * that this inode's truncate did not complete and it will again call
4388 * ext4_truncate() to have another go. So there will be instantiated blocks
4389 * to the right of the truncation point in a crashed ext4 filesystem. But
4390 * that's fine - as long as they are linked from the inode, the post-crash
4391 * ext4_truncate() run will find them and release them.
4393 int ext4_truncate(struct inode *inode)
4395 struct ext4_inode_info *ei = EXT4_I(inode);
4396 unsigned int credits;
4399 struct address_space *mapping = inode->i_mapping;
4402 * There is a possibility that we're either freeing the inode
4403 * or it's a completely new inode. In those cases we might not
4404 * have i_mutex locked because it's not necessary.
4406 if (!(inode->i_state & (I_NEW|I_FREEING)))
4407 WARN_ON(!inode_is_locked(inode));
4408 trace_ext4_truncate_enter(inode);
4410 if (!ext4_can_truncate(inode))
4413 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4415 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4416 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4418 if (ext4_has_inline_data(inode)) {
4421 err = ext4_inline_data_truncate(inode, &has_inline);
4428 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4429 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4430 if (ext4_inode_attach_jinode(inode) < 0)
4434 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4435 credits = ext4_writepage_trans_blocks(inode);
4437 credits = ext4_blocks_for_truncate(inode);
4439 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4441 return PTR_ERR(handle);
4443 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4444 ext4_block_truncate_page(handle, mapping, inode->i_size);
4447 * We add the inode to the orphan list, so that if this
4448 * truncate spans multiple transactions, and we crash, we will
4449 * resume the truncate when the filesystem recovers. It also
4450 * marks the inode dirty, to catch the new size.
4452 * Implication: the file must always be in a sane, consistent
4453 * truncatable state while each transaction commits.
4455 err = ext4_orphan_add(handle, inode);
4459 down_write(&EXT4_I(inode)->i_data_sem);
4461 ext4_discard_preallocations(inode);
4463 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4464 err = ext4_ext_truncate(handle, inode);
4466 ext4_ind_truncate(handle, inode);
4468 up_write(&ei->i_data_sem);
4473 ext4_handle_sync(handle);
4477 * If this was a simple ftruncate() and the file will remain alive,
4478 * then we need to clear up the orphan record which we created above.
4479 * However, if this was a real unlink then we were called by
4480 * ext4_evict_inode(), and we allow that function to clean up the
4481 * orphan info for us.
4484 ext4_orphan_del(handle, inode);
4486 inode->i_mtime = inode->i_ctime = current_time(inode);
4487 ext4_mark_inode_dirty(handle, inode);
4488 ext4_journal_stop(handle);
4490 trace_ext4_truncate_exit(inode);
4495 * ext4_get_inode_loc returns with an extra refcount against the inode's
4496 * underlying buffer_head on success. If 'in_mem' is true, we have all
4497 * data in memory that is needed to recreate the on-disk version of this
4500 static int __ext4_get_inode_loc(struct inode *inode,
4501 struct ext4_iloc *iloc, int in_mem)
4503 struct ext4_group_desc *gdp;
4504 struct buffer_head *bh;
4505 struct super_block *sb = inode->i_sb;
4507 int inodes_per_block, inode_offset;
4510 if (inode->i_ino < EXT4_ROOT_INO ||
4511 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4512 return -EFSCORRUPTED;
4514 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4515 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4520 * Figure out the offset within the block group inode table
4522 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4523 inode_offset = ((inode->i_ino - 1) %
4524 EXT4_INODES_PER_GROUP(sb));
4525 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4526 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4528 bh = sb_getblk(sb, block);
4531 if (!buffer_uptodate(bh)) {
4535 * If the buffer has the write error flag, we have failed
4536 * to write out another inode in the same block. In this
4537 * case, we don't have to read the block because we may
4538 * read the old inode data successfully.
4540 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4541 set_buffer_uptodate(bh);
4543 if (buffer_uptodate(bh)) {
4544 /* someone brought it uptodate while we waited */
4550 * If we have all information of the inode in memory and this
4551 * is the only valid inode in the block, we need not read the
4555 struct buffer_head *bitmap_bh;
4558 start = inode_offset & ~(inodes_per_block - 1);
4560 /* Is the inode bitmap in cache? */
4561 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4562 if (unlikely(!bitmap_bh))
4566 * If the inode bitmap isn't in cache then the
4567 * optimisation may end up performing two reads instead
4568 * of one, so skip it.
4570 if (!buffer_uptodate(bitmap_bh)) {
4574 for (i = start; i < start + inodes_per_block; i++) {
4575 if (i == inode_offset)
4577 if (ext4_test_bit(i, bitmap_bh->b_data))
4581 if (i == start + inodes_per_block) {
4582 /* all other inodes are free, so skip I/O */
4583 memset(bh->b_data, 0, bh->b_size);
4584 set_buffer_uptodate(bh);
4592 * If we need to do any I/O, try to pre-readahead extra
4593 * blocks from the inode table.
4595 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4596 ext4_fsblk_t b, end, table;
4598 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4600 table = ext4_inode_table(sb, gdp);
4601 /* s_inode_readahead_blks is always a power of 2 */
4602 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4606 num = EXT4_INODES_PER_GROUP(sb);
4607 if (ext4_has_group_desc_csum(sb))
4608 num -= ext4_itable_unused_count(sb, gdp);
4609 table += num / inodes_per_block;
4613 sb_breadahead_unmovable(sb, b++);
4617 * There are other valid inodes in the buffer, this inode
4618 * has in-inode xattrs, or we don't have this inode in memory.
4619 * Read the block from disk.
4621 trace_ext4_load_inode(inode);
4623 bh->b_end_io = end_buffer_read_sync;
4624 submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
4626 if (!buffer_uptodate(bh)) {
4627 EXT4_ERROR_INODE_BLOCK(inode, block,
4628 "unable to read itable block");
4638 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4640 /* We have all inode data except xattrs in memory here. */
4641 return __ext4_get_inode_loc(inode, iloc,
4642 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4645 void ext4_set_inode_flags(struct inode *inode)
4647 unsigned int flags = EXT4_I(inode)->i_flags;
4648 unsigned int new_fl = 0;
4650 if (flags & EXT4_SYNC_FL)
4652 if (flags & EXT4_APPEND_FL)
4654 if (flags & EXT4_IMMUTABLE_FL)
4655 new_fl |= S_IMMUTABLE;
4656 if (flags & EXT4_NOATIME_FL)
4657 new_fl |= S_NOATIME;
4658 if (flags & EXT4_DIRSYNC_FL)
4659 new_fl |= S_DIRSYNC;
4660 if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode) &&
4661 !ext4_should_journal_data(inode) && !ext4_has_inline_data(inode) &&
4662 !ext4_encrypted_inode(inode))
4664 inode_set_flags(inode, new_fl,
4665 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4668 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4669 struct ext4_inode_info *ei)
4672 struct inode *inode = &(ei->vfs_inode);
4673 struct super_block *sb = inode->i_sb;
4675 if (ext4_has_feature_huge_file(sb)) {
4676 /* we are using combined 48 bit field */
4677 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4678 le32_to_cpu(raw_inode->i_blocks_lo);
4679 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4680 /* i_blocks represent file system block size */
4681 return i_blocks << (inode->i_blkbits - 9);
4686 return le32_to_cpu(raw_inode->i_blocks_lo);
4690 static inline int ext4_iget_extra_inode(struct inode *inode,
4691 struct ext4_inode *raw_inode,
4692 struct ext4_inode_info *ei)
4694 __le32 *magic = (void *)raw_inode +
4695 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4697 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4698 EXT4_INODE_SIZE(inode->i_sb) &&
4699 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4700 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4701 return ext4_find_inline_data_nolock(inode);
4703 EXT4_I(inode)->i_inline_off = 0;
4707 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4709 if (!ext4_has_feature_project(inode->i_sb))
4711 *projid = EXT4_I(inode)->i_projid;
4715 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4716 ext4_iget_flags flags, const char *function,
4719 struct ext4_iloc iloc;
4720 struct ext4_inode *raw_inode;
4721 struct ext4_inode_info *ei;
4722 struct inode *inode;
4723 journal_t *journal = EXT4_SB(sb)->s_journal;
4731 if ((!(flags & EXT4_IGET_SPECIAL) &&
4732 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4733 (ino < EXT4_ROOT_INO) ||
4734 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4735 if (flags & EXT4_IGET_HANDLE)
4736 return ERR_PTR(-ESTALE);
4737 __ext4_error(sb, function, line,
4738 "inode #%lu: comm %s: iget: illegal inode #",
4739 ino, current->comm);
4740 return ERR_PTR(-EFSCORRUPTED);
4743 inode = iget_locked(sb, ino);
4745 return ERR_PTR(-ENOMEM);
4746 if (!(inode->i_state & I_NEW))
4752 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4755 raw_inode = ext4_raw_inode(&iloc);
4757 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4758 ext4_error_inode(inode, function, line, 0,
4759 "iget: root inode unallocated");
4760 ret = -EFSCORRUPTED;
4764 if ((flags & EXT4_IGET_HANDLE) &&
4765 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4770 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4771 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4772 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4773 EXT4_INODE_SIZE(inode->i_sb) ||
4774 (ei->i_extra_isize & 3)) {
4775 ext4_error_inode(inode, function, line, 0,
4776 "iget: bad extra_isize %u "
4779 EXT4_INODE_SIZE(inode->i_sb));
4780 ret = -EFSCORRUPTED;
4784 ei->i_extra_isize = 0;
4786 /* Precompute checksum seed for inode metadata */
4787 if (ext4_has_metadata_csum(sb)) {
4788 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4790 __le32 inum = cpu_to_le32(inode->i_ino);
4791 __le32 gen = raw_inode->i_generation;
4792 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4794 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4798 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4799 ext4_error_inode(inode, function, line, 0,
4800 "iget: checksum invalid");
4805 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4806 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4807 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4808 if (ext4_has_feature_project(sb) &&
4809 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4810 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4811 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4813 i_projid = EXT4_DEF_PROJID;
4815 if (!(test_opt(inode->i_sb, NO_UID32))) {
4816 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4817 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4819 i_uid_write(inode, i_uid);
4820 i_gid_write(inode, i_gid);
4821 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4822 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4824 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4825 ei->i_inline_off = 0;
4826 ei->i_dir_start_lookup = 0;
4827 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4828 /* We now have enough fields to check if the inode was active or not.
4829 * This is needed because nfsd might try to access dead inodes
4830 * the test is that same one that e2fsck uses
4831 * NeilBrown 1999oct15
4833 if (inode->i_nlink == 0) {
4834 if ((inode->i_mode == 0 ||
4835 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4836 ino != EXT4_BOOT_LOADER_INO) {
4837 /* this inode is deleted */
4841 /* The only unlinked inodes we let through here have
4842 * valid i_mode and are being read by the orphan
4843 * recovery code: that's fine, we're about to complete
4844 * the process of deleting those.
4845 * OR it is the EXT4_BOOT_LOADER_INO which is
4846 * not initialized on a new filesystem. */
4848 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4849 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4850 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4851 if (ext4_has_feature_64bit(sb))
4853 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4854 inode->i_size = ext4_isize(sb, raw_inode);
4855 if ((size = i_size_read(inode)) < 0) {
4856 ext4_error_inode(inode, function, line, 0,
4857 "iget: bad i_size value: %lld", size);
4858 ret = -EFSCORRUPTED;
4862 * If dir_index is not enabled but there's dir with INDEX flag set,
4863 * we'd normally treat htree data as empty space. But with metadata
4864 * checksumming that corrupts checksums so forbid that.
4866 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4867 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4868 EXT4_ERROR_INODE(inode,
4869 "iget: Dir with htree data on filesystem without dir_index feature.");
4870 ret = -EFSCORRUPTED;
4873 ei->i_disksize = inode->i_size;
4875 ei->i_reserved_quota = 0;
4877 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4878 ei->i_block_group = iloc.block_group;
4879 ei->i_last_alloc_group = ~0;
4881 * NOTE! The in-memory inode i_data array is in little-endian order
4882 * even on big-endian machines: we do NOT byteswap the block numbers!
4884 for (block = 0; block < EXT4_N_BLOCKS; block++)
4885 ei->i_data[block] = raw_inode->i_block[block];
4886 INIT_LIST_HEAD(&ei->i_orphan);
4889 * Set transaction id's of transactions that have to be committed
4890 * to finish f[data]sync. We set them to currently running transaction
4891 * as we cannot be sure that the inode or some of its metadata isn't
4892 * part of the transaction - the inode could have been reclaimed and
4893 * now it is reread from disk.
4896 transaction_t *transaction;
4899 read_lock(&journal->j_state_lock);
4900 if (journal->j_running_transaction)
4901 transaction = journal->j_running_transaction;
4903 transaction = journal->j_committing_transaction;
4905 tid = transaction->t_tid;
4907 tid = journal->j_commit_sequence;
4908 read_unlock(&journal->j_state_lock);
4909 ei->i_sync_tid = tid;
4910 ei->i_datasync_tid = tid;
4913 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4914 if (ei->i_extra_isize == 0) {
4915 /* The extra space is currently unused. Use it. */
4916 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4917 ei->i_extra_isize = sizeof(struct ext4_inode) -
4918 EXT4_GOOD_OLD_INODE_SIZE;
4920 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4926 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4927 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4928 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4929 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4931 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4932 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4933 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4934 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4936 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4941 if (ei->i_file_acl &&
4942 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4943 ext4_error_inode(inode, function, line, 0,
4944 "iget: bad extended attribute block %llu",
4946 ret = -EFSCORRUPTED;
4948 } else if (!ext4_has_inline_data(inode)) {
4949 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4950 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4951 (S_ISLNK(inode->i_mode) &&
4952 !ext4_inode_is_fast_symlink(inode))))
4953 /* Validate extent which is part of inode */
4954 ret = ext4_ext_check_inode(inode);
4955 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4956 (S_ISLNK(inode->i_mode) &&
4957 !ext4_inode_is_fast_symlink(inode))) {
4958 /* Validate block references which are part of inode */
4959 ret = ext4_ind_check_inode(inode);
4965 if (S_ISREG(inode->i_mode)) {
4966 inode->i_op = &ext4_file_inode_operations;
4967 inode->i_fop = &ext4_file_operations;
4968 ext4_set_aops(inode);
4969 } else if (S_ISDIR(inode->i_mode)) {
4970 inode->i_op = &ext4_dir_inode_operations;
4971 inode->i_fop = &ext4_dir_operations;
4972 } else if (S_ISLNK(inode->i_mode)) {
4973 if (ext4_encrypted_inode(inode)) {
4974 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4975 ext4_set_aops(inode);
4976 } else if (ext4_inode_is_fast_symlink(inode)) {
4977 inode->i_link = (char *)ei->i_data;
4978 inode->i_op = &ext4_fast_symlink_inode_operations;
4979 nd_terminate_link(ei->i_data, inode->i_size,
4980 sizeof(ei->i_data) - 1);
4982 inode->i_op = &ext4_symlink_inode_operations;
4983 ext4_set_aops(inode);
4985 inode_nohighmem(inode);
4986 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4987 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4988 inode->i_op = &ext4_special_inode_operations;
4989 if (raw_inode->i_block[0])
4990 init_special_inode(inode, inode->i_mode,
4991 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4993 init_special_inode(inode, inode->i_mode,
4994 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4995 } else if (ino == EXT4_BOOT_LOADER_INO) {
4996 make_bad_inode(inode);
4998 ret = -EFSCORRUPTED;
4999 ext4_error_inode(inode, function, line, 0,
5000 "iget: bogus i_mode (%o)", inode->i_mode);
5004 ext4_set_inode_flags(inode);
5006 unlock_new_inode(inode);
5012 return ERR_PTR(ret);
5015 static int ext4_inode_blocks_set(handle_t *handle,
5016 struct ext4_inode *raw_inode,
5017 struct ext4_inode_info *ei)
5019 struct inode *inode = &(ei->vfs_inode);
5020 u64 i_blocks = READ_ONCE(inode->i_blocks);
5021 struct super_block *sb = inode->i_sb;
5023 if (i_blocks <= ~0U) {
5025 * i_blocks can be represented in a 32 bit variable
5026 * as multiple of 512 bytes
5028 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5029 raw_inode->i_blocks_high = 0;
5030 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5033 if (!ext4_has_feature_huge_file(sb))
5036 if (i_blocks <= 0xffffffffffffULL) {
5038 * i_blocks can be represented in a 48 bit variable
5039 * as multiple of 512 bytes
5041 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5042 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5043 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5045 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5046 /* i_block is stored in file system block size */
5047 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5048 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5049 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5054 struct other_inode {
5055 unsigned long orig_ino;
5056 struct ext4_inode *raw_inode;
5059 static int other_inode_match(struct inode * inode, unsigned long ino,
5062 struct other_inode *oi = (struct other_inode *) data;
5064 if ((inode->i_ino != ino) ||
5065 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5067 ((inode->i_state & I_DIRTY_TIME) == 0))
5069 spin_lock(&inode->i_lock);
5070 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5071 I_DIRTY_INODE)) == 0) &&
5072 (inode->i_state & I_DIRTY_TIME)) {
5073 struct ext4_inode_info *ei = EXT4_I(inode);
5075 inode->i_state &= ~I_DIRTY_TIME;
5076 spin_unlock(&inode->i_lock);
5078 spin_lock(&ei->i_raw_lock);
5079 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
5080 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
5081 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
5082 ext4_inode_csum_set(inode, oi->raw_inode, ei);
5083 spin_unlock(&ei->i_raw_lock);
5084 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
5087 spin_unlock(&inode->i_lock);
5092 * Opportunistically update the other time fields for other inodes in
5093 * the same inode table block.
5095 static void ext4_update_other_inodes_time(struct super_block *sb,
5096 unsigned long orig_ino, char *buf)
5098 struct other_inode oi;
5100 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5101 int inode_size = EXT4_INODE_SIZE(sb);
5103 oi.orig_ino = orig_ino;
5105 * Calculate the first inode in the inode table block. Inode
5106 * numbers are one-based. That is, the first inode in a block
5107 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5109 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5110 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5111 if (ino == orig_ino)
5113 oi.raw_inode = (struct ext4_inode *) buf;
5114 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
5119 * Post the struct inode info into an on-disk inode location in the
5120 * buffer-cache. This gobbles the caller's reference to the
5121 * buffer_head in the inode location struct.
5123 * The caller must have write access to iloc->bh.
5125 static int ext4_do_update_inode(handle_t *handle,
5126 struct inode *inode,
5127 struct ext4_iloc *iloc)
5129 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5130 struct ext4_inode_info *ei = EXT4_I(inode);
5131 struct buffer_head *bh = iloc->bh;
5132 struct super_block *sb = inode->i_sb;
5134 int need_datasync = 0, set_large_file = 0;
5139 spin_lock(&ei->i_raw_lock);
5141 /* For fields not tracked in the in-memory inode,
5142 * initialise them to zero for new inodes. */
5143 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5144 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5146 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5148 spin_unlock(&ei->i_raw_lock);
5152 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5153 i_uid = i_uid_read(inode);
5154 i_gid = i_gid_read(inode);
5155 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5156 if (!(test_opt(inode->i_sb, NO_UID32))) {
5157 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5158 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5160 * Fix up interoperability with old kernels. Otherwise, old inodes get
5161 * re-used with the upper 16 bits of the uid/gid intact
5163 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5164 raw_inode->i_uid_high = 0;
5165 raw_inode->i_gid_high = 0;
5167 raw_inode->i_uid_high =
5168 cpu_to_le16(high_16_bits(i_uid));
5169 raw_inode->i_gid_high =
5170 cpu_to_le16(high_16_bits(i_gid));
5173 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5174 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5175 raw_inode->i_uid_high = 0;
5176 raw_inode->i_gid_high = 0;
5178 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5180 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5181 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5182 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5183 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5185 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5186 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5187 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5188 raw_inode->i_file_acl_high =
5189 cpu_to_le16(ei->i_file_acl >> 32);
5190 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5191 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5192 ext4_isize_set(raw_inode, ei->i_disksize);
5195 if (ei->i_disksize > 0x7fffffffULL) {
5196 if (!ext4_has_feature_large_file(sb) ||
5197 EXT4_SB(sb)->s_es->s_rev_level ==
5198 cpu_to_le32(EXT4_GOOD_OLD_REV))
5201 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5202 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5203 if (old_valid_dev(inode->i_rdev)) {
5204 raw_inode->i_block[0] =
5205 cpu_to_le32(old_encode_dev(inode->i_rdev));
5206 raw_inode->i_block[1] = 0;
5208 raw_inode->i_block[0] = 0;
5209 raw_inode->i_block[1] =
5210 cpu_to_le32(new_encode_dev(inode->i_rdev));
5211 raw_inode->i_block[2] = 0;
5213 } else if (!ext4_has_inline_data(inode)) {
5214 for (block = 0; block < EXT4_N_BLOCKS; block++)
5215 raw_inode->i_block[block] = ei->i_data[block];
5218 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5219 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5220 if (ei->i_extra_isize) {
5221 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5222 raw_inode->i_version_hi =
5223 cpu_to_le32(inode->i_version >> 32);
5224 raw_inode->i_extra_isize =
5225 cpu_to_le16(ei->i_extra_isize);
5229 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5230 i_projid != EXT4_DEF_PROJID);
5232 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5233 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5234 raw_inode->i_projid = cpu_to_le32(i_projid);
5236 ext4_inode_csum_set(inode, raw_inode, ei);
5237 spin_unlock(&ei->i_raw_lock);
5238 if (inode->i_sb->s_flags & MS_LAZYTIME)
5239 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5242 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5243 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5246 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5247 if (set_large_file) {
5248 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5249 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5252 ext4_update_dynamic_rev(sb);
5253 ext4_set_feature_large_file(sb);
5254 ext4_handle_sync(handle);
5255 err = ext4_handle_dirty_super(handle, sb);
5257 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5260 ext4_std_error(inode->i_sb, err);
5265 * ext4_write_inode()
5267 * We are called from a few places:
5269 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5270 * Here, there will be no transaction running. We wait for any running
5271 * transaction to commit.
5273 * - Within flush work (sys_sync(), kupdate and such).
5274 * We wait on commit, if told to.
5276 * - Within iput_final() -> write_inode_now()
5277 * We wait on commit, if told to.
5279 * In all cases it is actually safe for us to return without doing anything,
5280 * because the inode has been copied into a raw inode buffer in
5281 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5284 * Note that we are absolutely dependent upon all inode dirtiers doing the
5285 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5286 * which we are interested.
5288 * It would be a bug for them to not do this. The code:
5290 * mark_inode_dirty(inode)
5292 * inode->i_size = expr;
5294 * is in error because write_inode() could occur while `stuff()' is running,
5295 * and the new i_size will be lost. Plus the inode will no longer be on the
5296 * superblock's dirty inode list.
5298 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5302 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5303 sb_rdonly(inode->i_sb))
5306 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5309 if (EXT4_SB(inode->i_sb)->s_journal) {
5310 if (ext4_journal_current_handle()) {
5311 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5317 * No need to force transaction in WB_SYNC_NONE mode. Also
5318 * ext4_sync_fs() will force the commit after everything is
5321 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5324 err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5325 EXT4_I(inode)->i_sync_tid);
5327 struct ext4_iloc iloc;
5329 err = __ext4_get_inode_loc(inode, &iloc, 0);
5333 * sync(2) will flush the whole buffer cache. No need to do
5334 * it here separately for each inode.
5336 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5337 sync_dirty_buffer(iloc.bh);
5338 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5339 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5340 "IO error syncing inode");
5349 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5350 * buffers that are attached to a page stradding i_size and are undergoing
5351 * commit. In that case we have to wait for commit to finish and try again.
5353 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5357 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5358 tid_t commit_tid = 0;
5361 offset = inode->i_size & (PAGE_SIZE - 1);
5363 * If the page is fully truncated, we don't need to wait for any commit
5364 * (and we even should not as __ext4_journalled_invalidatepage() may
5365 * strip all buffers from the page but keep the page dirty which can then
5366 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5367 * buffers). Also we don't need to wait for any commit if all buffers in
5368 * the page remain valid. This is most beneficial for the common case of
5369 * blocksize == PAGESIZE.
5371 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5374 page = find_lock_page(inode->i_mapping,
5375 inode->i_size >> PAGE_SHIFT);
5378 ret = __ext4_journalled_invalidatepage(page, offset,
5379 PAGE_SIZE - offset);
5385 read_lock(&journal->j_state_lock);
5386 if (journal->j_committing_transaction)
5387 commit_tid = journal->j_committing_transaction->t_tid;
5388 read_unlock(&journal->j_state_lock);
5390 jbd2_log_wait_commit(journal, commit_tid);
5397 * Called from notify_change.
5399 * We want to trap VFS attempts to truncate the file as soon as
5400 * possible. In particular, we want to make sure that when the VFS
5401 * shrinks i_size, we put the inode on the orphan list and modify
5402 * i_disksize immediately, so that during the subsequent flushing of
5403 * dirty pages and freeing of disk blocks, we can guarantee that any
5404 * commit will leave the blocks being flushed in an unused state on
5405 * disk. (On recovery, the inode will get truncated and the blocks will
5406 * be freed, so we have a strong guarantee that no future commit will
5407 * leave these blocks visible to the user.)
5409 * Another thing we have to assure is that if we are in ordered mode
5410 * and inode is still attached to the committing transaction, we must
5411 * we start writeout of all the dirty pages which are being truncated.
5412 * This way we are sure that all the data written in the previous
5413 * transaction are already on disk (truncate waits for pages under
5416 * Called with inode->i_mutex down.
5418 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5420 struct inode *inode = d_inode(dentry);
5423 const unsigned int ia_valid = attr->ia_valid;
5425 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5428 if (unlikely(IS_IMMUTABLE(inode)))
5431 if (unlikely(IS_APPEND(inode) &&
5432 (ia_valid & (ATTR_MODE | ATTR_UID |
5433 ATTR_GID | ATTR_TIMES_SET))))
5436 error = setattr_prepare(dentry, attr);
5440 if (is_quota_modification(inode, attr)) {
5441 error = dquot_initialize(inode);
5445 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5446 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5449 /* (user+group)*(old+new) structure, inode write (sb,
5450 * inode block, ? - but truncate inode update has it) */
5451 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5452 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5453 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5454 if (IS_ERR(handle)) {
5455 error = PTR_ERR(handle);
5459 /* dquot_transfer() calls back ext4_get_inode_usage() which
5460 * counts xattr inode references.
5462 down_read(&EXT4_I(inode)->xattr_sem);
5463 error = dquot_transfer(inode, attr);
5464 up_read(&EXT4_I(inode)->xattr_sem);
5467 ext4_journal_stop(handle);
5470 /* Update corresponding info in inode so that everything is in
5471 * one transaction */
5472 if (attr->ia_valid & ATTR_UID)
5473 inode->i_uid = attr->ia_uid;
5474 if (attr->ia_valid & ATTR_GID)
5475 inode->i_gid = attr->ia_gid;
5476 error = ext4_mark_inode_dirty(handle, inode);
5477 ext4_journal_stop(handle);
5480 if (attr->ia_valid & ATTR_SIZE) {
5482 loff_t oldsize = inode->i_size;
5483 int shrink = (attr->ia_size <= inode->i_size);
5485 if (ext4_encrypted_inode(inode)) {
5486 error = fscrypt_get_encryption_info(inode);
5489 if (!fscrypt_has_encryption_key(inode))
5493 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5494 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5496 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5499 if (!S_ISREG(inode->i_mode))
5502 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5503 inode_inc_iversion(inode);
5505 if (ext4_should_order_data(inode) &&
5506 (attr->ia_size < inode->i_size)) {
5507 error = ext4_begin_ordered_truncate(inode,
5512 if (attr->ia_size != inode->i_size) {
5513 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5514 if (IS_ERR(handle)) {
5515 error = PTR_ERR(handle);
5518 if (ext4_handle_valid(handle) && shrink) {
5519 error = ext4_orphan_add(handle, inode);
5523 * Update c/mtime on truncate up, ext4_truncate() will
5524 * update c/mtime in shrink case below
5527 inode->i_mtime = current_time(inode);
5528 inode->i_ctime = inode->i_mtime;
5530 down_write(&EXT4_I(inode)->i_data_sem);
5531 EXT4_I(inode)->i_disksize = attr->ia_size;
5532 rc = ext4_mark_inode_dirty(handle, inode);
5536 * We have to update i_size under i_data_sem together
5537 * with i_disksize to avoid races with writeback code
5538 * running ext4_wb_update_i_disksize().
5541 i_size_write(inode, attr->ia_size);
5542 up_write(&EXT4_I(inode)->i_data_sem);
5543 ext4_journal_stop(handle);
5545 if (orphan && inode->i_nlink)
5546 ext4_orphan_del(NULL, inode);
5551 pagecache_isize_extended(inode, oldsize, inode->i_size);
5554 * Blocks are going to be removed from the inode. Wait
5555 * for dio in flight. Temporarily disable
5556 * dioread_nolock to prevent livelock.
5559 if (!ext4_should_journal_data(inode)) {
5560 ext4_inode_block_unlocked_dio(inode);
5561 inode_dio_wait(inode);
5562 ext4_inode_resume_unlocked_dio(inode);
5564 ext4_wait_for_tail_page_commit(inode);
5566 down_write(&EXT4_I(inode)->i_mmap_sem);
5568 * Truncate pagecache after we've waited for commit
5569 * in data=journal mode to make pages freeable.
5571 truncate_pagecache(inode, inode->i_size);
5573 rc = ext4_truncate(inode);
5577 up_write(&EXT4_I(inode)->i_mmap_sem);
5581 setattr_copy(inode, attr);
5582 mark_inode_dirty(inode);
5586 * If the call to ext4_truncate failed to get a transaction handle at
5587 * all, we need to clean up the in-core orphan list manually.
5589 if (orphan && inode->i_nlink)
5590 ext4_orphan_del(NULL, inode);
5592 if (!error && (ia_valid & ATTR_MODE))
5593 rc = posix_acl_chmod(inode, inode->i_mode);
5596 ext4_std_error(inode->i_sb, error);
5602 int ext4_getattr(const struct path *path, struct kstat *stat,
5603 u32 request_mask, unsigned int query_flags)
5605 struct inode *inode = d_inode(path->dentry);
5606 struct ext4_inode *raw_inode;
5607 struct ext4_inode_info *ei = EXT4_I(inode);
5610 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5611 stat->result_mask |= STATX_BTIME;
5612 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5613 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5616 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5617 if (flags & EXT4_APPEND_FL)
5618 stat->attributes |= STATX_ATTR_APPEND;
5619 if (flags & EXT4_COMPR_FL)
5620 stat->attributes |= STATX_ATTR_COMPRESSED;
5621 if (flags & EXT4_ENCRYPT_FL)
5622 stat->attributes |= STATX_ATTR_ENCRYPTED;
5623 if (flags & EXT4_IMMUTABLE_FL)
5624 stat->attributes |= STATX_ATTR_IMMUTABLE;
5625 if (flags & EXT4_NODUMP_FL)
5626 stat->attributes |= STATX_ATTR_NODUMP;
5628 stat->attributes_mask |= (STATX_ATTR_APPEND |
5629 STATX_ATTR_COMPRESSED |
5630 STATX_ATTR_ENCRYPTED |
5631 STATX_ATTR_IMMUTABLE |
5634 generic_fillattr(inode, stat);
5638 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5639 u32 request_mask, unsigned int query_flags)
5641 struct inode *inode = d_inode(path->dentry);
5642 u64 delalloc_blocks;
5644 ext4_getattr(path, stat, request_mask, query_flags);
5647 * If there is inline data in the inode, the inode will normally not
5648 * have data blocks allocated (it may have an external xattr block).
5649 * Report at least one sector for such files, so tools like tar, rsync,
5650 * others don't incorrectly think the file is completely sparse.
5652 if (unlikely(ext4_has_inline_data(inode)))
5653 stat->blocks += (stat->size + 511) >> 9;
5656 * We can't update i_blocks if the block allocation is delayed
5657 * otherwise in the case of system crash before the real block
5658 * allocation is done, we will have i_blocks inconsistent with
5659 * on-disk file blocks.
5660 * We always keep i_blocks updated together with real
5661 * allocation. But to not confuse with user, stat
5662 * will return the blocks that include the delayed allocation
5663 * blocks for this file.
5665 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5666 EXT4_I(inode)->i_reserved_data_blocks);
5667 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5671 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5674 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5675 return ext4_ind_trans_blocks(inode, lblocks);
5676 return ext4_ext_index_trans_blocks(inode, pextents);
5680 * Account for index blocks, block groups bitmaps and block group
5681 * descriptor blocks if modify datablocks and index blocks
5682 * worse case, the indexs blocks spread over different block groups
5684 * If datablocks are discontiguous, they are possible to spread over
5685 * different block groups too. If they are contiguous, with flexbg,
5686 * they could still across block group boundary.
5688 * Also account for superblock, inode, quota and xattr blocks
5690 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5693 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5699 * How many index blocks need to touch to map @lblocks logical blocks
5700 * to @pextents physical extents?
5702 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5707 * Now let's see how many group bitmaps and group descriptors need
5710 groups = idxblocks + pextents;
5712 if (groups > ngroups)
5714 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5715 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5717 /* bitmaps and block group descriptor blocks */
5718 ret += groups + gdpblocks;
5720 /* Blocks for super block, inode, quota and xattr blocks */
5721 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5727 * Calculate the total number of credits to reserve to fit
5728 * the modification of a single pages into a single transaction,
5729 * which may include multiple chunks of block allocations.
5731 * This could be called via ext4_write_begin()
5733 * We need to consider the worse case, when
5734 * one new block per extent.
5736 int ext4_writepage_trans_blocks(struct inode *inode)
5738 int bpp = ext4_journal_blocks_per_page(inode);
5741 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5743 /* Account for data blocks for journalled mode */
5744 if (ext4_should_journal_data(inode))
5750 * Calculate the journal credits for a chunk of data modification.
5752 * This is called from DIO, fallocate or whoever calling
5753 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5755 * journal buffers for data blocks are not included here, as DIO
5756 * and fallocate do no need to journal data buffers.
5758 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5760 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5764 * The caller must have previously called ext4_reserve_inode_write().
5765 * Give this, we know that the caller already has write access to iloc->bh.
5767 int ext4_mark_iloc_dirty(handle_t *handle,
5768 struct inode *inode, struct ext4_iloc *iloc)
5772 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5776 if (IS_I_VERSION(inode))
5777 inode_inc_iversion(inode);
5779 /* the do_update_inode consumes one bh->b_count */
5782 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5783 err = ext4_do_update_inode(handle, inode, iloc);
5789 * On success, We end up with an outstanding reference count against
5790 * iloc->bh. This _must_ be cleaned up later.
5794 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5795 struct ext4_iloc *iloc)
5799 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5802 err = ext4_get_inode_loc(inode, iloc);
5804 BUFFER_TRACE(iloc->bh, "get_write_access");
5805 err = ext4_journal_get_write_access(handle, iloc->bh);
5811 ext4_std_error(inode->i_sb, err);
5815 static int __ext4_expand_extra_isize(struct inode *inode,
5816 unsigned int new_extra_isize,
5817 struct ext4_iloc *iloc,
5818 handle_t *handle, int *no_expand)
5820 struct ext4_inode *raw_inode;
5821 struct ext4_xattr_ibody_header *header;
5822 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5823 struct ext4_inode_info *ei = EXT4_I(inode);
5826 /* this was checked at iget time, but double check for good measure */
5827 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5828 (ei->i_extra_isize & 3)) {
5829 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5831 EXT4_INODE_SIZE(inode->i_sb));
5832 return -EFSCORRUPTED;
5834 if ((new_extra_isize < ei->i_extra_isize) ||
5835 (new_extra_isize < 4) ||
5836 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5837 return -EINVAL; /* Should never happen */
5839 raw_inode = ext4_raw_inode(iloc);
5841 header = IHDR(inode, raw_inode);
5843 /* No extended attributes present */
5844 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5845 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5846 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5847 EXT4_I(inode)->i_extra_isize, 0,
5848 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5849 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5853 /* try to expand with EAs present */
5854 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5858 * Inode size expansion failed; don't try again
5867 * Expand an inode by new_extra_isize bytes.
5868 * Returns 0 on success or negative error number on failure.
5870 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5871 unsigned int new_extra_isize,
5872 struct ext4_iloc iloc,
5878 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5882 * In nojournal mode, we can immediately attempt to expand
5883 * the inode. When journaled, we first need to obtain extra
5884 * buffer credits since we may write into the EA block
5885 * with this same handle. If journal_extend fails, then it will
5886 * only result in a minor loss of functionality for that inode.
5887 * If this is felt to be critical, then e2fsck should be run to
5888 * force a large enough s_min_extra_isize.
5890 if (ext4_handle_valid(handle) &&
5891 jbd2_journal_extend(handle,
5892 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
5895 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5898 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5899 handle, &no_expand);
5900 ext4_write_unlock_xattr(inode, &no_expand);
5905 int ext4_expand_extra_isize(struct inode *inode,
5906 unsigned int new_extra_isize,
5907 struct ext4_iloc *iloc)
5913 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5918 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5919 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5920 if (IS_ERR(handle)) {
5921 error = PTR_ERR(handle);
5926 ext4_write_lock_xattr(inode, &no_expand);
5928 BUFFER_TRACE(iloc->bh, "get_write_access");
5929 error = ext4_journal_get_write_access(handle, iloc->bh);
5935 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5936 handle, &no_expand);
5938 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5943 ext4_write_unlock_xattr(inode, &no_expand);
5944 ext4_journal_stop(handle);
5949 * What we do here is to mark the in-core inode as clean with respect to inode
5950 * dirtiness (it may still be data-dirty).
5951 * This means that the in-core inode may be reaped by prune_icache
5952 * without having to perform any I/O. This is a very good thing,
5953 * because *any* task may call prune_icache - even ones which
5954 * have a transaction open against a different journal.
5956 * Is this cheating? Not really. Sure, we haven't written the
5957 * inode out, but prune_icache isn't a user-visible syncing function.
5958 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5959 * we start and wait on commits.
5961 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5963 struct ext4_iloc iloc;
5964 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5968 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5969 err = ext4_reserve_inode_write(handle, inode, &iloc);
5973 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5974 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5977 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5981 * ext4_dirty_inode() is called from __mark_inode_dirty()
5983 * We're really interested in the case where a file is being extended.
5984 * i_size has been changed by generic_commit_write() and we thus need
5985 * to include the updated inode in the current transaction.
5987 * Also, dquot_alloc_block() will always dirty the inode when blocks
5988 * are allocated to the file.
5990 * If the inode is marked synchronous, we don't honour that here - doing
5991 * so would cause a commit on atime updates, which we don't bother doing.
5992 * We handle synchronous inodes at the highest possible level.
5994 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5995 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5996 * to copy into the on-disk inode structure are the timestamp files.
5998 void ext4_dirty_inode(struct inode *inode, int flags)
6002 if (flags == I_DIRTY_TIME)
6004 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6008 ext4_mark_inode_dirty(handle, inode);
6010 ext4_journal_stop(handle);
6017 * Bind an inode's backing buffer_head into this transaction, to prevent
6018 * it from being flushed to disk early. Unlike
6019 * ext4_reserve_inode_write, this leaves behind no bh reference and
6020 * returns no iloc structure, so the caller needs to repeat the iloc
6021 * lookup to mark the inode dirty later.
6023 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
6025 struct ext4_iloc iloc;
6029 err = ext4_get_inode_loc(inode, &iloc);
6031 BUFFER_TRACE(iloc.bh, "get_write_access");
6032 err = jbd2_journal_get_write_access(handle, iloc.bh);
6034 err = ext4_handle_dirty_metadata(handle,
6040 ext4_std_error(inode->i_sb, err);
6045 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6050 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6053 * We have to be very careful here: changing a data block's
6054 * journaling status dynamically is dangerous. If we write a
6055 * data block to the journal, change the status and then delete
6056 * that block, we risk forgetting to revoke the old log record
6057 * from the journal and so a subsequent replay can corrupt data.
6058 * So, first we make sure that the journal is empty and that
6059 * nobody is changing anything.
6062 journal = EXT4_JOURNAL(inode);
6065 if (is_journal_aborted(journal))
6068 /* Wait for all existing dio workers */
6069 ext4_inode_block_unlocked_dio(inode);
6070 inode_dio_wait(inode);
6073 * Before flushing the journal and switching inode's aops, we have
6074 * to flush all dirty data the inode has. There can be outstanding
6075 * delayed allocations, there can be unwritten extents created by
6076 * fallocate or buffered writes in dioread_nolock mode covered by
6077 * dirty data which can be converted only after flushing the dirty
6078 * data (and journalled aops don't know how to handle these cases).
6081 down_write(&EXT4_I(inode)->i_mmap_sem);
6082 err = filemap_write_and_wait(inode->i_mapping);
6084 up_write(&EXT4_I(inode)->i_mmap_sem);
6085 ext4_inode_resume_unlocked_dio(inode);
6090 percpu_down_write(&sbi->s_writepages_rwsem);
6091 jbd2_journal_lock_updates(journal);
6094 * OK, there are no updates running now, and all cached data is
6095 * synced to disk. We are now in a completely consistent state
6096 * which doesn't have anything in the journal, and we know that
6097 * no filesystem updates are running, so it is safe to modify
6098 * the inode's in-core data-journaling state flag now.
6102 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6104 err = jbd2_journal_flush(journal);
6106 jbd2_journal_unlock_updates(journal);
6107 percpu_up_write(&sbi->s_writepages_rwsem);
6108 ext4_inode_resume_unlocked_dio(inode);
6111 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6113 ext4_set_aops(inode);
6115 jbd2_journal_unlock_updates(journal);
6116 percpu_up_write(&sbi->s_writepages_rwsem);
6119 up_write(&EXT4_I(inode)->i_mmap_sem);
6120 ext4_inode_resume_unlocked_dio(inode);
6122 /* Finally we can mark the inode as dirty. */
6124 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6126 return PTR_ERR(handle);
6128 err = ext4_mark_inode_dirty(handle, inode);
6129 ext4_handle_sync(handle);
6130 ext4_journal_stop(handle);
6131 ext4_std_error(inode->i_sb, err);
6136 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6138 return !buffer_mapped(bh);
6141 int ext4_page_mkwrite(struct vm_fault *vmf)
6143 struct vm_area_struct *vma = vmf->vma;
6144 struct page *page = vmf->page;
6148 struct file *file = vma->vm_file;
6149 struct inode *inode = file_inode(file);
6150 struct address_space *mapping = inode->i_mapping;
6152 get_block_t *get_block;
6155 if (unlikely(IS_IMMUTABLE(inode)))
6156 return VM_FAULT_SIGBUS;
6158 sb_start_pagefault(inode->i_sb);
6159 file_update_time(vma->vm_file);
6161 down_read(&EXT4_I(inode)->i_mmap_sem);
6163 ret = ext4_convert_inline_data(inode);
6167 /* Delalloc case is easy... */
6168 if (test_opt(inode->i_sb, DELALLOC) &&
6169 !ext4_should_journal_data(inode) &&
6170 !ext4_nonda_switch(inode->i_sb)) {
6172 ret = block_page_mkwrite(vma, vmf,
6173 ext4_da_get_block_prep);
6174 } while (ret == -ENOSPC &&
6175 ext4_should_retry_alloc(inode->i_sb, &retries));
6180 size = i_size_read(inode);
6181 /* Page got truncated from under us? */
6182 if (page->mapping != mapping || page_offset(page) > size) {
6184 ret = VM_FAULT_NOPAGE;
6188 if (page->index == size >> PAGE_SHIFT)
6189 len = size & ~PAGE_MASK;
6193 * Return if we have all the buffers mapped. This avoids the need to do
6194 * journal_start/journal_stop which can block and take a long time
6196 if (page_has_buffers(page)) {
6197 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6199 ext4_bh_unmapped)) {
6200 /* Wait so that we don't change page under IO */
6201 wait_for_stable_page(page);
6202 ret = VM_FAULT_LOCKED;
6207 /* OK, we need to fill the hole... */
6208 if (ext4_should_dioread_nolock(inode))
6209 get_block = ext4_get_block_unwritten;
6211 get_block = ext4_get_block;
6213 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6214 ext4_writepage_trans_blocks(inode));
6215 if (IS_ERR(handle)) {
6216 ret = VM_FAULT_SIGBUS;
6219 ret = block_page_mkwrite(vma, vmf, get_block);
6220 if (!ret && ext4_should_journal_data(inode)) {
6221 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
6222 PAGE_SIZE, NULL, do_journal_get_write_access)) {
6224 ret = VM_FAULT_SIGBUS;
6225 ext4_journal_stop(handle);
6228 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6230 ext4_journal_stop(handle);
6231 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6234 ret = block_page_mkwrite_return(ret);
6236 up_read(&EXT4_I(inode)->i_mmap_sem);
6237 sb_end_pagefault(inode->i_sb);
6241 int ext4_filemap_fault(struct vm_fault *vmf)
6243 struct inode *inode = file_inode(vmf->vma->vm_file);
6246 down_read(&EXT4_I(inode)->i_mmap_sem);
6247 err = filemap_fault(vmf);
6248 up_read(&EXT4_I(inode)->i_mmap_sem);
6254 * Find the first extent at or after @lblk in an inode that is not a hole.
6255 * Search for @map_len blocks at most. The extent is returned in @result.
6257 * The function returns 1 if we found an extent. The function returns 0 in
6258 * case there is no extent at or after @lblk and in that case also sets
6259 * @result->es_len to 0. In case of error, the error code is returned.
6261 int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
6262 unsigned int map_len, struct extent_status *result)
6264 struct ext4_map_blocks map;
6265 struct extent_status es = {};
6269 map.m_len = map_len;
6272 * For non-extent based files this loop may iterate several times since
6273 * we do not determine full hole size.
6275 while (map.m_len > 0) {
6276 ret = ext4_map_blocks(NULL, inode, &map, 0);
6279 /* There's extent covering m_lblk? Just return it. */
6283 ext4_es_store_pblock(result, map.m_pblk);
6284 result->es_lblk = map.m_lblk;
6285 result->es_len = map.m_len;
6286 if (map.m_flags & EXT4_MAP_UNWRITTEN)
6287 status = EXTENT_STATUS_UNWRITTEN;
6289 status = EXTENT_STATUS_WRITTEN;
6290 ext4_es_store_status(result, status);
6293 ext4_es_find_delayed_extent_range(inode, map.m_lblk,
6294 map.m_lblk + map.m_len - 1,
6296 /* Is delalloc data before next block in extent tree? */
6297 if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
6298 ext4_lblk_t offset = 0;
6300 if (es.es_lblk < lblk)
6301 offset = lblk - es.es_lblk;
6302 result->es_lblk = es.es_lblk + offset;
6303 ext4_es_store_pblock(result,
6304 ext4_es_pblock(&es) + offset);
6305 result->es_len = es.es_len - offset;
6306 ext4_es_store_status(result, ext4_es_status(&es));
6310 /* There's a hole at m_lblk, advance us after it */
6311 map.m_lblk += map.m_len;
6312 map_len -= map.m_len;
6313 map.m_len = map_len;