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>
48 #define MPAGE_DA_EXTENT_TAIL 0x01
50 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
51 struct ext4_inode_info *ei)
53 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 int offset = offsetof(struct ext4_inode, i_checksum_lo);
57 unsigned int csum_size = sizeof(dummy_csum);
59 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
60 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
62 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
63 EXT4_GOOD_OLD_INODE_SIZE - offset);
65 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
66 offset = offsetof(struct ext4_inode, i_checksum_hi);
67 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
68 EXT4_GOOD_OLD_INODE_SIZE,
69 offset - EXT4_GOOD_OLD_INODE_SIZE);
70 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
71 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
75 EXT4_INODE_SIZE(inode->i_sb) -
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);
667 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
668 * we have to be careful as someone else may be manipulating b_state as well.
670 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
672 unsigned long old_state;
673 unsigned long new_state;
675 flags &= EXT4_MAP_FLAGS;
677 /* Dummy buffer_head? Set non-atomically. */
679 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
683 * Someone else may be modifying b_state. Be careful! This is ugly but
684 * once we get rid of using bh as a container for mapping information
685 * to pass to / from get_block functions, this can go away.
688 old_state = READ_ONCE(bh->b_state);
689 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
691 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
694 /* Maximum number of blocks we map for direct IO at once. */
695 #define DIO_MAX_BLOCKS 4096
697 static int _ext4_get_block(struct inode *inode, sector_t iblock,
698 struct buffer_head *bh, int flags)
700 handle_t *handle = ext4_journal_current_handle();
701 struct ext4_map_blocks map;
702 int ret = 0, started = 0;
705 if (ext4_has_inline_data(inode))
709 map.m_len = bh->b_size >> inode->i_blkbits;
711 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
712 /* Direct IO write... */
713 if (map.m_len > DIO_MAX_BLOCKS)
714 map.m_len = DIO_MAX_BLOCKS;
715 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
716 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
718 if (IS_ERR(handle)) {
719 ret = PTR_ERR(handle);
725 ret = ext4_map_blocks(handle, inode, &map, flags);
727 ext4_io_end_t *io_end = ext4_inode_aio(inode);
729 map_bh(bh, inode->i_sb, map.m_pblk);
730 ext4_update_bh_state(bh, map.m_flags);
731 if (IS_DAX(inode) && buffer_unwritten(bh)) {
733 * dgc: I suspect unwritten conversion on ext4+DAX is
734 * fundamentally broken here when there are concurrent
735 * read/write in progress on this inode.
737 WARN_ON_ONCE(io_end);
738 bh->b_assoc_map = inode->i_mapping;
739 bh->b_private = (void *)(unsigned long)iblock;
741 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
742 set_buffer_defer_completion(bh);
743 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
747 ext4_journal_stop(handle);
751 int ext4_get_block(struct inode *inode, sector_t iblock,
752 struct buffer_head *bh, int create)
754 return _ext4_get_block(inode, iblock, bh,
755 create ? EXT4_GET_BLOCKS_CREATE : 0);
759 * `handle' can be NULL if create is zero
761 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
762 ext4_lblk_t block, int map_flags)
764 struct ext4_map_blocks map;
765 struct buffer_head *bh;
766 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
769 J_ASSERT(handle != NULL || create == 0);
773 err = ext4_map_blocks(handle, inode, &map, map_flags);
776 return create ? ERR_PTR(-ENOSPC) : NULL;
780 bh = sb_getblk(inode->i_sb, map.m_pblk);
782 return ERR_PTR(-ENOMEM);
783 if (map.m_flags & EXT4_MAP_NEW) {
784 J_ASSERT(create != 0);
785 J_ASSERT(handle != NULL);
788 * Now that we do not always journal data, we should
789 * keep in mind whether this should always journal the
790 * new buffer as metadata. For now, regular file
791 * writes use ext4_get_block instead, so it's not a
795 BUFFER_TRACE(bh, "call get_create_access");
796 err = ext4_journal_get_create_access(handle, bh);
801 if (!buffer_uptodate(bh)) {
802 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
803 set_buffer_uptodate(bh);
806 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
807 err = ext4_handle_dirty_metadata(handle, inode, bh);
811 BUFFER_TRACE(bh, "not a new buffer");
818 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
819 ext4_lblk_t block, int map_flags)
821 struct buffer_head *bh;
823 bh = ext4_getblk(handle, inode, block, map_flags);
826 if (!bh || buffer_uptodate(bh))
828 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
830 if (buffer_uptodate(bh))
833 return ERR_PTR(-EIO);
836 int ext4_walk_page_buffers(handle_t *handle,
837 struct buffer_head *head,
841 int (*fn)(handle_t *handle,
842 struct buffer_head *bh))
844 struct buffer_head *bh;
845 unsigned block_start, block_end;
846 unsigned blocksize = head->b_size;
848 struct buffer_head *next;
850 for (bh = head, block_start = 0;
851 ret == 0 && (bh != head || !block_start);
852 block_start = block_end, bh = next) {
853 next = bh->b_this_page;
854 block_end = block_start + blocksize;
855 if (block_end <= from || block_start >= to) {
856 if (partial && !buffer_uptodate(bh))
860 err = (*fn)(handle, bh);
868 * To preserve ordering, it is essential that the hole instantiation and
869 * the data write be encapsulated in a single transaction. We cannot
870 * close off a transaction and start a new one between the ext4_get_block()
871 * and the commit_write(). So doing the jbd2_journal_start at the start of
872 * prepare_write() is the right place.
874 * Also, this function can nest inside ext4_writepage(). In that case, we
875 * *know* that ext4_writepage() has generated enough buffer credits to do the
876 * whole page. So we won't block on the journal in that case, which is good,
877 * because the caller may be PF_MEMALLOC.
879 * By accident, ext4 can be reentered when a transaction is open via
880 * quota file writes. If we were to commit the transaction while thus
881 * reentered, there can be a deadlock - we would be holding a quota
882 * lock, and the commit would never complete if another thread had a
883 * transaction open and was blocking on the quota lock - a ranking
886 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
887 * will _not_ run commit under these circumstances because handle->h_ref
888 * is elevated. We'll still have enough credits for the tiny quotafile
891 int do_journal_get_write_access(handle_t *handle,
892 struct buffer_head *bh)
894 int dirty = buffer_dirty(bh);
897 if (!buffer_mapped(bh) || buffer_freed(bh))
900 * __block_write_begin() could have dirtied some buffers. Clean
901 * the dirty bit as jbd2_journal_get_write_access() could complain
902 * otherwise about fs integrity issues. Setting of the dirty bit
903 * by __block_write_begin() isn't a real problem here as we clear
904 * the bit before releasing a page lock and thus writeback cannot
905 * ever write the buffer.
908 clear_buffer_dirty(bh);
909 BUFFER_TRACE(bh, "get write access");
910 ret = ext4_journal_get_write_access(handle, bh);
912 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
916 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
917 struct buffer_head *bh_result, int create);
919 #ifdef CONFIG_EXT4_FS_ENCRYPTION
920 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
921 get_block_t *get_block)
923 unsigned from = pos & (PAGE_CACHE_SIZE - 1);
924 unsigned to = from + len;
925 struct inode *inode = page->mapping->host;
926 unsigned block_start, block_end;
929 unsigned blocksize = inode->i_sb->s_blocksize;
931 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
932 bool decrypt = false;
934 BUG_ON(!PageLocked(page));
935 BUG_ON(from > PAGE_CACHE_SIZE);
936 BUG_ON(to > PAGE_CACHE_SIZE);
939 if (!page_has_buffers(page))
940 create_empty_buffers(page, blocksize, 0);
941 head = page_buffers(page);
942 bbits = ilog2(blocksize);
943 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
945 for (bh = head, block_start = 0; bh != head || !block_start;
946 block++, block_start = block_end, bh = bh->b_this_page) {
947 block_end = block_start + blocksize;
948 if (block_end <= from || block_start >= to) {
949 if (PageUptodate(page)) {
950 if (!buffer_uptodate(bh))
951 set_buffer_uptodate(bh);
956 clear_buffer_new(bh);
957 if (!buffer_mapped(bh)) {
958 WARN_ON(bh->b_size != blocksize);
959 err = get_block(inode, block, bh, 1);
962 if (buffer_new(bh)) {
963 unmap_underlying_metadata(bh->b_bdev,
965 if (PageUptodate(page)) {
966 clear_buffer_new(bh);
967 set_buffer_uptodate(bh);
968 mark_buffer_dirty(bh);
971 if (block_end > to || block_start < from)
972 zero_user_segments(page, to, block_end,
977 if (PageUptodate(page)) {
978 if (!buffer_uptodate(bh))
979 set_buffer_uptodate(bh);
982 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
983 !buffer_unwritten(bh) &&
984 (block_start < from || block_end > to)) {
985 ll_rw_block(READ, 1, &bh);
987 decrypt = ext4_encrypted_inode(inode) &&
988 S_ISREG(inode->i_mode);
992 * If we issued read requests, let them complete.
994 while (wait_bh > wait) {
995 wait_on_buffer(*--wait_bh);
996 if (!buffer_uptodate(*wait_bh))
1000 page_zero_new_buffers(page, from, to);
1002 err = ext4_decrypt(page);
1007 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1008 loff_t pos, unsigned len, unsigned flags,
1009 struct page **pagep, void **fsdata)
1011 struct inode *inode = mapping->host;
1012 int ret, needed_blocks;
1019 trace_ext4_write_begin(inode, pos, len, flags);
1021 * Reserve one block more for addition to orphan list in case
1022 * we allocate blocks but write fails for some reason
1024 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1025 index = pos >> PAGE_CACHE_SHIFT;
1026 from = pos & (PAGE_CACHE_SIZE - 1);
1029 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1030 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1039 * grab_cache_page_write_begin() can take a long time if the
1040 * system is thrashing due to memory pressure, or if the page
1041 * is being written back. So grab it first before we start
1042 * the transaction handle. This also allows us to allocate
1043 * the page (if needed) without using GFP_NOFS.
1046 page = grab_cache_page_write_begin(mapping, index, flags);
1052 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1053 if (IS_ERR(handle)) {
1054 page_cache_release(page);
1055 return PTR_ERR(handle);
1059 if (page->mapping != mapping) {
1060 /* The page got truncated from under us */
1062 page_cache_release(page);
1063 ext4_journal_stop(handle);
1066 /* In case writeback began while the page was unlocked */
1067 wait_for_stable_page(page);
1069 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1070 if (ext4_should_dioread_nolock(inode))
1071 ret = ext4_block_write_begin(page, pos, len,
1072 ext4_get_block_write);
1074 ret = ext4_block_write_begin(page, pos, len,
1077 if (ext4_should_dioread_nolock(inode))
1078 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1080 ret = __block_write_begin(page, pos, len, ext4_get_block);
1082 if (!ret && ext4_should_journal_data(inode)) {
1083 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1085 do_journal_get_write_access);
1091 * __block_write_begin may have instantiated a few blocks
1092 * outside i_size. Trim these off again. Don't need
1093 * i_size_read because we hold i_mutex.
1095 * Add inode to orphan list in case we crash before
1098 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1099 ext4_orphan_add(handle, inode);
1101 ext4_journal_stop(handle);
1102 if (pos + len > inode->i_size) {
1103 ext4_truncate_failed_write(inode);
1105 * If truncate failed early the inode might
1106 * still be on the orphan list; we need to
1107 * make sure the inode is removed from the
1108 * orphan list in that case.
1111 ext4_orphan_del(NULL, inode);
1114 if (ret == -ENOSPC &&
1115 ext4_should_retry_alloc(inode->i_sb, &retries))
1117 page_cache_release(page);
1124 /* For write_end() in data=journal mode */
1125 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1128 if (!buffer_mapped(bh) || buffer_freed(bh))
1130 set_buffer_uptodate(bh);
1131 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1132 clear_buffer_meta(bh);
1133 clear_buffer_prio(bh);
1138 * We need to pick up the new inode size which generic_commit_write gave us
1139 * `file' can be NULL - eg, when called from page_symlink().
1141 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1142 * buffers are managed internally.
1144 static int ext4_write_end(struct file *file,
1145 struct address_space *mapping,
1146 loff_t pos, unsigned len, unsigned copied,
1147 struct page *page, void *fsdata)
1149 handle_t *handle = ext4_journal_current_handle();
1150 struct inode *inode = mapping->host;
1151 loff_t old_size = inode->i_size;
1153 int i_size_changed = 0;
1155 trace_ext4_write_end(inode, pos, len, copied);
1156 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1157 ret = ext4_jbd2_file_inode(handle, inode);
1160 page_cache_release(page);
1165 if (ext4_has_inline_data(inode)) {
1166 ret = ext4_write_inline_data_end(inode, pos, len,
1175 copied = block_write_end(file, mapping, pos,
1176 len, copied, page, fsdata);
1178 * it's important to update i_size while still holding page lock:
1179 * page writeout could otherwise come in and zero beyond i_size.
1181 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1183 page_cache_release(page);
1186 pagecache_isize_extended(inode, old_size, pos);
1188 * Don't mark the inode dirty under page lock. First, it unnecessarily
1189 * makes the holding time of page lock longer. Second, it forces lock
1190 * ordering of page lock and transaction start for journaling
1194 ext4_mark_inode_dirty(handle, inode);
1196 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1197 /* if we have allocated more blocks and copied
1198 * less. We will have blocks allocated outside
1199 * inode->i_size. So truncate them
1201 ext4_orphan_add(handle, inode);
1203 ret2 = ext4_journal_stop(handle);
1207 if (pos + len > inode->i_size) {
1208 ext4_truncate_failed_write(inode);
1210 * If truncate failed early the inode might still be
1211 * on the orphan list; we need to make sure the inode
1212 * is removed from the orphan list in that case.
1215 ext4_orphan_del(NULL, inode);
1218 return ret ? ret : copied;
1222 * This is a private version of page_zero_new_buffers() which doesn't
1223 * set the buffer to be dirty, since in data=journalled mode we need
1224 * to call ext4_handle_dirty_metadata() instead.
1226 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1228 unsigned from, unsigned to)
1230 unsigned int block_start = 0, block_end;
1231 struct buffer_head *head, *bh;
1233 bh = head = page_buffers(page);
1235 block_end = block_start + bh->b_size;
1236 if (buffer_new(bh)) {
1237 if (block_end > from && block_start < to) {
1238 if (!PageUptodate(page)) {
1239 unsigned start, size;
1241 start = max(from, block_start);
1242 size = min(to, block_end) - start;
1244 zero_user(page, start, size);
1245 write_end_fn(handle, bh);
1247 clear_buffer_new(bh);
1250 block_start = block_end;
1251 bh = bh->b_this_page;
1252 } while (bh != head);
1255 static int ext4_journalled_write_end(struct file *file,
1256 struct address_space *mapping,
1257 loff_t pos, unsigned len, unsigned copied,
1258 struct page *page, void *fsdata)
1260 handle_t *handle = ext4_journal_current_handle();
1261 struct inode *inode = mapping->host;
1262 loff_t old_size = inode->i_size;
1266 int size_changed = 0;
1268 trace_ext4_journalled_write_end(inode, pos, len, copied);
1269 from = pos & (PAGE_CACHE_SIZE - 1);
1272 BUG_ON(!ext4_handle_valid(handle));
1274 if (ext4_has_inline_data(inode)) {
1275 ret = ext4_write_inline_data_end(inode, pos, len,
1283 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1285 ext4_journalled_zero_new_buffers(handle, page, from, to);
1287 if (unlikely(copied < len))
1288 ext4_journalled_zero_new_buffers(handle, page,
1290 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1291 from + copied, &partial,
1294 SetPageUptodate(page);
1296 size_changed = ext4_update_inode_size(inode, pos + copied);
1297 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1298 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1300 page_cache_release(page);
1303 pagecache_isize_extended(inode, old_size, pos);
1306 ret2 = ext4_mark_inode_dirty(handle, inode);
1311 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1312 /* if we have allocated more blocks and copied
1313 * less. We will have blocks allocated outside
1314 * inode->i_size. So truncate them
1316 ext4_orphan_add(handle, inode);
1319 ret2 = ext4_journal_stop(handle);
1322 if (pos + len > inode->i_size) {
1323 ext4_truncate_failed_write(inode);
1325 * If truncate failed early the inode might still be
1326 * on the orphan list; we need to make sure the inode
1327 * is removed from the orphan list in that case.
1330 ext4_orphan_del(NULL, inode);
1333 return ret ? ret : copied;
1337 * Reserve space for a single cluster
1339 static int ext4_da_reserve_space(struct inode *inode)
1341 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1342 struct ext4_inode_info *ei = EXT4_I(inode);
1346 * We will charge metadata quota at writeout time; this saves
1347 * us from metadata over-estimation, though we may go over by
1348 * a small amount in the end. Here we just reserve for data.
1350 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1354 spin_lock(&ei->i_block_reservation_lock);
1355 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1356 spin_unlock(&ei->i_block_reservation_lock);
1357 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1360 ei->i_reserved_data_blocks++;
1361 trace_ext4_da_reserve_space(inode);
1362 spin_unlock(&ei->i_block_reservation_lock);
1364 return 0; /* success */
1367 static void ext4_da_release_space(struct inode *inode, int to_free)
1369 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1370 struct ext4_inode_info *ei = EXT4_I(inode);
1373 return; /* Nothing to release, exit */
1375 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1377 trace_ext4_da_release_space(inode, to_free);
1378 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1380 * if there aren't enough reserved blocks, then the
1381 * counter is messed up somewhere. Since this
1382 * function is called from invalidate page, it's
1383 * harmless to return without any action.
1385 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1386 "ino %lu, to_free %d with only %d reserved "
1387 "data blocks", inode->i_ino, to_free,
1388 ei->i_reserved_data_blocks);
1390 to_free = ei->i_reserved_data_blocks;
1392 ei->i_reserved_data_blocks -= to_free;
1394 /* update fs dirty data blocks counter */
1395 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1397 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1399 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1402 static void ext4_da_page_release_reservation(struct page *page,
1403 unsigned int offset,
1404 unsigned int length)
1406 int to_release = 0, contiguous_blks = 0;
1407 struct buffer_head *head, *bh;
1408 unsigned int curr_off = 0;
1409 struct inode *inode = page->mapping->host;
1410 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1411 unsigned int stop = offset + length;
1415 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1417 head = page_buffers(page);
1420 unsigned int next_off = curr_off + bh->b_size;
1422 if (next_off > stop)
1425 if ((offset <= curr_off) && (buffer_delay(bh))) {
1428 clear_buffer_delay(bh);
1429 } else if (contiguous_blks) {
1430 lblk = page->index <<
1431 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1432 lblk += (curr_off >> inode->i_blkbits) -
1434 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1435 contiguous_blks = 0;
1437 curr_off = next_off;
1438 } while ((bh = bh->b_this_page) != head);
1440 if (contiguous_blks) {
1441 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1442 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1443 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1446 /* If we have released all the blocks belonging to a cluster, then we
1447 * need to release the reserved space for that cluster. */
1448 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1449 while (num_clusters > 0) {
1450 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1451 ((num_clusters - 1) << sbi->s_cluster_bits);
1452 if (sbi->s_cluster_ratio == 1 ||
1453 !ext4_find_delalloc_cluster(inode, lblk))
1454 ext4_da_release_space(inode, 1);
1461 * Delayed allocation stuff
1464 struct mpage_da_data {
1465 struct inode *inode;
1466 struct writeback_control *wbc;
1468 pgoff_t first_page; /* The first page to write */
1469 pgoff_t next_page; /* Current page to examine */
1470 pgoff_t last_page; /* Last page to examine */
1472 * Extent to map - this can be after first_page because that can be
1473 * fully mapped. We somewhat abuse m_flags to store whether the extent
1474 * is delalloc or unwritten.
1476 struct ext4_map_blocks map;
1477 struct ext4_io_submit io_submit; /* IO submission data */
1480 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1485 struct pagevec pvec;
1486 struct inode *inode = mpd->inode;
1487 struct address_space *mapping = inode->i_mapping;
1489 /* This is necessary when next_page == 0. */
1490 if (mpd->first_page >= mpd->next_page)
1493 index = mpd->first_page;
1494 end = mpd->next_page - 1;
1496 ext4_lblk_t start, last;
1497 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1498 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1499 ext4_es_remove_extent(inode, start, last - start + 1);
1502 pagevec_init(&pvec, 0);
1503 while (index <= end) {
1504 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1507 for (i = 0; i < nr_pages; i++) {
1508 struct page *page = pvec.pages[i];
1509 if (page->index > end)
1511 BUG_ON(!PageLocked(page));
1512 BUG_ON(PageWriteback(page));
1514 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1515 ClearPageUptodate(page);
1519 index = pvec.pages[nr_pages - 1]->index + 1;
1520 pagevec_release(&pvec);
1524 static void ext4_print_free_blocks(struct inode *inode)
1526 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1527 struct super_block *sb = inode->i_sb;
1528 struct ext4_inode_info *ei = EXT4_I(inode);
1530 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1531 EXT4_C2B(EXT4_SB(inode->i_sb),
1532 ext4_count_free_clusters(sb)));
1533 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1534 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1535 (long long) EXT4_C2B(EXT4_SB(sb),
1536 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1537 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1538 (long long) EXT4_C2B(EXT4_SB(sb),
1539 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1540 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1541 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1542 ei->i_reserved_data_blocks);
1546 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1548 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1552 * This function is grabs code from the very beginning of
1553 * ext4_map_blocks, but assumes that the caller is from delayed write
1554 * time. This function looks up the requested blocks and sets the
1555 * buffer delay bit under the protection of i_data_sem.
1557 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1558 struct ext4_map_blocks *map,
1559 struct buffer_head *bh)
1561 struct extent_status es;
1563 sector_t invalid_block = ~((sector_t) 0xffff);
1564 #ifdef ES_AGGRESSIVE_TEST
1565 struct ext4_map_blocks orig_map;
1567 memcpy(&orig_map, map, sizeof(*map));
1570 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1574 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1575 "logical block %lu\n", inode->i_ino, map->m_len,
1576 (unsigned long) map->m_lblk);
1578 /* Lookup extent status tree firstly */
1579 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1580 if (ext4_es_is_hole(&es)) {
1582 down_read(&EXT4_I(inode)->i_data_sem);
1587 * Delayed extent could be allocated by fallocate.
1588 * So we need to check it.
1590 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1591 map_bh(bh, inode->i_sb, invalid_block);
1593 set_buffer_delay(bh);
1597 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1598 retval = es.es_len - (iblock - es.es_lblk);
1599 if (retval > map->m_len)
1600 retval = map->m_len;
1601 map->m_len = retval;
1602 if (ext4_es_is_written(&es))
1603 map->m_flags |= EXT4_MAP_MAPPED;
1604 else if (ext4_es_is_unwritten(&es))
1605 map->m_flags |= EXT4_MAP_UNWRITTEN;
1609 #ifdef ES_AGGRESSIVE_TEST
1610 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1616 * Try to see if we can get the block without requesting a new
1617 * file system block.
1619 down_read(&EXT4_I(inode)->i_data_sem);
1620 if (ext4_has_inline_data(inode))
1622 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1623 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1625 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1631 * XXX: __block_prepare_write() unmaps passed block,
1635 * If the block was allocated from previously allocated cluster,
1636 * then we don't need to reserve it again. However we still need
1637 * to reserve metadata for every block we're going to write.
1639 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1640 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1641 ret = ext4_da_reserve_space(inode);
1643 /* not enough space to reserve */
1649 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1650 ~0, EXTENT_STATUS_DELAYED);
1656 map_bh(bh, inode->i_sb, invalid_block);
1658 set_buffer_delay(bh);
1659 } else if (retval > 0) {
1661 unsigned int status;
1663 if (unlikely(retval != map->m_len)) {
1664 ext4_warning(inode->i_sb,
1665 "ES len assertion failed for inode "
1666 "%lu: retval %d != map->m_len %d",
1667 inode->i_ino, retval, map->m_len);
1671 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1672 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1673 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1674 map->m_pblk, status);
1680 up_read((&EXT4_I(inode)->i_data_sem));
1686 * This is a special get_block_t callback which is used by
1687 * ext4_da_write_begin(). It will either return mapped block or
1688 * reserve space for a single block.
1690 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1691 * We also have b_blocknr = -1 and b_bdev initialized properly
1693 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1694 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1695 * initialized properly.
1697 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1698 struct buffer_head *bh, int create)
1700 struct ext4_map_blocks map;
1703 BUG_ON(create == 0);
1704 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1706 map.m_lblk = iblock;
1710 * first, we need to know whether the block is allocated already
1711 * preallocated blocks are unmapped but should treated
1712 * the same as allocated blocks.
1714 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1718 map_bh(bh, inode->i_sb, map.m_pblk);
1719 ext4_update_bh_state(bh, map.m_flags);
1721 if (buffer_unwritten(bh)) {
1722 /* A delayed write to unwritten bh should be marked
1723 * new and mapped. Mapped ensures that we don't do
1724 * get_block multiple times when we write to the same
1725 * offset and new ensures that we do proper zero out
1726 * for partial write.
1729 set_buffer_mapped(bh);
1734 static int bget_one(handle_t *handle, struct buffer_head *bh)
1740 static int bput_one(handle_t *handle, struct buffer_head *bh)
1746 static int __ext4_journalled_writepage(struct page *page,
1749 struct address_space *mapping = page->mapping;
1750 struct inode *inode = mapping->host;
1751 struct buffer_head *page_bufs = NULL;
1752 handle_t *handle = NULL;
1753 int ret = 0, err = 0;
1754 int inline_data = ext4_has_inline_data(inode);
1755 struct buffer_head *inode_bh = NULL;
1757 ClearPageChecked(page);
1760 BUG_ON(page->index != 0);
1761 BUG_ON(len > ext4_get_max_inline_size(inode));
1762 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1763 if (inode_bh == NULL)
1766 page_bufs = page_buffers(page);
1771 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1775 * We need to release the page lock before we start the
1776 * journal, so grab a reference so the page won't disappear
1777 * out from under us.
1782 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1783 ext4_writepage_trans_blocks(inode));
1784 if (IS_ERR(handle)) {
1785 ret = PTR_ERR(handle);
1787 goto out_no_pagelock;
1789 BUG_ON(!ext4_handle_valid(handle));
1793 if (page->mapping != mapping) {
1794 /* The page got truncated from under us */
1795 ext4_journal_stop(handle);
1801 BUFFER_TRACE(inode_bh, "get write access");
1802 ret = ext4_journal_get_write_access(handle, inode_bh);
1804 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1807 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1808 do_journal_get_write_access);
1810 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1815 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1816 err = ext4_journal_stop(handle);
1820 if (!ext4_has_inline_data(inode))
1821 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1823 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1832 * Note that we don't need to start a transaction unless we're journaling data
1833 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1834 * need to file the inode to the transaction's list in ordered mode because if
1835 * we are writing back data added by write(), the inode is already there and if
1836 * we are writing back data modified via mmap(), no one guarantees in which
1837 * transaction the data will hit the disk. In case we are journaling data, we
1838 * cannot start transaction directly because transaction start ranks above page
1839 * lock so we have to do some magic.
1841 * This function can get called via...
1842 * - ext4_writepages after taking page lock (have journal handle)
1843 * - journal_submit_inode_data_buffers (no journal handle)
1844 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1845 * - grab_page_cache when doing write_begin (have journal handle)
1847 * We don't do any block allocation in this function. If we have page with
1848 * multiple blocks we need to write those buffer_heads that are mapped. This
1849 * is important for mmaped based write. So if we do with blocksize 1K
1850 * truncate(f, 1024);
1851 * a = mmap(f, 0, 4096);
1853 * truncate(f, 4096);
1854 * we have in the page first buffer_head mapped via page_mkwrite call back
1855 * but other buffer_heads would be unmapped but dirty (dirty done via the
1856 * do_wp_page). So writepage should write the first block. If we modify
1857 * the mmap area beyond 1024 we will again get a page_fault and the
1858 * page_mkwrite callback will do the block allocation and mark the
1859 * buffer_heads mapped.
1861 * We redirty the page if we have any buffer_heads that is either delay or
1862 * unwritten in the page.
1864 * We can get recursively called as show below.
1866 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1869 * But since we don't do any block allocation we should not deadlock.
1870 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1872 static int ext4_writepage(struct page *page,
1873 struct writeback_control *wbc)
1878 struct buffer_head *page_bufs = NULL;
1879 struct inode *inode = page->mapping->host;
1880 struct ext4_io_submit io_submit;
1881 bool keep_towrite = false;
1883 trace_ext4_writepage(page);
1884 size = i_size_read(inode);
1885 if (page->index == size >> PAGE_CACHE_SHIFT)
1886 len = size & ~PAGE_CACHE_MASK;
1888 len = PAGE_CACHE_SIZE;
1890 page_bufs = page_buffers(page);
1892 * We cannot do block allocation or other extent handling in this
1893 * function. If there are buffers needing that, we have to redirty
1894 * the page. But we may reach here when we do a journal commit via
1895 * journal_submit_inode_data_buffers() and in that case we must write
1896 * allocated buffers to achieve data=ordered mode guarantees.
1898 * Also, if there is only one buffer per page (the fs block
1899 * size == the page size), if one buffer needs block
1900 * allocation or needs to modify the extent tree to clear the
1901 * unwritten flag, we know that the page can't be written at
1902 * all, so we might as well refuse the write immediately.
1903 * Unfortunately if the block size != page size, we can't as
1904 * easily detect this case using ext4_walk_page_buffers(), but
1905 * for the extremely common case, this is an optimization that
1906 * skips a useless round trip through ext4_bio_write_page().
1908 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1909 ext4_bh_delay_or_unwritten)) {
1910 redirty_page_for_writepage(wbc, page);
1911 if ((current->flags & PF_MEMALLOC) ||
1912 (inode->i_sb->s_blocksize == PAGE_CACHE_SIZE)) {
1914 * For memory cleaning there's no point in writing only
1915 * some buffers. So just bail out. Warn if we came here
1916 * from direct reclaim.
1918 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1923 keep_towrite = true;
1926 if (PageChecked(page) && ext4_should_journal_data(inode))
1928 * It's mmapped pagecache. Add buffers and journal it. There
1929 * doesn't seem much point in redirtying the page here.
1931 return __ext4_journalled_writepage(page, len);
1933 ext4_io_submit_init(&io_submit, wbc);
1934 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1935 if (!io_submit.io_end) {
1936 redirty_page_for_writepage(wbc, page);
1940 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1941 ext4_io_submit(&io_submit);
1942 /* Drop io_end reference we got from init */
1943 ext4_put_io_end_defer(io_submit.io_end);
1947 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1950 loff_t size = i_size_read(mpd->inode);
1953 BUG_ON(page->index != mpd->first_page);
1954 if (page->index == size >> PAGE_CACHE_SHIFT)
1955 len = size & ~PAGE_CACHE_MASK;
1957 len = PAGE_CACHE_SIZE;
1958 clear_page_dirty_for_io(page);
1959 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1961 mpd->wbc->nr_to_write--;
1967 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1970 * mballoc gives us at most this number of blocks...
1971 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1972 * The rest of mballoc seems to handle chunks up to full group size.
1974 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1977 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1979 * @mpd - extent of blocks
1980 * @lblk - logical number of the block in the file
1981 * @bh - buffer head we want to add to the extent
1983 * The function is used to collect contig. blocks in the same state. If the
1984 * buffer doesn't require mapping for writeback and we haven't started the
1985 * extent of buffers to map yet, the function returns 'true' immediately - the
1986 * caller can write the buffer right away. Otherwise the function returns true
1987 * if the block has been added to the extent, false if the block couldn't be
1990 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1991 struct buffer_head *bh)
1993 struct ext4_map_blocks *map = &mpd->map;
1995 /* Buffer that doesn't need mapping for writeback? */
1996 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1997 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1998 /* So far no extent to map => we write the buffer right away */
1999 if (map->m_len == 0)
2004 /* First block in the extent? */
2005 if (map->m_len == 0) {
2008 map->m_flags = bh->b_state & BH_FLAGS;
2012 /* Don't go larger than mballoc is willing to allocate */
2013 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2016 /* Can we merge the block to our big extent? */
2017 if (lblk == map->m_lblk + map->m_len &&
2018 (bh->b_state & BH_FLAGS) == map->m_flags) {
2026 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2028 * @mpd - extent of blocks for mapping
2029 * @head - the first buffer in the page
2030 * @bh - buffer we should start processing from
2031 * @lblk - logical number of the block in the file corresponding to @bh
2033 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2034 * the page for IO if all buffers in this page were mapped and there's no
2035 * accumulated extent of buffers to map or add buffers in the page to the
2036 * extent of buffers to map. The function returns 1 if the caller can continue
2037 * by processing the next page, 0 if it should stop adding buffers to the
2038 * extent to map because we cannot extend it anymore. It can also return value
2039 * < 0 in case of error during IO submission.
2041 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2042 struct buffer_head *head,
2043 struct buffer_head *bh,
2046 struct inode *inode = mpd->inode;
2048 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
2049 >> inode->i_blkbits;
2052 BUG_ON(buffer_locked(bh));
2054 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2055 /* Found extent to map? */
2058 /* Everything mapped so far and we hit EOF */
2061 } while (lblk++, (bh = bh->b_this_page) != head);
2062 /* So far everything mapped? Submit the page for IO. */
2063 if (mpd->map.m_len == 0) {
2064 err = mpage_submit_page(mpd, head->b_page);
2068 return lblk < blocks;
2072 * mpage_map_buffers - update buffers corresponding to changed extent and
2073 * submit fully mapped pages for IO
2075 * @mpd - description of extent to map, on return next extent to map
2077 * Scan buffers corresponding to changed extent (we expect corresponding pages
2078 * to be already locked) and update buffer state according to new extent state.
2079 * We map delalloc buffers to their physical location, clear unwritten bits,
2080 * and mark buffers as uninit when we perform writes to unwritten extents
2081 * and do extent conversion after IO is finished. If the last page is not fully
2082 * mapped, we update @map to the next extent in the last page that needs
2083 * mapping. Otherwise we submit the page for IO.
2085 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2087 struct pagevec pvec;
2089 struct inode *inode = mpd->inode;
2090 struct buffer_head *head, *bh;
2091 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2097 start = mpd->map.m_lblk >> bpp_bits;
2098 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2099 lblk = start << bpp_bits;
2100 pblock = mpd->map.m_pblk;
2102 pagevec_init(&pvec, 0);
2103 while (start <= end) {
2104 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2108 for (i = 0; i < nr_pages; i++) {
2109 struct page *page = pvec.pages[i];
2111 if (page->index > end)
2113 /* Up to 'end' pages must be contiguous */
2114 BUG_ON(page->index != start);
2115 bh = head = page_buffers(page);
2117 if (lblk < mpd->map.m_lblk)
2119 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2121 * Buffer after end of mapped extent.
2122 * Find next buffer in the page to map.
2125 mpd->map.m_flags = 0;
2127 * FIXME: If dioread_nolock supports
2128 * blocksize < pagesize, we need to make
2129 * sure we add size mapped so far to
2130 * io_end->size as the following call
2131 * can submit the page for IO.
2133 err = mpage_process_page_bufs(mpd, head,
2135 pagevec_release(&pvec);
2140 if (buffer_delay(bh)) {
2141 clear_buffer_delay(bh);
2142 bh->b_blocknr = pblock++;
2144 clear_buffer_unwritten(bh);
2145 } while (lblk++, (bh = bh->b_this_page) != head);
2148 * FIXME: This is going to break if dioread_nolock
2149 * supports blocksize < pagesize as we will try to
2150 * convert potentially unmapped parts of inode.
2152 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2153 /* Page fully mapped - let IO run! */
2154 err = mpage_submit_page(mpd, page);
2156 pagevec_release(&pvec);
2161 pagevec_release(&pvec);
2163 /* Extent fully mapped and matches with page boundary. We are done. */
2165 mpd->map.m_flags = 0;
2169 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2171 struct inode *inode = mpd->inode;
2172 struct ext4_map_blocks *map = &mpd->map;
2173 int get_blocks_flags;
2174 int err, dioread_nolock;
2176 trace_ext4_da_write_pages_extent(inode, map);
2178 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2179 * to convert an unwritten extent to be initialized (in the case
2180 * where we have written into one or more preallocated blocks). It is
2181 * possible that we're going to need more metadata blocks than
2182 * previously reserved. However we must not fail because we're in
2183 * writeback and there is nothing we can do about it so it might result
2184 * in data loss. So use reserved blocks to allocate metadata if
2187 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2188 * the blocks in question are delalloc blocks. This indicates
2189 * that the blocks and quotas has already been checked when
2190 * the data was copied into the page cache.
2192 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2193 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2194 dioread_nolock = ext4_should_dioread_nolock(inode);
2196 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2197 if (map->m_flags & (1 << BH_Delay))
2198 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2200 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2203 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2204 if (!mpd->io_submit.io_end->handle &&
2205 ext4_handle_valid(handle)) {
2206 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2207 handle->h_rsv_handle = NULL;
2209 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2212 BUG_ON(map->m_len == 0);
2213 if (map->m_flags & EXT4_MAP_NEW) {
2214 struct block_device *bdev = inode->i_sb->s_bdev;
2217 for (i = 0; i < map->m_len; i++)
2218 unmap_underlying_metadata(bdev, map->m_pblk + i);
2224 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2225 * mpd->len and submit pages underlying it for IO
2227 * @handle - handle for journal operations
2228 * @mpd - extent to map
2229 * @give_up_on_write - we set this to true iff there is a fatal error and there
2230 * is no hope of writing the data. The caller should discard
2231 * dirty pages to avoid infinite loops.
2233 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2234 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2235 * them to initialized or split the described range from larger unwritten
2236 * extent. Note that we need not map all the described range since allocation
2237 * can return less blocks or the range is covered by more unwritten extents. We
2238 * cannot map more because we are limited by reserved transaction credits. On
2239 * the other hand we always make sure that the last touched page is fully
2240 * mapped so that it can be written out (and thus forward progress is
2241 * guaranteed). After mapping we submit all mapped pages for IO.
2243 static int mpage_map_and_submit_extent(handle_t *handle,
2244 struct mpage_da_data *mpd,
2245 bool *give_up_on_write)
2247 struct inode *inode = mpd->inode;
2248 struct ext4_map_blocks *map = &mpd->map;
2253 mpd->io_submit.io_end->offset =
2254 ((loff_t)map->m_lblk) << inode->i_blkbits;
2256 err = mpage_map_one_extent(handle, mpd);
2258 struct super_block *sb = inode->i_sb;
2260 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2261 goto invalidate_dirty_pages;
2263 * Let the uper layers retry transient errors.
2264 * In the case of ENOSPC, if ext4_count_free_blocks()
2265 * is non-zero, a commit should free up blocks.
2267 if ((err == -ENOMEM) ||
2268 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2270 goto update_disksize;
2273 ext4_msg(sb, KERN_CRIT,
2274 "Delayed block allocation failed for "
2275 "inode %lu at logical offset %llu with"
2276 " max blocks %u with error %d",
2278 (unsigned long long)map->m_lblk,
2279 (unsigned)map->m_len, -err);
2280 ext4_msg(sb, KERN_CRIT,
2281 "This should not happen!! Data will "
2284 ext4_print_free_blocks(inode);
2285 invalidate_dirty_pages:
2286 *give_up_on_write = true;
2291 * Update buffer state, submit mapped pages, and get us new
2294 err = mpage_map_and_submit_buffers(mpd);
2296 goto update_disksize;
2297 } while (map->m_len);
2301 * Update on-disk size after IO is submitted. Races with
2302 * truncate are avoided by checking i_size under i_data_sem.
2304 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2305 if (disksize > EXT4_I(inode)->i_disksize) {
2309 down_write(&EXT4_I(inode)->i_data_sem);
2310 i_size = i_size_read(inode);
2311 if (disksize > i_size)
2313 if (disksize > EXT4_I(inode)->i_disksize)
2314 EXT4_I(inode)->i_disksize = disksize;
2315 err2 = ext4_mark_inode_dirty(handle, inode);
2316 up_write(&EXT4_I(inode)->i_data_sem);
2318 ext4_error(inode->i_sb,
2319 "Failed to mark inode %lu dirty",
2328 * Calculate the total number of credits to reserve for one writepages
2329 * iteration. This is called from ext4_writepages(). We map an extent of
2330 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2331 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2332 * bpp - 1 blocks in bpp different extents.
2334 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2336 int bpp = ext4_journal_blocks_per_page(inode);
2338 return ext4_meta_trans_blocks(inode,
2339 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2343 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2344 * and underlying extent to map
2346 * @mpd - where to look for pages
2348 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2349 * IO immediately. When we find a page which isn't mapped we start accumulating
2350 * extent of buffers underlying these pages that needs mapping (formed by
2351 * either delayed or unwritten buffers). We also lock the pages containing
2352 * these buffers. The extent found is returned in @mpd structure (starting at
2353 * mpd->lblk with length mpd->len blocks).
2355 * Note that this function can attach bios to one io_end structure which are
2356 * neither logically nor physically contiguous. Although it may seem as an
2357 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2358 * case as we need to track IO to all buffers underlying a page in one io_end.
2360 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2362 struct address_space *mapping = mpd->inode->i_mapping;
2363 struct pagevec pvec;
2364 unsigned int nr_pages;
2365 long left = mpd->wbc->nr_to_write;
2366 pgoff_t index = mpd->first_page;
2367 pgoff_t end = mpd->last_page;
2370 int blkbits = mpd->inode->i_blkbits;
2372 struct buffer_head *head;
2374 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2375 tag = PAGECACHE_TAG_TOWRITE;
2377 tag = PAGECACHE_TAG_DIRTY;
2379 pagevec_init(&pvec, 0);
2381 mpd->next_page = index;
2382 while (index <= end) {
2383 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2384 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2388 for (i = 0; i < nr_pages; i++) {
2389 struct page *page = pvec.pages[i];
2392 * At this point, the page may be truncated or
2393 * invalidated (changing page->mapping to NULL), or
2394 * even swizzled back from swapper_space to tmpfs file
2395 * mapping. However, page->index will not change
2396 * because we have a reference on the page.
2398 if (page->index > end)
2402 * Accumulated enough dirty pages? This doesn't apply
2403 * to WB_SYNC_ALL mode. For integrity sync we have to
2404 * keep going because someone may be concurrently
2405 * dirtying pages, and we might have synced a lot of
2406 * newly appeared dirty pages, but have not synced all
2407 * of the old dirty pages.
2409 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2412 /* If we can't merge this page, we are done. */
2413 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2418 * If the page is no longer dirty, or its mapping no
2419 * longer corresponds to inode we are writing (which
2420 * means it has been truncated or invalidated), or the
2421 * page is already under writeback and we are not doing
2422 * a data integrity writeback, skip the page
2424 if (!PageDirty(page) ||
2425 (PageWriteback(page) &&
2426 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2427 unlikely(page->mapping != mapping)) {
2432 wait_on_page_writeback(page);
2433 BUG_ON(PageWriteback(page));
2435 if (mpd->map.m_len == 0)
2436 mpd->first_page = page->index;
2437 mpd->next_page = page->index + 1;
2438 /* Add all dirty buffers to mpd */
2439 lblk = ((ext4_lblk_t)page->index) <<
2440 (PAGE_CACHE_SHIFT - blkbits);
2441 head = page_buffers(page);
2442 err = mpage_process_page_bufs(mpd, head, head, lblk);
2448 pagevec_release(&pvec);
2453 pagevec_release(&pvec);
2457 static int __writepage(struct page *page, struct writeback_control *wbc,
2460 struct address_space *mapping = data;
2461 int ret = ext4_writepage(page, wbc);
2462 mapping_set_error(mapping, ret);
2466 static int ext4_writepages(struct address_space *mapping,
2467 struct writeback_control *wbc)
2469 pgoff_t writeback_index = 0;
2470 long nr_to_write = wbc->nr_to_write;
2471 int range_whole = 0;
2473 handle_t *handle = NULL;
2474 struct mpage_da_data mpd;
2475 struct inode *inode = mapping->host;
2476 int needed_blocks, rsv_blocks = 0, ret = 0;
2477 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2479 struct blk_plug plug;
2480 bool give_up_on_write = false;
2482 trace_ext4_writepages(inode, wbc);
2485 * No pages to write? This is mainly a kludge to avoid starting
2486 * a transaction for special inodes like journal inode on last iput()
2487 * because that could violate lock ordering on umount
2489 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2490 goto out_writepages;
2492 if (ext4_should_journal_data(inode)) {
2493 struct blk_plug plug;
2495 blk_start_plug(&plug);
2496 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2497 blk_finish_plug(&plug);
2498 goto out_writepages;
2502 * If the filesystem has aborted, it is read-only, so return
2503 * right away instead of dumping stack traces later on that
2504 * will obscure the real source of the problem. We test
2505 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2506 * the latter could be true if the filesystem is mounted
2507 * read-only, and in that case, ext4_writepages should
2508 * *never* be called, so if that ever happens, we would want
2511 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2513 goto out_writepages;
2516 if (ext4_should_dioread_nolock(inode)) {
2518 * We may need to convert up to one extent per block in
2519 * the page and we may dirty the inode.
2521 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2525 * If we have inline data and arrive here, it means that
2526 * we will soon create the block for the 1st page, so
2527 * we'd better clear the inline data here.
2529 if (ext4_has_inline_data(inode)) {
2530 /* Just inode will be modified... */
2531 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2532 if (IS_ERR(handle)) {
2533 ret = PTR_ERR(handle);
2534 goto out_writepages;
2536 BUG_ON(ext4_test_inode_state(inode,
2537 EXT4_STATE_MAY_INLINE_DATA));
2538 ext4_destroy_inline_data(handle, inode);
2539 ext4_journal_stop(handle);
2542 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2545 if (wbc->range_cyclic) {
2546 writeback_index = mapping->writeback_index;
2547 if (writeback_index)
2549 mpd.first_page = writeback_index;
2552 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2553 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2558 ext4_io_submit_init(&mpd.io_submit, wbc);
2560 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2561 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2563 blk_start_plug(&plug);
2564 while (!done && mpd.first_page <= mpd.last_page) {
2565 /* For each extent of pages we use new io_end */
2566 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2567 if (!mpd.io_submit.io_end) {
2573 * We have two constraints: We find one extent to map and we
2574 * must always write out whole page (makes a difference when
2575 * blocksize < pagesize) so that we don't block on IO when we
2576 * try to write out the rest of the page. Journalled mode is
2577 * not supported by delalloc.
2579 BUG_ON(ext4_should_journal_data(inode));
2580 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2582 /* start a new transaction */
2583 handle = ext4_journal_start_with_reserve(inode,
2584 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2585 if (IS_ERR(handle)) {
2586 ret = PTR_ERR(handle);
2587 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2588 "%ld pages, ino %lu; err %d", __func__,
2589 wbc->nr_to_write, inode->i_ino, ret);
2590 /* Release allocated io_end */
2591 ext4_put_io_end(mpd.io_submit.io_end);
2595 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2596 ret = mpage_prepare_extent_to_map(&mpd);
2599 ret = mpage_map_and_submit_extent(handle, &mpd,
2603 * We scanned the whole range (or exhausted
2604 * nr_to_write), submitted what was mapped and
2605 * didn't find anything needing mapping. We are
2612 * Caution: If the handle is synchronous,
2613 * ext4_journal_stop() can wait for transaction commit
2614 * to finish which may depend on writeback of pages to
2615 * complete or on page lock to be released. In that
2616 * case, we have to wait until after after we have
2617 * submitted all the IO, released page locks we hold,
2618 * and dropped io_end reference (for extent conversion
2619 * to be able to complete) before stopping the handle.
2621 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2622 ext4_journal_stop(handle);
2625 /* Submit prepared bio */
2626 ext4_io_submit(&mpd.io_submit);
2627 /* Unlock pages we didn't use */
2628 mpage_release_unused_pages(&mpd, give_up_on_write);
2630 * Drop our io_end reference we got from init. We have
2631 * to be careful and use deferred io_end finishing if
2632 * we are still holding the transaction as we can
2633 * release the last reference to io_end which may end
2634 * up doing unwritten extent conversion.
2637 ext4_put_io_end_defer(mpd.io_submit.io_end);
2638 ext4_journal_stop(handle);
2640 ext4_put_io_end(mpd.io_submit.io_end);
2642 if (ret == -ENOSPC && sbi->s_journal) {
2644 * Commit the transaction which would
2645 * free blocks released in the transaction
2648 jbd2_journal_force_commit_nested(sbi->s_journal);
2652 /* Fatal error - ENOMEM, EIO... */
2656 blk_finish_plug(&plug);
2657 if (!ret && !cycled && wbc->nr_to_write > 0) {
2659 mpd.last_page = writeback_index - 1;
2665 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2667 * Set the writeback_index so that range_cyclic
2668 * mode will write it back later
2670 mapping->writeback_index = mpd.first_page;
2673 trace_ext4_writepages_result(inode, wbc, ret,
2674 nr_to_write - wbc->nr_to_write);
2678 static int ext4_nonda_switch(struct super_block *sb)
2680 s64 free_clusters, dirty_clusters;
2681 struct ext4_sb_info *sbi = EXT4_SB(sb);
2684 * switch to non delalloc mode if we are running low
2685 * on free block. The free block accounting via percpu
2686 * counters can get slightly wrong with percpu_counter_batch getting
2687 * accumulated on each CPU without updating global counters
2688 * Delalloc need an accurate free block accounting. So switch
2689 * to non delalloc when we are near to error range.
2692 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2694 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2696 * Start pushing delalloc when 1/2 of free blocks are dirty.
2698 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2699 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2701 if (2 * free_clusters < 3 * dirty_clusters ||
2702 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2704 * free block count is less than 150% of dirty blocks
2705 * or free blocks is less than watermark
2712 /* We always reserve for an inode update; the superblock could be there too */
2713 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2715 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2718 if (pos + len <= 0x7fffffffULL)
2721 /* We might need to update the superblock to set LARGE_FILE */
2725 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2726 loff_t pos, unsigned len, unsigned flags,
2727 struct page **pagep, void **fsdata)
2729 int ret, retries = 0;
2732 struct inode *inode = mapping->host;
2735 index = pos >> PAGE_CACHE_SHIFT;
2737 if (ext4_nonda_switch(inode->i_sb)) {
2738 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2739 return ext4_write_begin(file, mapping, pos,
2740 len, flags, pagep, fsdata);
2742 *fsdata = (void *)0;
2743 trace_ext4_da_write_begin(inode, pos, len, flags);
2745 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2746 ret = ext4_da_write_inline_data_begin(mapping, inode,
2756 * grab_cache_page_write_begin() can take a long time if the
2757 * system is thrashing due to memory pressure, or if the page
2758 * is being written back. So grab it first before we start
2759 * the transaction handle. This also allows us to allocate
2760 * the page (if needed) without using GFP_NOFS.
2763 page = grab_cache_page_write_begin(mapping, index, flags);
2769 * With delayed allocation, we don't log the i_disksize update
2770 * if there is delayed block allocation. But we still need
2771 * to journalling the i_disksize update if writes to the end
2772 * of file which has an already mapped buffer.
2775 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2776 ext4_da_write_credits(inode, pos, len));
2777 if (IS_ERR(handle)) {
2778 page_cache_release(page);
2779 return PTR_ERR(handle);
2783 if (page->mapping != mapping) {
2784 /* The page got truncated from under us */
2786 page_cache_release(page);
2787 ext4_journal_stop(handle);
2790 /* In case writeback began while the page was unlocked */
2791 wait_for_stable_page(page);
2793 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2794 ret = ext4_block_write_begin(page, pos, len,
2795 ext4_da_get_block_prep);
2797 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2801 ext4_journal_stop(handle);
2803 * block_write_begin may have instantiated a few blocks
2804 * outside i_size. Trim these off again. Don't need
2805 * i_size_read because we hold i_mutex.
2807 if (pos + len > inode->i_size)
2808 ext4_truncate_failed_write(inode);
2810 if (ret == -ENOSPC &&
2811 ext4_should_retry_alloc(inode->i_sb, &retries))
2814 page_cache_release(page);
2823 * Check if we should update i_disksize
2824 * when write to the end of file but not require block allocation
2826 static int ext4_da_should_update_i_disksize(struct page *page,
2827 unsigned long offset)
2829 struct buffer_head *bh;
2830 struct inode *inode = page->mapping->host;
2834 bh = page_buffers(page);
2835 idx = offset >> inode->i_blkbits;
2837 for (i = 0; i < idx; i++)
2838 bh = bh->b_this_page;
2840 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2845 static int ext4_da_write_end(struct file *file,
2846 struct address_space *mapping,
2847 loff_t pos, unsigned len, unsigned copied,
2848 struct page *page, void *fsdata)
2850 struct inode *inode = mapping->host;
2852 handle_t *handle = ext4_journal_current_handle();
2854 unsigned long start, end;
2855 int write_mode = (int)(unsigned long)fsdata;
2857 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2858 return ext4_write_end(file, mapping, pos,
2859 len, copied, page, fsdata);
2861 trace_ext4_da_write_end(inode, pos, len, copied);
2862 start = pos & (PAGE_CACHE_SIZE - 1);
2863 end = start + copied - 1;
2866 * generic_write_end() will run mark_inode_dirty() if i_size
2867 * changes. So let's piggyback the i_disksize mark_inode_dirty
2870 new_i_size = pos + copied;
2871 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2872 if (ext4_has_inline_data(inode) ||
2873 ext4_da_should_update_i_disksize(page, end)) {
2874 ext4_update_i_disksize(inode, new_i_size);
2875 /* We need to mark inode dirty even if
2876 * new_i_size is less that inode->i_size
2877 * bu greater than i_disksize.(hint delalloc)
2879 ext4_mark_inode_dirty(handle, inode);
2883 if (write_mode != CONVERT_INLINE_DATA &&
2884 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2885 ext4_has_inline_data(inode))
2886 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2889 ret2 = generic_write_end(file, mapping, pos, len, copied,
2895 ret2 = ext4_journal_stop(handle);
2899 return ret ? ret : copied;
2902 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2903 unsigned int length)
2906 * Drop reserved blocks
2908 BUG_ON(!PageLocked(page));
2909 if (!page_has_buffers(page))
2912 ext4_da_page_release_reservation(page, offset, length);
2915 ext4_invalidatepage(page, offset, length);
2921 * Force all delayed allocation blocks to be allocated for a given inode.
2923 int ext4_alloc_da_blocks(struct inode *inode)
2925 trace_ext4_alloc_da_blocks(inode);
2927 if (!EXT4_I(inode)->i_reserved_data_blocks)
2931 * We do something simple for now. The filemap_flush() will
2932 * also start triggering a write of the data blocks, which is
2933 * not strictly speaking necessary (and for users of
2934 * laptop_mode, not even desirable). However, to do otherwise
2935 * would require replicating code paths in:
2937 * ext4_writepages() ->
2938 * write_cache_pages() ---> (via passed in callback function)
2939 * __mpage_da_writepage() -->
2940 * mpage_add_bh_to_extent()
2941 * mpage_da_map_blocks()
2943 * The problem is that write_cache_pages(), located in
2944 * mm/page-writeback.c, marks pages clean in preparation for
2945 * doing I/O, which is not desirable if we're not planning on
2948 * We could call write_cache_pages(), and then redirty all of
2949 * the pages by calling redirty_page_for_writepage() but that
2950 * would be ugly in the extreme. So instead we would need to
2951 * replicate parts of the code in the above functions,
2952 * simplifying them because we wouldn't actually intend to
2953 * write out the pages, but rather only collect contiguous
2954 * logical block extents, call the multi-block allocator, and
2955 * then update the buffer heads with the block allocations.
2957 * For now, though, we'll cheat by calling filemap_flush(),
2958 * which will map the blocks, and start the I/O, but not
2959 * actually wait for the I/O to complete.
2961 return filemap_flush(inode->i_mapping);
2965 * bmap() is special. It gets used by applications such as lilo and by
2966 * the swapper to find the on-disk block of a specific piece of data.
2968 * Naturally, this is dangerous if the block concerned is still in the
2969 * journal. If somebody makes a swapfile on an ext4 data-journaling
2970 * filesystem and enables swap, then they may get a nasty shock when the
2971 * data getting swapped to that swapfile suddenly gets overwritten by
2972 * the original zero's written out previously to the journal and
2973 * awaiting writeback in the kernel's buffer cache.
2975 * So, if we see any bmap calls here on a modified, data-journaled file,
2976 * take extra steps to flush any blocks which might be in the cache.
2978 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2980 struct inode *inode = mapping->host;
2985 * We can get here for an inline file via the FIBMAP ioctl
2987 if (ext4_has_inline_data(inode))
2990 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2991 test_opt(inode->i_sb, DELALLOC)) {
2993 * With delalloc we want to sync the file
2994 * so that we can make sure we allocate
2997 filemap_write_and_wait(mapping);
3000 if (EXT4_JOURNAL(inode) &&
3001 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3003 * This is a REALLY heavyweight approach, but the use of
3004 * bmap on dirty files is expected to be extremely rare:
3005 * only if we run lilo or swapon on a freshly made file
3006 * do we expect this to happen.
3008 * (bmap requires CAP_SYS_RAWIO so this does not
3009 * represent an unprivileged user DOS attack --- we'd be
3010 * in trouble if mortal users could trigger this path at
3013 * NB. EXT4_STATE_JDATA is not set on files other than
3014 * regular files. If somebody wants to bmap a directory
3015 * or symlink and gets confused because the buffer
3016 * hasn't yet been flushed to disk, they deserve
3017 * everything they get.
3020 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3021 journal = EXT4_JOURNAL(inode);
3022 jbd2_journal_lock_updates(journal);
3023 err = jbd2_journal_flush(journal);
3024 jbd2_journal_unlock_updates(journal);
3030 return generic_block_bmap(mapping, block, ext4_get_block);
3033 static int ext4_readpage(struct file *file, struct page *page)
3036 struct inode *inode = page->mapping->host;
3038 trace_ext4_readpage(page);
3040 if (ext4_has_inline_data(inode))
3041 ret = ext4_readpage_inline(inode, page);
3044 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3050 ext4_readpages(struct file *file, struct address_space *mapping,
3051 struct list_head *pages, unsigned nr_pages)
3053 struct inode *inode = mapping->host;
3055 /* If the file has inline data, no need to do readpages. */
3056 if (ext4_has_inline_data(inode))
3059 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3062 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3063 unsigned int length)
3065 trace_ext4_invalidatepage(page, offset, length);
3067 /* No journalling happens on data buffers when this function is used */
3068 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3070 block_invalidatepage(page, offset, length);
3073 static int __ext4_journalled_invalidatepage(struct page *page,
3074 unsigned int offset,
3075 unsigned int length)
3077 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3079 trace_ext4_journalled_invalidatepage(page, offset, length);
3082 * If it's a full truncate we just forget about the pending dirtying
3084 if (offset == 0 && length == PAGE_CACHE_SIZE)
3085 ClearPageChecked(page);
3087 return jbd2_journal_invalidatepage(journal, page, offset, length);
3090 /* Wrapper for aops... */
3091 static void ext4_journalled_invalidatepage(struct page *page,
3092 unsigned int offset,
3093 unsigned int length)
3095 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3098 static int ext4_releasepage(struct page *page, gfp_t wait)
3100 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3102 trace_ext4_releasepage(page);
3104 /* Page has dirty journalled data -> cannot release */
3105 if (PageChecked(page))
3108 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3110 return try_to_free_buffers(page);
3114 * ext4_get_block used when preparing for a DIO write or buffer write.
3115 * We allocate an uinitialized extent if blocks haven't been allocated.
3116 * The extent will be converted to initialized after the IO is complete.
3118 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3119 struct buffer_head *bh_result, int create)
3121 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3122 inode->i_ino, create);
3123 return _ext4_get_block(inode, iblock, bh_result,
3124 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3127 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3128 struct buffer_head *bh_result, int create)
3130 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3131 inode->i_ino, create);
3132 return _ext4_get_block(inode, iblock, bh_result,
3133 EXT4_GET_BLOCKS_NO_LOCK);
3136 int ext4_get_block_dax(struct inode *inode, sector_t iblock,
3137 struct buffer_head *bh_result, int create)
3139 int flags = EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_UNWRIT_EXT;
3141 flags |= EXT4_GET_BLOCKS_CREATE;
3142 ext4_debug("ext4_get_block_dax: inode %lu, create flag %d\n",
3143 inode->i_ino, create);
3144 return _ext4_get_block(inode, iblock, bh_result, flags);
3147 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3148 ssize_t size, void *private)
3150 ext4_io_end_t *io_end = iocb->private;
3152 /* if not async direct IO just return */
3156 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3157 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3158 iocb->private, io_end->inode->i_ino, iocb, offset,
3161 iocb->private = NULL;
3162 io_end->offset = offset;
3163 io_end->size = size;
3164 ext4_put_io_end(io_end);
3168 * For ext4 extent files, ext4 will do direct-io write to holes,
3169 * preallocated extents, and those write extend the file, no need to
3170 * fall back to buffered IO.
3172 * For holes, we fallocate those blocks, mark them as unwritten
3173 * If those blocks were preallocated, we mark sure they are split, but
3174 * still keep the range to write as unwritten.
3176 * The unwritten extents will be converted to written when DIO is completed.
3177 * For async direct IO, since the IO may still pending when return, we
3178 * set up an end_io call back function, which will do the conversion
3179 * when async direct IO completed.
3181 * If the O_DIRECT write will extend the file then add this inode to the
3182 * orphan list. So recovery will truncate it back to the original size
3183 * if the machine crashes during the write.
3186 static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3189 struct file *file = iocb->ki_filp;
3190 struct inode *inode = file->f_mapping->host;
3192 size_t count = iov_iter_count(iter);
3194 get_block_t *get_block_func = NULL;
3196 loff_t final_size = offset + count;
3197 ext4_io_end_t *io_end = NULL;
3199 /* Use the old path for reads and writes beyond i_size. */
3200 if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size)
3201 return ext4_ind_direct_IO(iocb, iter, offset);
3203 BUG_ON(iocb->private == NULL);
3206 * Make all waiters for direct IO properly wait also for extent
3207 * conversion. This also disallows race between truncate() and
3208 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3210 if (iov_iter_rw(iter) == WRITE)
3211 inode_dio_begin(inode);
3213 /* If we do a overwrite dio, i_mutex locking can be released */
3214 overwrite = *((int *)iocb->private);
3217 down_read(&EXT4_I(inode)->i_data_sem);
3218 mutex_unlock(&inode->i_mutex);
3222 * We could direct write to holes and fallocate.
3224 * Allocated blocks to fill the hole are marked as
3225 * unwritten to prevent parallel buffered read to expose
3226 * the stale data before DIO complete the data IO.
3228 * As to previously fallocated extents, ext4 get_block will
3229 * just simply mark the buffer mapped but still keep the
3230 * extents unwritten.
3232 * For non AIO case, we will convert those unwritten extents
3233 * to written after return back from blockdev_direct_IO.
3235 * For async DIO, the conversion needs to be deferred when the
3236 * IO is completed. The ext4 end_io callback function will be
3237 * called to take care of the conversion work. Here for async
3238 * case, we allocate an io_end structure to hook to the iocb.
3240 iocb->private = NULL;
3241 ext4_inode_aio_set(inode, NULL);
3242 if (!is_sync_kiocb(iocb)) {
3243 io_end = ext4_init_io_end(inode, GFP_NOFS);
3249 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
3251 iocb->private = ext4_get_io_end(io_end);
3253 * we save the io structure for current async direct
3254 * IO, so that later ext4_map_blocks() could flag the
3255 * io structure whether there is a unwritten extents
3256 * needs to be converted when IO is completed.
3258 ext4_inode_aio_set(inode, io_end);
3262 get_block_func = ext4_get_block_write_nolock;
3264 get_block_func = ext4_get_block_write;
3265 dio_flags = DIO_LOCKING;
3267 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3268 BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
3271 ret = dax_do_io(iocb, inode, iter, offset, get_block_func,
3272 ext4_end_io_dio, dio_flags);
3274 ret = __blockdev_direct_IO(iocb, inode,
3275 inode->i_sb->s_bdev, iter, offset,
3277 ext4_end_io_dio, NULL, dio_flags);
3280 * Put our reference to io_end. This can free the io_end structure e.g.
3281 * in sync IO case or in case of error. It can even perform extent
3282 * conversion if all bios we submitted finished before we got here.
3283 * Note that in that case iocb->private can be already set to NULL
3287 ext4_inode_aio_set(inode, NULL);
3288 ext4_put_io_end(io_end);
3290 * When no IO was submitted ext4_end_io_dio() was not
3291 * called so we have to put iocb's reference.
3293 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3294 WARN_ON(iocb->private != io_end);
3295 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3296 ext4_put_io_end(io_end);
3297 iocb->private = NULL;
3300 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3301 EXT4_STATE_DIO_UNWRITTEN)) {
3304 * for non AIO case, since the IO is already
3305 * completed, we could do the conversion right here
3307 err = ext4_convert_unwritten_extents(NULL, inode,
3311 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3315 if (iov_iter_rw(iter) == WRITE)
3316 inode_dio_end(inode);
3317 /* take i_mutex locking again if we do a ovewrite dio */
3319 up_read(&EXT4_I(inode)->i_data_sem);
3320 mutex_lock(&inode->i_mutex);
3326 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3329 struct file *file = iocb->ki_filp;
3330 struct inode *inode = file->f_mapping->host;
3331 size_t count = iov_iter_count(iter);
3334 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3335 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3340 * If we are doing data journalling we don't support O_DIRECT
3342 if (ext4_should_journal_data(inode))
3345 /* Let buffer I/O handle the inline data case. */
3346 if (ext4_has_inline_data(inode))
3349 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3350 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3351 ret = ext4_ext_direct_IO(iocb, iter, offset);
3353 ret = ext4_ind_direct_IO(iocb, iter, offset);
3354 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3359 * Pages can be marked dirty completely asynchronously from ext4's journalling
3360 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3361 * much here because ->set_page_dirty is called under VFS locks. The page is
3362 * not necessarily locked.
3364 * We cannot just dirty the page and leave attached buffers clean, because the
3365 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3366 * or jbddirty because all the journalling code will explode.
3368 * So what we do is to mark the page "pending dirty" and next time writepage
3369 * is called, propagate that into the buffers appropriately.
3371 static int ext4_journalled_set_page_dirty(struct page *page)
3373 SetPageChecked(page);
3374 return __set_page_dirty_nobuffers(page);
3377 static const struct address_space_operations ext4_aops = {
3378 .readpage = ext4_readpage,
3379 .readpages = ext4_readpages,
3380 .writepage = ext4_writepage,
3381 .writepages = ext4_writepages,
3382 .write_begin = ext4_write_begin,
3383 .write_end = ext4_write_end,
3385 .invalidatepage = ext4_invalidatepage,
3386 .releasepage = ext4_releasepage,
3387 .direct_IO = ext4_direct_IO,
3388 .migratepage = buffer_migrate_page,
3389 .is_partially_uptodate = block_is_partially_uptodate,
3390 .error_remove_page = generic_error_remove_page,
3393 static const struct address_space_operations ext4_journalled_aops = {
3394 .readpage = ext4_readpage,
3395 .readpages = ext4_readpages,
3396 .writepage = ext4_writepage,
3397 .writepages = ext4_writepages,
3398 .write_begin = ext4_write_begin,
3399 .write_end = ext4_journalled_write_end,
3400 .set_page_dirty = ext4_journalled_set_page_dirty,
3402 .invalidatepage = ext4_journalled_invalidatepage,
3403 .releasepage = ext4_releasepage,
3404 .direct_IO = ext4_direct_IO,
3405 .is_partially_uptodate = block_is_partially_uptodate,
3406 .error_remove_page = generic_error_remove_page,
3409 static const struct address_space_operations ext4_da_aops = {
3410 .readpage = ext4_readpage,
3411 .readpages = ext4_readpages,
3412 .writepage = ext4_writepage,
3413 .writepages = ext4_writepages,
3414 .write_begin = ext4_da_write_begin,
3415 .write_end = ext4_da_write_end,
3417 .invalidatepage = ext4_da_invalidatepage,
3418 .releasepage = ext4_releasepage,
3419 .direct_IO = ext4_direct_IO,
3420 .migratepage = buffer_migrate_page,
3421 .is_partially_uptodate = block_is_partially_uptodate,
3422 .error_remove_page = generic_error_remove_page,
3425 void ext4_set_aops(struct inode *inode)
3427 switch (ext4_inode_journal_mode(inode)) {
3428 case EXT4_INODE_ORDERED_DATA_MODE:
3429 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3431 case EXT4_INODE_WRITEBACK_DATA_MODE:
3432 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3434 case EXT4_INODE_JOURNAL_DATA_MODE:
3435 inode->i_mapping->a_ops = &ext4_journalled_aops;
3440 if (test_opt(inode->i_sb, DELALLOC))
3441 inode->i_mapping->a_ops = &ext4_da_aops;
3443 inode->i_mapping->a_ops = &ext4_aops;
3446 static int __ext4_block_zero_page_range(handle_t *handle,
3447 struct address_space *mapping, loff_t from, loff_t length)
3449 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3450 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3451 unsigned blocksize, pos;
3453 struct inode *inode = mapping->host;
3454 struct buffer_head *bh;
3458 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3459 mapping_gfp_constraint(mapping, ~__GFP_FS));
3463 blocksize = inode->i_sb->s_blocksize;
3465 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3467 if (!page_has_buffers(page))
3468 create_empty_buffers(page, blocksize, 0);
3470 /* Find the buffer that contains "offset" */
3471 bh = page_buffers(page);
3473 while (offset >= pos) {
3474 bh = bh->b_this_page;
3478 if (buffer_freed(bh)) {
3479 BUFFER_TRACE(bh, "freed: skip");
3482 if (!buffer_mapped(bh)) {
3483 BUFFER_TRACE(bh, "unmapped");
3484 ext4_get_block(inode, iblock, bh, 0);
3485 /* unmapped? It's a hole - nothing to do */
3486 if (!buffer_mapped(bh)) {
3487 BUFFER_TRACE(bh, "still unmapped");
3492 /* Ok, it's mapped. Make sure it's up-to-date */
3493 if (PageUptodate(page))
3494 set_buffer_uptodate(bh);
3496 if (!buffer_uptodate(bh)) {
3498 ll_rw_block(READ, 1, &bh);
3500 /* Uhhuh. Read error. Complain and punt. */
3501 if (!buffer_uptodate(bh))
3503 if (S_ISREG(inode->i_mode) &&
3504 ext4_encrypted_inode(inode)) {
3505 /* We expect the key to be set. */
3506 BUG_ON(!ext4_has_encryption_key(inode));
3507 BUG_ON(blocksize != PAGE_CACHE_SIZE);
3508 WARN_ON_ONCE(ext4_decrypt(page));
3511 if (ext4_should_journal_data(inode)) {
3512 BUFFER_TRACE(bh, "get write access");
3513 err = ext4_journal_get_write_access(handle, bh);
3517 zero_user(page, offset, length);
3518 BUFFER_TRACE(bh, "zeroed end of block");
3520 if (ext4_should_journal_data(inode)) {
3521 err = ext4_handle_dirty_metadata(handle, inode, bh);
3524 mark_buffer_dirty(bh);
3525 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3526 err = ext4_jbd2_file_inode(handle, inode);
3531 page_cache_release(page);
3536 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3537 * starting from file offset 'from'. The range to be zero'd must
3538 * be contained with in one block. If the specified range exceeds
3539 * the end of the block it will be shortened to end of the block
3540 * that cooresponds to 'from'
3542 static int ext4_block_zero_page_range(handle_t *handle,
3543 struct address_space *mapping, loff_t from, loff_t length)
3545 struct inode *inode = mapping->host;
3546 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3547 unsigned blocksize = inode->i_sb->s_blocksize;
3548 unsigned max = blocksize - (offset & (blocksize - 1));
3551 * correct length if it does not fall between
3552 * 'from' and the end of the block
3554 if (length > max || length < 0)
3558 return dax_zero_page_range(inode, from, length, ext4_get_block);
3559 return __ext4_block_zero_page_range(handle, mapping, from, length);
3563 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3564 * up to the end of the block which corresponds to `from'.
3565 * This required during truncate. We need to physically zero the tail end
3566 * of that block so it doesn't yield old data if the file is later grown.
3568 static int ext4_block_truncate_page(handle_t *handle,
3569 struct address_space *mapping, loff_t from)
3571 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3574 struct inode *inode = mapping->host;
3576 blocksize = inode->i_sb->s_blocksize;
3577 length = blocksize - (offset & (blocksize - 1));
3579 return ext4_block_zero_page_range(handle, mapping, from, length);
3582 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3583 loff_t lstart, loff_t length)
3585 struct super_block *sb = inode->i_sb;
3586 struct address_space *mapping = inode->i_mapping;
3587 unsigned partial_start, partial_end;
3588 ext4_fsblk_t start, end;
3589 loff_t byte_end = (lstart + length - 1);
3592 partial_start = lstart & (sb->s_blocksize - 1);
3593 partial_end = byte_end & (sb->s_blocksize - 1);
3595 start = lstart >> sb->s_blocksize_bits;
3596 end = byte_end >> sb->s_blocksize_bits;
3598 /* Handle partial zero within the single block */
3600 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3601 err = ext4_block_zero_page_range(handle, mapping,
3605 /* Handle partial zero out on the start of the range */
3606 if (partial_start) {
3607 err = ext4_block_zero_page_range(handle, mapping,
3608 lstart, sb->s_blocksize);
3612 /* Handle partial zero out on the end of the range */
3613 if (partial_end != sb->s_blocksize - 1)
3614 err = ext4_block_zero_page_range(handle, mapping,
3615 byte_end - partial_end,
3620 int ext4_can_truncate(struct inode *inode)
3622 if (S_ISREG(inode->i_mode))
3624 if (S_ISDIR(inode->i_mode))
3626 if (S_ISLNK(inode->i_mode))
3627 return !ext4_inode_is_fast_symlink(inode);
3632 * We have to make sure i_disksize gets properly updated before we truncate
3633 * page cache due to hole punching or zero range. Otherwise i_disksize update
3634 * can get lost as it may have been postponed to submission of writeback but
3635 * that will never happen after we truncate page cache.
3637 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3641 loff_t size = i_size_read(inode);
3643 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3644 if (offset > size || offset + len < size)
3647 if (EXT4_I(inode)->i_disksize >= size)
3650 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3652 return PTR_ERR(handle);
3653 ext4_update_i_disksize(inode, size);
3654 ext4_mark_inode_dirty(handle, inode);
3655 ext4_journal_stop(handle);
3661 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3662 * associated with the given offset and length
3664 * @inode: File inode
3665 * @offset: The offset where the hole will begin
3666 * @len: The length of the hole
3668 * Returns: 0 on success or negative on failure
3671 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3673 struct super_block *sb = inode->i_sb;
3674 ext4_lblk_t first_block, stop_block;
3675 struct address_space *mapping = inode->i_mapping;
3676 loff_t first_block_offset, last_block_offset;
3678 unsigned int credits;
3681 if (!S_ISREG(inode->i_mode))
3684 trace_ext4_punch_hole(inode, offset, length, 0);
3687 * Write out all dirty pages to avoid race conditions
3688 * Then release them.
3690 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3691 ret = filemap_write_and_wait_range(mapping, offset,
3692 offset + length - 1);
3697 mutex_lock(&inode->i_mutex);
3699 /* No need to punch hole beyond i_size */
3700 if (offset >= inode->i_size)
3704 * If the hole extends beyond i_size, set the hole
3705 * to end after the page that contains i_size
3707 if (offset + length > inode->i_size) {
3708 length = inode->i_size +
3709 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3713 if (offset & (sb->s_blocksize - 1) ||
3714 (offset + length) & (sb->s_blocksize - 1)) {
3716 * Attach jinode to inode for jbd2 if we do any zeroing of
3719 ret = ext4_inode_attach_jinode(inode);
3725 /* Wait all existing dio workers, newcomers will block on i_mutex */
3726 ext4_inode_block_unlocked_dio(inode);
3727 inode_dio_wait(inode);
3730 * Prevent page faults from reinstantiating pages we have released from
3733 down_write(&EXT4_I(inode)->i_mmap_sem);
3734 first_block_offset = round_up(offset, sb->s_blocksize);
3735 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3737 /* Now release the pages and zero block aligned part of pages*/
3738 if (last_block_offset > first_block_offset) {
3739 ret = ext4_update_disksize_before_punch(inode, offset, length);
3742 truncate_pagecache_range(inode, first_block_offset,
3746 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3747 credits = ext4_writepage_trans_blocks(inode);
3749 credits = ext4_blocks_for_truncate(inode);
3750 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3751 if (IS_ERR(handle)) {
3752 ret = PTR_ERR(handle);
3753 ext4_std_error(sb, ret);
3757 ret = ext4_zero_partial_blocks(handle, inode, offset,
3762 first_block = (offset + sb->s_blocksize - 1) >>
3763 EXT4_BLOCK_SIZE_BITS(sb);
3764 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3766 /* If there are no blocks to remove, return now */
3767 if (first_block >= stop_block)
3770 down_write(&EXT4_I(inode)->i_data_sem);
3771 ext4_discard_preallocations(inode);
3773 ret = ext4_es_remove_extent(inode, first_block,
3774 stop_block - first_block);
3776 up_write(&EXT4_I(inode)->i_data_sem);
3780 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3781 ret = ext4_ext_remove_space(inode, first_block,
3784 ret = ext4_ind_remove_space(handle, inode, first_block,
3787 up_write(&EXT4_I(inode)->i_data_sem);
3789 ext4_handle_sync(handle);
3791 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3792 ext4_mark_inode_dirty(handle, inode);
3794 ext4_journal_stop(handle);
3796 up_write(&EXT4_I(inode)->i_mmap_sem);
3797 ext4_inode_resume_unlocked_dio(inode);
3799 mutex_unlock(&inode->i_mutex);
3803 int ext4_inode_attach_jinode(struct inode *inode)
3805 struct ext4_inode_info *ei = EXT4_I(inode);
3806 struct jbd2_inode *jinode;
3808 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3811 jinode = jbd2_alloc_inode(GFP_KERNEL);
3812 spin_lock(&inode->i_lock);
3815 spin_unlock(&inode->i_lock);
3818 ei->jinode = jinode;
3819 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3822 spin_unlock(&inode->i_lock);
3823 if (unlikely(jinode != NULL))
3824 jbd2_free_inode(jinode);
3831 * We block out ext4_get_block() block instantiations across the entire
3832 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3833 * simultaneously on behalf of the same inode.
3835 * As we work through the truncate and commit bits of it to the journal there
3836 * is one core, guiding principle: the file's tree must always be consistent on
3837 * disk. We must be able to restart the truncate after a crash.
3839 * The file's tree may be transiently inconsistent in memory (although it
3840 * probably isn't), but whenever we close off and commit a journal transaction,
3841 * the contents of (the filesystem + the journal) must be consistent and
3842 * restartable. It's pretty simple, really: bottom up, right to left (although
3843 * left-to-right works OK too).
3845 * Note that at recovery time, journal replay occurs *before* the restart of
3846 * truncate against the orphan inode list.
3848 * The committed inode has the new, desired i_size (which is the same as
3849 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3850 * that this inode's truncate did not complete and it will again call
3851 * ext4_truncate() to have another go. So there will be instantiated blocks
3852 * to the right of the truncation point in a crashed ext4 filesystem. But
3853 * that's fine - as long as they are linked from the inode, the post-crash
3854 * ext4_truncate() run will find them and release them.
3856 void ext4_truncate(struct inode *inode)
3858 struct ext4_inode_info *ei = EXT4_I(inode);
3859 unsigned int credits;
3861 struct address_space *mapping = inode->i_mapping;
3864 * There is a possibility that we're either freeing the inode
3865 * or it's a completely new inode. In those cases we might not
3866 * have i_mutex locked because it's not necessary.
3868 if (!(inode->i_state & (I_NEW|I_FREEING)))
3869 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3870 trace_ext4_truncate_enter(inode);
3872 if (!ext4_can_truncate(inode))
3875 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3877 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3878 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3880 if (ext4_has_inline_data(inode)) {
3883 ext4_inline_data_truncate(inode, &has_inline);
3888 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3889 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3890 if (ext4_inode_attach_jinode(inode) < 0)
3894 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3895 credits = ext4_writepage_trans_blocks(inode);
3897 credits = ext4_blocks_for_truncate(inode);
3899 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3900 if (IS_ERR(handle)) {
3901 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3905 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3906 ext4_block_truncate_page(handle, mapping, inode->i_size);
3909 * We add the inode to the orphan list, so that if this
3910 * truncate spans multiple transactions, and we crash, we will
3911 * resume the truncate when the filesystem recovers. It also
3912 * marks the inode dirty, to catch the new size.
3914 * Implication: the file must always be in a sane, consistent
3915 * truncatable state while each transaction commits.
3917 if (ext4_orphan_add(handle, inode))
3920 down_write(&EXT4_I(inode)->i_data_sem);
3922 ext4_discard_preallocations(inode);
3924 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3925 ext4_ext_truncate(handle, inode);
3927 ext4_ind_truncate(handle, inode);
3929 up_write(&ei->i_data_sem);
3932 ext4_handle_sync(handle);
3936 * If this was a simple ftruncate() and the file will remain alive,
3937 * then we need to clear up the orphan record which we created above.
3938 * However, if this was a real unlink then we were called by
3939 * ext4_evict_inode(), and we allow that function to clean up the
3940 * orphan info for us.
3943 ext4_orphan_del(handle, inode);
3945 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3946 ext4_mark_inode_dirty(handle, inode);
3947 ext4_journal_stop(handle);
3949 trace_ext4_truncate_exit(inode);
3953 * ext4_get_inode_loc returns with an extra refcount against the inode's
3954 * underlying buffer_head on success. If 'in_mem' is true, we have all
3955 * data in memory that is needed to recreate the on-disk version of this
3958 static int __ext4_get_inode_loc(struct inode *inode,
3959 struct ext4_iloc *iloc, int in_mem)
3961 struct ext4_group_desc *gdp;
3962 struct buffer_head *bh;
3963 struct super_block *sb = inode->i_sb;
3965 int inodes_per_block, inode_offset;
3968 if (!ext4_valid_inum(sb, inode->i_ino))
3969 return -EFSCORRUPTED;
3971 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3972 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3977 * Figure out the offset within the block group inode table
3979 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3980 inode_offset = ((inode->i_ino - 1) %
3981 EXT4_INODES_PER_GROUP(sb));
3982 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3983 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3985 bh = sb_getblk(sb, block);
3988 if (!buffer_uptodate(bh)) {
3992 * If the buffer has the write error flag, we have failed
3993 * to write out another inode in the same block. In this
3994 * case, we don't have to read the block because we may
3995 * read the old inode data successfully.
3997 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3998 set_buffer_uptodate(bh);
4000 if (buffer_uptodate(bh)) {
4001 /* someone brought it uptodate while we waited */
4007 * If we have all information of the inode in memory and this
4008 * is the only valid inode in the block, we need not read the
4012 struct buffer_head *bitmap_bh;
4015 start = inode_offset & ~(inodes_per_block - 1);
4017 /* Is the inode bitmap in cache? */
4018 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4019 if (unlikely(!bitmap_bh))
4023 * If the inode bitmap isn't in cache then the
4024 * optimisation may end up performing two reads instead
4025 * of one, so skip it.
4027 if (!buffer_uptodate(bitmap_bh)) {
4031 for (i = start; i < start + inodes_per_block; i++) {
4032 if (i == inode_offset)
4034 if (ext4_test_bit(i, bitmap_bh->b_data))
4038 if (i == start + inodes_per_block) {
4039 /* all other inodes are free, so skip I/O */
4040 memset(bh->b_data, 0, bh->b_size);
4041 set_buffer_uptodate(bh);
4049 * If we need to do any I/O, try to pre-readahead extra
4050 * blocks from the inode table.
4052 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4053 ext4_fsblk_t b, end, table;
4055 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4057 table = ext4_inode_table(sb, gdp);
4058 /* s_inode_readahead_blks is always a power of 2 */
4059 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4063 num = EXT4_INODES_PER_GROUP(sb);
4064 if (ext4_has_group_desc_csum(sb))
4065 num -= ext4_itable_unused_count(sb, gdp);
4066 table += num / inodes_per_block;
4070 sb_breadahead(sb, b++);
4074 * There are other valid inodes in the buffer, this inode
4075 * has in-inode xattrs, or we don't have this inode in memory.
4076 * Read the block from disk.
4078 trace_ext4_load_inode(inode);
4080 bh->b_end_io = end_buffer_read_sync;
4081 submit_bh(READ | REQ_META | REQ_PRIO, bh);
4083 if (!buffer_uptodate(bh)) {
4084 EXT4_ERROR_INODE_BLOCK(inode, block,
4085 "unable to read itable block");
4095 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4097 /* We have all inode data except xattrs in memory here. */
4098 return __ext4_get_inode_loc(inode, iloc,
4099 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4102 void ext4_set_inode_flags(struct inode *inode)
4104 unsigned int flags = EXT4_I(inode)->i_flags;
4105 unsigned int new_fl = 0;
4107 if (flags & EXT4_SYNC_FL)
4109 if (flags & EXT4_APPEND_FL)
4111 if (flags & EXT4_IMMUTABLE_FL)
4112 new_fl |= S_IMMUTABLE;
4113 if (flags & EXT4_NOATIME_FL)
4114 new_fl |= S_NOATIME;
4115 if (flags & EXT4_DIRSYNC_FL)
4116 new_fl |= S_DIRSYNC;
4117 if (test_opt(inode->i_sb, DAX))
4119 inode_set_flags(inode, new_fl,
4120 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4123 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4124 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4126 unsigned int vfs_fl;
4127 unsigned long old_fl, new_fl;
4130 vfs_fl = ei->vfs_inode.i_flags;
4131 old_fl = ei->i_flags;
4132 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4133 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4135 if (vfs_fl & S_SYNC)
4136 new_fl |= EXT4_SYNC_FL;
4137 if (vfs_fl & S_APPEND)
4138 new_fl |= EXT4_APPEND_FL;
4139 if (vfs_fl & S_IMMUTABLE)
4140 new_fl |= EXT4_IMMUTABLE_FL;
4141 if (vfs_fl & S_NOATIME)
4142 new_fl |= EXT4_NOATIME_FL;
4143 if (vfs_fl & S_DIRSYNC)
4144 new_fl |= EXT4_DIRSYNC_FL;
4145 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4148 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4149 struct ext4_inode_info *ei)
4152 struct inode *inode = &(ei->vfs_inode);
4153 struct super_block *sb = inode->i_sb;
4155 if (ext4_has_feature_huge_file(sb)) {
4156 /* we are using combined 48 bit field */
4157 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4158 le32_to_cpu(raw_inode->i_blocks_lo);
4159 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4160 /* i_blocks represent file system block size */
4161 return i_blocks << (inode->i_blkbits - 9);
4166 return le32_to_cpu(raw_inode->i_blocks_lo);
4170 static inline void ext4_iget_extra_inode(struct inode *inode,
4171 struct ext4_inode *raw_inode,
4172 struct ext4_inode_info *ei)
4174 __le32 *magic = (void *)raw_inode +
4175 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4176 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4177 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4178 ext4_find_inline_data_nolock(inode);
4180 EXT4_I(inode)->i_inline_off = 0;
4183 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4185 struct ext4_iloc iloc;
4186 struct ext4_inode *raw_inode;
4187 struct ext4_inode_info *ei;
4188 struct inode *inode;
4189 journal_t *journal = EXT4_SB(sb)->s_journal;
4196 inode = iget_locked(sb, ino);
4198 return ERR_PTR(-ENOMEM);
4199 if (!(inode->i_state & I_NEW))
4205 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4208 raw_inode = ext4_raw_inode(&iloc);
4210 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4211 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4212 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4213 EXT4_INODE_SIZE(inode->i_sb)) {
4214 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4215 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4216 EXT4_INODE_SIZE(inode->i_sb));
4217 ret = -EFSCORRUPTED;
4221 ei->i_extra_isize = 0;
4223 /* Precompute checksum seed for inode metadata */
4224 if (ext4_has_metadata_csum(sb)) {
4225 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4227 __le32 inum = cpu_to_le32(inode->i_ino);
4228 __le32 gen = raw_inode->i_generation;
4229 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4231 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4235 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4236 EXT4_ERROR_INODE(inode, "checksum invalid");
4241 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4242 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4243 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4244 if (!(test_opt(inode->i_sb, NO_UID32))) {
4245 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4246 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4248 i_uid_write(inode, i_uid);
4249 i_gid_write(inode, i_gid);
4250 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4252 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4253 ei->i_inline_off = 0;
4254 ei->i_dir_start_lookup = 0;
4255 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4256 /* We now have enough fields to check if the inode was active or not.
4257 * This is needed because nfsd might try to access dead inodes
4258 * the test is that same one that e2fsck uses
4259 * NeilBrown 1999oct15
4261 if (inode->i_nlink == 0) {
4262 if ((inode->i_mode == 0 ||
4263 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4264 ino != EXT4_BOOT_LOADER_INO) {
4265 /* this inode is deleted */
4269 /* The only unlinked inodes we let through here have
4270 * valid i_mode and are being read by the orphan
4271 * recovery code: that's fine, we're about to complete
4272 * the process of deleting those.
4273 * OR it is the EXT4_BOOT_LOADER_INO which is
4274 * not initialized on a new filesystem. */
4276 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4277 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4278 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4279 if (ext4_has_feature_64bit(sb))
4281 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4282 inode->i_size = ext4_isize(raw_inode);
4283 if ((size = i_size_read(inode)) < 0) {
4284 EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
4285 ret = -EFSCORRUPTED;
4288 ei->i_disksize = inode->i_size;
4290 ei->i_reserved_quota = 0;
4292 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4293 ei->i_block_group = iloc.block_group;
4294 ei->i_last_alloc_group = ~0;
4296 * NOTE! The in-memory inode i_data array is in little-endian order
4297 * even on big-endian machines: we do NOT byteswap the block numbers!
4299 for (block = 0; block < EXT4_N_BLOCKS; block++)
4300 ei->i_data[block] = raw_inode->i_block[block];
4301 INIT_LIST_HEAD(&ei->i_orphan);
4304 * Set transaction id's of transactions that have to be committed
4305 * to finish f[data]sync. We set them to currently running transaction
4306 * as we cannot be sure that the inode or some of its metadata isn't
4307 * part of the transaction - the inode could have been reclaimed and
4308 * now it is reread from disk.
4311 transaction_t *transaction;
4314 read_lock(&journal->j_state_lock);
4315 if (journal->j_running_transaction)
4316 transaction = journal->j_running_transaction;
4318 transaction = journal->j_committing_transaction;
4320 tid = transaction->t_tid;
4322 tid = journal->j_commit_sequence;
4323 read_unlock(&journal->j_state_lock);
4324 ei->i_sync_tid = tid;
4325 ei->i_datasync_tid = tid;
4328 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4329 if (ei->i_extra_isize == 0) {
4330 /* The extra space is currently unused. Use it. */
4331 ei->i_extra_isize = sizeof(struct ext4_inode) -
4332 EXT4_GOOD_OLD_INODE_SIZE;
4334 ext4_iget_extra_inode(inode, raw_inode, ei);
4338 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4339 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4340 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4341 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4343 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4344 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4345 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4346 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4348 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4353 if (ei->i_file_acl &&
4354 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4355 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4357 ret = -EFSCORRUPTED;
4359 } else if (!ext4_has_inline_data(inode)) {
4360 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4361 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4362 (S_ISLNK(inode->i_mode) &&
4363 !ext4_inode_is_fast_symlink(inode))))
4364 /* Validate extent which is part of inode */
4365 ret = ext4_ext_check_inode(inode);
4366 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4367 (S_ISLNK(inode->i_mode) &&
4368 !ext4_inode_is_fast_symlink(inode))) {
4369 /* Validate block references which are part of inode */
4370 ret = ext4_ind_check_inode(inode);
4376 if (S_ISREG(inode->i_mode)) {
4377 inode->i_op = &ext4_file_inode_operations;
4378 inode->i_fop = &ext4_file_operations;
4379 ext4_set_aops(inode);
4380 } else if (S_ISDIR(inode->i_mode)) {
4381 inode->i_op = &ext4_dir_inode_operations;
4382 inode->i_fop = &ext4_dir_operations;
4383 } else if (S_ISLNK(inode->i_mode)) {
4384 if (ext4_encrypted_inode(inode)) {
4385 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4386 ext4_set_aops(inode);
4387 } else if (ext4_inode_is_fast_symlink(inode)) {
4388 inode->i_link = (char *)ei->i_data;
4389 inode->i_op = &ext4_fast_symlink_inode_operations;
4390 nd_terminate_link(ei->i_data, inode->i_size,
4391 sizeof(ei->i_data) - 1);
4393 inode->i_op = &ext4_symlink_inode_operations;
4394 ext4_set_aops(inode);
4396 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4397 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4398 inode->i_op = &ext4_special_inode_operations;
4399 if (raw_inode->i_block[0])
4400 init_special_inode(inode, inode->i_mode,
4401 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4403 init_special_inode(inode, inode->i_mode,
4404 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4405 } else if (ino == EXT4_BOOT_LOADER_INO) {
4406 make_bad_inode(inode);
4408 ret = -EFSCORRUPTED;
4409 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4413 ext4_set_inode_flags(inode);
4414 unlock_new_inode(inode);
4420 return ERR_PTR(ret);
4423 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4425 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4426 return ERR_PTR(-EFSCORRUPTED);
4427 return ext4_iget(sb, ino);
4430 static int ext4_inode_blocks_set(handle_t *handle,
4431 struct ext4_inode *raw_inode,
4432 struct ext4_inode_info *ei)
4434 struct inode *inode = &(ei->vfs_inode);
4435 u64 i_blocks = inode->i_blocks;
4436 struct super_block *sb = inode->i_sb;
4438 if (i_blocks <= ~0U) {
4440 * i_blocks can be represented in a 32 bit variable
4441 * as multiple of 512 bytes
4443 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4444 raw_inode->i_blocks_high = 0;
4445 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4448 if (!ext4_has_feature_huge_file(sb))
4451 if (i_blocks <= 0xffffffffffffULL) {
4453 * i_blocks can be represented in a 48 bit variable
4454 * as multiple of 512 bytes
4456 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4457 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4458 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4460 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4461 /* i_block is stored in file system block size */
4462 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4463 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4464 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4469 struct other_inode {
4470 unsigned long orig_ino;
4471 struct ext4_inode *raw_inode;
4474 static int other_inode_match(struct inode * inode, unsigned long ino,
4477 struct other_inode *oi = (struct other_inode *) data;
4479 if ((inode->i_ino != ino) ||
4480 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4481 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4482 ((inode->i_state & I_DIRTY_TIME) == 0))
4484 spin_lock(&inode->i_lock);
4485 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4486 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4487 (inode->i_state & I_DIRTY_TIME)) {
4488 struct ext4_inode_info *ei = EXT4_I(inode);
4490 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4491 spin_unlock(&inode->i_lock);
4493 spin_lock(&ei->i_raw_lock);
4494 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4495 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4496 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4497 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4498 spin_unlock(&ei->i_raw_lock);
4499 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4502 spin_unlock(&inode->i_lock);
4507 * Opportunistically update the other time fields for other inodes in
4508 * the same inode table block.
4510 static void ext4_update_other_inodes_time(struct super_block *sb,
4511 unsigned long orig_ino, char *buf)
4513 struct other_inode oi;
4515 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4516 int inode_size = EXT4_INODE_SIZE(sb);
4518 oi.orig_ino = orig_ino;
4520 * Calculate the first inode in the inode table block. Inode
4521 * numbers are one-based. That is, the first inode in a block
4522 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4524 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4525 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4526 if (ino == orig_ino)
4528 oi.raw_inode = (struct ext4_inode *) buf;
4529 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4534 * Post the struct inode info into an on-disk inode location in the
4535 * buffer-cache. This gobbles the caller's reference to the
4536 * buffer_head in the inode location struct.
4538 * The caller must have write access to iloc->bh.
4540 static int ext4_do_update_inode(handle_t *handle,
4541 struct inode *inode,
4542 struct ext4_iloc *iloc)
4544 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4545 struct ext4_inode_info *ei = EXT4_I(inode);
4546 struct buffer_head *bh = iloc->bh;
4547 struct super_block *sb = inode->i_sb;
4548 int err = 0, rc, block;
4549 int need_datasync = 0, set_large_file = 0;
4553 spin_lock(&ei->i_raw_lock);
4555 /* For fields not tracked in the in-memory inode,
4556 * initialise them to zero for new inodes. */
4557 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4558 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4560 ext4_get_inode_flags(ei);
4561 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4562 i_uid = i_uid_read(inode);
4563 i_gid = i_gid_read(inode);
4564 if (!(test_opt(inode->i_sb, NO_UID32))) {
4565 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4566 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4568 * Fix up interoperability with old kernels. Otherwise, old inodes get
4569 * re-used with the upper 16 bits of the uid/gid intact
4571 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4572 raw_inode->i_uid_high = 0;
4573 raw_inode->i_gid_high = 0;
4575 raw_inode->i_uid_high =
4576 cpu_to_le16(high_16_bits(i_uid));
4577 raw_inode->i_gid_high =
4578 cpu_to_le16(high_16_bits(i_gid));
4581 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4582 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4583 raw_inode->i_uid_high = 0;
4584 raw_inode->i_gid_high = 0;
4586 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4588 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4589 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4590 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4591 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4593 err = ext4_inode_blocks_set(handle, raw_inode, ei);
4595 spin_unlock(&ei->i_raw_lock);
4598 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4599 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4600 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4601 raw_inode->i_file_acl_high =
4602 cpu_to_le16(ei->i_file_acl >> 32);
4603 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4604 if (ei->i_disksize != ext4_isize(raw_inode)) {
4605 ext4_isize_set(raw_inode, ei->i_disksize);
4608 if (ei->i_disksize > 0x7fffffffULL) {
4609 if (!ext4_has_feature_large_file(sb) ||
4610 EXT4_SB(sb)->s_es->s_rev_level ==
4611 cpu_to_le32(EXT4_GOOD_OLD_REV))
4614 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4615 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4616 if (old_valid_dev(inode->i_rdev)) {
4617 raw_inode->i_block[0] =
4618 cpu_to_le32(old_encode_dev(inode->i_rdev));
4619 raw_inode->i_block[1] = 0;
4621 raw_inode->i_block[0] = 0;
4622 raw_inode->i_block[1] =
4623 cpu_to_le32(new_encode_dev(inode->i_rdev));
4624 raw_inode->i_block[2] = 0;
4626 } else if (!ext4_has_inline_data(inode)) {
4627 for (block = 0; block < EXT4_N_BLOCKS; block++)
4628 raw_inode->i_block[block] = ei->i_data[block];
4631 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4632 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4633 if (ei->i_extra_isize) {
4634 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4635 raw_inode->i_version_hi =
4636 cpu_to_le32(inode->i_version >> 32);
4637 raw_inode->i_extra_isize =
4638 cpu_to_le16(ei->i_extra_isize);
4641 ext4_inode_csum_set(inode, raw_inode, ei);
4642 spin_unlock(&ei->i_raw_lock);
4643 if (inode->i_sb->s_flags & MS_LAZYTIME)
4644 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4647 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4648 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4651 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4652 if (set_large_file) {
4653 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4654 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4657 ext4_update_dynamic_rev(sb);
4658 ext4_set_feature_large_file(sb);
4659 ext4_handle_sync(handle);
4660 err = ext4_handle_dirty_super(handle, sb);
4662 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4665 ext4_std_error(inode->i_sb, err);
4670 * ext4_write_inode()
4672 * We are called from a few places:
4674 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4675 * Here, there will be no transaction running. We wait for any running
4676 * transaction to commit.
4678 * - Within flush work (sys_sync(), kupdate and such).
4679 * We wait on commit, if told to.
4681 * - Within iput_final() -> write_inode_now()
4682 * We wait on commit, if told to.
4684 * In all cases it is actually safe for us to return without doing anything,
4685 * because the inode has been copied into a raw inode buffer in
4686 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4689 * Note that we are absolutely dependent upon all inode dirtiers doing the
4690 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4691 * which we are interested.
4693 * It would be a bug for them to not do this. The code:
4695 * mark_inode_dirty(inode)
4697 * inode->i_size = expr;
4699 * is in error because write_inode() could occur while `stuff()' is running,
4700 * and the new i_size will be lost. Plus the inode will no longer be on the
4701 * superblock's dirty inode list.
4703 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4707 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4710 if (EXT4_SB(inode->i_sb)->s_journal) {
4711 if (ext4_journal_current_handle()) {
4712 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4718 * No need to force transaction in WB_SYNC_NONE mode. Also
4719 * ext4_sync_fs() will force the commit after everything is
4722 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4725 err = ext4_force_commit(inode->i_sb);
4727 struct ext4_iloc iloc;
4729 err = __ext4_get_inode_loc(inode, &iloc, 0);
4733 * sync(2) will flush the whole buffer cache. No need to do
4734 * it here separately for each inode.
4736 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4737 sync_dirty_buffer(iloc.bh);
4738 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4739 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4740 "IO error syncing inode");
4749 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4750 * buffers that are attached to a page stradding i_size and are undergoing
4751 * commit. In that case we have to wait for commit to finish and try again.
4753 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4757 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4758 tid_t commit_tid = 0;
4761 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4763 * All buffers in the last page remain valid? Then there's nothing to
4764 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4767 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4770 page = find_lock_page(inode->i_mapping,
4771 inode->i_size >> PAGE_CACHE_SHIFT);
4774 ret = __ext4_journalled_invalidatepage(page, offset,
4775 PAGE_CACHE_SIZE - offset);
4777 page_cache_release(page);
4781 read_lock(&journal->j_state_lock);
4782 if (journal->j_committing_transaction)
4783 commit_tid = journal->j_committing_transaction->t_tid;
4784 read_unlock(&journal->j_state_lock);
4786 jbd2_log_wait_commit(journal, commit_tid);
4793 * Called from notify_change.
4795 * We want to trap VFS attempts to truncate the file as soon as
4796 * possible. In particular, we want to make sure that when the VFS
4797 * shrinks i_size, we put the inode on the orphan list and modify
4798 * i_disksize immediately, so that during the subsequent flushing of
4799 * dirty pages and freeing of disk blocks, we can guarantee that any
4800 * commit will leave the blocks being flushed in an unused state on
4801 * disk. (On recovery, the inode will get truncated and the blocks will
4802 * be freed, so we have a strong guarantee that no future commit will
4803 * leave these blocks visible to the user.)
4805 * Another thing we have to assure is that if we are in ordered mode
4806 * and inode is still attached to the committing transaction, we must
4807 * we start writeout of all the dirty pages which are being truncated.
4808 * This way we are sure that all the data written in the previous
4809 * transaction are already on disk (truncate waits for pages under
4812 * Called with inode->i_mutex down.
4814 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4816 struct inode *inode = d_inode(dentry);
4819 const unsigned int ia_valid = attr->ia_valid;
4821 error = inode_change_ok(inode, attr);
4825 if (is_quota_modification(inode, attr)) {
4826 error = dquot_initialize(inode);
4830 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4831 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4834 /* (user+group)*(old+new) structure, inode write (sb,
4835 * inode block, ? - but truncate inode update has it) */
4836 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4837 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4838 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4839 if (IS_ERR(handle)) {
4840 error = PTR_ERR(handle);
4843 error = dquot_transfer(inode, attr);
4845 ext4_journal_stop(handle);
4848 /* Update corresponding info in inode so that everything is in
4849 * one transaction */
4850 if (attr->ia_valid & ATTR_UID)
4851 inode->i_uid = attr->ia_uid;
4852 if (attr->ia_valid & ATTR_GID)
4853 inode->i_gid = attr->ia_gid;
4854 error = ext4_mark_inode_dirty(handle, inode);
4855 ext4_journal_stop(handle);
4858 if (attr->ia_valid & ATTR_SIZE) {
4860 loff_t oldsize = inode->i_size;
4861 int shrink = (attr->ia_size <= inode->i_size);
4863 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4864 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4866 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4869 if (!S_ISREG(inode->i_mode))
4872 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4873 inode_inc_iversion(inode);
4875 if (ext4_should_order_data(inode) &&
4876 (attr->ia_size < inode->i_size)) {
4877 error = ext4_begin_ordered_truncate(inode,
4882 if (attr->ia_size != inode->i_size) {
4883 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4884 if (IS_ERR(handle)) {
4885 error = PTR_ERR(handle);
4888 if (ext4_handle_valid(handle) && shrink) {
4889 error = ext4_orphan_add(handle, inode);
4893 * Update c/mtime on truncate up, ext4_truncate() will
4894 * update c/mtime in shrink case below
4897 inode->i_mtime = ext4_current_time(inode);
4898 inode->i_ctime = inode->i_mtime;
4900 down_write(&EXT4_I(inode)->i_data_sem);
4901 EXT4_I(inode)->i_disksize = attr->ia_size;
4902 rc = ext4_mark_inode_dirty(handle, inode);
4906 * We have to update i_size under i_data_sem together
4907 * with i_disksize to avoid races with writeback code
4908 * running ext4_wb_update_i_disksize().
4911 i_size_write(inode, attr->ia_size);
4912 up_write(&EXT4_I(inode)->i_data_sem);
4913 ext4_journal_stop(handle);
4916 ext4_orphan_del(NULL, inode);
4921 pagecache_isize_extended(inode, oldsize, inode->i_size);
4924 * Blocks are going to be removed from the inode. Wait
4925 * for dio in flight. Temporarily disable
4926 * dioread_nolock to prevent livelock.
4929 if (!ext4_should_journal_data(inode)) {
4930 ext4_inode_block_unlocked_dio(inode);
4931 inode_dio_wait(inode);
4932 ext4_inode_resume_unlocked_dio(inode);
4934 ext4_wait_for_tail_page_commit(inode);
4936 down_write(&EXT4_I(inode)->i_mmap_sem);
4938 * Truncate pagecache after we've waited for commit
4939 * in data=journal mode to make pages freeable.
4941 truncate_pagecache(inode, inode->i_size);
4943 ext4_truncate(inode);
4944 up_write(&EXT4_I(inode)->i_mmap_sem);
4948 setattr_copy(inode, attr);
4949 mark_inode_dirty(inode);
4953 * If the call to ext4_truncate failed to get a transaction handle at
4954 * all, we need to clean up the in-core orphan list manually.
4956 if (orphan && inode->i_nlink)
4957 ext4_orphan_del(NULL, inode);
4959 if (!rc && (ia_valid & ATTR_MODE))
4960 rc = posix_acl_chmod(inode, inode->i_mode);
4963 ext4_std_error(inode->i_sb, error);
4969 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4972 struct inode *inode;
4973 unsigned long long delalloc_blocks;
4975 inode = d_inode(dentry);
4976 generic_fillattr(inode, stat);
4979 * If there is inline data in the inode, the inode will normally not
4980 * have data blocks allocated (it may have an external xattr block).
4981 * Report at least one sector for such files, so tools like tar, rsync,
4982 * others doen't incorrectly think the file is completely sparse.
4984 if (unlikely(ext4_has_inline_data(inode)))
4985 stat->blocks += (stat->size + 511) >> 9;
4988 * We can't update i_blocks if the block allocation is delayed
4989 * otherwise in the case of system crash before the real block
4990 * allocation is done, we will have i_blocks inconsistent with
4991 * on-disk file blocks.
4992 * We always keep i_blocks updated together with real
4993 * allocation. But to not confuse with user, stat
4994 * will return the blocks that include the delayed allocation
4995 * blocks for this file.
4997 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4998 EXT4_I(inode)->i_reserved_data_blocks);
4999 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5003 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5006 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5007 return ext4_ind_trans_blocks(inode, lblocks);
5008 return ext4_ext_index_trans_blocks(inode, pextents);
5012 * Account for index blocks, block groups bitmaps and block group
5013 * descriptor blocks if modify datablocks and index blocks
5014 * worse case, the indexs blocks spread over different block groups
5016 * If datablocks are discontiguous, they are possible to spread over
5017 * different block groups too. If they are contiguous, with flexbg,
5018 * they could still across block group boundary.
5020 * Also account for superblock, inode, quota and xattr blocks
5022 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5025 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5031 * How many index blocks need to touch to map @lblocks logical blocks
5032 * to @pextents physical extents?
5034 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5039 * Now let's see how many group bitmaps and group descriptors need
5042 groups = idxblocks + pextents;
5044 if (groups > ngroups)
5046 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5047 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5049 /* bitmaps and block group descriptor blocks */
5050 ret += groups + gdpblocks;
5052 /* Blocks for super block, inode, quota and xattr blocks */
5053 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5059 * Calculate the total number of credits to reserve to fit
5060 * the modification of a single pages into a single transaction,
5061 * which may include multiple chunks of block allocations.
5063 * This could be called via ext4_write_begin()
5065 * We need to consider the worse case, when
5066 * one new block per extent.
5068 int ext4_writepage_trans_blocks(struct inode *inode)
5070 int bpp = ext4_journal_blocks_per_page(inode);
5073 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5075 /* Account for data blocks for journalled mode */
5076 if (ext4_should_journal_data(inode))
5082 * Calculate the journal credits for a chunk of data modification.
5084 * This is called from DIO, fallocate or whoever calling
5085 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5087 * journal buffers for data blocks are not included here, as DIO
5088 * and fallocate do no need to journal data buffers.
5090 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5092 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5096 * The caller must have previously called ext4_reserve_inode_write().
5097 * Give this, we know that the caller already has write access to iloc->bh.
5099 int ext4_mark_iloc_dirty(handle_t *handle,
5100 struct inode *inode, struct ext4_iloc *iloc)
5104 if (IS_I_VERSION(inode))
5105 inode_inc_iversion(inode);
5107 /* the do_update_inode consumes one bh->b_count */
5110 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5111 err = ext4_do_update_inode(handle, inode, iloc);
5117 * On success, We end up with an outstanding reference count against
5118 * iloc->bh. This _must_ be cleaned up later.
5122 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5123 struct ext4_iloc *iloc)
5127 err = ext4_get_inode_loc(inode, iloc);
5129 BUFFER_TRACE(iloc->bh, "get_write_access");
5130 err = ext4_journal_get_write_access(handle, iloc->bh);
5136 ext4_std_error(inode->i_sb, err);
5141 * Expand an inode by new_extra_isize bytes.
5142 * Returns 0 on success or negative error number on failure.
5144 static int ext4_expand_extra_isize(struct inode *inode,
5145 unsigned int new_extra_isize,
5146 struct ext4_iloc iloc,
5149 struct ext4_inode *raw_inode;
5150 struct ext4_xattr_ibody_header *header;
5152 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5155 raw_inode = ext4_raw_inode(&iloc);
5157 header = IHDR(inode, raw_inode);
5159 /* No extended attributes present */
5160 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5161 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5162 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5164 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5168 /* try to expand with EAs present */
5169 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5174 * What we do here is to mark the in-core inode as clean with respect to inode
5175 * dirtiness (it may still be data-dirty).
5176 * This means that the in-core inode may be reaped by prune_icache
5177 * without having to perform any I/O. This is a very good thing,
5178 * because *any* task may call prune_icache - even ones which
5179 * have a transaction open against a different journal.
5181 * Is this cheating? Not really. Sure, we haven't written the
5182 * inode out, but prune_icache isn't a user-visible syncing function.
5183 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5184 * we start and wait on commits.
5186 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5188 struct ext4_iloc iloc;
5189 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5190 static unsigned int mnt_count;
5194 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5195 err = ext4_reserve_inode_write(handle, inode, &iloc);
5198 if (ext4_handle_valid(handle) &&
5199 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5200 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5202 * We need extra buffer credits since we may write into EA block
5203 * with this same handle. If journal_extend fails, then it will
5204 * only result in a minor loss of functionality for that inode.
5205 * If this is felt to be critical, then e2fsck should be run to
5206 * force a large enough s_min_extra_isize.
5208 if ((jbd2_journal_extend(handle,
5209 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5210 ret = ext4_expand_extra_isize(inode,
5211 sbi->s_want_extra_isize,
5215 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5216 ext4_warning(inode->i_sb,
5217 "Unable to expand inode %lu. Delete"
5218 " some EAs or run e2fsck.",
5221 le16_to_cpu(sbi->s_es->s_mnt_count);
5226 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5230 * ext4_dirty_inode() is called from __mark_inode_dirty()
5232 * We're really interested in the case where a file is being extended.
5233 * i_size has been changed by generic_commit_write() and we thus need
5234 * to include the updated inode in the current transaction.
5236 * Also, dquot_alloc_block() will always dirty the inode when blocks
5237 * are allocated to the file.
5239 * If the inode is marked synchronous, we don't honour that here - doing
5240 * so would cause a commit on atime updates, which we don't bother doing.
5241 * We handle synchronous inodes at the highest possible level.
5243 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5244 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5245 * to copy into the on-disk inode structure are the timestamp files.
5247 void ext4_dirty_inode(struct inode *inode, int flags)
5251 if (flags == I_DIRTY_TIME)
5253 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5257 ext4_mark_inode_dirty(handle, inode);
5259 ext4_journal_stop(handle);
5266 * Bind an inode's backing buffer_head into this transaction, to prevent
5267 * it from being flushed to disk early. Unlike
5268 * ext4_reserve_inode_write, this leaves behind no bh reference and
5269 * returns no iloc structure, so the caller needs to repeat the iloc
5270 * lookup to mark the inode dirty later.
5272 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5274 struct ext4_iloc iloc;
5278 err = ext4_get_inode_loc(inode, &iloc);
5280 BUFFER_TRACE(iloc.bh, "get_write_access");
5281 err = jbd2_journal_get_write_access(handle, iloc.bh);
5283 err = ext4_handle_dirty_metadata(handle,
5289 ext4_std_error(inode->i_sb, err);
5294 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5301 * We have to be very careful here: changing a data block's
5302 * journaling status dynamically is dangerous. If we write a
5303 * data block to the journal, change the status and then delete
5304 * that block, we risk forgetting to revoke the old log record
5305 * from the journal and so a subsequent replay can corrupt data.
5306 * So, first we make sure that the journal is empty and that
5307 * nobody is changing anything.
5310 journal = EXT4_JOURNAL(inode);
5313 if (is_journal_aborted(journal))
5315 /* We have to allocate physical blocks for delalloc blocks
5316 * before flushing journal. otherwise delalloc blocks can not
5317 * be allocated any more. even more truncate on delalloc blocks
5318 * could trigger BUG by flushing delalloc blocks in journal.
5319 * There is no delalloc block in non-journal data mode.
5321 if (val && test_opt(inode->i_sb, DELALLOC)) {
5322 err = ext4_alloc_da_blocks(inode);
5327 /* Wait for all existing dio workers */
5328 ext4_inode_block_unlocked_dio(inode);
5329 inode_dio_wait(inode);
5331 jbd2_journal_lock_updates(journal);
5334 * OK, there are no updates running now, and all cached data is
5335 * synced to disk. We are now in a completely consistent state
5336 * which doesn't have anything in the journal, and we know that
5337 * no filesystem updates are running, so it is safe to modify
5338 * the inode's in-core data-journaling state flag now.
5342 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5344 err = jbd2_journal_flush(journal);
5346 jbd2_journal_unlock_updates(journal);
5347 ext4_inode_resume_unlocked_dio(inode);
5350 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5352 ext4_set_aops(inode);
5354 jbd2_journal_unlock_updates(journal);
5355 ext4_inode_resume_unlocked_dio(inode);
5357 /* Finally we can mark the inode as dirty. */
5359 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5361 return PTR_ERR(handle);
5363 err = ext4_mark_inode_dirty(handle, inode);
5364 ext4_handle_sync(handle);
5365 ext4_journal_stop(handle);
5366 ext4_std_error(inode->i_sb, err);
5371 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5373 return !buffer_mapped(bh);
5376 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5378 struct page *page = vmf->page;
5382 struct file *file = vma->vm_file;
5383 struct inode *inode = file_inode(file);
5384 struct address_space *mapping = inode->i_mapping;
5386 get_block_t *get_block;
5389 sb_start_pagefault(inode->i_sb);
5390 file_update_time(vma->vm_file);
5392 down_read(&EXT4_I(inode)->i_mmap_sem);
5393 /* Delalloc case is easy... */
5394 if (test_opt(inode->i_sb, DELALLOC) &&
5395 !ext4_should_journal_data(inode) &&
5396 !ext4_nonda_switch(inode->i_sb)) {
5398 ret = block_page_mkwrite(vma, vmf,
5399 ext4_da_get_block_prep);
5400 } while (ret == -ENOSPC &&
5401 ext4_should_retry_alloc(inode->i_sb, &retries));
5406 size = i_size_read(inode);
5407 /* Page got truncated from under us? */
5408 if (page->mapping != mapping || page_offset(page) > size) {
5410 ret = VM_FAULT_NOPAGE;
5414 if (page->index == size >> PAGE_CACHE_SHIFT)
5415 len = size & ~PAGE_CACHE_MASK;
5417 len = PAGE_CACHE_SIZE;
5419 * Return if we have all the buffers mapped. This avoids the need to do
5420 * journal_start/journal_stop which can block and take a long time
5422 if (page_has_buffers(page)) {
5423 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5425 ext4_bh_unmapped)) {
5426 /* Wait so that we don't change page under IO */
5427 wait_for_stable_page(page);
5428 ret = VM_FAULT_LOCKED;
5433 /* OK, we need to fill the hole... */
5434 if (ext4_should_dioread_nolock(inode))
5435 get_block = ext4_get_block_write;
5437 get_block = ext4_get_block;
5439 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5440 ext4_writepage_trans_blocks(inode));
5441 if (IS_ERR(handle)) {
5442 ret = VM_FAULT_SIGBUS;
5445 ret = block_page_mkwrite(vma, vmf, get_block);
5446 if (!ret && ext4_should_journal_data(inode)) {
5447 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5448 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5450 ret = VM_FAULT_SIGBUS;
5451 ext4_journal_stop(handle);
5454 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5456 ext4_journal_stop(handle);
5457 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5460 ret = block_page_mkwrite_return(ret);
5462 up_read(&EXT4_I(inode)->i_mmap_sem);
5463 sb_end_pagefault(inode->i_sb);
5467 int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5469 struct inode *inode = file_inode(vma->vm_file);
5472 down_read(&EXT4_I(inode)->i_mmap_sem);
5473 err = filemap_fault(vma, vmf);
5474 up_read(&EXT4_I(inode)->i_mmap_sem);