2 * linux/fs/ext4/inode.c
4 * Copyright (C) 1992, 1993, 1994, 1995
5 * Remy Card (card@masi.ibp.fr)
6 * Laboratoire MASI - Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
22 #include <linux/time.h>
23 #include <linux/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/dax.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/bitops.h>
41 #include "ext4_jbd2.h"
46 #include <trace/events/ext4.h>
47 #include <trace/events/android_fs.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57 int offset = offsetof(struct ext4_inode, i_checksum_lo);
58 unsigned int csum_size = sizeof(dummy_csum);
60 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
61 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
64 EXT4_GOOD_OLD_INODE_SIZE - offset);
66 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
67 offset = offsetof(struct ext4_inode, i_checksum_hi);
68 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
69 EXT4_GOOD_OLD_INODE_SIZE,
70 offset - EXT4_GOOD_OLD_INODE_SIZE);
71 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
72 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
76 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
77 EXT4_INODE_SIZE(inode->i_sb) - offset);
83 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84 struct ext4_inode_info *ei)
86 __u32 provided, calculated;
88 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89 cpu_to_le32(EXT4_OS_LINUX) ||
90 !ext4_has_metadata_csum(inode->i_sb))
93 provided = le16_to_cpu(raw->i_checksum_lo);
94 calculated = ext4_inode_csum(inode, raw, ei);
95 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
101 return provided == calculated;
104 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105 struct ext4_inode_info *ei)
109 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110 cpu_to_le32(EXT4_OS_LINUX) ||
111 !ext4_has_metadata_csum(inode->i_sb))
114 csum = ext4_inode_csum(inode, raw, ei);
115 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
121 static inline int ext4_begin_ordered_truncate(struct inode *inode,
124 trace_ext4_begin_ordered_truncate(inode, new_size);
126 * If jinode is zero, then we never opened the file for
127 * writing, so there's no need to call
128 * jbd2_journal_begin_ordered_truncate() since there's no
129 * outstanding writes we need to flush.
131 if (!EXT4_I(inode)->jinode)
133 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
134 EXT4_I(inode)->jinode,
138 static void ext4_invalidatepage(struct page *page, unsigned int offset,
139 unsigned int length);
140 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
146 * Test whether an inode is a fast symlink.
148 int ext4_inode_is_fast_symlink(struct inode *inode)
150 int ea_blocks = EXT4_I(inode)->i_file_acl ?
151 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
153 if (ext4_has_inline_data(inode))
156 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
160 * Restart the transaction associated with *handle. This does a commit,
161 * so before we call here everything must be consistently dirtied against
164 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
170 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
171 * moment, get_block can be called only for blocks inside i_size since
172 * page cache has been already dropped and writes are blocked by
173 * i_mutex. So we can safely drop the i_data_sem here.
175 BUG_ON(EXT4_JOURNAL(inode) == NULL);
176 jbd_debug(2, "restarting handle %p\n", handle);
177 up_write(&EXT4_I(inode)->i_data_sem);
178 ret = ext4_journal_restart(handle, nblocks);
179 down_write(&EXT4_I(inode)->i_data_sem);
180 ext4_discard_preallocations(inode);
186 * Called at the last iput() if i_nlink is zero.
188 void ext4_evict_inode(struct inode *inode)
193 trace_ext4_evict_inode(inode);
195 if (inode->i_nlink) {
197 * When journalling data dirty buffers are tracked only in the
198 * journal. So although mm thinks everything is clean and
199 * ready for reaping the inode might still have some pages to
200 * write in the running transaction or waiting to be
201 * checkpointed. Thus calling jbd2_journal_invalidatepage()
202 * (via truncate_inode_pages()) to discard these buffers can
203 * cause data loss. Also even if we did not discard these
204 * buffers, we would have no way to find them after the inode
205 * is reaped and thus user could see stale data if he tries to
206 * read them before the transaction is checkpointed. So be
207 * careful and force everything to disk here... We use
208 * ei->i_datasync_tid to store the newest transaction
209 * containing inode's data.
211 * Note that directories do not have this problem because they
212 * don't use page cache.
214 if (inode->i_ino != EXT4_JOURNAL_INO &&
215 ext4_should_journal_data(inode) &&
216 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
217 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
218 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
220 jbd2_complete_transaction(journal, commit_tid);
221 filemap_write_and_wait(&inode->i_data);
223 truncate_inode_pages_final(&inode->i_data);
225 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
229 if (is_bad_inode(inode))
231 dquot_initialize(inode);
233 if (ext4_should_order_data(inode))
234 ext4_begin_ordered_truncate(inode, 0);
235 truncate_inode_pages_final(&inode->i_data);
237 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
240 * Protect us against freezing - iput() caller didn't have to have any
241 * protection against it
243 sb_start_intwrite(inode->i_sb);
244 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
245 ext4_blocks_for_truncate(inode)+3);
246 if (IS_ERR(handle)) {
247 ext4_std_error(inode->i_sb, PTR_ERR(handle));
249 * If we're going to skip the normal cleanup, we still need to
250 * make sure that the in-core orphan linked list is properly
253 ext4_orphan_del(NULL, inode);
254 sb_end_intwrite(inode->i_sb);
259 ext4_handle_sync(handle);
261 err = ext4_mark_inode_dirty(handle, inode);
263 ext4_warning(inode->i_sb,
264 "couldn't mark inode dirty (err %d)", err);
268 ext4_truncate(inode);
271 * ext4_ext_truncate() doesn't reserve any slop when it
272 * restarts journal transactions; therefore there may not be
273 * enough credits left in the handle to remove the inode from
274 * the orphan list and set the dtime field.
276 if (!ext4_handle_has_enough_credits(handle, 3)) {
277 err = ext4_journal_extend(handle, 3);
279 err = ext4_journal_restart(handle, 3);
281 ext4_warning(inode->i_sb,
282 "couldn't extend journal (err %d)", err);
284 ext4_journal_stop(handle);
285 ext4_orphan_del(NULL, inode);
286 sb_end_intwrite(inode->i_sb);
292 * Kill off the orphan record which ext4_truncate created.
293 * AKPM: I think this can be inside the above `if'.
294 * Note that ext4_orphan_del() has to be able to cope with the
295 * deletion of a non-existent orphan - this is because we don't
296 * know if ext4_truncate() actually created an orphan record.
297 * (Well, we could do this if we need to, but heck - it works)
299 ext4_orphan_del(handle, inode);
300 EXT4_I(inode)->i_dtime = get_seconds();
303 * One subtle ordering requirement: if anything has gone wrong
304 * (transaction abort, IO errors, whatever), then we can still
305 * do these next steps (the fs will already have been marked as
306 * having errors), but we can't free the inode if the mark_dirty
309 if (ext4_mark_inode_dirty(handle, inode))
310 /* If that failed, just do the required in-core inode clear. */
311 ext4_clear_inode(inode);
313 ext4_free_inode(handle, inode);
314 ext4_journal_stop(handle);
315 sb_end_intwrite(inode->i_sb);
318 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
322 qsize_t *ext4_get_reserved_space(struct inode *inode)
324 return &EXT4_I(inode)->i_reserved_quota;
329 * Called with i_data_sem down, which is important since we can call
330 * ext4_discard_preallocations() from here.
332 void ext4_da_update_reserve_space(struct inode *inode,
333 int used, int quota_claim)
335 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
336 struct ext4_inode_info *ei = EXT4_I(inode);
338 spin_lock(&ei->i_block_reservation_lock);
339 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
340 if (unlikely(used > ei->i_reserved_data_blocks)) {
341 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
342 "with only %d reserved data blocks",
343 __func__, inode->i_ino, used,
344 ei->i_reserved_data_blocks);
346 used = ei->i_reserved_data_blocks;
349 /* Update per-inode reservations */
350 ei->i_reserved_data_blocks -= used;
351 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
353 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
355 /* Update quota subsystem for data blocks */
357 dquot_claim_block(inode, EXT4_C2B(sbi, used));
360 * We did fallocate with an offset that is already delayed
361 * allocated. So on delayed allocated writeback we should
362 * not re-claim the quota for fallocated blocks.
364 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
368 * If we have done all the pending block allocations and if
369 * there aren't any writers on the inode, we can discard the
370 * inode's preallocations.
372 if ((ei->i_reserved_data_blocks == 0) &&
373 (atomic_read(&inode->i_writecount) == 0))
374 ext4_discard_preallocations(inode);
377 static int __check_block_validity(struct inode *inode, const char *func,
379 struct ext4_map_blocks *map)
381 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
383 ext4_error_inode(inode, func, line, map->m_pblk,
384 "lblock %lu mapped to illegal pblock "
385 "(length %d)", (unsigned long) map->m_lblk,
387 return -EFSCORRUPTED;
392 #define check_block_validity(inode, map) \
393 __check_block_validity((inode), __func__, __LINE__, (map))
395 #ifdef ES_AGGRESSIVE_TEST
396 static void ext4_map_blocks_es_recheck(handle_t *handle,
398 struct ext4_map_blocks *es_map,
399 struct ext4_map_blocks *map,
406 * There is a race window that the result is not the same.
407 * e.g. xfstests #223 when dioread_nolock enables. The reason
408 * is that we lookup a block mapping in extent status tree with
409 * out taking i_data_sem. So at the time the unwritten extent
410 * could be converted.
412 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
413 down_read(&EXT4_I(inode)->i_data_sem);
414 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
415 retval = ext4_ext_map_blocks(handle, inode, map, flags &
416 EXT4_GET_BLOCKS_KEEP_SIZE);
418 retval = ext4_ind_map_blocks(handle, inode, map, flags &
419 EXT4_GET_BLOCKS_KEEP_SIZE);
421 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
422 up_read((&EXT4_I(inode)->i_data_sem));
425 * We don't check m_len because extent will be collpased in status
426 * tree. So the m_len might not equal.
428 if (es_map->m_lblk != map->m_lblk ||
429 es_map->m_flags != map->m_flags ||
430 es_map->m_pblk != map->m_pblk) {
431 printk("ES cache assertion failed for inode: %lu "
432 "es_cached ex [%d/%d/%llu/%x] != "
433 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
434 inode->i_ino, es_map->m_lblk, es_map->m_len,
435 es_map->m_pblk, es_map->m_flags, map->m_lblk,
436 map->m_len, map->m_pblk, map->m_flags,
440 #endif /* ES_AGGRESSIVE_TEST */
443 * The ext4_map_blocks() function tries to look up the requested blocks,
444 * and returns if the blocks are already mapped.
446 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
447 * and store the allocated blocks in the result buffer head and mark it
450 * If file type is extents based, it will call ext4_ext_map_blocks(),
451 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
454 * On success, it returns the number of blocks being mapped or allocated.
455 * if create==0 and the blocks are pre-allocated and unwritten block,
456 * the result buffer head is unmapped. If the create ==1, it will make sure
457 * the buffer head is mapped.
459 * It returns 0 if plain look up failed (blocks have not been allocated), in
460 * that case, buffer head is unmapped
462 * It returns the error in case of allocation failure.
464 int ext4_map_blocks(handle_t *handle, struct inode *inode,
465 struct ext4_map_blocks *map, int flags)
467 struct extent_status es;
470 #ifdef ES_AGGRESSIVE_TEST
471 struct ext4_map_blocks orig_map;
473 memcpy(&orig_map, map, sizeof(*map));
477 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
478 "logical block %lu\n", inode->i_ino, flags, map->m_len,
479 (unsigned long) map->m_lblk);
482 * ext4_map_blocks returns an int, and m_len is an unsigned int
484 if (unlikely(map->m_len > INT_MAX))
485 map->m_len = INT_MAX;
487 /* We can handle the block number less than EXT_MAX_BLOCKS */
488 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
489 return -EFSCORRUPTED;
491 /* Lookup extent status tree firstly */
492 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
493 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
494 map->m_pblk = ext4_es_pblock(&es) +
495 map->m_lblk - es.es_lblk;
496 map->m_flags |= ext4_es_is_written(&es) ?
497 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
498 retval = es.es_len - (map->m_lblk - es.es_lblk);
499 if (retval > map->m_len)
502 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
507 #ifdef ES_AGGRESSIVE_TEST
508 ext4_map_blocks_es_recheck(handle, inode, map,
515 * Try to see if we can get the block without requesting a new
518 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
519 down_read(&EXT4_I(inode)->i_data_sem);
520 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
521 retval = ext4_ext_map_blocks(handle, inode, map, flags &
522 EXT4_GET_BLOCKS_KEEP_SIZE);
524 retval = ext4_ind_map_blocks(handle, inode, map, flags &
525 EXT4_GET_BLOCKS_KEEP_SIZE);
530 if (unlikely(retval != map->m_len)) {
531 ext4_warning(inode->i_sb,
532 "ES len assertion failed for inode "
533 "%lu: retval %d != map->m_len %d",
534 inode->i_ino, retval, map->m_len);
538 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
539 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
540 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
541 !(status & EXTENT_STATUS_WRITTEN) &&
542 ext4_find_delalloc_range(inode, map->m_lblk,
543 map->m_lblk + map->m_len - 1))
544 status |= EXTENT_STATUS_DELAYED;
545 ret = ext4_es_insert_extent(inode, map->m_lblk,
546 map->m_len, map->m_pblk, status);
550 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
551 up_read((&EXT4_I(inode)->i_data_sem));
554 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
555 ret = check_block_validity(inode, map);
560 /* If it is only a block(s) look up */
561 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
565 * Returns if the blocks have already allocated
567 * Note that if blocks have been preallocated
568 * ext4_ext_get_block() returns the create = 0
569 * with buffer head unmapped.
571 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
573 * If we need to convert extent to unwritten
574 * we continue and do the actual work in
575 * ext4_ext_map_blocks()
577 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
581 * Here we clear m_flags because after allocating an new extent,
582 * it will be set again.
584 map->m_flags &= ~EXT4_MAP_FLAGS;
587 * New blocks allocate and/or writing to unwritten extent
588 * will possibly result in updating i_data, so we take
589 * the write lock of i_data_sem, and call get_block()
590 * with create == 1 flag.
592 down_write(&EXT4_I(inode)->i_data_sem);
595 * We need to check for EXT4 here because migrate
596 * could have changed the inode type in between
598 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
599 retval = ext4_ext_map_blocks(handle, inode, map, flags);
601 retval = ext4_ind_map_blocks(handle, inode, map, flags);
603 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
605 * We allocated new blocks which will result in
606 * i_data's format changing. Force the migrate
607 * to fail by clearing migrate flags
609 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
613 * Update reserved blocks/metadata blocks after successful
614 * block allocation which had been deferred till now. We don't
615 * support fallocate for non extent files. So we can update
616 * reserve space here.
619 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
620 ext4_da_update_reserve_space(inode, retval, 1);
626 if (unlikely(retval != map->m_len)) {
627 ext4_warning(inode->i_sb,
628 "ES len assertion failed for inode "
629 "%lu: retval %d != map->m_len %d",
630 inode->i_ino, retval, map->m_len);
635 * If the extent has been zeroed out, we don't need to update
636 * extent status tree.
638 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
639 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
640 if (ext4_es_is_written(&es))
643 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
644 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
645 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
646 !(status & EXTENT_STATUS_WRITTEN) &&
647 ext4_find_delalloc_range(inode, map->m_lblk,
648 map->m_lblk + map->m_len - 1))
649 status |= EXTENT_STATUS_DELAYED;
650 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
651 map->m_pblk, status);
657 up_write((&EXT4_I(inode)->i_data_sem));
658 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
659 ret = check_block_validity(inode, map);
664 * Inodes with freshly allocated blocks where contents will be
665 * visible after transaction commit must be on transaction's
668 if (map->m_flags & EXT4_MAP_NEW &&
669 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
670 !IS_NOQUOTA(inode) &&
671 ext4_should_order_data(inode)) {
672 ret = ext4_jbd2_file_inode(handle, inode);
681 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
682 * we have to be careful as someone else may be manipulating b_state as well.
684 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
686 unsigned long old_state;
687 unsigned long new_state;
689 flags &= EXT4_MAP_FLAGS;
691 /* Dummy buffer_head? Set non-atomically. */
693 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
697 * Someone else may be modifying b_state. Be careful! This is ugly but
698 * once we get rid of using bh as a container for mapping information
699 * to pass to / from get_block functions, this can go away.
702 old_state = READ_ONCE(bh->b_state);
703 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
705 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
708 /* Maximum number of blocks we map for direct IO at once. */
709 #define DIO_MAX_BLOCKS 4096
711 static int _ext4_get_block(struct inode *inode, sector_t iblock,
712 struct buffer_head *bh, int flags)
714 handle_t *handle = ext4_journal_current_handle();
715 struct ext4_map_blocks map;
716 int ret = 0, started = 0;
719 if (ext4_has_inline_data(inode))
723 map.m_len = bh->b_size >> inode->i_blkbits;
725 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
726 /* Direct IO write... */
727 if (map.m_len > DIO_MAX_BLOCKS)
728 map.m_len = DIO_MAX_BLOCKS;
729 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
730 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
732 if (IS_ERR(handle)) {
733 ret = PTR_ERR(handle);
739 ret = ext4_map_blocks(handle, inode, &map, flags);
741 ext4_io_end_t *io_end = ext4_inode_aio(inode);
743 map_bh(bh, inode->i_sb, map.m_pblk);
744 ext4_update_bh_state(bh, map.m_flags);
745 if (IS_DAX(inode) && buffer_unwritten(bh)) {
747 * dgc: I suspect unwritten conversion on ext4+DAX is
748 * fundamentally broken here when there are concurrent
749 * read/write in progress on this inode.
751 WARN_ON_ONCE(io_end);
752 bh->b_assoc_map = inode->i_mapping;
753 bh->b_private = (void *)(unsigned long)iblock;
755 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
756 set_buffer_defer_completion(bh);
757 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
761 ext4_journal_stop(handle);
765 int ext4_get_block(struct inode *inode, sector_t iblock,
766 struct buffer_head *bh, int create)
768 return _ext4_get_block(inode, iblock, bh,
769 create ? EXT4_GET_BLOCKS_CREATE : 0);
773 * `handle' can be NULL if create is zero
775 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
776 ext4_lblk_t block, int map_flags)
778 struct ext4_map_blocks map;
779 struct buffer_head *bh;
780 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
783 J_ASSERT(handle != NULL || create == 0);
787 err = ext4_map_blocks(handle, inode, &map, map_flags);
790 return create ? ERR_PTR(-ENOSPC) : NULL;
794 bh = sb_getblk(inode->i_sb, map.m_pblk);
796 return ERR_PTR(-ENOMEM);
797 if (map.m_flags & EXT4_MAP_NEW) {
798 J_ASSERT(create != 0);
799 J_ASSERT(handle != NULL);
802 * Now that we do not always journal data, we should
803 * keep in mind whether this should always journal the
804 * new buffer as metadata. For now, regular file
805 * writes use ext4_get_block instead, so it's not a
809 BUFFER_TRACE(bh, "call get_create_access");
810 err = ext4_journal_get_create_access(handle, bh);
815 if (!buffer_uptodate(bh)) {
816 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
817 set_buffer_uptodate(bh);
820 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
821 err = ext4_handle_dirty_metadata(handle, inode, bh);
825 BUFFER_TRACE(bh, "not a new buffer");
832 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
833 ext4_lblk_t block, int map_flags)
835 struct buffer_head *bh;
837 bh = ext4_getblk(handle, inode, block, map_flags);
840 if (!bh || buffer_uptodate(bh))
842 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
844 if (buffer_uptodate(bh))
847 return ERR_PTR(-EIO);
850 int ext4_walk_page_buffers(handle_t *handle,
851 struct buffer_head *head,
855 int (*fn)(handle_t *handle,
856 struct buffer_head *bh))
858 struct buffer_head *bh;
859 unsigned block_start, block_end;
860 unsigned blocksize = head->b_size;
862 struct buffer_head *next;
864 for (bh = head, block_start = 0;
865 ret == 0 && (bh != head || !block_start);
866 block_start = block_end, bh = next) {
867 next = bh->b_this_page;
868 block_end = block_start + blocksize;
869 if (block_end <= from || block_start >= to) {
870 if (partial && !buffer_uptodate(bh))
874 err = (*fn)(handle, bh);
882 * To preserve ordering, it is essential that the hole instantiation and
883 * the data write be encapsulated in a single transaction. We cannot
884 * close off a transaction and start a new one between the ext4_get_block()
885 * and the commit_write(). So doing the jbd2_journal_start at the start of
886 * prepare_write() is the right place.
888 * Also, this function can nest inside ext4_writepage(). In that case, we
889 * *know* that ext4_writepage() has generated enough buffer credits to do the
890 * whole page. So we won't block on the journal in that case, which is good,
891 * because the caller may be PF_MEMALLOC.
893 * By accident, ext4 can be reentered when a transaction is open via
894 * quota file writes. If we were to commit the transaction while thus
895 * reentered, there can be a deadlock - we would be holding a quota
896 * lock, and the commit would never complete if another thread had a
897 * transaction open and was blocking on the quota lock - a ranking
900 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
901 * will _not_ run commit under these circumstances because handle->h_ref
902 * is elevated. We'll still have enough credits for the tiny quotafile
905 int do_journal_get_write_access(handle_t *handle,
906 struct buffer_head *bh)
908 int dirty = buffer_dirty(bh);
911 if (!buffer_mapped(bh) || buffer_freed(bh))
914 * __block_write_begin() could have dirtied some buffers. Clean
915 * the dirty bit as jbd2_journal_get_write_access() could complain
916 * otherwise about fs integrity issues. Setting of the dirty bit
917 * by __block_write_begin() isn't a real problem here as we clear
918 * the bit before releasing a page lock and thus writeback cannot
919 * ever write the buffer.
922 clear_buffer_dirty(bh);
923 BUFFER_TRACE(bh, "get write access");
924 ret = ext4_journal_get_write_access(handle, bh);
926 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
930 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
931 struct buffer_head *bh_result, int create);
933 #ifdef CONFIG_EXT4_FS_ENCRYPTION
934 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
935 get_block_t *get_block)
937 unsigned from = pos & (PAGE_CACHE_SIZE - 1);
938 unsigned to = from + len;
939 struct inode *inode = page->mapping->host;
940 unsigned block_start, block_end;
943 unsigned blocksize = inode->i_sb->s_blocksize;
945 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
946 bool decrypt = false;
948 BUG_ON(!PageLocked(page));
949 BUG_ON(from > PAGE_CACHE_SIZE);
950 BUG_ON(to > PAGE_CACHE_SIZE);
953 if (!page_has_buffers(page))
954 create_empty_buffers(page, blocksize, 0);
955 head = page_buffers(page);
956 bbits = ilog2(blocksize);
957 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
959 for (bh = head, block_start = 0; bh != head || !block_start;
960 block++, block_start = block_end, bh = bh->b_this_page) {
961 block_end = block_start + blocksize;
962 if (block_end <= from || block_start >= to) {
963 if (PageUptodate(page)) {
964 if (!buffer_uptodate(bh))
965 set_buffer_uptodate(bh);
970 clear_buffer_new(bh);
971 if (!buffer_mapped(bh)) {
972 WARN_ON(bh->b_size != blocksize);
973 err = get_block(inode, block, bh, 1);
976 if (buffer_new(bh)) {
977 unmap_underlying_metadata(bh->b_bdev,
979 if (PageUptodate(page)) {
980 clear_buffer_new(bh);
981 set_buffer_uptodate(bh);
982 mark_buffer_dirty(bh);
985 if (block_end > to || block_start < from)
986 zero_user_segments(page, to, block_end,
991 if (PageUptodate(page)) {
992 if (!buffer_uptodate(bh))
993 set_buffer_uptodate(bh);
996 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
997 !buffer_unwritten(bh) &&
998 (block_start < from || block_end > to)) {
999 ll_rw_block(READ, 1, &bh);
1001 decrypt = ext4_encrypted_inode(inode) &&
1002 S_ISREG(inode->i_mode);
1006 * If we issued read requests, let them complete.
1008 while (wait_bh > wait) {
1009 wait_on_buffer(*--wait_bh);
1010 if (!buffer_uptodate(*wait_bh))
1014 page_zero_new_buffers(page, from, to);
1016 err = ext4_decrypt(page);
1021 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1022 loff_t pos, unsigned len, unsigned flags,
1023 struct page **pagep, void **fsdata)
1025 struct inode *inode = mapping->host;
1026 int ret, needed_blocks;
1033 if (trace_android_fs_datawrite_start_enabled()) {
1034 char *path, pathbuf[MAX_TRACE_PATHBUF_LEN];
1036 path = android_fstrace_get_pathname(pathbuf,
1037 MAX_TRACE_PATHBUF_LEN,
1039 trace_android_fs_datawrite_start(inode, pos, len,
1043 trace_ext4_write_begin(inode, pos, len, flags);
1045 * Reserve one block more for addition to orphan list in case
1046 * we allocate blocks but write fails for some reason
1048 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1049 index = pos >> PAGE_CACHE_SHIFT;
1050 from = pos & (PAGE_CACHE_SIZE - 1);
1053 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1054 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1063 * grab_cache_page_write_begin() can take a long time if the
1064 * system is thrashing due to memory pressure, or if the page
1065 * is being written back. So grab it first before we start
1066 * the transaction handle. This also allows us to allocate
1067 * the page (if needed) without using GFP_NOFS.
1070 page = grab_cache_page_write_begin(mapping, index, flags);
1076 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1077 if (IS_ERR(handle)) {
1078 page_cache_release(page);
1079 return PTR_ERR(handle);
1083 if (page->mapping != mapping) {
1084 /* The page got truncated from under us */
1086 page_cache_release(page);
1087 ext4_journal_stop(handle);
1090 /* In case writeback began while the page was unlocked */
1091 wait_for_stable_page(page);
1093 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1094 if (ext4_should_dioread_nolock(inode))
1095 ret = ext4_block_write_begin(page, pos, len,
1096 ext4_get_block_write);
1098 ret = ext4_block_write_begin(page, pos, len,
1101 if (ext4_should_dioread_nolock(inode))
1102 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1104 ret = __block_write_begin(page, pos, len, ext4_get_block);
1106 if (!ret && ext4_should_journal_data(inode)) {
1107 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1109 do_journal_get_write_access);
1115 * __block_write_begin may have instantiated a few blocks
1116 * outside i_size. Trim these off again. Don't need
1117 * i_size_read because we hold i_mutex.
1119 * Add inode to orphan list in case we crash before
1122 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1123 ext4_orphan_add(handle, inode);
1125 ext4_journal_stop(handle);
1126 if (pos + len > inode->i_size) {
1127 ext4_truncate_failed_write(inode);
1129 * If truncate failed early the inode might
1130 * still be on the orphan list; we need to
1131 * make sure the inode is removed from the
1132 * orphan list in that case.
1135 ext4_orphan_del(NULL, inode);
1138 if (ret == -ENOSPC &&
1139 ext4_should_retry_alloc(inode->i_sb, &retries))
1141 page_cache_release(page);
1148 /* For write_end() in data=journal mode */
1149 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1152 if (!buffer_mapped(bh) || buffer_freed(bh))
1154 set_buffer_uptodate(bh);
1155 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1156 clear_buffer_meta(bh);
1157 clear_buffer_prio(bh);
1162 * We need to pick up the new inode size which generic_commit_write gave us
1163 * `file' can be NULL - eg, when called from page_symlink().
1165 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1166 * buffers are managed internally.
1168 static int ext4_write_end(struct file *file,
1169 struct address_space *mapping,
1170 loff_t pos, unsigned len, unsigned copied,
1171 struct page *page, void *fsdata)
1173 handle_t *handle = ext4_journal_current_handle();
1174 struct inode *inode = mapping->host;
1175 loff_t old_size = inode->i_size;
1177 int i_size_changed = 0;
1179 trace_android_fs_datawrite_end(inode, pos, len);
1180 trace_ext4_write_end(inode, pos, len, copied);
1181 if (ext4_has_inline_data(inode)) {
1182 ret = ext4_write_inline_data_end(inode, pos, len,
1191 copied = block_write_end(file, mapping, pos,
1192 len, copied, page, fsdata);
1194 * it's important to update i_size while still holding page lock:
1195 * page writeout could otherwise come in and zero beyond i_size.
1197 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1199 page_cache_release(page);
1202 pagecache_isize_extended(inode, old_size, pos);
1204 * Don't mark the inode dirty under page lock. First, it unnecessarily
1205 * makes the holding time of page lock longer. Second, it forces lock
1206 * ordering of page lock and transaction start for journaling
1210 ext4_mark_inode_dirty(handle, inode);
1212 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1213 /* if we have allocated more blocks and copied
1214 * less. We will have blocks allocated outside
1215 * inode->i_size. So truncate them
1217 ext4_orphan_add(handle, inode);
1219 ret2 = ext4_journal_stop(handle);
1223 if (pos + len > inode->i_size) {
1224 ext4_truncate_failed_write(inode);
1226 * If truncate failed early the inode might still be
1227 * on the orphan list; we need to make sure the inode
1228 * is removed from the orphan list in that case.
1231 ext4_orphan_del(NULL, inode);
1234 return ret ? ret : copied;
1238 * This is a private version of page_zero_new_buffers() which doesn't
1239 * set the buffer to be dirty, since in data=journalled mode we need
1240 * to call ext4_handle_dirty_metadata() instead.
1242 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1244 unsigned from, unsigned to)
1246 unsigned int block_start = 0, block_end;
1247 struct buffer_head *head, *bh;
1249 bh = head = page_buffers(page);
1251 block_end = block_start + bh->b_size;
1252 if (buffer_new(bh)) {
1253 if (block_end > from && block_start < to) {
1254 if (!PageUptodate(page)) {
1255 unsigned start, size;
1257 start = max(from, block_start);
1258 size = min(to, block_end) - start;
1260 zero_user(page, start, size);
1261 write_end_fn(handle, bh);
1263 clear_buffer_new(bh);
1266 block_start = block_end;
1267 bh = bh->b_this_page;
1268 } while (bh != head);
1271 static int ext4_journalled_write_end(struct file *file,
1272 struct address_space *mapping,
1273 loff_t pos, unsigned len, unsigned copied,
1274 struct page *page, void *fsdata)
1276 handle_t *handle = ext4_journal_current_handle();
1277 struct inode *inode = mapping->host;
1278 loff_t old_size = inode->i_size;
1282 int size_changed = 0;
1284 trace_android_fs_datawrite_end(inode, pos, len);
1285 trace_ext4_journalled_write_end(inode, pos, len, copied);
1286 from = pos & (PAGE_CACHE_SIZE - 1);
1289 BUG_ON(!ext4_handle_valid(handle));
1291 if (ext4_has_inline_data(inode)) {
1292 ret = ext4_write_inline_data_end(inode, pos, len,
1300 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1302 ext4_journalled_zero_new_buffers(handle, page, from, to);
1304 if (unlikely(copied < len))
1305 ext4_journalled_zero_new_buffers(handle, page,
1307 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1308 from + copied, &partial,
1311 SetPageUptodate(page);
1313 size_changed = ext4_update_inode_size(inode, pos + copied);
1314 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1315 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1317 page_cache_release(page);
1320 pagecache_isize_extended(inode, old_size, pos);
1323 ret2 = ext4_mark_inode_dirty(handle, inode);
1328 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1329 /* if we have allocated more blocks and copied
1330 * less. We will have blocks allocated outside
1331 * inode->i_size. So truncate them
1333 ext4_orphan_add(handle, inode);
1336 ret2 = ext4_journal_stop(handle);
1339 if (pos + len > inode->i_size) {
1340 ext4_truncate_failed_write(inode);
1342 * If truncate failed early the inode might still be
1343 * on the orphan list; we need to make sure the inode
1344 * is removed from the orphan list in that case.
1347 ext4_orphan_del(NULL, inode);
1350 return ret ? ret : copied;
1354 * Reserve space for a single cluster
1356 static int ext4_da_reserve_space(struct inode *inode)
1358 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1359 struct ext4_inode_info *ei = EXT4_I(inode);
1363 * We will charge metadata quota at writeout time; this saves
1364 * us from metadata over-estimation, though we may go over by
1365 * a small amount in the end. Here we just reserve for data.
1367 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1371 spin_lock(&ei->i_block_reservation_lock);
1372 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1373 spin_unlock(&ei->i_block_reservation_lock);
1374 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1377 ei->i_reserved_data_blocks++;
1378 trace_ext4_da_reserve_space(inode);
1379 spin_unlock(&ei->i_block_reservation_lock);
1381 return 0; /* success */
1384 static void ext4_da_release_space(struct inode *inode, int to_free)
1386 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1387 struct ext4_inode_info *ei = EXT4_I(inode);
1390 return; /* Nothing to release, exit */
1392 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1394 trace_ext4_da_release_space(inode, to_free);
1395 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1397 * if there aren't enough reserved blocks, then the
1398 * counter is messed up somewhere. Since this
1399 * function is called from invalidate page, it's
1400 * harmless to return without any action.
1402 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1403 "ino %lu, to_free %d with only %d reserved "
1404 "data blocks", inode->i_ino, to_free,
1405 ei->i_reserved_data_blocks);
1407 to_free = ei->i_reserved_data_blocks;
1409 ei->i_reserved_data_blocks -= to_free;
1411 /* update fs dirty data blocks counter */
1412 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1414 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1416 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1419 static void ext4_da_page_release_reservation(struct page *page,
1420 unsigned int offset,
1421 unsigned int length)
1423 int to_release = 0, contiguous_blks = 0;
1424 struct buffer_head *head, *bh;
1425 unsigned int curr_off = 0;
1426 struct inode *inode = page->mapping->host;
1427 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1428 unsigned int stop = offset + length;
1432 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1434 head = page_buffers(page);
1437 unsigned int next_off = curr_off + bh->b_size;
1439 if (next_off > stop)
1442 if ((offset <= curr_off) && (buffer_delay(bh))) {
1445 clear_buffer_delay(bh);
1446 } else if (contiguous_blks) {
1447 lblk = page->index <<
1448 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1449 lblk += (curr_off >> inode->i_blkbits) -
1451 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1452 contiguous_blks = 0;
1454 curr_off = next_off;
1455 } while ((bh = bh->b_this_page) != head);
1457 if (contiguous_blks) {
1458 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1459 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1460 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1463 /* If we have released all the blocks belonging to a cluster, then we
1464 * need to release the reserved space for that cluster. */
1465 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1466 while (num_clusters > 0) {
1467 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1468 ((num_clusters - 1) << sbi->s_cluster_bits);
1469 if (sbi->s_cluster_ratio == 1 ||
1470 !ext4_find_delalloc_cluster(inode, lblk))
1471 ext4_da_release_space(inode, 1);
1478 * Delayed allocation stuff
1481 struct mpage_da_data {
1482 struct inode *inode;
1483 struct writeback_control *wbc;
1485 pgoff_t first_page; /* The first page to write */
1486 pgoff_t next_page; /* Current page to examine */
1487 pgoff_t last_page; /* Last page to examine */
1489 * Extent to map - this can be after first_page because that can be
1490 * fully mapped. We somewhat abuse m_flags to store whether the extent
1491 * is delalloc or unwritten.
1493 struct ext4_map_blocks map;
1494 struct ext4_io_submit io_submit; /* IO submission data */
1497 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1502 struct pagevec pvec;
1503 struct inode *inode = mpd->inode;
1504 struct address_space *mapping = inode->i_mapping;
1506 /* This is necessary when next_page == 0. */
1507 if (mpd->first_page >= mpd->next_page)
1510 index = mpd->first_page;
1511 end = mpd->next_page - 1;
1513 ext4_lblk_t start, last;
1514 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1515 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1516 ext4_es_remove_extent(inode, start, last - start + 1);
1519 pagevec_init(&pvec, 0);
1520 while (index <= end) {
1521 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1524 for (i = 0; i < nr_pages; i++) {
1525 struct page *page = pvec.pages[i];
1526 if (page->index > end)
1528 BUG_ON(!PageLocked(page));
1529 BUG_ON(PageWriteback(page));
1531 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1532 ClearPageUptodate(page);
1536 index = pvec.pages[nr_pages - 1]->index + 1;
1537 pagevec_release(&pvec);
1541 static void ext4_print_free_blocks(struct inode *inode)
1543 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1544 struct super_block *sb = inode->i_sb;
1545 struct ext4_inode_info *ei = EXT4_I(inode);
1547 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1548 EXT4_C2B(EXT4_SB(inode->i_sb),
1549 ext4_count_free_clusters(sb)));
1550 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1551 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1552 (long long) EXT4_C2B(EXT4_SB(sb),
1553 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1554 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1555 (long long) EXT4_C2B(EXT4_SB(sb),
1556 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1557 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1558 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1559 ei->i_reserved_data_blocks);
1563 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1565 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1569 * This function is grabs code from the very beginning of
1570 * ext4_map_blocks, but assumes that the caller is from delayed write
1571 * time. This function looks up the requested blocks and sets the
1572 * buffer delay bit under the protection of i_data_sem.
1574 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1575 struct ext4_map_blocks *map,
1576 struct buffer_head *bh)
1578 struct extent_status es;
1580 sector_t invalid_block = ~((sector_t) 0xffff);
1581 #ifdef ES_AGGRESSIVE_TEST
1582 struct ext4_map_blocks orig_map;
1584 memcpy(&orig_map, map, sizeof(*map));
1587 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1591 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1592 "logical block %lu\n", inode->i_ino, map->m_len,
1593 (unsigned long) map->m_lblk);
1595 /* Lookup extent status tree firstly */
1596 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1597 if (ext4_es_is_hole(&es)) {
1599 down_read(&EXT4_I(inode)->i_data_sem);
1604 * Delayed extent could be allocated by fallocate.
1605 * So we need to check it.
1607 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1608 map_bh(bh, inode->i_sb, invalid_block);
1610 set_buffer_delay(bh);
1614 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1615 retval = es.es_len - (iblock - es.es_lblk);
1616 if (retval > map->m_len)
1617 retval = map->m_len;
1618 map->m_len = retval;
1619 if (ext4_es_is_written(&es))
1620 map->m_flags |= EXT4_MAP_MAPPED;
1621 else if (ext4_es_is_unwritten(&es))
1622 map->m_flags |= EXT4_MAP_UNWRITTEN;
1626 #ifdef ES_AGGRESSIVE_TEST
1627 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1633 * Try to see if we can get the block without requesting a new
1634 * file system block.
1636 down_read(&EXT4_I(inode)->i_data_sem);
1637 if (ext4_has_inline_data(inode))
1639 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1640 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1642 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1648 * XXX: __block_prepare_write() unmaps passed block,
1652 * If the block was allocated from previously allocated cluster,
1653 * then we don't need to reserve it again. However we still need
1654 * to reserve metadata for every block we're going to write.
1656 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1657 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1658 ret = ext4_da_reserve_space(inode);
1660 /* not enough space to reserve */
1666 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1667 ~0, EXTENT_STATUS_DELAYED);
1673 map_bh(bh, inode->i_sb, invalid_block);
1675 set_buffer_delay(bh);
1676 } else if (retval > 0) {
1678 unsigned int status;
1680 if (unlikely(retval != map->m_len)) {
1681 ext4_warning(inode->i_sb,
1682 "ES len assertion failed for inode "
1683 "%lu: retval %d != map->m_len %d",
1684 inode->i_ino, retval, map->m_len);
1688 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1689 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1690 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1691 map->m_pblk, status);
1697 up_read((&EXT4_I(inode)->i_data_sem));
1703 * This is a special get_block_t callback which is used by
1704 * ext4_da_write_begin(). It will either return mapped block or
1705 * reserve space for a single block.
1707 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1708 * We also have b_blocknr = -1 and b_bdev initialized properly
1710 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1711 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1712 * initialized properly.
1714 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1715 struct buffer_head *bh, int create)
1717 struct ext4_map_blocks map;
1720 BUG_ON(create == 0);
1721 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1723 map.m_lblk = iblock;
1727 * first, we need to know whether the block is allocated already
1728 * preallocated blocks are unmapped but should treated
1729 * the same as allocated blocks.
1731 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1735 map_bh(bh, inode->i_sb, map.m_pblk);
1736 ext4_update_bh_state(bh, map.m_flags);
1738 if (buffer_unwritten(bh)) {
1739 /* A delayed write to unwritten bh should be marked
1740 * new and mapped. Mapped ensures that we don't do
1741 * get_block multiple times when we write to the same
1742 * offset and new ensures that we do proper zero out
1743 * for partial write.
1746 set_buffer_mapped(bh);
1751 static int bget_one(handle_t *handle, struct buffer_head *bh)
1757 static int bput_one(handle_t *handle, struct buffer_head *bh)
1763 static int __ext4_journalled_writepage(struct page *page,
1766 struct address_space *mapping = page->mapping;
1767 struct inode *inode = mapping->host;
1768 struct buffer_head *page_bufs = NULL;
1769 handle_t *handle = NULL;
1770 int ret = 0, err = 0;
1771 int inline_data = ext4_has_inline_data(inode);
1772 struct buffer_head *inode_bh = NULL;
1774 ClearPageChecked(page);
1777 BUG_ON(page->index != 0);
1778 BUG_ON(len > ext4_get_max_inline_size(inode));
1779 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1780 if (inode_bh == NULL)
1783 page_bufs = page_buffers(page);
1788 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1792 * We need to release the page lock before we start the
1793 * journal, so grab a reference so the page won't disappear
1794 * out from under us.
1799 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1800 ext4_writepage_trans_blocks(inode));
1801 if (IS_ERR(handle)) {
1802 ret = PTR_ERR(handle);
1804 goto out_no_pagelock;
1806 BUG_ON(!ext4_handle_valid(handle));
1810 if (page->mapping != mapping) {
1811 /* The page got truncated from under us */
1812 ext4_journal_stop(handle);
1818 BUFFER_TRACE(inode_bh, "get write access");
1819 ret = ext4_journal_get_write_access(handle, inode_bh);
1821 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1824 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1825 do_journal_get_write_access);
1827 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1832 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1833 err = ext4_journal_stop(handle);
1837 if (!ext4_has_inline_data(inode))
1838 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1840 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1849 * Note that we don't need to start a transaction unless we're journaling data
1850 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1851 * need to file the inode to the transaction's list in ordered mode because if
1852 * we are writing back data added by write(), the inode is already there and if
1853 * we are writing back data modified via mmap(), no one guarantees in which
1854 * transaction the data will hit the disk. In case we are journaling data, we
1855 * cannot start transaction directly because transaction start ranks above page
1856 * lock so we have to do some magic.
1858 * This function can get called via...
1859 * - ext4_writepages after taking page lock (have journal handle)
1860 * - journal_submit_inode_data_buffers (no journal handle)
1861 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1862 * - grab_page_cache when doing write_begin (have journal handle)
1864 * We don't do any block allocation in this function. If we have page with
1865 * multiple blocks we need to write those buffer_heads that are mapped. This
1866 * is important for mmaped based write. So if we do with blocksize 1K
1867 * truncate(f, 1024);
1868 * a = mmap(f, 0, 4096);
1870 * truncate(f, 4096);
1871 * we have in the page first buffer_head mapped via page_mkwrite call back
1872 * but other buffer_heads would be unmapped but dirty (dirty done via the
1873 * do_wp_page). So writepage should write the first block. If we modify
1874 * the mmap area beyond 1024 we will again get a page_fault and the
1875 * page_mkwrite callback will do the block allocation and mark the
1876 * buffer_heads mapped.
1878 * We redirty the page if we have any buffer_heads that is either delay or
1879 * unwritten in the page.
1881 * We can get recursively called as show below.
1883 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1886 * But since we don't do any block allocation we should not deadlock.
1887 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1889 static int ext4_writepage(struct page *page,
1890 struct writeback_control *wbc)
1895 struct buffer_head *page_bufs = NULL;
1896 struct inode *inode = page->mapping->host;
1897 struct ext4_io_submit io_submit;
1898 bool keep_towrite = false;
1900 trace_ext4_writepage(page);
1901 size = i_size_read(inode);
1902 if (page->index == size >> PAGE_CACHE_SHIFT)
1903 len = size & ~PAGE_CACHE_MASK;
1905 len = PAGE_CACHE_SIZE;
1907 page_bufs = page_buffers(page);
1909 * We cannot do block allocation or other extent handling in this
1910 * function. If there are buffers needing that, we have to redirty
1911 * the page. But we may reach here when we do a journal commit via
1912 * journal_submit_inode_data_buffers() and in that case we must write
1913 * allocated buffers to achieve data=ordered mode guarantees.
1915 * Also, if there is only one buffer per page (the fs block
1916 * size == the page size), if one buffer needs block
1917 * allocation or needs to modify the extent tree to clear the
1918 * unwritten flag, we know that the page can't be written at
1919 * all, so we might as well refuse the write immediately.
1920 * Unfortunately if the block size != page size, we can't as
1921 * easily detect this case using ext4_walk_page_buffers(), but
1922 * for the extremely common case, this is an optimization that
1923 * skips a useless round trip through ext4_bio_write_page().
1925 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1926 ext4_bh_delay_or_unwritten)) {
1927 redirty_page_for_writepage(wbc, page);
1928 if ((current->flags & PF_MEMALLOC) ||
1929 (inode->i_sb->s_blocksize == PAGE_CACHE_SIZE)) {
1931 * For memory cleaning there's no point in writing only
1932 * some buffers. So just bail out. Warn if we came here
1933 * from direct reclaim.
1935 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1940 keep_towrite = true;
1943 if (PageChecked(page) && ext4_should_journal_data(inode))
1945 * It's mmapped pagecache. Add buffers and journal it. There
1946 * doesn't seem much point in redirtying the page here.
1948 return __ext4_journalled_writepage(page, len);
1950 ext4_io_submit_init(&io_submit, wbc);
1951 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1952 if (!io_submit.io_end) {
1953 redirty_page_for_writepage(wbc, page);
1957 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1958 ext4_io_submit(&io_submit);
1959 /* Drop io_end reference we got from init */
1960 ext4_put_io_end_defer(io_submit.io_end);
1964 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1967 loff_t size = i_size_read(mpd->inode);
1970 BUG_ON(page->index != mpd->first_page);
1971 if (page->index == size >> PAGE_CACHE_SHIFT)
1972 len = size & ~PAGE_CACHE_MASK;
1974 len = PAGE_CACHE_SIZE;
1975 clear_page_dirty_for_io(page);
1976 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1978 mpd->wbc->nr_to_write--;
1984 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1987 * mballoc gives us at most this number of blocks...
1988 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1989 * The rest of mballoc seems to handle chunks up to full group size.
1991 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1994 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1996 * @mpd - extent of blocks
1997 * @lblk - logical number of the block in the file
1998 * @bh - buffer head we want to add to the extent
2000 * The function is used to collect contig. blocks in the same state. If the
2001 * buffer doesn't require mapping for writeback and we haven't started the
2002 * extent of buffers to map yet, the function returns 'true' immediately - the
2003 * caller can write the buffer right away. Otherwise the function returns true
2004 * if the block has been added to the extent, false if the block couldn't be
2007 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2008 struct buffer_head *bh)
2010 struct ext4_map_blocks *map = &mpd->map;
2012 /* Buffer that doesn't need mapping for writeback? */
2013 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2014 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2015 /* So far no extent to map => we write the buffer right away */
2016 if (map->m_len == 0)
2021 /* First block in the extent? */
2022 if (map->m_len == 0) {
2025 map->m_flags = bh->b_state & BH_FLAGS;
2029 /* Don't go larger than mballoc is willing to allocate */
2030 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2033 /* Can we merge the block to our big extent? */
2034 if (lblk == map->m_lblk + map->m_len &&
2035 (bh->b_state & BH_FLAGS) == map->m_flags) {
2043 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2045 * @mpd - extent of blocks for mapping
2046 * @head - the first buffer in the page
2047 * @bh - buffer we should start processing from
2048 * @lblk - logical number of the block in the file corresponding to @bh
2050 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2051 * the page for IO if all buffers in this page were mapped and there's no
2052 * accumulated extent of buffers to map or add buffers in the page to the
2053 * extent of buffers to map. The function returns 1 if the caller can continue
2054 * by processing the next page, 0 if it should stop adding buffers to the
2055 * extent to map because we cannot extend it anymore. It can also return value
2056 * < 0 in case of error during IO submission.
2058 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2059 struct buffer_head *head,
2060 struct buffer_head *bh,
2063 struct inode *inode = mpd->inode;
2065 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2066 >> inode->i_blkbits;
2069 BUG_ON(buffer_locked(bh));
2071 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2072 /* Found extent to map? */
2075 /* Everything mapped so far and we hit EOF */
2078 } while (lblk++, (bh = bh->b_this_page) != head);
2079 /* So far everything mapped? Submit the page for IO. */
2080 if (mpd->map.m_len == 0) {
2081 err = mpage_submit_page(mpd, head->b_page);
2085 return lblk < blocks;
2089 * mpage_map_buffers - update buffers corresponding to changed extent and
2090 * submit fully mapped pages for IO
2092 * @mpd - description of extent to map, on return next extent to map
2094 * Scan buffers corresponding to changed extent (we expect corresponding pages
2095 * to be already locked) and update buffer state according to new extent state.
2096 * We map delalloc buffers to their physical location, clear unwritten bits,
2097 * and mark buffers as uninit when we perform writes to unwritten extents
2098 * and do extent conversion after IO is finished. If the last page is not fully
2099 * mapped, we update @map to the next extent in the last page that needs
2100 * mapping. Otherwise we submit the page for IO.
2102 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2104 struct pagevec pvec;
2106 struct inode *inode = mpd->inode;
2107 struct buffer_head *head, *bh;
2108 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2114 start = mpd->map.m_lblk >> bpp_bits;
2115 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2116 lblk = start << bpp_bits;
2117 pblock = mpd->map.m_pblk;
2119 pagevec_init(&pvec, 0);
2120 while (start <= end) {
2121 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2125 for (i = 0; i < nr_pages; i++) {
2126 struct page *page = pvec.pages[i];
2128 if (page->index > end)
2130 /* Up to 'end' pages must be contiguous */
2131 BUG_ON(page->index != start);
2132 bh = head = page_buffers(page);
2134 if (lblk < mpd->map.m_lblk)
2136 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2138 * Buffer after end of mapped extent.
2139 * Find next buffer in the page to map.
2142 mpd->map.m_flags = 0;
2144 * FIXME: If dioread_nolock supports
2145 * blocksize < pagesize, we need to make
2146 * sure we add size mapped so far to
2147 * io_end->size as the following call
2148 * can submit the page for IO.
2150 err = mpage_process_page_bufs(mpd, head,
2152 pagevec_release(&pvec);
2157 if (buffer_delay(bh)) {
2158 clear_buffer_delay(bh);
2159 bh->b_blocknr = pblock++;
2161 clear_buffer_unwritten(bh);
2162 } while (lblk++, (bh = bh->b_this_page) != head);
2165 * FIXME: This is going to break if dioread_nolock
2166 * supports blocksize < pagesize as we will try to
2167 * convert potentially unmapped parts of inode.
2169 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2170 /* Page fully mapped - let IO run! */
2171 err = mpage_submit_page(mpd, page);
2173 pagevec_release(&pvec);
2178 pagevec_release(&pvec);
2180 /* Extent fully mapped and matches with page boundary. We are done. */
2182 mpd->map.m_flags = 0;
2186 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2188 struct inode *inode = mpd->inode;
2189 struct ext4_map_blocks *map = &mpd->map;
2190 int get_blocks_flags;
2191 int err, dioread_nolock;
2193 trace_ext4_da_write_pages_extent(inode, map);
2195 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2196 * to convert an unwritten extent to be initialized (in the case
2197 * where we have written into one or more preallocated blocks). It is
2198 * possible that we're going to need more metadata blocks than
2199 * previously reserved. However we must not fail because we're in
2200 * writeback and there is nothing we can do about it so it might result
2201 * in data loss. So use reserved blocks to allocate metadata if
2204 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2205 * the blocks in question are delalloc blocks. This indicates
2206 * that the blocks and quotas has already been checked when
2207 * the data was copied into the page cache.
2209 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2210 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2211 dioread_nolock = ext4_should_dioread_nolock(inode);
2213 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2214 if (map->m_flags & (1 << BH_Delay))
2215 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2217 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2220 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2221 if (!mpd->io_submit.io_end->handle &&
2222 ext4_handle_valid(handle)) {
2223 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2224 handle->h_rsv_handle = NULL;
2226 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2229 BUG_ON(map->m_len == 0);
2230 if (map->m_flags & EXT4_MAP_NEW) {
2231 struct block_device *bdev = inode->i_sb->s_bdev;
2234 for (i = 0; i < map->m_len; i++)
2235 unmap_underlying_metadata(bdev, map->m_pblk + i);
2241 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2242 * mpd->len and submit pages underlying it for IO
2244 * @handle - handle for journal operations
2245 * @mpd - extent to map
2246 * @give_up_on_write - we set this to true iff there is a fatal error and there
2247 * is no hope of writing the data. The caller should discard
2248 * dirty pages to avoid infinite loops.
2250 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2251 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2252 * them to initialized or split the described range from larger unwritten
2253 * extent. Note that we need not map all the described range since allocation
2254 * can return less blocks or the range is covered by more unwritten extents. We
2255 * cannot map more because we are limited by reserved transaction credits. On
2256 * the other hand we always make sure that the last touched page is fully
2257 * mapped so that it can be written out (and thus forward progress is
2258 * guaranteed). After mapping we submit all mapped pages for IO.
2260 static int mpage_map_and_submit_extent(handle_t *handle,
2261 struct mpage_da_data *mpd,
2262 bool *give_up_on_write)
2264 struct inode *inode = mpd->inode;
2265 struct ext4_map_blocks *map = &mpd->map;
2270 mpd->io_submit.io_end->offset =
2271 ((loff_t)map->m_lblk) << inode->i_blkbits;
2273 err = mpage_map_one_extent(handle, mpd);
2275 struct super_block *sb = inode->i_sb;
2277 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2278 goto invalidate_dirty_pages;
2280 * Let the uper layers retry transient errors.
2281 * In the case of ENOSPC, if ext4_count_free_blocks()
2282 * is non-zero, a commit should free up blocks.
2284 if ((err == -ENOMEM) ||
2285 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2287 goto update_disksize;
2290 ext4_msg(sb, KERN_CRIT,
2291 "Delayed block allocation failed for "
2292 "inode %lu at logical offset %llu with"
2293 " max blocks %u with error %d",
2295 (unsigned long long)map->m_lblk,
2296 (unsigned)map->m_len, -err);
2297 ext4_msg(sb, KERN_CRIT,
2298 "This should not happen!! Data will "
2301 ext4_print_free_blocks(inode);
2302 invalidate_dirty_pages:
2303 *give_up_on_write = true;
2308 * Update buffer state, submit mapped pages, and get us new
2311 err = mpage_map_and_submit_buffers(mpd);
2313 goto update_disksize;
2314 } while (map->m_len);
2318 * Update on-disk size after IO is submitted. Races with
2319 * truncate are avoided by checking i_size under i_data_sem.
2321 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2322 if (disksize > EXT4_I(inode)->i_disksize) {
2326 down_write(&EXT4_I(inode)->i_data_sem);
2327 i_size = i_size_read(inode);
2328 if (disksize > i_size)
2330 if (disksize > EXT4_I(inode)->i_disksize)
2331 EXT4_I(inode)->i_disksize = disksize;
2332 err2 = ext4_mark_inode_dirty(handle, inode);
2333 up_write(&EXT4_I(inode)->i_data_sem);
2335 ext4_error(inode->i_sb,
2336 "Failed to mark inode %lu dirty",
2345 * Calculate the total number of credits to reserve for one writepages
2346 * iteration. This is called from ext4_writepages(). We map an extent of
2347 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2348 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2349 * bpp - 1 blocks in bpp different extents.
2351 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2353 int bpp = ext4_journal_blocks_per_page(inode);
2355 return ext4_meta_trans_blocks(inode,
2356 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2360 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2361 * and underlying extent to map
2363 * @mpd - where to look for pages
2365 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2366 * IO immediately. When we find a page which isn't mapped we start accumulating
2367 * extent of buffers underlying these pages that needs mapping (formed by
2368 * either delayed or unwritten buffers). We also lock the pages containing
2369 * these buffers. The extent found is returned in @mpd structure (starting at
2370 * mpd->lblk with length mpd->len blocks).
2372 * Note that this function can attach bios to one io_end structure which are
2373 * neither logically nor physically contiguous. Although it may seem as an
2374 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2375 * case as we need to track IO to all buffers underlying a page in one io_end.
2377 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2379 struct address_space *mapping = mpd->inode->i_mapping;
2380 struct pagevec pvec;
2381 unsigned int nr_pages;
2382 long left = mpd->wbc->nr_to_write;
2383 pgoff_t index = mpd->first_page;
2384 pgoff_t end = mpd->last_page;
2387 int blkbits = mpd->inode->i_blkbits;
2389 struct buffer_head *head;
2391 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2392 tag = PAGECACHE_TAG_TOWRITE;
2394 tag = PAGECACHE_TAG_DIRTY;
2396 pagevec_init(&pvec, 0);
2398 mpd->next_page = index;
2399 while (index <= end) {
2400 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2401 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2405 for (i = 0; i < nr_pages; i++) {
2406 struct page *page = pvec.pages[i];
2409 * At this point, the page may be truncated or
2410 * invalidated (changing page->mapping to NULL), or
2411 * even swizzled back from swapper_space to tmpfs file
2412 * mapping. However, page->index will not change
2413 * because we have a reference on the page.
2415 if (page->index > end)
2419 * Accumulated enough dirty pages? This doesn't apply
2420 * to WB_SYNC_ALL mode. For integrity sync we have to
2421 * keep going because someone may be concurrently
2422 * dirtying pages, and we might have synced a lot of
2423 * newly appeared dirty pages, but have not synced all
2424 * of the old dirty pages.
2426 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2429 /* If we can't merge this page, we are done. */
2430 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2435 * If the page is no longer dirty, or its mapping no
2436 * longer corresponds to inode we are writing (which
2437 * means it has been truncated or invalidated), or the
2438 * page is already under writeback and we are not doing
2439 * a data integrity writeback, skip the page
2441 if (!PageDirty(page) ||
2442 (PageWriteback(page) &&
2443 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2444 unlikely(page->mapping != mapping)) {
2449 wait_on_page_writeback(page);
2450 BUG_ON(PageWriteback(page));
2452 if (mpd->map.m_len == 0)
2453 mpd->first_page = page->index;
2454 mpd->next_page = page->index + 1;
2455 /* Add all dirty buffers to mpd */
2456 lblk = ((ext4_lblk_t)page->index) <<
2457 (PAGE_CACHE_SHIFT - blkbits);
2458 head = page_buffers(page);
2459 err = mpage_process_page_bufs(mpd, head, head, lblk);
2465 pagevec_release(&pvec);
2470 pagevec_release(&pvec);
2474 static int __writepage(struct page *page, struct writeback_control *wbc,
2477 struct address_space *mapping = data;
2478 int ret = ext4_writepage(page, wbc);
2479 mapping_set_error(mapping, ret);
2483 static int ext4_writepages(struct address_space *mapping,
2484 struct writeback_control *wbc)
2486 pgoff_t writeback_index = 0;
2487 long nr_to_write = wbc->nr_to_write;
2488 int range_whole = 0;
2490 handle_t *handle = NULL;
2491 struct mpage_da_data mpd;
2492 struct inode *inode = mapping->host;
2493 int needed_blocks, rsv_blocks = 0, ret = 0;
2494 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2496 struct blk_plug plug;
2497 bool give_up_on_write = false;
2499 trace_ext4_writepages(inode, wbc);
2502 * No pages to write? This is mainly a kludge to avoid starting
2503 * a transaction for special inodes like journal inode on last iput()
2504 * because that could violate lock ordering on umount
2506 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2507 goto out_writepages;
2509 if (ext4_should_journal_data(inode)) {
2510 struct blk_plug plug;
2512 blk_start_plug(&plug);
2513 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2514 blk_finish_plug(&plug);
2515 goto out_writepages;
2519 * If the filesystem has aborted, it is read-only, so return
2520 * right away instead of dumping stack traces later on that
2521 * will obscure the real source of the problem. We test
2522 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2523 * the latter could be true if the filesystem is mounted
2524 * read-only, and in that case, ext4_writepages should
2525 * *never* be called, so if that ever happens, we would want
2528 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2530 goto out_writepages;
2533 if (ext4_should_dioread_nolock(inode)) {
2535 * We may need to convert up to one extent per block in
2536 * the page and we may dirty the inode.
2538 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2542 * If we have inline data and arrive here, it means that
2543 * we will soon create the block for the 1st page, so
2544 * we'd better clear the inline data here.
2546 if (ext4_has_inline_data(inode)) {
2547 /* Just inode will be modified... */
2548 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2549 if (IS_ERR(handle)) {
2550 ret = PTR_ERR(handle);
2551 goto out_writepages;
2553 BUG_ON(ext4_test_inode_state(inode,
2554 EXT4_STATE_MAY_INLINE_DATA));
2555 ext4_destroy_inline_data(handle, inode);
2556 ext4_journal_stop(handle);
2559 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2562 if (wbc->range_cyclic) {
2563 writeback_index = mapping->writeback_index;
2564 if (writeback_index)
2566 mpd.first_page = writeback_index;
2569 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2570 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2575 ext4_io_submit_init(&mpd.io_submit, wbc);
2577 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2578 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2580 blk_start_plug(&plug);
2581 while (!done && mpd.first_page <= mpd.last_page) {
2582 /* For each extent of pages we use new io_end */
2583 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2584 if (!mpd.io_submit.io_end) {
2590 * We have two constraints: We find one extent to map and we
2591 * must always write out whole page (makes a difference when
2592 * blocksize < pagesize) so that we don't block on IO when we
2593 * try to write out the rest of the page. Journalled mode is
2594 * not supported by delalloc.
2596 BUG_ON(ext4_should_journal_data(inode));
2597 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2599 /* start a new transaction */
2600 handle = ext4_journal_start_with_reserve(inode,
2601 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2602 if (IS_ERR(handle)) {
2603 ret = PTR_ERR(handle);
2604 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2605 "%ld pages, ino %lu; err %d", __func__,
2606 wbc->nr_to_write, inode->i_ino, ret);
2607 /* Release allocated io_end */
2608 ext4_put_io_end(mpd.io_submit.io_end);
2612 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2613 ret = mpage_prepare_extent_to_map(&mpd);
2616 ret = mpage_map_and_submit_extent(handle, &mpd,
2620 * We scanned the whole range (or exhausted
2621 * nr_to_write), submitted what was mapped and
2622 * didn't find anything needing mapping. We are
2629 * Caution: If the handle is synchronous,
2630 * ext4_journal_stop() can wait for transaction commit
2631 * to finish which may depend on writeback of pages to
2632 * complete or on page lock to be released. In that
2633 * case, we have to wait until after after we have
2634 * submitted all the IO, released page locks we hold,
2635 * and dropped io_end reference (for extent conversion
2636 * to be able to complete) before stopping the handle.
2638 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2639 ext4_journal_stop(handle);
2642 /* Submit prepared bio */
2643 ext4_io_submit(&mpd.io_submit);
2644 /* Unlock pages we didn't use */
2645 mpage_release_unused_pages(&mpd, give_up_on_write);
2647 * Drop our io_end reference we got from init. We have
2648 * to be careful and use deferred io_end finishing if
2649 * we are still holding the transaction as we can
2650 * release the last reference to io_end which may end
2651 * up doing unwritten extent conversion.
2654 ext4_put_io_end_defer(mpd.io_submit.io_end);
2655 ext4_journal_stop(handle);
2657 ext4_put_io_end(mpd.io_submit.io_end);
2659 if (ret == -ENOSPC && sbi->s_journal) {
2661 * Commit the transaction which would
2662 * free blocks released in the transaction
2665 jbd2_journal_force_commit_nested(sbi->s_journal);
2669 /* Fatal error - ENOMEM, EIO... */
2673 blk_finish_plug(&plug);
2674 if (!ret && !cycled && wbc->nr_to_write > 0) {
2676 mpd.last_page = writeback_index - 1;
2682 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2684 * Set the writeback_index so that range_cyclic
2685 * mode will write it back later
2687 mapping->writeback_index = mpd.first_page;
2690 trace_ext4_writepages_result(inode, wbc, ret,
2691 nr_to_write - wbc->nr_to_write);
2695 static int ext4_nonda_switch(struct super_block *sb)
2697 s64 free_clusters, dirty_clusters;
2698 struct ext4_sb_info *sbi = EXT4_SB(sb);
2701 * switch to non delalloc mode if we are running low
2702 * on free block. The free block accounting via percpu
2703 * counters can get slightly wrong with percpu_counter_batch getting
2704 * accumulated on each CPU without updating global counters
2705 * Delalloc need an accurate free block accounting. So switch
2706 * to non delalloc when we are near to error range.
2709 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2711 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2713 * Start pushing delalloc when 1/2 of free blocks are dirty.
2715 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2716 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2718 if (2 * free_clusters < 3 * dirty_clusters ||
2719 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2721 * free block count is less than 150% of dirty blocks
2722 * or free blocks is less than watermark
2729 /* We always reserve for an inode update; the superblock could be there too */
2730 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2732 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2735 if (pos + len <= 0x7fffffffULL)
2738 /* We might need to update the superblock to set LARGE_FILE */
2742 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2743 loff_t pos, unsigned len, unsigned flags,
2744 struct page **pagep, void **fsdata)
2746 int ret, retries = 0;
2749 struct inode *inode = mapping->host;
2752 index = pos >> PAGE_CACHE_SHIFT;
2754 if (ext4_nonda_switch(inode->i_sb)) {
2755 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2756 return ext4_write_begin(file, mapping, pos,
2757 len, flags, pagep, fsdata);
2759 *fsdata = (void *)0;
2760 if (trace_android_fs_datawrite_start_enabled()) {
2761 char *path, pathbuf[MAX_TRACE_PATHBUF_LEN];
2763 path = android_fstrace_get_pathname(pathbuf,
2764 MAX_TRACE_PATHBUF_LEN,
2766 trace_android_fs_datawrite_start(inode, pos, len,
2768 path, current->comm);
2770 trace_ext4_da_write_begin(inode, pos, len, flags);
2772 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2773 ret = ext4_da_write_inline_data_begin(mapping, inode,
2783 * grab_cache_page_write_begin() can take a long time if the
2784 * system is thrashing due to memory pressure, or if the page
2785 * is being written back. So grab it first before we start
2786 * the transaction handle. This also allows us to allocate
2787 * the page (if needed) without using GFP_NOFS.
2790 page = grab_cache_page_write_begin(mapping, index, flags);
2796 * With delayed allocation, we don't log the i_disksize update
2797 * if there is delayed block allocation. But we still need
2798 * to journalling the i_disksize update if writes to the end
2799 * of file which has an already mapped buffer.
2802 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2803 ext4_da_write_credits(inode, pos, len));
2804 if (IS_ERR(handle)) {
2805 page_cache_release(page);
2806 return PTR_ERR(handle);
2810 if (page->mapping != mapping) {
2811 /* The page got truncated from under us */
2813 page_cache_release(page);
2814 ext4_journal_stop(handle);
2817 /* In case writeback began while the page was unlocked */
2818 wait_for_stable_page(page);
2820 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2821 ret = ext4_block_write_begin(page, pos, len,
2822 ext4_da_get_block_prep);
2824 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2828 ext4_journal_stop(handle);
2830 * block_write_begin may have instantiated a few blocks
2831 * outside i_size. Trim these off again. Don't need
2832 * i_size_read because we hold i_mutex.
2834 if (pos + len > inode->i_size)
2835 ext4_truncate_failed_write(inode);
2837 if (ret == -ENOSPC &&
2838 ext4_should_retry_alloc(inode->i_sb, &retries))
2841 page_cache_release(page);
2850 * Check if we should update i_disksize
2851 * when write to the end of file but not require block allocation
2853 static int ext4_da_should_update_i_disksize(struct page *page,
2854 unsigned long offset)
2856 struct buffer_head *bh;
2857 struct inode *inode = page->mapping->host;
2861 bh = page_buffers(page);
2862 idx = offset >> inode->i_blkbits;
2864 for (i = 0; i < idx; i++)
2865 bh = bh->b_this_page;
2867 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2872 static int ext4_da_write_end(struct file *file,
2873 struct address_space *mapping,
2874 loff_t pos, unsigned len, unsigned copied,
2875 struct page *page, void *fsdata)
2877 struct inode *inode = mapping->host;
2879 handle_t *handle = ext4_journal_current_handle();
2881 unsigned long start, end;
2882 int write_mode = (int)(unsigned long)fsdata;
2884 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2885 return ext4_write_end(file, mapping, pos,
2886 len, copied, page, fsdata);
2888 trace_android_fs_datawrite_end(inode, pos, len);
2889 trace_ext4_da_write_end(inode, pos, len, copied);
2890 start = pos & (PAGE_CACHE_SIZE - 1);
2891 end = start + copied - 1;
2894 * generic_write_end() will run mark_inode_dirty() if i_size
2895 * changes. So let's piggyback the i_disksize mark_inode_dirty
2898 new_i_size = pos + copied;
2899 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2900 if (ext4_has_inline_data(inode) ||
2901 ext4_da_should_update_i_disksize(page, end)) {
2902 ext4_update_i_disksize(inode, new_i_size);
2903 /* We need to mark inode dirty even if
2904 * new_i_size is less that inode->i_size
2905 * bu greater than i_disksize.(hint delalloc)
2907 ext4_mark_inode_dirty(handle, inode);
2911 if (write_mode != CONVERT_INLINE_DATA &&
2912 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2913 ext4_has_inline_data(inode))
2914 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2917 ret2 = generic_write_end(file, mapping, pos, len, copied,
2923 ret2 = ext4_journal_stop(handle);
2927 return ret ? ret : copied;
2930 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2931 unsigned int length)
2934 * Drop reserved blocks
2936 BUG_ON(!PageLocked(page));
2937 if (!page_has_buffers(page))
2940 ext4_da_page_release_reservation(page, offset, length);
2943 ext4_invalidatepage(page, offset, length);
2949 * Force all delayed allocation blocks to be allocated for a given inode.
2951 int ext4_alloc_da_blocks(struct inode *inode)
2953 trace_ext4_alloc_da_blocks(inode);
2955 if (!EXT4_I(inode)->i_reserved_data_blocks)
2959 * We do something simple for now. The filemap_flush() will
2960 * also start triggering a write of the data blocks, which is
2961 * not strictly speaking necessary (and for users of
2962 * laptop_mode, not even desirable). However, to do otherwise
2963 * would require replicating code paths in:
2965 * ext4_writepages() ->
2966 * write_cache_pages() ---> (via passed in callback function)
2967 * __mpage_da_writepage() -->
2968 * mpage_add_bh_to_extent()
2969 * mpage_da_map_blocks()
2971 * The problem is that write_cache_pages(), located in
2972 * mm/page-writeback.c, marks pages clean in preparation for
2973 * doing I/O, which is not desirable if we're not planning on
2976 * We could call write_cache_pages(), and then redirty all of
2977 * the pages by calling redirty_page_for_writepage() but that
2978 * would be ugly in the extreme. So instead we would need to
2979 * replicate parts of the code in the above functions,
2980 * simplifying them because we wouldn't actually intend to
2981 * write out the pages, but rather only collect contiguous
2982 * logical block extents, call the multi-block allocator, and
2983 * then update the buffer heads with the block allocations.
2985 * For now, though, we'll cheat by calling filemap_flush(),
2986 * which will map the blocks, and start the I/O, but not
2987 * actually wait for the I/O to complete.
2989 return filemap_flush(inode->i_mapping);
2993 * bmap() is special. It gets used by applications such as lilo and by
2994 * the swapper to find the on-disk block of a specific piece of data.
2996 * Naturally, this is dangerous if the block concerned is still in the
2997 * journal. If somebody makes a swapfile on an ext4 data-journaling
2998 * filesystem and enables swap, then they may get a nasty shock when the
2999 * data getting swapped to that swapfile suddenly gets overwritten by
3000 * the original zero's written out previously to the journal and
3001 * awaiting writeback in the kernel's buffer cache.
3003 * So, if we see any bmap calls here on a modified, data-journaled file,
3004 * take extra steps to flush any blocks which might be in the cache.
3006 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3008 struct inode *inode = mapping->host;
3013 * We can get here for an inline file via the FIBMAP ioctl
3015 if (ext4_has_inline_data(inode))
3018 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3019 test_opt(inode->i_sb, DELALLOC)) {
3021 * With delalloc we want to sync the file
3022 * so that we can make sure we allocate
3025 filemap_write_and_wait(mapping);
3028 if (EXT4_JOURNAL(inode) &&
3029 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3031 * This is a REALLY heavyweight approach, but the use of
3032 * bmap on dirty files is expected to be extremely rare:
3033 * only if we run lilo or swapon on a freshly made file
3034 * do we expect this to happen.
3036 * (bmap requires CAP_SYS_RAWIO so this does not
3037 * represent an unprivileged user DOS attack --- we'd be
3038 * in trouble if mortal users could trigger this path at
3041 * NB. EXT4_STATE_JDATA is not set on files other than
3042 * regular files. If somebody wants to bmap a directory
3043 * or symlink and gets confused because the buffer
3044 * hasn't yet been flushed to disk, they deserve
3045 * everything they get.
3048 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3049 journal = EXT4_JOURNAL(inode);
3050 jbd2_journal_lock_updates(journal);
3051 err = jbd2_journal_flush(journal);
3052 jbd2_journal_unlock_updates(journal);
3058 return generic_block_bmap(mapping, block, ext4_get_block);
3061 static int ext4_readpage(struct file *file, struct page *page)
3064 struct inode *inode = page->mapping->host;
3066 trace_ext4_readpage(page);
3068 if (ext4_has_inline_data(inode))
3069 ret = ext4_readpage_inline(inode, page);
3072 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3078 ext4_readpages(struct file *file, struct address_space *mapping,
3079 struct list_head *pages, unsigned nr_pages)
3081 struct inode *inode = mapping->host;
3083 /* If the file has inline data, no need to do readpages. */
3084 if (ext4_has_inline_data(inode))
3087 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3090 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3091 unsigned int length)
3093 trace_ext4_invalidatepage(page, offset, length);
3095 /* No journalling happens on data buffers when this function is used */
3096 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3098 block_invalidatepage(page, offset, length);
3101 static int __ext4_journalled_invalidatepage(struct page *page,
3102 unsigned int offset,
3103 unsigned int length)
3105 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3107 trace_ext4_journalled_invalidatepage(page, offset, length);
3110 * If it's a full truncate we just forget about the pending dirtying
3112 if (offset == 0 && length == PAGE_CACHE_SIZE)
3113 ClearPageChecked(page);
3115 return jbd2_journal_invalidatepage(journal, page, offset, length);
3118 /* Wrapper for aops... */
3119 static void ext4_journalled_invalidatepage(struct page *page,
3120 unsigned int offset,
3121 unsigned int length)
3123 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3126 static int ext4_releasepage(struct page *page, gfp_t wait)
3128 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3130 trace_ext4_releasepage(page);
3132 /* Page has dirty journalled data -> cannot release */
3133 if (PageChecked(page))
3136 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3138 return try_to_free_buffers(page);
3142 * ext4_get_block used when preparing for a DIO write or buffer write.
3143 * We allocate an uinitialized extent if blocks haven't been allocated.
3144 * The extent will be converted to initialized after the IO is complete.
3146 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3147 struct buffer_head *bh_result, int create)
3149 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3150 inode->i_ino, create);
3151 return _ext4_get_block(inode, iblock, bh_result,
3152 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3155 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3156 struct buffer_head *bh_result, int create)
3158 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3159 inode->i_ino, create);
3160 return _ext4_get_block(inode, iblock, bh_result,
3161 EXT4_GET_BLOCKS_NO_LOCK);
3164 int ext4_get_block_dax(struct inode *inode, sector_t iblock,
3165 struct buffer_head *bh_result, int create)
3167 int flags = EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_UNWRIT_EXT;
3169 flags |= EXT4_GET_BLOCKS_CREATE;
3170 ext4_debug("ext4_get_block_dax: inode %lu, create flag %d\n",
3171 inode->i_ino, create);
3172 return _ext4_get_block(inode, iblock, bh_result, flags);
3175 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3176 ssize_t size, void *private)
3178 ext4_io_end_t *io_end = iocb->private;
3180 /* if not async direct IO just return */
3184 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3185 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3186 iocb->private, io_end->inode->i_ino, iocb, offset,
3189 iocb->private = NULL;
3190 io_end->offset = offset;
3191 io_end->size = size;
3192 ext4_put_io_end(io_end);
3196 * For ext4 extent files, ext4 will do direct-io write to holes,
3197 * preallocated extents, and those write extend the file, no need to
3198 * fall back to buffered IO.
3200 * For holes, we fallocate those blocks, mark them as unwritten
3201 * If those blocks were preallocated, we mark sure they are split, but
3202 * still keep the range to write as unwritten.
3204 * The unwritten extents will be converted to written when DIO is completed.
3205 * For async direct IO, since the IO may still pending when return, we
3206 * set up an end_io call back function, which will do the conversion
3207 * when async direct IO completed.
3209 * If the O_DIRECT write will extend the file then add this inode to the
3210 * orphan list. So recovery will truncate it back to the original size
3211 * if the machine crashes during the write.
3214 static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3217 struct file *file = iocb->ki_filp;
3218 struct inode *inode = file->f_mapping->host;
3220 size_t count = iov_iter_count(iter);
3222 get_block_t *get_block_func = NULL;
3224 loff_t final_size = offset + count;
3225 ext4_io_end_t *io_end = NULL;
3227 /* Use the old path for reads and writes beyond i_size. */
3228 if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size)
3229 return ext4_ind_direct_IO(iocb, iter, offset);
3231 BUG_ON(iocb->private == NULL);
3234 * Make all waiters for direct IO properly wait also for extent
3235 * conversion. This also disallows race between truncate() and
3236 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3238 if (iov_iter_rw(iter) == WRITE)
3239 inode_dio_begin(inode);
3241 /* If we do a overwrite dio, i_mutex locking can be released */
3242 overwrite = *((int *)iocb->private);
3245 down_read(&EXT4_I(inode)->i_data_sem);
3246 mutex_unlock(&inode->i_mutex);
3250 * We could direct write to holes and fallocate.
3252 * Allocated blocks to fill the hole are marked as
3253 * unwritten to prevent parallel buffered read to expose
3254 * the stale data before DIO complete the data IO.
3256 * As to previously fallocated extents, ext4 get_block will
3257 * just simply mark the buffer mapped but still keep the
3258 * extents unwritten.
3260 * For non AIO case, we will convert those unwritten extents
3261 * to written after return back from blockdev_direct_IO.
3263 * For async DIO, the conversion needs to be deferred when the
3264 * IO is completed. The ext4 end_io callback function will be
3265 * called to take care of the conversion work. Here for async
3266 * case, we allocate an io_end structure to hook to the iocb.
3268 iocb->private = NULL;
3269 ext4_inode_aio_set(inode, NULL);
3270 if (!is_sync_kiocb(iocb)) {
3271 io_end = ext4_init_io_end(inode, GFP_NOFS);
3277 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
3279 iocb->private = ext4_get_io_end(io_end);
3281 * we save the io structure for current async direct
3282 * IO, so that later ext4_map_blocks() could flag the
3283 * io structure whether there is a unwritten extents
3284 * needs to be converted when IO is completed.
3286 ext4_inode_aio_set(inode, io_end);
3290 get_block_func = ext4_get_block_write_nolock;
3292 get_block_func = ext4_get_block_write;
3293 dio_flags = DIO_LOCKING;
3295 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3296 BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
3299 ret = dax_do_io(iocb, inode, iter, offset, get_block_func,
3300 ext4_end_io_dio, dio_flags);
3302 ret = __blockdev_direct_IO(iocb, inode,
3303 inode->i_sb->s_bdev, iter, offset,
3305 ext4_end_io_dio, NULL, dio_flags);
3308 * Put our reference to io_end. This can free the io_end structure e.g.
3309 * in sync IO case or in case of error. It can even perform extent
3310 * conversion if all bios we submitted finished before we got here.
3311 * Note that in that case iocb->private can be already set to NULL
3315 ext4_inode_aio_set(inode, NULL);
3316 ext4_put_io_end(io_end);
3318 * When no IO was submitted ext4_end_io_dio() was not
3319 * called so we have to put iocb's reference.
3321 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3322 WARN_ON(iocb->private != io_end);
3323 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3324 ext4_put_io_end(io_end);
3325 iocb->private = NULL;
3328 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3329 EXT4_STATE_DIO_UNWRITTEN)) {
3332 * for non AIO case, since the IO is already
3333 * completed, we could do the conversion right here
3335 err = ext4_convert_unwritten_extents(NULL, inode,
3339 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3343 if (iov_iter_rw(iter) == WRITE)
3344 inode_dio_end(inode);
3345 /* take i_mutex locking again if we do a ovewrite dio */
3347 up_read(&EXT4_I(inode)->i_data_sem);
3348 mutex_lock(&inode->i_mutex);
3354 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3357 struct file *file = iocb->ki_filp;
3358 struct inode *inode = file->f_mapping->host;
3359 size_t count = iov_iter_count(iter);
3362 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3363 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3368 * If we are doing data journalling we don't support O_DIRECT
3370 if (ext4_should_journal_data(inode))
3373 /* Let buffer I/O handle the inline data case. */
3374 if (ext4_has_inline_data(inode))
3377 if (trace_android_fs_dataread_start_enabled() &&
3378 (iov_iter_rw(iter) == READ)) {
3379 char *path, pathbuf[MAX_TRACE_PATHBUF_LEN];
3381 path = android_fstrace_get_pathname(pathbuf,
3382 MAX_TRACE_PATHBUF_LEN,
3384 trace_android_fs_dataread_start(inode, offset, count,
3388 if (trace_android_fs_datawrite_start_enabled() &&
3389 (iov_iter_rw(iter) == WRITE)) {
3390 char *path, pathbuf[MAX_TRACE_PATHBUF_LEN];
3392 path = android_fstrace_get_pathname(pathbuf,
3393 MAX_TRACE_PATHBUF_LEN,
3395 trace_android_fs_datawrite_start(inode, offset, count,
3399 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3400 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3401 ret = ext4_ext_direct_IO(iocb, iter, offset);
3403 ret = ext4_ind_direct_IO(iocb, iter, offset);
3404 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3406 if (trace_android_fs_dataread_start_enabled() &&
3407 (iov_iter_rw(iter) == READ))
3408 trace_android_fs_dataread_end(inode, offset, count);
3409 if (trace_android_fs_datawrite_start_enabled() &&
3410 (iov_iter_rw(iter) == WRITE))
3411 trace_android_fs_datawrite_end(inode, offset, count);
3417 * Pages can be marked dirty completely asynchronously from ext4's journalling
3418 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3419 * much here because ->set_page_dirty is called under VFS locks. The page is
3420 * not necessarily locked.
3422 * We cannot just dirty the page and leave attached buffers clean, because the
3423 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3424 * or jbddirty because all the journalling code will explode.
3426 * So what we do is to mark the page "pending dirty" and next time writepage
3427 * is called, propagate that into the buffers appropriately.
3429 static int ext4_journalled_set_page_dirty(struct page *page)
3431 SetPageChecked(page);
3432 return __set_page_dirty_nobuffers(page);
3435 static const struct address_space_operations ext4_aops = {
3436 .readpage = ext4_readpage,
3437 .readpages = ext4_readpages,
3438 .writepage = ext4_writepage,
3439 .writepages = ext4_writepages,
3440 .write_begin = ext4_write_begin,
3441 .write_end = ext4_write_end,
3443 .invalidatepage = ext4_invalidatepage,
3444 .releasepage = ext4_releasepage,
3445 .direct_IO = ext4_direct_IO,
3446 .migratepage = buffer_migrate_page,
3447 .is_partially_uptodate = block_is_partially_uptodate,
3448 .error_remove_page = generic_error_remove_page,
3451 static const struct address_space_operations ext4_journalled_aops = {
3452 .readpage = ext4_readpage,
3453 .readpages = ext4_readpages,
3454 .writepage = ext4_writepage,
3455 .writepages = ext4_writepages,
3456 .write_begin = ext4_write_begin,
3457 .write_end = ext4_journalled_write_end,
3458 .set_page_dirty = ext4_journalled_set_page_dirty,
3460 .invalidatepage = ext4_journalled_invalidatepage,
3461 .releasepage = ext4_releasepage,
3462 .direct_IO = ext4_direct_IO,
3463 .is_partially_uptodate = block_is_partially_uptodate,
3464 .error_remove_page = generic_error_remove_page,
3467 static const struct address_space_operations ext4_da_aops = {
3468 .readpage = ext4_readpage,
3469 .readpages = ext4_readpages,
3470 .writepage = ext4_writepage,
3471 .writepages = ext4_writepages,
3472 .write_begin = ext4_da_write_begin,
3473 .write_end = ext4_da_write_end,
3475 .invalidatepage = ext4_da_invalidatepage,
3476 .releasepage = ext4_releasepage,
3477 .direct_IO = ext4_direct_IO,
3478 .migratepage = buffer_migrate_page,
3479 .is_partially_uptodate = block_is_partially_uptodate,
3480 .error_remove_page = generic_error_remove_page,
3483 void ext4_set_aops(struct inode *inode)
3485 switch (ext4_inode_journal_mode(inode)) {
3486 case EXT4_INODE_ORDERED_DATA_MODE:
3487 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3489 case EXT4_INODE_WRITEBACK_DATA_MODE:
3490 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3492 case EXT4_INODE_JOURNAL_DATA_MODE:
3493 inode->i_mapping->a_ops = &ext4_journalled_aops;
3498 if (test_opt(inode->i_sb, DELALLOC))
3499 inode->i_mapping->a_ops = &ext4_da_aops;
3501 inode->i_mapping->a_ops = &ext4_aops;
3504 static int __ext4_block_zero_page_range(handle_t *handle,
3505 struct address_space *mapping, loff_t from, loff_t length)
3507 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3508 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3509 unsigned blocksize, pos;
3511 struct inode *inode = mapping->host;
3512 struct buffer_head *bh;
3516 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3517 mapping_gfp_constraint(mapping, ~__GFP_FS));
3521 blocksize = inode->i_sb->s_blocksize;
3523 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3525 if (!page_has_buffers(page))
3526 create_empty_buffers(page, blocksize, 0);
3528 /* Find the buffer that contains "offset" */
3529 bh = page_buffers(page);
3531 while (offset >= pos) {
3532 bh = bh->b_this_page;
3536 if (buffer_freed(bh)) {
3537 BUFFER_TRACE(bh, "freed: skip");
3540 if (!buffer_mapped(bh)) {
3541 BUFFER_TRACE(bh, "unmapped");
3542 ext4_get_block(inode, iblock, bh, 0);
3543 /* unmapped? It's a hole - nothing to do */
3544 if (!buffer_mapped(bh)) {
3545 BUFFER_TRACE(bh, "still unmapped");
3550 /* Ok, it's mapped. Make sure it's up-to-date */
3551 if (PageUptodate(page))
3552 set_buffer_uptodate(bh);
3554 if (!buffer_uptodate(bh)) {
3556 ll_rw_block(READ, 1, &bh);
3558 /* Uhhuh. Read error. Complain and punt. */
3559 if (!buffer_uptodate(bh))
3561 if (S_ISREG(inode->i_mode) &&
3562 ext4_encrypted_inode(inode)) {
3563 /* We expect the key to be set. */
3564 BUG_ON(!ext4_has_encryption_key(inode));
3565 BUG_ON(blocksize != PAGE_CACHE_SIZE);
3566 WARN_ON_ONCE(ext4_decrypt(page));
3569 if (ext4_should_journal_data(inode)) {
3570 BUFFER_TRACE(bh, "get write access");
3571 err = ext4_journal_get_write_access(handle, bh);
3575 zero_user(page, offset, length);
3576 BUFFER_TRACE(bh, "zeroed end of block");
3578 if (ext4_should_journal_data(inode)) {
3579 err = ext4_handle_dirty_metadata(handle, inode, bh);
3582 mark_buffer_dirty(bh);
3583 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3584 err = ext4_jbd2_file_inode(handle, inode);
3589 page_cache_release(page);
3594 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3595 * starting from file offset 'from'. The range to be zero'd must
3596 * be contained with in one block. If the specified range exceeds
3597 * the end of the block it will be shortened to end of the block
3598 * that cooresponds to 'from'
3600 static int ext4_block_zero_page_range(handle_t *handle,
3601 struct address_space *mapping, loff_t from, loff_t length)
3603 struct inode *inode = mapping->host;
3604 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3605 unsigned blocksize = inode->i_sb->s_blocksize;
3606 unsigned max = blocksize - (offset & (blocksize - 1));
3609 * correct length if it does not fall between
3610 * 'from' and the end of the block
3612 if (length > max || length < 0)
3616 return dax_zero_page_range(inode, from, length, ext4_get_block);
3617 return __ext4_block_zero_page_range(handle, mapping, from, length);
3621 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3622 * up to the end of the block which corresponds to `from'.
3623 * This required during truncate. We need to physically zero the tail end
3624 * of that block so it doesn't yield old data if the file is later grown.
3626 static int ext4_block_truncate_page(handle_t *handle,
3627 struct address_space *mapping, loff_t from)
3629 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3632 struct inode *inode = mapping->host;
3634 /* If we are processing an encrypted inode during orphan list handling */
3635 if (ext4_encrypted_inode(inode) && !ext4_has_encryption_key(inode))
3638 blocksize = inode->i_sb->s_blocksize;
3639 length = blocksize - (offset & (blocksize - 1));
3641 return ext4_block_zero_page_range(handle, mapping, from, length);
3644 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3645 loff_t lstart, loff_t length)
3647 struct super_block *sb = inode->i_sb;
3648 struct address_space *mapping = inode->i_mapping;
3649 unsigned partial_start, partial_end;
3650 ext4_fsblk_t start, end;
3651 loff_t byte_end = (lstart + length - 1);
3654 partial_start = lstart & (sb->s_blocksize - 1);
3655 partial_end = byte_end & (sb->s_blocksize - 1);
3657 start = lstart >> sb->s_blocksize_bits;
3658 end = byte_end >> sb->s_blocksize_bits;
3660 /* Handle partial zero within the single block */
3662 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3663 err = ext4_block_zero_page_range(handle, mapping,
3667 /* Handle partial zero out on the start of the range */
3668 if (partial_start) {
3669 err = ext4_block_zero_page_range(handle, mapping,
3670 lstart, sb->s_blocksize);
3674 /* Handle partial zero out on the end of the range */
3675 if (partial_end != sb->s_blocksize - 1)
3676 err = ext4_block_zero_page_range(handle, mapping,
3677 byte_end - partial_end,
3682 int ext4_can_truncate(struct inode *inode)
3684 if (S_ISREG(inode->i_mode))
3686 if (S_ISDIR(inode->i_mode))
3688 if (S_ISLNK(inode->i_mode))
3689 return !ext4_inode_is_fast_symlink(inode);
3694 * We have to make sure i_disksize gets properly updated before we truncate
3695 * page cache due to hole punching or zero range. Otherwise i_disksize update
3696 * can get lost as it may have been postponed to submission of writeback but
3697 * that will never happen after we truncate page cache.
3699 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3703 loff_t size = i_size_read(inode);
3705 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3706 if (offset > size || offset + len < size)
3709 if (EXT4_I(inode)->i_disksize >= size)
3712 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3714 return PTR_ERR(handle);
3715 ext4_update_i_disksize(inode, size);
3716 ext4_mark_inode_dirty(handle, inode);
3717 ext4_journal_stop(handle);
3723 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3724 * associated with the given offset and length
3726 * @inode: File inode
3727 * @offset: The offset where the hole will begin
3728 * @len: The length of the hole
3730 * Returns: 0 on success or negative on failure
3733 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3735 struct super_block *sb = inode->i_sb;
3736 ext4_lblk_t first_block, stop_block;
3737 struct address_space *mapping = inode->i_mapping;
3738 loff_t first_block_offset, last_block_offset;
3740 unsigned int credits;
3743 if (!S_ISREG(inode->i_mode))
3746 trace_ext4_punch_hole(inode, offset, length, 0);
3749 * Write out all dirty pages to avoid race conditions
3750 * Then release them.
3752 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3753 ret = filemap_write_and_wait_range(mapping, offset,
3754 offset + length - 1);
3759 mutex_lock(&inode->i_mutex);
3761 /* No need to punch hole beyond i_size */
3762 if (offset >= inode->i_size)
3766 * If the hole extends beyond i_size, set the hole
3767 * to end after the page that contains i_size
3769 if (offset + length > inode->i_size) {
3770 length = inode->i_size +
3771 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3775 if (offset & (sb->s_blocksize - 1) ||
3776 (offset + length) & (sb->s_blocksize - 1)) {
3778 * Attach jinode to inode for jbd2 if we do any zeroing of
3781 ret = ext4_inode_attach_jinode(inode);
3787 /* Wait all existing dio workers, newcomers will block on i_mutex */
3788 ext4_inode_block_unlocked_dio(inode);
3789 inode_dio_wait(inode);
3792 * Prevent page faults from reinstantiating pages we have released from
3795 down_write(&EXT4_I(inode)->i_mmap_sem);
3796 first_block_offset = round_up(offset, sb->s_blocksize);
3797 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3799 /* Now release the pages and zero block aligned part of pages*/
3800 if (last_block_offset > first_block_offset) {
3801 ret = ext4_update_disksize_before_punch(inode, offset, length);
3804 truncate_pagecache_range(inode, first_block_offset,
3808 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3809 credits = ext4_writepage_trans_blocks(inode);
3811 credits = ext4_blocks_for_truncate(inode);
3812 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3813 if (IS_ERR(handle)) {
3814 ret = PTR_ERR(handle);
3815 ext4_std_error(sb, ret);
3819 ret = ext4_zero_partial_blocks(handle, inode, offset,
3824 first_block = (offset + sb->s_blocksize - 1) >>
3825 EXT4_BLOCK_SIZE_BITS(sb);
3826 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3828 /* If there are no blocks to remove, return now */
3829 if (first_block >= stop_block)
3832 down_write(&EXT4_I(inode)->i_data_sem);
3833 ext4_discard_preallocations(inode);
3835 ret = ext4_es_remove_extent(inode, first_block,
3836 stop_block - first_block);
3838 up_write(&EXT4_I(inode)->i_data_sem);
3842 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3843 ret = ext4_ext_remove_space(inode, first_block,
3846 ret = ext4_ind_remove_space(handle, inode, first_block,
3849 up_write(&EXT4_I(inode)->i_data_sem);
3851 ext4_handle_sync(handle);
3853 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3854 ext4_mark_inode_dirty(handle, inode);
3856 ext4_update_inode_fsync_trans(handle, inode, 1);
3858 ext4_journal_stop(handle);
3860 up_write(&EXT4_I(inode)->i_mmap_sem);
3861 ext4_inode_resume_unlocked_dio(inode);
3863 mutex_unlock(&inode->i_mutex);
3867 int ext4_inode_attach_jinode(struct inode *inode)
3869 struct ext4_inode_info *ei = EXT4_I(inode);
3870 struct jbd2_inode *jinode;
3872 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3875 jinode = jbd2_alloc_inode(GFP_KERNEL);
3876 spin_lock(&inode->i_lock);
3879 spin_unlock(&inode->i_lock);
3882 ei->jinode = jinode;
3883 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3886 spin_unlock(&inode->i_lock);
3887 if (unlikely(jinode != NULL))
3888 jbd2_free_inode(jinode);
3895 * We block out ext4_get_block() block instantiations across the entire
3896 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3897 * simultaneously on behalf of the same inode.
3899 * As we work through the truncate and commit bits of it to the journal there
3900 * is one core, guiding principle: the file's tree must always be consistent on
3901 * disk. We must be able to restart the truncate after a crash.
3903 * The file's tree may be transiently inconsistent in memory (although it
3904 * probably isn't), but whenever we close off and commit a journal transaction,
3905 * the contents of (the filesystem + the journal) must be consistent and
3906 * restartable. It's pretty simple, really: bottom up, right to left (although
3907 * left-to-right works OK too).
3909 * Note that at recovery time, journal replay occurs *before* the restart of
3910 * truncate against the orphan inode list.
3912 * The committed inode has the new, desired i_size (which is the same as
3913 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3914 * that this inode's truncate did not complete and it will again call
3915 * ext4_truncate() to have another go. So there will be instantiated blocks
3916 * to the right of the truncation point in a crashed ext4 filesystem. But
3917 * that's fine - as long as they are linked from the inode, the post-crash
3918 * ext4_truncate() run will find them and release them.
3920 void ext4_truncate(struct inode *inode)
3922 struct ext4_inode_info *ei = EXT4_I(inode);
3923 unsigned int credits;
3925 struct address_space *mapping = inode->i_mapping;
3928 * There is a possibility that we're either freeing the inode
3929 * or it's a completely new inode. In those cases we might not
3930 * have i_mutex locked because it's not necessary.
3932 if (!(inode->i_state & (I_NEW|I_FREEING)))
3933 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3934 trace_ext4_truncate_enter(inode);
3936 if (!ext4_can_truncate(inode))
3939 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3941 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3942 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3944 if (ext4_has_inline_data(inode)) {
3947 ext4_inline_data_truncate(inode, &has_inline);
3952 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3953 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3954 if (ext4_inode_attach_jinode(inode) < 0)
3958 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3959 credits = ext4_writepage_trans_blocks(inode);
3961 credits = ext4_blocks_for_truncate(inode);
3963 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3964 if (IS_ERR(handle)) {
3965 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3969 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3970 ext4_block_truncate_page(handle, mapping, inode->i_size);
3973 * We add the inode to the orphan list, so that if this
3974 * truncate spans multiple transactions, and we crash, we will
3975 * resume the truncate when the filesystem recovers. It also
3976 * marks the inode dirty, to catch the new size.
3978 * Implication: the file must always be in a sane, consistent
3979 * truncatable state while each transaction commits.
3981 if (ext4_orphan_add(handle, inode))
3984 down_write(&EXT4_I(inode)->i_data_sem);
3986 ext4_discard_preallocations(inode);
3988 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3989 ext4_ext_truncate(handle, inode);
3991 ext4_ind_truncate(handle, inode);
3993 up_write(&ei->i_data_sem);
3996 ext4_handle_sync(handle);
4000 * If this was a simple ftruncate() and the file will remain alive,
4001 * then we need to clear up the orphan record which we created above.
4002 * However, if this was a real unlink then we were called by
4003 * ext4_evict_inode(), and we allow that function to clean up the
4004 * orphan info for us.
4007 ext4_orphan_del(handle, inode);
4009 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4010 ext4_mark_inode_dirty(handle, inode);
4011 ext4_journal_stop(handle);
4013 trace_ext4_truncate_exit(inode);
4017 * ext4_get_inode_loc returns with an extra refcount against the inode's
4018 * underlying buffer_head on success. If 'in_mem' is true, we have all
4019 * data in memory that is needed to recreate the on-disk version of this
4022 static int __ext4_get_inode_loc(struct inode *inode,
4023 struct ext4_iloc *iloc, int in_mem)
4025 struct ext4_group_desc *gdp;
4026 struct buffer_head *bh;
4027 struct super_block *sb = inode->i_sb;
4029 int inodes_per_block, inode_offset;
4032 if (!ext4_valid_inum(sb, inode->i_ino))
4033 return -EFSCORRUPTED;
4035 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4036 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4041 * Figure out the offset within the block group inode table
4043 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4044 inode_offset = ((inode->i_ino - 1) %
4045 EXT4_INODES_PER_GROUP(sb));
4046 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4047 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4049 bh = sb_getblk(sb, block);
4052 if (!buffer_uptodate(bh)) {
4056 * If the buffer has the write error flag, we have failed
4057 * to write out another inode in the same block. In this
4058 * case, we don't have to read the block because we may
4059 * read the old inode data successfully.
4061 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4062 set_buffer_uptodate(bh);
4064 if (buffer_uptodate(bh)) {
4065 /* someone brought it uptodate while we waited */
4071 * If we have all information of the inode in memory and this
4072 * is the only valid inode in the block, we need not read the
4076 struct buffer_head *bitmap_bh;
4079 start = inode_offset & ~(inodes_per_block - 1);
4081 /* Is the inode bitmap in cache? */
4082 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4083 if (unlikely(!bitmap_bh))
4087 * If the inode bitmap isn't in cache then the
4088 * optimisation may end up performing two reads instead
4089 * of one, so skip it.
4091 if (!buffer_uptodate(bitmap_bh)) {
4095 for (i = start; i < start + inodes_per_block; i++) {
4096 if (i == inode_offset)
4098 if (ext4_test_bit(i, bitmap_bh->b_data))
4102 if (i == start + inodes_per_block) {
4103 /* all other inodes are free, so skip I/O */
4104 memset(bh->b_data, 0, bh->b_size);
4105 set_buffer_uptodate(bh);
4113 * If we need to do any I/O, try to pre-readahead extra
4114 * blocks from the inode table.
4116 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4117 ext4_fsblk_t b, end, table;
4119 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4121 table = ext4_inode_table(sb, gdp);
4122 /* s_inode_readahead_blks is always a power of 2 */
4123 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4127 num = EXT4_INODES_PER_GROUP(sb);
4128 if (ext4_has_group_desc_csum(sb))
4129 num -= ext4_itable_unused_count(sb, gdp);
4130 table += num / inodes_per_block;
4134 sb_breadahead(sb, b++);
4138 * There are other valid inodes in the buffer, this inode
4139 * has in-inode xattrs, or we don't have this inode in memory.
4140 * Read the block from disk.
4142 trace_ext4_load_inode(inode);
4144 bh->b_end_io = end_buffer_read_sync;
4145 submit_bh(READ | REQ_META | REQ_PRIO, bh);
4147 if (!buffer_uptodate(bh)) {
4148 EXT4_ERROR_INODE_BLOCK(inode, block,
4149 "unable to read itable block");
4159 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4161 /* We have all inode data except xattrs in memory here. */
4162 return __ext4_get_inode_loc(inode, iloc,
4163 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4166 void ext4_set_inode_flags(struct inode *inode)
4168 unsigned int flags = EXT4_I(inode)->i_flags;
4169 unsigned int new_fl = 0;
4171 if (flags & EXT4_SYNC_FL)
4173 if (flags & EXT4_APPEND_FL)
4175 if (flags & EXT4_IMMUTABLE_FL)
4176 new_fl |= S_IMMUTABLE;
4177 if (flags & EXT4_NOATIME_FL)
4178 new_fl |= S_NOATIME;
4179 if (flags & EXT4_DIRSYNC_FL)
4180 new_fl |= S_DIRSYNC;
4181 if (test_opt(inode->i_sb, DAX))
4183 inode_set_flags(inode, new_fl,
4184 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4187 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4188 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4190 unsigned int vfs_fl;
4191 unsigned long old_fl, new_fl;
4194 vfs_fl = ei->vfs_inode.i_flags;
4195 old_fl = ei->i_flags;
4196 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4197 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4199 if (vfs_fl & S_SYNC)
4200 new_fl |= EXT4_SYNC_FL;
4201 if (vfs_fl & S_APPEND)
4202 new_fl |= EXT4_APPEND_FL;
4203 if (vfs_fl & S_IMMUTABLE)
4204 new_fl |= EXT4_IMMUTABLE_FL;
4205 if (vfs_fl & S_NOATIME)
4206 new_fl |= EXT4_NOATIME_FL;
4207 if (vfs_fl & S_DIRSYNC)
4208 new_fl |= EXT4_DIRSYNC_FL;
4209 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4212 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4213 struct ext4_inode_info *ei)
4216 struct inode *inode = &(ei->vfs_inode);
4217 struct super_block *sb = inode->i_sb;
4219 if (ext4_has_feature_huge_file(sb)) {
4220 /* we are using combined 48 bit field */
4221 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4222 le32_to_cpu(raw_inode->i_blocks_lo);
4223 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4224 /* i_blocks represent file system block size */
4225 return i_blocks << (inode->i_blkbits - 9);
4230 return le32_to_cpu(raw_inode->i_blocks_lo);
4234 static inline void ext4_iget_extra_inode(struct inode *inode,
4235 struct ext4_inode *raw_inode,
4236 struct ext4_inode_info *ei)
4238 __le32 *magic = (void *)raw_inode +
4239 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4240 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4241 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4242 ext4_find_inline_data_nolock(inode);
4244 EXT4_I(inode)->i_inline_off = 0;
4247 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4249 struct ext4_iloc iloc;
4250 struct ext4_inode *raw_inode;
4251 struct ext4_inode_info *ei;
4252 struct inode *inode;
4253 journal_t *journal = EXT4_SB(sb)->s_journal;
4260 inode = iget_locked(sb, ino);
4262 return ERR_PTR(-ENOMEM);
4263 if (!(inode->i_state & I_NEW))
4269 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4272 raw_inode = ext4_raw_inode(&iloc);
4274 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4275 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4276 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4277 EXT4_INODE_SIZE(inode->i_sb)) {
4278 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4279 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4280 EXT4_INODE_SIZE(inode->i_sb));
4281 ret = -EFSCORRUPTED;
4285 ei->i_extra_isize = 0;
4287 /* Precompute checksum seed for inode metadata */
4288 if (ext4_has_metadata_csum(sb)) {
4289 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4291 __le32 inum = cpu_to_le32(inode->i_ino);
4292 __le32 gen = raw_inode->i_generation;
4293 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4295 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4299 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4300 EXT4_ERROR_INODE(inode, "checksum invalid");
4305 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4306 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4307 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4308 if (!(test_opt(inode->i_sb, NO_UID32))) {
4309 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4310 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4312 i_uid_write(inode, i_uid);
4313 i_gid_write(inode, i_gid);
4314 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4316 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4317 ei->i_inline_off = 0;
4318 ei->i_dir_start_lookup = 0;
4319 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4320 /* We now have enough fields to check if the inode was active or not.
4321 * This is needed because nfsd might try to access dead inodes
4322 * the test is that same one that e2fsck uses
4323 * NeilBrown 1999oct15
4325 if (inode->i_nlink == 0) {
4326 if ((inode->i_mode == 0 ||
4327 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4328 ino != EXT4_BOOT_LOADER_INO) {
4329 /* this inode is deleted */
4333 /* The only unlinked inodes we let through here have
4334 * valid i_mode and are being read by the orphan
4335 * recovery code: that's fine, we're about to complete
4336 * the process of deleting those.
4337 * OR it is the EXT4_BOOT_LOADER_INO which is
4338 * not initialized on a new filesystem. */
4340 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4341 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4342 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4343 if (ext4_has_feature_64bit(sb))
4345 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4346 inode->i_size = ext4_isize(raw_inode);
4347 if ((size = i_size_read(inode)) < 0) {
4348 EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
4349 ret = -EFSCORRUPTED;
4352 ei->i_disksize = inode->i_size;
4354 ei->i_reserved_quota = 0;
4356 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4357 ei->i_block_group = iloc.block_group;
4358 ei->i_last_alloc_group = ~0;
4360 * NOTE! The in-memory inode i_data array is in little-endian order
4361 * even on big-endian machines: we do NOT byteswap the block numbers!
4363 for (block = 0; block < EXT4_N_BLOCKS; block++)
4364 ei->i_data[block] = raw_inode->i_block[block];
4365 INIT_LIST_HEAD(&ei->i_orphan);
4368 * Set transaction id's of transactions that have to be committed
4369 * to finish f[data]sync. We set them to currently running transaction
4370 * as we cannot be sure that the inode or some of its metadata isn't
4371 * part of the transaction - the inode could have been reclaimed and
4372 * now it is reread from disk.
4375 transaction_t *transaction;
4378 read_lock(&journal->j_state_lock);
4379 if (journal->j_running_transaction)
4380 transaction = journal->j_running_transaction;
4382 transaction = journal->j_committing_transaction;
4384 tid = transaction->t_tid;
4386 tid = journal->j_commit_sequence;
4387 read_unlock(&journal->j_state_lock);
4388 ei->i_sync_tid = tid;
4389 ei->i_datasync_tid = tid;
4392 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4393 if (ei->i_extra_isize == 0) {
4394 /* The extra space is currently unused. Use it. */
4395 ei->i_extra_isize = sizeof(struct ext4_inode) -
4396 EXT4_GOOD_OLD_INODE_SIZE;
4398 ext4_iget_extra_inode(inode, raw_inode, ei);
4402 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4403 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4404 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4405 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4407 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4408 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4409 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4410 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4412 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4417 if (ei->i_file_acl &&
4418 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4419 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4421 ret = -EFSCORRUPTED;
4423 } else if (!ext4_has_inline_data(inode)) {
4424 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4425 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4426 (S_ISLNK(inode->i_mode) &&
4427 !ext4_inode_is_fast_symlink(inode))))
4428 /* Validate extent which is part of inode */
4429 ret = ext4_ext_check_inode(inode);
4430 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4431 (S_ISLNK(inode->i_mode) &&
4432 !ext4_inode_is_fast_symlink(inode))) {
4433 /* Validate block references which are part of inode */
4434 ret = ext4_ind_check_inode(inode);
4440 if (S_ISREG(inode->i_mode)) {
4441 inode->i_op = &ext4_file_inode_operations;
4442 inode->i_fop = &ext4_file_operations;
4443 ext4_set_aops(inode);
4444 } else if (S_ISDIR(inode->i_mode)) {
4445 inode->i_op = &ext4_dir_inode_operations;
4446 inode->i_fop = &ext4_dir_operations;
4447 } else if (S_ISLNK(inode->i_mode)) {
4448 if (ext4_encrypted_inode(inode)) {
4449 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4450 ext4_set_aops(inode);
4451 } else if (ext4_inode_is_fast_symlink(inode)) {
4452 inode->i_link = (char *)ei->i_data;
4453 inode->i_op = &ext4_fast_symlink_inode_operations;
4454 nd_terminate_link(ei->i_data, inode->i_size,
4455 sizeof(ei->i_data) - 1);
4457 inode->i_op = &ext4_symlink_inode_operations;
4458 ext4_set_aops(inode);
4460 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4461 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4462 inode->i_op = &ext4_special_inode_operations;
4463 if (raw_inode->i_block[0])
4464 init_special_inode(inode, inode->i_mode,
4465 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4467 init_special_inode(inode, inode->i_mode,
4468 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4469 } else if (ino == EXT4_BOOT_LOADER_INO) {
4470 make_bad_inode(inode);
4472 ret = -EFSCORRUPTED;
4473 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4477 ext4_set_inode_flags(inode);
4478 unlock_new_inode(inode);
4484 return ERR_PTR(ret);
4487 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4489 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4490 return ERR_PTR(-EFSCORRUPTED);
4491 return ext4_iget(sb, ino);
4494 static int ext4_inode_blocks_set(handle_t *handle,
4495 struct ext4_inode *raw_inode,
4496 struct ext4_inode_info *ei)
4498 struct inode *inode = &(ei->vfs_inode);
4499 u64 i_blocks = inode->i_blocks;
4500 struct super_block *sb = inode->i_sb;
4502 if (i_blocks <= ~0U) {
4504 * i_blocks can be represented in a 32 bit variable
4505 * as multiple of 512 bytes
4507 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4508 raw_inode->i_blocks_high = 0;
4509 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4512 if (!ext4_has_feature_huge_file(sb))
4515 if (i_blocks <= 0xffffffffffffULL) {
4517 * i_blocks can be represented in a 48 bit variable
4518 * as multiple of 512 bytes
4520 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4521 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4522 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4524 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4525 /* i_block is stored in file system block size */
4526 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4527 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4528 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4533 struct other_inode {
4534 unsigned long orig_ino;
4535 struct ext4_inode *raw_inode;
4538 static int other_inode_match(struct inode * inode, unsigned long ino,
4541 struct other_inode *oi = (struct other_inode *) data;
4543 if ((inode->i_ino != ino) ||
4544 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4545 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4546 ((inode->i_state & I_DIRTY_TIME) == 0))
4548 spin_lock(&inode->i_lock);
4549 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4550 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4551 (inode->i_state & I_DIRTY_TIME)) {
4552 struct ext4_inode_info *ei = EXT4_I(inode);
4554 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4555 spin_unlock(&inode->i_lock);
4557 spin_lock(&ei->i_raw_lock);
4558 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4559 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4560 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4561 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4562 spin_unlock(&ei->i_raw_lock);
4563 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4566 spin_unlock(&inode->i_lock);
4571 * Opportunistically update the other time fields for other inodes in
4572 * the same inode table block.
4574 static void ext4_update_other_inodes_time(struct super_block *sb,
4575 unsigned long orig_ino, char *buf)
4577 struct other_inode oi;
4579 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4580 int inode_size = EXT4_INODE_SIZE(sb);
4582 oi.orig_ino = orig_ino;
4584 * Calculate the first inode in the inode table block. Inode
4585 * numbers are one-based. That is, the first inode in a block
4586 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4588 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4589 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4590 if (ino == orig_ino)
4592 oi.raw_inode = (struct ext4_inode *) buf;
4593 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4598 * Post the struct inode info into an on-disk inode location in the
4599 * buffer-cache. This gobbles the caller's reference to the
4600 * buffer_head in the inode location struct.
4602 * The caller must have write access to iloc->bh.
4604 static int ext4_do_update_inode(handle_t *handle,
4605 struct inode *inode,
4606 struct ext4_iloc *iloc)
4608 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4609 struct ext4_inode_info *ei = EXT4_I(inode);
4610 struct buffer_head *bh = iloc->bh;
4611 struct super_block *sb = inode->i_sb;
4612 int err = 0, rc, block;
4613 int need_datasync = 0, set_large_file = 0;
4617 spin_lock(&ei->i_raw_lock);
4619 /* For fields not tracked in the in-memory inode,
4620 * initialise them to zero for new inodes. */
4621 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4622 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4624 ext4_get_inode_flags(ei);
4625 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4626 i_uid = i_uid_read(inode);
4627 i_gid = i_gid_read(inode);
4628 if (!(test_opt(inode->i_sb, NO_UID32))) {
4629 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4630 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4632 * Fix up interoperability with old kernels. Otherwise, old inodes get
4633 * re-used with the upper 16 bits of the uid/gid intact
4635 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4636 raw_inode->i_uid_high = 0;
4637 raw_inode->i_gid_high = 0;
4639 raw_inode->i_uid_high =
4640 cpu_to_le16(high_16_bits(i_uid));
4641 raw_inode->i_gid_high =
4642 cpu_to_le16(high_16_bits(i_gid));
4645 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4646 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4647 raw_inode->i_uid_high = 0;
4648 raw_inode->i_gid_high = 0;
4650 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4652 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4653 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4654 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4655 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4657 err = ext4_inode_blocks_set(handle, raw_inode, ei);
4659 spin_unlock(&ei->i_raw_lock);
4662 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4663 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4664 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4665 raw_inode->i_file_acl_high =
4666 cpu_to_le16(ei->i_file_acl >> 32);
4667 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4668 if (ei->i_disksize != ext4_isize(raw_inode)) {
4669 ext4_isize_set(raw_inode, ei->i_disksize);
4672 if (ei->i_disksize > 0x7fffffffULL) {
4673 if (!ext4_has_feature_large_file(sb) ||
4674 EXT4_SB(sb)->s_es->s_rev_level ==
4675 cpu_to_le32(EXT4_GOOD_OLD_REV))
4678 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4679 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4680 if (old_valid_dev(inode->i_rdev)) {
4681 raw_inode->i_block[0] =
4682 cpu_to_le32(old_encode_dev(inode->i_rdev));
4683 raw_inode->i_block[1] = 0;
4685 raw_inode->i_block[0] = 0;
4686 raw_inode->i_block[1] =
4687 cpu_to_le32(new_encode_dev(inode->i_rdev));
4688 raw_inode->i_block[2] = 0;
4690 } else if (!ext4_has_inline_data(inode)) {
4691 for (block = 0; block < EXT4_N_BLOCKS; block++)
4692 raw_inode->i_block[block] = ei->i_data[block];
4695 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4696 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4697 if (ei->i_extra_isize) {
4698 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4699 raw_inode->i_version_hi =
4700 cpu_to_le32(inode->i_version >> 32);
4701 raw_inode->i_extra_isize =
4702 cpu_to_le16(ei->i_extra_isize);
4705 ext4_inode_csum_set(inode, raw_inode, ei);
4706 spin_unlock(&ei->i_raw_lock);
4707 if (inode->i_sb->s_flags & MS_LAZYTIME)
4708 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4711 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4712 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4715 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4716 if (set_large_file) {
4717 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4718 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4721 ext4_update_dynamic_rev(sb);
4722 ext4_set_feature_large_file(sb);
4723 ext4_handle_sync(handle);
4724 err = ext4_handle_dirty_super(handle, sb);
4726 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4729 ext4_std_error(inode->i_sb, err);
4734 * ext4_write_inode()
4736 * We are called from a few places:
4738 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4739 * Here, there will be no transaction running. We wait for any running
4740 * transaction to commit.
4742 * - Within flush work (sys_sync(), kupdate and such).
4743 * We wait on commit, if told to.
4745 * - Within iput_final() -> write_inode_now()
4746 * We wait on commit, if told to.
4748 * In all cases it is actually safe for us to return without doing anything,
4749 * because the inode has been copied into a raw inode buffer in
4750 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4753 * Note that we are absolutely dependent upon all inode dirtiers doing the
4754 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4755 * which we are interested.
4757 * It would be a bug for them to not do this. The code:
4759 * mark_inode_dirty(inode)
4761 * inode->i_size = expr;
4763 * is in error because write_inode() could occur while `stuff()' is running,
4764 * and the new i_size will be lost. Plus the inode will no longer be on the
4765 * superblock's dirty inode list.
4767 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4771 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4774 if (EXT4_SB(inode->i_sb)->s_journal) {
4775 if (ext4_journal_current_handle()) {
4776 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4782 * No need to force transaction in WB_SYNC_NONE mode. Also
4783 * ext4_sync_fs() will force the commit after everything is
4786 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4789 err = ext4_force_commit(inode->i_sb);
4791 struct ext4_iloc iloc;
4793 err = __ext4_get_inode_loc(inode, &iloc, 0);
4797 * sync(2) will flush the whole buffer cache. No need to do
4798 * it here separately for each inode.
4800 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4801 sync_dirty_buffer(iloc.bh);
4802 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4803 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4804 "IO error syncing inode");
4813 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4814 * buffers that are attached to a page stradding i_size and are undergoing
4815 * commit. In that case we have to wait for commit to finish and try again.
4817 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4821 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4822 tid_t commit_tid = 0;
4825 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4827 * All buffers in the last page remain valid? Then there's nothing to
4828 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4831 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4834 page = find_lock_page(inode->i_mapping,
4835 inode->i_size >> PAGE_CACHE_SHIFT);
4838 ret = __ext4_journalled_invalidatepage(page, offset,
4839 PAGE_CACHE_SIZE - offset);
4841 page_cache_release(page);
4845 read_lock(&journal->j_state_lock);
4846 if (journal->j_committing_transaction)
4847 commit_tid = journal->j_committing_transaction->t_tid;
4848 read_unlock(&journal->j_state_lock);
4850 jbd2_log_wait_commit(journal, commit_tid);
4857 * Called from notify_change.
4859 * We want to trap VFS attempts to truncate the file as soon as
4860 * possible. In particular, we want to make sure that when the VFS
4861 * shrinks i_size, we put the inode on the orphan list and modify
4862 * i_disksize immediately, so that during the subsequent flushing of
4863 * dirty pages and freeing of disk blocks, we can guarantee that any
4864 * commit will leave the blocks being flushed in an unused state on
4865 * disk. (On recovery, the inode will get truncated and the blocks will
4866 * be freed, so we have a strong guarantee that no future commit will
4867 * leave these blocks visible to the user.)
4869 * Another thing we have to assure is that if we are in ordered mode
4870 * and inode is still attached to the committing transaction, we must
4871 * we start writeout of all the dirty pages which are being truncated.
4872 * This way we are sure that all the data written in the previous
4873 * transaction are already on disk (truncate waits for pages under
4876 * Called with inode->i_mutex down.
4878 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4880 struct inode *inode = d_inode(dentry);
4883 const unsigned int ia_valid = attr->ia_valid;
4885 error = inode_change_ok(inode, attr);
4889 if (is_quota_modification(inode, attr)) {
4890 error = dquot_initialize(inode);
4894 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4895 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4898 /* (user+group)*(old+new) structure, inode write (sb,
4899 * inode block, ? - but truncate inode update has it) */
4900 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4901 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4902 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4903 if (IS_ERR(handle)) {
4904 error = PTR_ERR(handle);
4907 error = dquot_transfer(inode, attr);
4909 ext4_journal_stop(handle);
4912 /* Update corresponding info in inode so that everything is in
4913 * one transaction */
4914 if (attr->ia_valid & ATTR_UID)
4915 inode->i_uid = attr->ia_uid;
4916 if (attr->ia_valid & ATTR_GID)
4917 inode->i_gid = attr->ia_gid;
4918 error = ext4_mark_inode_dirty(handle, inode);
4919 ext4_journal_stop(handle);
4922 if (attr->ia_valid & ATTR_SIZE) {
4924 loff_t oldsize = inode->i_size;
4925 int shrink = (attr->ia_size <= inode->i_size);
4927 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4928 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4930 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4933 if (!S_ISREG(inode->i_mode))
4936 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4937 inode_inc_iversion(inode);
4939 if (ext4_should_order_data(inode) &&
4940 (attr->ia_size < inode->i_size)) {
4941 error = ext4_begin_ordered_truncate(inode,
4946 if (attr->ia_size != inode->i_size) {
4947 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4948 if (IS_ERR(handle)) {
4949 error = PTR_ERR(handle);
4952 if (ext4_handle_valid(handle) && shrink) {
4953 error = ext4_orphan_add(handle, inode);
4957 * Update c/mtime on truncate up, ext4_truncate() will
4958 * update c/mtime in shrink case below
4961 inode->i_mtime = ext4_current_time(inode);
4962 inode->i_ctime = inode->i_mtime;
4964 down_write(&EXT4_I(inode)->i_data_sem);
4965 EXT4_I(inode)->i_disksize = attr->ia_size;
4966 rc = ext4_mark_inode_dirty(handle, inode);
4970 * We have to update i_size under i_data_sem together
4971 * with i_disksize to avoid races with writeback code
4972 * running ext4_wb_update_i_disksize().
4975 i_size_write(inode, attr->ia_size);
4976 up_write(&EXT4_I(inode)->i_data_sem);
4977 ext4_journal_stop(handle);
4980 ext4_orphan_del(NULL, inode);
4985 pagecache_isize_extended(inode, oldsize, inode->i_size);
4988 * Blocks are going to be removed from the inode. Wait
4989 * for dio in flight. Temporarily disable
4990 * dioread_nolock to prevent livelock.
4993 if (!ext4_should_journal_data(inode)) {
4994 ext4_inode_block_unlocked_dio(inode);
4995 inode_dio_wait(inode);
4996 ext4_inode_resume_unlocked_dio(inode);
4998 ext4_wait_for_tail_page_commit(inode);
5000 down_write(&EXT4_I(inode)->i_mmap_sem);
5002 * Truncate pagecache after we've waited for commit
5003 * in data=journal mode to make pages freeable.
5005 truncate_pagecache(inode, inode->i_size);
5007 ext4_truncate(inode);
5008 up_write(&EXT4_I(inode)->i_mmap_sem);
5012 setattr_copy(inode, attr);
5013 mark_inode_dirty(inode);
5017 * If the call to ext4_truncate failed to get a transaction handle at
5018 * all, we need to clean up the in-core orphan list manually.
5020 if (orphan && inode->i_nlink)
5021 ext4_orphan_del(NULL, inode);
5023 if (!rc && (ia_valid & ATTR_MODE))
5024 rc = posix_acl_chmod(inode, inode->i_mode);
5027 ext4_std_error(inode->i_sb, error);
5033 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5036 struct inode *inode;
5037 unsigned long long delalloc_blocks;
5039 inode = d_inode(dentry);
5040 generic_fillattr(inode, stat);
5043 * If there is inline data in the inode, the inode will normally not
5044 * have data blocks allocated (it may have an external xattr block).
5045 * Report at least one sector for such files, so tools like tar, rsync,
5046 * others doen't incorrectly think the file is completely sparse.
5048 if (unlikely(ext4_has_inline_data(inode)))
5049 stat->blocks += (stat->size + 511) >> 9;
5052 * We can't update i_blocks if the block allocation is delayed
5053 * otherwise in the case of system crash before the real block
5054 * allocation is done, we will have i_blocks inconsistent with
5055 * on-disk file blocks.
5056 * We always keep i_blocks updated together with real
5057 * allocation. But to not confuse with user, stat
5058 * will return the blocks that include the delayed allocation
5059 * blocks for this file.
5061 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5062 EXT4_I(inode)->i_reserved_data_blocks);
5063 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5067 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5070 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5071 return ext4_ind_trans_blocks(inode, lblocks);
5072 return ext4_ext_index_trans_blocks(inode, pextents);
5076 * Account for index blocks, block groups bitmaps and block group
5077 * descriptor blocks if modify datablocks and index blocks
5078 * worse case, the indexs blocks spread over different block groups
5080 * If datablocks are discontiguous, they are possible to spread over
5081 * different block groups too. If they are contiguous, with flexbg,
5082 * they could still across block group boundary.
5084 * Also account for superblock, inode, quota and xattr blocks
5086 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5089 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5095 * How many index blocks need to touch to map @lblocks logical blocks
5096 * to @pextents physical extents?
5098 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5103 * Now let's see how many group bitmaps and group descriptors need
5106 groups = idxblocks + pextents;
5108 if (groups > ngroups)
5110 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5111 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5113 /* bitmaps and block group descriptor blocks */
5114 ret += groups + gdpblocks;
5116 /* Blocks for super block, inode, quota and xattr blocks */
5117 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5123 * Calculate the total number of credits to reserve to fit
5124 * the modification of a single pages into a single transaction,
5125 * which may include multiple chunks of block allocations.
5127 * This could be called via ext4_write_begin()
5129 * We need to consider the worse case, when
5130 * one new block per extent.
5132 int ext4_writepage_trans_blocks(struct inode *inode)
5134 int bpp = ext4_journal_blocks_per_page(inode);
5137 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5139 /* Account for data blocks for journalled mode */
5140 if (ext4_should_journal_data(inode))
5146 * Calculate the journal credits for a chunk of data modification.
5148 * This is called from DIO, fallocate or whoever calling
5149 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5151 * journal buffers for data blocks are not included here, as DIO
5152 * and fallocate do no need to journal data buffers.
5154 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5156 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5160 * The caller must have previously called ext4_reserve_inode_write().
5161 * Give this, we know that the caller already has write access to iloc->bh.
5163 int ext4_mark_iloc_dirty(handle_t *handle,
5164 struct inode *inode, struct ext4_iloc *iloc)
5168 if (IS_I_VERSION(inode))
5169 inode_inc_iversion(inode);
5171 /* the do_update_inode consumes one bh->b_count */
5174 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5175 err = ext4_do_update_inode(handle, inode, iloc);
5181 * On success, We end up with an outstanding reference count against
5182 * iloc->bh. This _must_ be cleaned up later.
5186 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5187 struct ext4_iloc *iloc)
5191 err = ext4_get_inode_loc(inode, iloc);
5193 BUFFER_TRACE(iloc->bh, "get_write_access");
5194 err = ext4_journal_get_write_access(handle, iloc->bh);
5200 ext4_std_error(inode->i_sb, err);
5205 * Expand an inode by new_extra_isize bytes.
5206 * Returns 0 on success or negative error number on failure.
5208 static int ext4_expand_extra_isize(struct inode *inode,
5209 unsigned int new_extra_isize,
5210 struct ext4_iloc iloc,
5213 struct ext4_inode *raw_inode;
5214 struct ext4_xattr_ibody_header *header;
5216 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5219 raw_inode = ext4_raw_inode(&iloc);
5221 header = IHDR(inode, raw_inode);
5223 /* No extended attributes present */
5224 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5225 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5226 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5227 EXT4_I(inode)->i_extra_isize, 0,
5228 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5229 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5233 /* try to expand with EAs present */
5234 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5239 * What we do here is to mark the in-core inode as clean with respect to inode
5240 * dirtiness (it may still be data-dirty).
5241 * This means that the in-core inode may be reaped by prune_icache
5242 * without having to perform any I/O. This is a very good thing,
5243 * because *any* task may call prune_icache - even ones which
5244 * have a transaction open against a different journal.
5246 * Is this cheating? Not really. Sure, we haven't written the
5247 * inode out, but prune_icache isn't a user-visible syncing function.
5248 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5249 * we start and wait on commits.
5251 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5253 struct ext4_iloc iloc;
5254 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5255 static unsigned int mnt_count;
5259 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5260 err = ext4_reserve_inode_write(handle, inode, &iloc);
5263 if (ext4_handle_valid(handle) &&
5264 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5265 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5267 * We need extra buffer credits since we may write into EA block
5268 * with this same handle. If journal_extend fails, then it will
5269 * only result in a minor loss of functionality for that inode.
5270 * If this is felt to be critical, then e2fsck should be run to
5271 * force a large enough s_min_extra_isize.
5273 if ((jbd2_journal_extend(handle,
5274 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5275 ret = ext4_expand_extra_isize(inode,
5276 sbi->s_want_extra_isize,
5280 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5281 ext4_warning(inode->i_sb,
5282 "Unable to expand inode %lu. Delete"
5283 " some EAs or run e2fsck.",
5286 le16_to_cpu(sbi->s_es->s_mnt_count);
5291 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5295 * ext4_dirty_inode() is called from __mark_inode_dirty()
5297 * We're really interested in the case where a file is being extended.
5298 * i_size has been changed by generic_commit_write() and we thus need
5299 * to include the updated inode in the current transaction.
5301 * Also, dquot_alloc_block() will always dirty the inode when blocks
5302 * are allocated to the file.
5304 * If the inode is marked synchronous, we don't honour that here - doing
5305 * so would cause a commit on atime updates, which we don't bother doing.
5306 * We handle synchronous inodes at the highest possible level.
5308 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5309 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5310 * to copy into the on-disk inode structure are the timestamp files.
5312 void ext4_dirty_inode(struct inode *inode, int flags)
5316 if (flags == I_DIRTY_TIME)
5318 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5322 ext4_mark_inode_dirty(handle, inode);
5324 ext4_journal_stop(handle);
5331 * Bind an inode's backing buffer_head into this transaction, to prevent
5332 * it from being flushed to disk early. Unlike
5333 * ext4_reserve_inode_write, this leaves behind no bh reference and
5334 * returns no iloc structure, so the caller needs to repeat the iloc
5335 * lookup to mark the inode dirty later.
5337 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5339 struct ext4_iloc iloc;
5343 err = ext4_get_inode_loc(inode, &iloc);
5345 BUFFER_TRACE(iloc.bh, "get_write_access");
5346 err = jbd2_journal_get_write_access(handle, iloc.bh);
5348 err = ext4_handle_dirty_metadata(handle,
5354 ext4_std_error(inode->i_sb, err);
5359 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5366 * We have to be very careful here: changing a data block's
5367 * journaling status dynamically is dangerous. If we write a
5368 * data block to the journal, change the status and then delete
5369 * that block, we risk forgetting to revoke the old log record
5370 * from the journal and so a subsequent replay can corrupt data.
5371 * So, first we make sure that the journal is empty and that
5372 * nobody is changing anything.
5375 journal = EXT4_JOURNAL(inode);
5378 if (is_journal_aborted(journal))
5380 /* We have to allocate physical blocks for delalloc blocks
5381 * before flushing journal. otherwise delalloc blocks can not
5382 * be allocated any more. even more truncate on delalloc blocks
5383 * could trigger BUG by flushing delalloc blocks in journal.
5384 * There is no delalloc block in non-journal data mode.
5386 if (val && test_opt(inode->i_sb, DELALLOC)) {
5387 err = ext4_alloc_da_blocks(inode);
5392 /* Wait for all existing dio workers */
5393 ext4_inode_block_unlocked_dio(inode);
5394 inode_dio_wait(inode);
5396 jbd2_journal_lock_updates(journal);
5399 * OK, there are no updates running now, and all cached data is
5400 * synced to disk. We are now in a completely consistent state
5401 * which doesn't have anything in the journal, and we know that
5402 * no filesystem updates are running, so it is safe to modify
5403 * the inode's in-core data-journaling state flag now.
5407 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5409 err = jbd2_journal_flush(journal);
5411 jbd2_journal_unlock_updates(journal);
5412 ext4_inode_resume_unlocked_dio(inode);
5415 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5417 ext4_set_aops(inode);
5419 jbd2_journal_unlock_updates(journal);
5420 ext4_inode_resume_unlocked_dio(inode);
5422 /* Finally we can mark the inode as dirty. */
5424 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5426 return PTR_ERR(handle);
5428 err = ext4_mark_inode_dirty(handle, inode);
5429 ext4_handle_sync(handle);
5430 ext4_journal_stop(handle);
5431 ext4_std_error(inode->i_sb, err);
5436 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5438 return !buffer_mapped(bh);
5441 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5443 struct page *page = vmf->page;
5447 struct file *file = vma->vm_file;
5448 struct inode *inode = file_inode(file);
5449 struct address_space *mapping = inode->i_mapping;
5451 get_block_t *get_block;
5454 sb_start_pagefault(inode->i_sb);
5455 file_update_time(vma->vm_file);
5457 down_read(&EXT4_I(inode)->i_mmap_sem);
5459 ret = ext4_convert_inline_data(inode);
5463 /* Delalloc case is easy... */
5464 if (test_opt(inode->i_sb, DELALLOC) &&
5465 !ext4_should_journal_data(inode) &&
5466 !ext4_nonda_switch(inode->i_sb)) {
5468 ret = block_page_mkwrite(vma, vmf,
5469 ext4_da_get_block_prep);
5470 } while (ret == -ENOSPC &&
5471 ext4_should_retry_alloc(inode->i_sb, &retries));
5476 size = i_size_read(inode);
5477 /* Page got truncated from under us? */
5478 if (page->mapping != mapping || page_offset(page) > size) {
5480 ret = VM_FAULT_NOPAGE;
5484 if (page->index == size >> PAGE_CACHE_SHIFT)
5485 len = size & ~PAGE_CACHE_MASK;
5487 len = PAGE_CACHE_SIZE;
5489 * Return if we have all the buffers mapped. This avoids the need to do
5490 * journal_start/journal_stop which can block and take a long time
5492 if (page_has_buffers(page)) {
5493 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5495 ext4_bh_unmapped)) {
5496 /* Wait so that we don't change page under IO */
5497 wait_for_stable_page(page);
5498 ret = VM_FAULT_LOCKED;
5503 /* OK, we need to fill the hole... */
5504 if (ext4_should_dioread_nolock(inode))
5505 get_block = ext4_get_block_write;
5507 get_block = ext4_get_block;
5509 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5510 ext4_writepage_trans_blocks(inode));
5511 if (IS_ERR(handle)) {
5512 ret = VM_FAULT_SIGBUS;
5515 ret = block_page_mkwrite(vma, vmf, get_block);
5516 if (!ret && ext4_should_journal_data(inode)) {
5517 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5518 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5520 ret = VM_FAULT_SIGBUS;
5521 ext4_journal_stop(handle);
5524 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5526 ext4_journal_stop(handle);
5527 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5530 ret = block_page_mkwrite_return(ret);
5532 up_read(&EXT4_I(inode)->i_mmap_sem);
5533 sb_end_pagefault(inode->i_sb);
5537 int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5539 struct inode *inode = file_inode(vma->vm_file);
5542 down_read(&EXT4_I(inode)->i_mmap_sem);
5543 err = filemap_fault(vma, vmf);
5544 up_read(&EXT4_I(inode)->i_mmap_sem);