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/quotaops.h>
26 #include <linux/string.h>
27 #include <linux/buffer_head.h>
28 #include <linux/writeback.h>
29 #include <linux/pagevec.h>
30 #include <linux/mpage.h>
31 #include <linux/namei.h>
32 #include <linux/uio.h>
33 #include <linux/bio.h>
34 #include <linux/workqueue.h>
35 #include <linux/kernel.h>
36 #include <linux/printk.h>
37 #include <linux/slab.h>
38 #include <linux/bitops.h>
40 #include "ext4_jbd2.h"
45 #include <trace/events/ext4.h>
47 #define MPAGE_DA_EXTENT_TAIL 0x01
49 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
50 struct ext4_inode_info *ei)
52 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57 csum_lo = le16_to_cpu(raw->i_checksum_lo);
58 raw->i_checksum_lo = 0;
59 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
60 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
61 csum_hi = le16_to_cpu(raw->i_checksum_hi);
62 raw->i_checksum_hi = 0;
65 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
66 EXT4_INODE_SIZE(inode->i_sb));
68 raw->i_checksum_lo = cpu_to_le16(csum_lo);
69 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
70 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
71 raw->i_checksum_hi = cpu_to_le16(csum_hi);
76 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
77 struct ext4_inode_info *ei)
79 __u32 provided, calculated;
81 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
82 cpu_to_le32(EXT4_OS_LINUX) ||
83 !ext4_has_metadata_csum(inode->i_sb))
86 provided = le16_to_cpu(raw->i_checksum_lo);
87 calculated = ext4_inode_csum(inode, raw, ei);
88 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
89 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
90 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
94 return provided == calculated;
97 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
98 struct ext4_inode_info *ei)
102 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
103 cpu_to_le32(EXT4_OS_LINUX) ||
104 !ext4_has_metadata_csum(inode->i_sb))
107 csum = ext4_inode_csum(inode, raw, ei);
108 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
109 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
110 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
111 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
114 static inline int ext4_begin_ordered_truncate(struct inode *inode,
117 trace_ext4_begin_ordered_truncate(inode, new_size);
119 * If jinode is zero, then we never opened the file for
120 * writing, so there's no need to call
121 * jbd2_journal_begin_ordered_truncate() since there's no
122 * outstanding writes we need to flush.
124 if (!EXT4_I(inode)->jinode)
126 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
127 EXT4_I(inode)->jinode,
131 static void ext4_invalidatepage(struct page *page, unsigned int offset,
132 unsigned int length);
133 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
134 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
135 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
139 * Test whether an inode is a fast symlink.
141 int ext4_inode_is_fast_symlink(struct inode *inode)
143 int ea_blocks = EXT4_I(inode)->i_file_acl ?
144 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
146 if (ext4_has_inline_data(inode))
149 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
153 * Restart the transaction associated with *handle. This does a commit,
154 * so before we call here everything must be consistently dirtied against
157 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
163 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
164 * moment, get_block can be called only for blocks inside i_size since
165 * page cache has been already dropped and writes are blocked by
166 * i_mutex. So we can safely drop the i_data_sem here.
168 BUG_ON(EXT4_JOURNAL(inode) == NULL);
169 jbd_debug(2, "restarting handle %p\n", handle);
170 up_write(&EXT4_I(inode)->i_data_sem);
171 ret = ext4_journal_restart(handle, nblocks);
172 down_write(&EXT4_I(inode)->i_data_sem);
173 ext4_discard_preallocations(inode);
179 * Called at the last iput() if i_nlink is zero.
181 void ext4_evict_inode(struct inode *inode)
186 trace_ext4_evict_inode(inode);
188 if (inode->i_nlink) {
190 * When journalling data dirty buffers are tracked only in the
191 * journal. So although mm thinks everything is clean and
192 * ready for reaping the inode might still have some pages to
193 * write in the running transaction or waiting to be
194 * checkpointed. Thus calling jbd2_journal_invalidatepage()
195 * (via truncate_inode_pages()) to discard these buffers can
196 * cause data loss. Also even if we did not discard these
197 * buffers, we would have no way to find them after the inode
198 * is reaped and thus user could see stale data if he tries to
199 * read them before the transaction is checkpointed. So be
200 * careful and force everything to disk here... We use
201 * ei->i_datasync_tid to store the newest transaction
202 * containing inode's data.
204 * Note that directories do not have this problem because they
205 * don't use page cache.
207 if (ext4_should_journal_data(inode) &&
208 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
209 inode->i_ino != EXT4_JOURNAL_INO) {
210 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
211 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
213 jbd2_complete_transaction(journal, commit_tid);
214 filemap_write_and_wait(&inode->i_data);
216 truncate_inode_pages_final(&inode->i_data);
218 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
222 if (is_bad_inode(inode))
224 dquot_initialize(inode);
226 if (ext4_should_order_data(inode))
227 ext4_begin_ordered_truncate(inode, 0);
228 truncate_inode_pages_final(&inode->i_data);
230 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
233 * Protect us against freezing - iput() caller didn't have to have any
234 * protection against it
236 sb_start_intwrite(inode->i_sb);
237 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
238 ext4_blocks_for_truncate(inode)+3);
239 if (IS_ERR(handle)) {
240 ext4_std_error(inode->i_sb, PTR_ERR(handle));
242 * If we're going to skip the normal cleanup, we still need to
243 * make sure that the in-core orphan linked list is properly
246 ext4_orphan_del(NULL, inode);
247 sb_end_intwrite(inode->i_sb);
252 ext4_handle_sync(handle);
254 err = ext4_mark_inode_dirty(handle, inode);
256 ext4_warning(inode->i_sb,
257 "couldn't mark inode dirty (err %d)", err);
261 ext4_truncate(inode);
264 * ext4_ext_truncate() doesn't reserve any slop when it
265 * restarts journal transactions; therefore there may not be
266 * enough credits left in the handle to remove the inode from
267 * the orphan list and set the dtime field.
269 if (!ext4_handle_has_enough_credits(handle, 3)) {
270 err = ext4_journal_extend(handle, 3);
272 err = ext4_journal_restart(handle, 3);
274 ext4_warning(inode->i_sb,
275 "couldn't extend journal (err %d)", err);
277 ext4_journal_stop(handle);
278 ext4_orphan_del(NULL, inode);
279 sb_end_intwrite(inode->i_sb);
285 * Kill off the orphan record which ext4_truncate created.
286 * AKPM: I think this can be inside the above `if'.
287 * Note that ext4_orphan_del() has to be able to cope with the
288 * deletion of a non-existent orphan - this is because we don't
289 * know if ext4_truncate() actually created an orphan record.
290 * (Well, we could do this if we need to, but heck - it works)
292 ext4_orphan_del(handle, inode);
293 EXT4_I(inode)->i_dtime = get_seconds();
296 * One subtle ordering requirement: if anything has gone wrong
297 * (transaction abort, IO errors, whatever), then we can still
298 * do these next steps (the fs will already have been marked as
299 * having errors), but we can't free the inode if the mark_dirty
302 if (ext4_mark_inode_dirty(handle, inode))
303 /* If that failed, just do the required in-core inode clear. */
304 ext4_clear_inode(inode);
306 ext4_free_inode(handle, inode);
307 ext4_journal_stop(handle);
308 sb_end_intwrite(inode->i_sb);
311 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
315 qsize_t *ext4_get_reserved_space(struct inode *inode)
317 return &EXT4_I(inode)->i_reserved_quota;
322 * Called with i_data_sem down, which is important since we can call
323 * ext4_discard_preallocations() from here.
325 void ext4_da_update_reserve_space(struct inode *inode,
326 int used, int quota_claim)
328 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
329 struct ext4_inode_info *ei = EXT4_I(inode);
331 spin_lock(&ei->i_block_reservation_lock);
332 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
333 if (unlikely(used > ei->i_reserved_data_blocks)) {
334 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
335 "with only %d reserved data blocks",
336 __func__, inode->i_ino, used,
337 ei->i_reserved_data_blocks);
339 used = ei->i_reserved_data_blocks;
342 /* Update per-inode reservations */
343 ei->i_reserved_data_blocks -= used;
344 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
346 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
348 /* Update quota subsystem for data blocks */
350 dquot_claim_block(inode, EXT4_C2B(sbi, used));
353 * We did fallocate with an offset that is already delayed
354 * allocated. So on delayed allocated writeback we should
355 * not re-claim the quota for fallocated blocks.
357 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
361 * If we have done all the pending block allocations and if
362 * there aren't any writers on the inode, we can discard the
363 * inode's preallocations.
365 if ((ei->i_reserved_data_blocks == 0) &&
366 (atomic_read(&inode->i_writecount) == 0))
367 ext4_discard_preallocations(inode);
370 static int __check_block_validity(struct inode *inode, const char *func,
372 struct ext4_map_blocks *map)
374 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
376 ext4_error_inode(inode, func, line, map->m_pblk,
377 "lblock %lu mapped to illegal pblock "
378 "(length %d)", (unsigned long) map->m_lblk,
385 #define check_block_validity(inode, map) \
386 __check_block_validity((inode), __func__, __LINE__, (map))
388 #ifdef ES_AGGRESSIVE_TEST
389 static void ext4_map_blocks_es_recheck(handle_t *handle,
391 struct ext4_map_blocks *es_map,
392 struct ext4_map_blocks *map,
399 * There is a race window that the result is not the same.
400 * e.g. xfstests #223 when dioread_nolock enables. The reason
401 * is that we lookup a block mapping in extent status tree with
402 * out taking i_data_sem. So at the time the unwritten extent
403 * could be converted.
405 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
406 down_read(&EXT4_I(inode)->i_data_sem);
407 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
408 retval = ext4_ext_map_blocks(handle, inode, map, flags &
409 EXT4_GET_BLOCKS_KEEP_SIZE);
411 retval = ext4_ind_map_blocks(handle, inode, map, flags &
412 EXT4_GET_BLOCKS_KEEP_SIZE);
414 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
415 up_read((&EXT4_I(inode)->i_data_sem));
418 * We don't check m_len because extent will be collpased in status
419 * tree. So the m_len might not equal.
421 if (es_map->m_lblk != map->m_lblk ||
422 es_map->m_flags != map->m_flags ||
423 es_map->m_pblk != map->m_pblk) {
424 printk("ES cache assertion failed for inode: %lu "
425 "es_cached ex [%d/%d/%llu/%x] != "
426 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
427 inode->i_ino, es_map->m_lblk, es_map->m_len,
428 es_map->m_pblk, es_map->m_flags, map->m_lblk,
429 map->m_len, map->m_pblk, map->m_flags,
433 #endif /* ES_AGGRESSIVE_TEST */
436 * The ext4_map_blocks() function tries to look up the requested blocks,
437 * and returns if the blocks are already mapped.
439 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
440 * and store the allocated blocks in the result buffer head and mark it
443 * If file type is extents based, it will call ext4_ext_map_blocks(),
444 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
447 * On success, it returns the number of blocks being mapped or allocated.
448 * if create==0 and the blocks are pre-allocated and unwritten block,
449 * the result buffer head is unmapped. If the create ==1, it will make sure
450 * the buffer head is mapped.
452 * It returns 0 if plain look up failed (blocks have not been allocated), in
453 * that case, buffer head is unmapped
455 * It returns the error in case of allocation failure.
457 int ext4_map_blocks(handle_t *handle, struct inode *inode,
458 struct ext4_map_blocks *map, int flags)
460 struct extent_status es;
463 #ifdef ES_AGGRESSIVE_TEST
464 struct ext4_map_blocks orig_map;
466 memcpy(&orig_map, map, sizeof(*map));
470 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
471 "logical block %lu\n", inode->i_ino, flags, map->m_len,
472 (unsigned long) map->m_lblk);
475 * ext4_map_blocks returns an int, and m_len is an unsigned int
477 if (unlikely(map->m_len > INT_MAX))
478 map->m_len = INT_MAX;
480 /* We can handle the block number less than EXT_MAX_BLOCKS */
481 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
484 /* Lookup extent status tree firstly */
485 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
486 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
487 map->m_pblk = ext4_es_pblock(&es) +
488 map->m_lblk - es.es_lblk;
489 map->m_flags |= ext4_es_is_written(&es) ?
490 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
491 retval = es.es_len - (map->m_lblk - es.es_lblk);
492 if (retval > map->m_len)
495 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
500 #ifdef ES_AGGRESSIVE_TEST
501 ext4_map_blocks_es_recheck(handle, inode, map,
508 * Try to see if we can get the block without requesting a new
511 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
512 down_read(&EXT4_I(inode)->i_data_sem);
513 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
514 retval = ext4_ext_map_blocks(handle, inode, map, flags &
515 EXT4_GET_BLOCKS_KEEP_SIZE);
517 retval = ext4_ind_map_blocks(handle, inode, map, flags &
518 EXT4_GET_BLOCKS_KEEP_SIZE);
523 if (unlikely(retval != map->m_len)) {
524 ext4_warning(inode->i_sb,
525 "ES len assertion failed for inode "
526 "%lu: retval %d != map->m_len %d",
527 inode->i_ino, retval, map->m_len);
531 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
532 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
533 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
534 ext4_find_delalloc_range(inode, map->m_lblk,
535 map->m_lblk + map->m_len - 1))
536 status |= EXTENT_STATUS_DELAYED;
537 ret = ext4_es_insert_extent(inode, map->m_lblk,
538 map->m_len, map->m_pblk, status);
542 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
543 up_read((&EXT4_I(inode)->i_data_sem));
546 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
547 ret = check_block_validity(inode, map);
552 /* If it is only a block(s) look up */
553 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
557 * Returns if the blocks have already allocated
559 * Note that if blocks have been preallocated
560 * ext4_ext_get_block() returns the create = 0
561 * with buffer head unmapped.
563 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
565 * If we need to convert extent to unwritten
566 * we continue and do the actual work in
567 * ext4_ext_map_blocks()
569 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
573 * Here we clear m_flags because after allocating an new extent,
574 * it will be set again.
576 map->m_flags &= ~EXT4_MAP_FLAGS;
579 * New blocks allocate and/or writing to unwritten extent
580 * will possibly result in updating i_data, so we take
581 * the write lock of i_data_sem, and call get_block()
582 * with create == 1 flag.
584 down_write(&EXT4_I(inode)->i_data_sem);
587 * We need to check for EXT4 here because migrate
588 * could have changed the inode type in between
590 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
591 retval = ext4_ext_map_blocks(handle, inode, map, flags);
593 retval = ext4_ind_map_blocks(handle, inode, map, flags);
595 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
597 * We allocated new blocks which will result in
598 * i_data's format changing. Force the migrate
599 * to fail by clearing migrate flags
601 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
605 * Update reserved blocks/metadata blocks after successful
606 * block allocation which had been deferred till now. We don't
607 * support fallocate for non extent files. So we can update
608 * reserve space here.
611 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
612 ext4_da_update_reserve_space(inode, retval, 1);
618 if (unlikely(retval != map->m_len)) {
619 ext4_warning(inode->i_sb,
620 "ES len assertion failed for inode "
621 "%lu: retval %d != map->m_len %d",
622 inode->i_ino, retval, map->m_len);
627 * If the extent has been zeroed out, we don't need to update
628 * extent status tree.
630 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
631 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
632 if (ext4_es_is_written(&es))
635 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
636 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
637 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
638 ext4_find_delalloc_range(inode, map->m_lblk,
639 map->m_lblk + map->m_len - 1))
640 status |= EXTENT_STATUS_DELAYED;
641 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
642 map->m_pblk, status);
648 up_write((&EXT4_I(inode)->i_data_sem));
649 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
650 ret = check_block_validity(inode, map);
657 static void ext4_end_io_unwritten(struct buffer_head *bh, int uptodate)
659 struct inode *inode = bh->b_assoc_map->host;
660 /* XXX: breaks on 32-bit > 16GB. Is that even supported? */
661 loff_t offset = (loff_t)(uintptr_t)bh->b_private << inode->i_blkbits;
665 WARN_ON(!buffer_unwritten(bh));
666 err = ext4_convert_unwritten_extents(NULL, inode, offset, bh->b_size);
669 /* Maximum number of blocks we map for direct IO at once. */
670 #define DIO_MAX_BLOCKS 4096
672 static int _ext4_get_block(struct inode *inode, sector_t iblock,
673 struct buffer_head *bh, int flags)
675 handle_t *handle = ext4_journal_current_handle();
676 struct ext4_map_blocks map;
677 int ret = 0, started = 0;
680 if (ext4_has_inline_data(inode))
684 map.m_len = bh->b_size >> inode->i_blkbits;
686 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
687 /* Direct IO write... */
688 if (map.m_len > DIO_MAX_BLOCKS)
689 map.m_len = DIO_MAX_BLOCKS;
690 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
691 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
693 if (IS_ERR(handle)) {
694 ret = PTR_ERR(handle);
700 ret = ext4_map_blocks(handle, inode, &map, flags);
702 ext4_io_end_t *io_end = ext4_inode_aio(inode);
704 map_bh(bh, inode->i_sb, map.m_pblk);
705 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
706 if (IS_DAX(inode) && buffer_unwritten(bh) && !io_end) {
707 bh->b_assoc_map = inode->i_mapping;
708 bh->b_private = (void *)(unsigned long)iblock;
709 bh->b_end_io = ext4_end_io_unwritten;
711 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
712 set_buffer_defer_completion(bh);
713 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
717 ext4_journal_stop(handle);
721 int ext4_get_block(struct inode *inode, sector_t iblock,
722 struct buffer_head *bh, int create)
724 return _ext4_get_block(inode, iblock, bh,
725 create ? EXT4_GET_BLOCKS_CREATE : 0);
729 * `handle' can be NULL if create is zero
731 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
732 ext4_lblk_t block, int create)
734 struct ext4_map_blocks map;
735 struct buffer_head *bh;
738 J_ASSERT(handle != NULL || create == 0);
742 err = ext4_map_blocks(handle, inode, &map,
743 create ? EXT4_GET_BLOCKS_CREATE : 0);
746 return create ? ERR_PTR(-ENOSPC) : NULL;
750 bh = sb_getblk(inode->i_sb, map.m_pblk);
752 return ERR_PTR(-ENOMEM);
753 if (map.m_flags & EXT4_MAP_NEW) {
754 J_ASSERT(create != 0);
755 J_ASSERT(handle != NULL);
758 * Now that we do not always journal data, we should
759 * keep in mind whether this should always journal the
760 * new buffer as metadata. For now, regular file
761 * writes use ext4_get_block instead, so it's not a
765 BUFFER_TRACE(bh, "call get_create_access");
766 err = ext4_journal_get_create_access(handle, bh);
771 if (!buffer_uptodate(bh)) {
772 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
773 set_buffer_uptodate(bh);
776 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
777 err = ext4_handle_dirty_metadata(handle, inode, bh);
781 BUFFER_TRACE(bh, "not a new buffer");
788 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
789 ext4_lblk_t block, int create)
791 struct buffer_head *bh;
793 bh = ext4_getblk(handle, inode, block, create);
796 if (!bh || buffer_uptodate(bh))
798 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
800 if (buffer_uptodate(bh))
803 return ERR_PTR(-EIO);
806 int ext4_walk_page_buffers(handle_t *handle,
807 struct buffer_head *head,
811 int (*fn)(handle_t *handle,
812 struct buffer_head *bh))
814 struct buffer_head *bh;
815 unsigned block_start, block_end;
816 unsigned blocksize = head->b_size;
818 struct buffer_head *next;
820 for (bh = head, block_start = 0;
821 ret == 0 && (bh != head || !block_start);
822 block_start = block_end, bh = next) {
823 next = bh->b_this_page;
824 block_end = block_start + blocksize;
825 if (block_end <= from || block_start >= to) {
826 if (partial && !buffer_uptodate(bh))
830 err = (*fn)(handle, bh);
838 * To preserve ordering, it is essential that the hole instantiation and
839 * the data write be encapsulated in a single transaction. We cannot
840 * close off a transaction and start a new one between the ext4_get_block()
841 * and the commit_write(). So doing the jbd2_journal_start at the start of
842 * prepare_write() is the right place.
844 * Also, this function can nest inside ext4_writepage(). In that case, we
845 * *know* that ext4_writepage() has generated enough buffer credits to do the
846 * whole page. So we won't block on the journal in that case, which is good,
847 * because the caller may be PF_MEMALLOC.
849 * By accident, ext4 can be reentered when a transaction is open via
850 * quota file writes. If we were to commit the transaction while thus
851 * reentered, there can be a deadlock - we would be holding a quota
852 * lock, and the commit would never complete if another thread had a
853 * transaction open and was blocking on the quota lock - a ranking
856 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
857 * will _not_ run commit under these circumstances because handle->h_ref
858 * is elevated. We'll still have enough credits for the tiny quotafile
861 int do_journal_get_write_access(handle_t *handle,
862 struct buffer_head *bh)
864 int dirty = buffer_dirty(bh);
867 if (!buffer_mapped(bh) || buffer_freed(bh))
870 * __block_write_begin() could have dirtied some buffers. Clean
871 * the dirty bit as jbd2_journal_get_write_access() could complain
872 * otherwise about fs integrity issues. Setting of the dirty bit
873 * by __block_write_begin() isn't a real problem here as we clear
874 * the bit before releasing a page lock and thus writeback cannot
875 * ever write the buffer.
878 clear_buffer_dirty(bh);
879 BUFFER_TRACE(bh, "get write access");
880 ret = ext4_journal_get_write_access(handle, bh);
882 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
886 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
887 struct buffer_head *bh_result, int create);
889 #ifdef CONFIG_EXT4_FS_ENCRYPTION
890 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
891 get_block_t *get_block)
893 unsigned from = pos & (PAGE_CACHE_SIZE - 1);
894 unsigned to = from + len;
895 struct inode *inode = page->mapping->host;
896 unsigned block_start, block_end;
899 unsigned blocksize = inode->i_sb->s_blocksize;
901 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
902 bool decrypt = false;
904 BUG_ON(!PageLocked(page));
905 BUG_ON(from > PAGE_CACHE_SIZE);
906 BUG_ON(to > PAGE_CACHE_SIZE);
909 if (!page_has_buffers(page))
910 create_empty_buffers(page, blocksize, 0);
911 head = page_buffers(page);
912 bbits = ilog2(blocksize);
913 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
915 for (bh = head, block_start = 0; bh != head || !block_start;
916 block++, block_start = block_end, bh = bh->b_this_page) {
917 block_end = block_start + blocksize;
918 if (block_end <= from || block_start >= to) {
919 if (PageUptodate(page)) {
920 if (!buffer_uptodate(bh))
921 set_buffer_uptodate(bh);
926 clear_buffer_new(bh);
927 if (!buffer_mapped(bh)) {
928 WARN_ON(bh->b_size != blocksize);
929 err = get_block(inode, block, bh, 1);
932 if (buffer_new(bh)) {
933 unmap_underlying_metadata(bh->b_bdev,
935 if (PageUptodate(page)) {
936 clear_buffer_new(bh);
937 set_buffer_uptodate(bh);
938 mark_buffer_dirty(bh);
941 if (block_end > to || block_start < from)
942 zero_user_segments(page, to, block_end,
947 if (PageUptodate(page)) {
948 if (!buffer_uptodate(bh))
949 set_buffer_uptodate(bh);
952 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
953 !buffer_unwritten(bh) &&
954 (block_start < from || block_end > to)) {
955 ll_rw_block(READ, 1, &bh);
957 decrypt = ext4_encrypted_inode(inode) &&
958 S_ISREG(inode->i_mode);
962 * If we issued read requests, let them complete.
964 while (wait_bh > wait) {
965 wait_on_buffer(*--wait_bh);
966 if (!buffer_uptodate(*wait_bh))
970 page_zero_new_buffers(page, from, to);
972 err = ext4_decrypt_one(inode, page);
977 static int ext4_write_begin(struct file *file, struct address_space *mapping,
978 loff_t pos, unsigned len, unsigned flags,
979 struct page **pagep, void **fsdata)
981 struct inode *inode = mapping->host;
982 int ret, needed_blocks;
989 trace_ext4_write_begin(inode, pos, len, flags);
991 * Reserve one block more for addition to orphan list in case
992 * we allocate blocks but write fails for some reason
994 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
995 index = pos >> PAGE_CACHE_SHIFT;
996 from = pos & (PAGE_CACHE_SIZE - 1);
999 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1000 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1009 * grab_cache_page_write_begin() can take a long time if the
1010 * system is thrashing due to memory pressure, or if the page
1011 * is being written back. So grab it first before we start
1012 * the transaction handle. This also allows us to allocate
1013 * the page (if needed) without using GFP_NOFS.
1016 page = grab_cache_page_write_begin(mapping, index, flags);
1022 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1023 if (IS_ERR(handle)) {
1024 page_cache_release(page);
1025 return PTR_ERR(handle);
1029 if (page->mapping != mapping) {
1030 /* The page got truncated from under us */
1032 page_cache_release(page);
1033 ext4_journal_stop(handle);
1036 /* In case writeback began while the page was unlocked */
1037 wait_for_stable_page(page);
1039 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1040 if (ext4_should_dioread_nolock(inode))
1041 ret = ext4_block_write_begin(page, pos, len,
1042 ext4_get_block_write);
1044 ret = ext4_block_write_begin(page, pos, len,
1047 if (ext4_should_dioread_nolock(inode))
1048 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1050 ret = __block_write_begin(page, pos, len, ext4_get_block);
1052 if (!ret && ext4_should_journal_data(inode)) {
1053 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1055 do_journal_get_write_access);
1061 * __block_write_begin may have instantiated a few blocks
1062 * outside i_size. Trim these off again. Don't need
1063 * i_size_read because we hold i_mutex.
1065 * Add inode to orphan list in case we crash before
1068 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1069 ext4_orphan_add(handle, inode);
1071 ext4_journal_stop(handle);
1072 if (pos + len > inode->i_size) {
1073 ext4_truncate_failed_write(inode);
1075 * If truncate failed early the inode might
1076 * still be on the orphan list; we need to
1077 * make sure the inode is removed from the
1078 * orphan list in that case.
1081 ext4_orphan_del(NULL, inode);
1084 if (ret == -ENOSPC &&
1085 ext4_should_retry_alloc(inode->i_sb, &retries))
1087 page_cache_release(page);
1094 /* For write_end() in data=journal mode */
1095 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1098 if (!buffer_mapped(bh) || buffer_freed(bh))
1100 set_buffer_uptodate(bh);
1101 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1102 clear_buffer_meta(bh);
1103 clear_buffer_prio(bh);
1108 * We need to pick up the new inode size which generic_commit_write gave us
1109 * `file' can be NULL - eg, when called from page_symlink().
1111 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1112 * buffers are managed internally.
1114 static int ext4_write_end(struct file *file,
1115 struct address_space *mapping,
1116 loff_t pos, unsigned len, unsigned copied,
1117 struct page *page, void *fsdata)
1119 handle_t *handle = ext4_journal_current_handle();
1120 struct inode *inode = mapping->host;
1121 loff_t old_size = inode->i_size;
1123 int i_size_changed = 0;
1125 trace_ext4_write_end(inode, pos, len, copied);
1126 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1127 ret = ext4_jbd2_file_inode(handle, inode);
1130 page_cache_release(page);
1135 if (ext4_has_inline_data(inode)) {
1136 ret = ext4_write_inline_data_end(inode, pos, len,
1142 copied = block_write_end(file, mapping, pos,
1143 len, copied, page, fsdata);
1145 * it's important to update i_size while still holding page lock:
1146 * page writeout could otherwise come in and zero beyond i_size.
1148 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1150 page_cache_release(page);
1153 pagecache_isize_extended(inode, old_size, pos);
1155 * Don't mark the inode dirty under page lock. First, it unnecessarily
1156 * makes the holding time of page lock longer. Second, it forces lock
1157 * ordering of page lock and transaction start for journaling
1161 ext4_mark_inode_dirty(handle, inode);
1163 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1164 /* if we have allocated more blocks and copied
1165 * less. We will have blocks allocated outside
1166 * inode->i_size. So truncate them
1168 ext4_orphan_add(handle, inode);
1170 ret2 = ext4_journal_stop(handle);
1174 if (pos + len > inode->i_size) {
1175 ext4_truncate_failed_write(inode);
1177 * If truncate failed early the inode might still be
1178 * on the orphan list; we need to make sure the inode
1179 * is removed from the orphan list in that case.
1182 ext4_orphan_del(NULL, inode);
1185 return ret ? ret : copied;
1188 static int ext4_journalled_write_end(struct file *file,
1189 struct address_space *mapping,
1190 loff_t pos, unsigned len, unsigned copied,
1191 struct page *page, void *fsdata)
1193 handle_t *handle = ext4_journal_current_handle();
1194 struct inode *inode = mapping->host;
1195 loff_t old_size = inode->i_size;
1199 int size_changed = 0;
1201 trace_ext4_journalled_write_end(inode, pos, len, copied);
1202 from = pos & (PAGE_CACHE_SIZE - 1);
1205 BUG_ON(!ext4_handle_valid(handle));
1207 if (ext4_has_inline_data(inode))
1208 copied = ext4_write_inline_data_end(inode, pos, len,
1212 if (!PageUptodate(page))
1214 page_zero_new_buffers(page, from+copied, to);
1217 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1218 to, &partial, write_end_fn);
1220 SetPageUptodate(page);
1222 size_changed = ext4_update_inode_size(inode, pos + copied);
1223 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1224 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1226 page_cache_release(page);
1229 pagecache_isize_extended(inode, old_size, pos);
1232 ret2 = ext4_mark_inode_dirty(handle, inode);
1237 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1238 /* if we have allocated more blocks and copied
1239 * less. We will have blocks allocated outside
1240 * inode->i_size. So truncate them
1242 ext4_orphan_add(handle, inode);
1244 ret2 = ext4_journal_stop(handle);
1247 if (pos + len > inode->i_size) {
1248 ext4_truncate_failed_write(inode);
1250 * If truncate failed early the inode might still be
1251 * on the orphan list; we need to make sure the inode
1252 * is removed from the orphan list in that case.
1255 ext4_orphan_del(NULL, inode);
1258 return ret ? ret : copied;
1262 * Reserve a single cluster located at lblock
1264 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1266 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1267 struct ext4_inode_info *ei = EXT4_I(inode);
1268 unsigned int md_needed;
1272 * We will charge metadata quota at writeout time; this saves
1273 * us from metadata over-estimation, though we may go over by
1274 * a small amount in the end. Here we just reserve for data.
1276 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1281 * recalculate the amount of metadata blocks to reserve
1282 * in order to allocate nrblocks
1283 * worse case is one extent per block
1285 spin_lock(&ei->i_block_reservation_lock);
1287 * ext4_calc_metadata_amount() has side effects, which we have
1288 * to be prepared undo if we fail to claim space.
1291 trace_ext4_da_reserve_space(inode, 0);
1293 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1294 spin_unlock(&ei->i_block_reservation_lock);
1295 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1298 ei->i_reserved_data_blocks++;
1299 spin_unlock(&ei->i_block_reservation_lock);
1301 return 0; /* success */
1304 static void ext4_da_release_space(struct inode *inode, int to_free)
1306 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1307 struct ext4_inode_info *ei = EXT4_I(inode);
1310 return; /* Nothing to release, exit */
1312 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1314 trace_ext4_da_release_space(inode, to_free);
1315 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1317 * if there aren't enough reserved blocks, then the
1318 * counter is messed up somewhere. Since this
1319 * function is called from invalidate page, it's
1320 * harmless to return without any action.
1322 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1323 "ino %lu, to_free %d with only %d reserved "
1324 "data blocks", inode->i_ino, to_free,
1325 ei->i_reserved_data_blocks);
1327 to_free = ei->i_reserved_data_blocks;
1329 ei->i_reserved_data_blocks -= to_free;
1331 /* update fs dirty data blocks counter */
1332 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1334 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1336 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1339 static void ext4_da_page_release_reservation(struct page *page,
1340 unsigned int offset,
1341 unsigned int length)
1344 struct buffer_head *head, *bh;
1345 unsigned int curr_off = 0;
1346 struct inode *inode = page->mapping->host;
1347 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1348 unsigned int stop = offset + length;
1352 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1354 head = page_buffers(page);
1357 unsigned int next_off = curr_off + bh->b_size;
1359 if (next_off > stop)
1362 if ((offset <= curr_off) && (buffer_delay(bh))) {
1364 clear_buffer_delay(bh);
1366 curr_off = next_off;
1367 } while ((bh = bh->b_this_page) != head);
1370 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1371 ext4_es_remove_extent(inode, lblk, to_release);
1374 /* If we have released all the blocks belonging to a cluster, then we
1375 * need to release the reserved space for that cluster. */
1376 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1377 while (num_clusters > 0) {
1378 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1379 ((num_clusters - 1) << sbi->s_cluster_bits);
1380 if (sbi->s_cluster_ratio == 1 ||
1381 !ext4_find_delalloc_cluster(inode, lblk))
1382 ext4_da_release_space(inode, 1);
1389 * Delayed allocation stuff
1392 struct mpage_da_data {
1393 struct inode *inode;
1394 struct writeback_control *wbc;
1396 pgoff_t first_page; /* The first page to write */
1397 pgoff_t next_page; /* Current page to examine */
1398 pgoff_t last_page; /* Last page to examine */
1400 * Extent to map - this can be after first_page because that can be
1401 * fully mapped. We somewhat abuse m_flags to store whether the extent
1402 * is delalloc or unwritten.
1404 struct ext4_map_blocks map;
1405 struct ext4_io_submit io_submit; /* IO submission data */
1408 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1413 struct pagevec pvec;
1414 struct inode *inode = mpd->inode;
1415 struct address_space *mapping = inode->i_mapping;
1417 /* This is necessary when next_page == 0. */
1418 if (mpd->first_page >= mpd->next_page)
1421 index = mpd->first_page;
1422 end = mpd->next_page - 1;
1424 ext4_lblk_t start, last;
1425 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1426 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1427 ext4_es_remove_extent(inode, start, last - start + 1);
1430 pagevec_init(&pvec, 0);
1431 while (index <= end) {
1432 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1435 for (i = 0; i < nr_pages; i++) {
1436 struct page *page = pvec.pages[i];
1437 if (page->index > end)
1439 BUG_ON(!PageLocked(page));
1440 BUG_ON(PageWriteback(page));
1442 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1443 ClearPageUptodate(page);
1447 index = pvec.pages[nr_pages - 1]->index + 1;
1448 pagevec_release(&pvec);
1452 static void ext4_print_free_blocks(struct inode *inode)
1454 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1455 struct super_block *sb = inode->i_sb;
1456 struct ext4_inode_info *ei = EXT4_I(inode);
1458 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1459 EXT4_C2B(EXT4_SB(inode->i_sb),
1460 ext4_count_free_clusters(sb)));
1461 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1462 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1463 (long long) EXT4_C2B(EXT4_SB(sb),
1464 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1465 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1466 (long long) EXT4_C2B(EXT4_SB(sb),
1467 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1468 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1469 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1470 ei->i_reserved_data_blocks);
1474 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1476 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1480 * This function is grabs code from the very beginning of
1481 * ext4_map_blocks, but assumes that the caller is from delayed write
1482 * time. This function looks up the requested blocks and sets the
1483 * buffer delay bit under the protection of i_data_sem.
1485 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1486 struct ext4_map_blocks *map,
1487 struct buffer_head *bh)
1489 struct extent_status es;
1491 sector_t invalid_block = ~((sector_t) 0xffff);
1492 #ifdef ES_AGGRESSIVE_TEST
1493 struct ext4_map_blocks orig_map;
1495 memcpy(&orig_map, map, sizeof(*map));
1498 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1502 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1503 "logical block %lu\n", inode->i_ino, map->m_len,
1504 (unsigned long) map->m_lblk);
1506 /* Lookup extent status tree firstly */
1507 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1508 if (ext4_es_is_hole(&es)) {
1510 down_read(&EXT4_I(inode)->i_data_sem);
1515 * Delayed extent could be allocated by fallocate.
1516 * So we need to check it.
1518 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1519 map_bh(bh, inode->i_sb, invalid_block);
1521 set_buffer_delay(bh);
1525 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1526 retval = es.es_len - (iblock - es.es_lblk);
1527 if (retval > map->m_len)
1528 retval = map->m_len;
1529 map->m_len = retval;
1530 if (ext4_es_is_written(&es))
1531 map->m_flags |= EXT4_MAP_MAPPED;
1532 else if (ext4_es_is_unwritten(&es))
1533 map->m_flags |= EXT4_MAP_UNWRITTEN;
1537 #ifdef ES_AGGRESSIVE_TEST
1538 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1544 * Try to see if we can get the block without requesting a new
1545 * file system block.
1547 down_read(&EXT4_I(inode)->i_data_sem);
1548 if (ext4_has_inline_data(inode))
1550 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1551 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1553 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1559 * XXX: __block_prepare_write() unmaps passed block,
1563 * If the block was allocated from previously allocated cluster,
1564 * then we don't need to reserve it again. However we still need
1565 * to reserve metadata for every block we're going to write.
1567 if (EXT4_SB(inode->i_sb)->s_cluster_ratio <= 1 ||
1568 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1569 ret = ext4_da_reserve_space(inode, iblock);
1571 /* not enough space to reserve */
1577 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1578 ~0, EXTENT_STATUS_DELAYED);
1584 map_bh(bh, inode->i_sb, invalid_block);
1586 set_buffer_delay(bh);
1587 } else if (retval > 0) {
1589 unsigned int status;
1591 if (unlikely(retval != map->m_len)) {
1592 ext4_warning(inode->i_sb,
1593 "ES len assertion failed for inode "
1594 "%lu: retval %d != map->m_len %d",
1595 inode->i_ino, retval, map->m_len);
1599 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1600 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1601 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1602 map->m_pblk, status);
1608 up_read((&EXT4_I(inode)->i_data_sem));
1614 * This is a special get_block_t callback which is used by
1615 * ext4_da_write_begin(). It will either return mapped block or
1616 * reserve space for a single block.
1618 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1619 * We also have b_blocknr = -1 and b_bdev initialized properly
1621 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1622 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1623 * initialized properly.
1625 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1626 struct buffer_head *bh, int create)
1628 struct ext4_map_blocks map;
1631 BUG_ON(create == 0);
1632 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1634 map.m_lblk = iblock;
1638 * first, we need to know whether the block is allocated already
1639 * preallocated blocks are unmapped but should treated
1640 * the same as allocated blocks.
1642 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1646 map_bh(bh, inode->i_sb, map.m_pblk);
1647 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1649 if (buffer_unwritten(bh)) {
1650 /* A delayed write to unwritten bh should be marked
1651 * new and mapped. Mapped ensures that we don't do
1652 * get_block multiple times when we write to the same
1653 * offset and new ensures that we do proper zero out
1654 * for partial write.
1657 set_buffer_mapped(bh);
1662 static int bget_one(handle_t *handle, struct buffer_head *bh)
1668 static int bput_one(handle_t *handle, struct buffer_head *bh)
1674 static int __ext4_journalled_writepage(struct page *page,
1677 struct address_space *mapping = page->mapping;
1678 struct inode *inode = mapping->host;
1679 struct buffer_head *page_bufs = NULL;
1680 handle_t *handle = NULL;
1681 int ret = 0, err = 0;
1682 int inline_data = ext4_has_inline_data(inode);
1683 struct buffer_head *inode_bh = NULL;
1685 ClearPageChecked(page);
1688 BUG_ON(page->index != 0);
1689 BUG_ON(len > ext4_get_max_inline_size(inode));
1690 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1691 if (inode_bh == NULL)
1694 page_bufs = page_buffers(page);
1699 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1702 /* As soon as we unlock the page, it can go away, but we have
1703 * references to buffers so we are safe */
1706 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1707 ext4_writepage_trans_blocks(inode));
1708 if (IS_ERR(handle)) {
1709 ret = PTR_ERR(handle);
1713 BUG_ON(!ext4_handle_valid(handle));
1716 BUFFER_TRACE(inode_bh, "get write access");
1717 ret = ext4_journal_get_write_access(handle, inode_bh);
1719 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1722 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1723 do_journal_get_write_access);
1725 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1730 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1731 err = ext4_journal_stop(handle);
1735 if (!ext4_has_inline_data(inode))
1736 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1738 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1745 * Note that we don't need to start a transaction unless we're journaling data
1746 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1747 * need to file the inode to the transaction's list in ordered mode because if
1748 * we are writing back data added by write(), the inode is already there and if
1749 * we are writing back data modified via mmap(), no one guarantees in which
1750 * transaction the data will hit the disk. In case we are journaling data, we
1751 * cannot start transaction directly because transaction start ranks above page
1752 * lock so we have to do some magic.
1754 * This function can get called via...
1755 * - ext4_writepages after taking page lock (have journal handle)
1756 * - journal_submit_inode_data_buffers (no journal handle)
1757 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1758 * - grab_page_cache when doing write_begin (have journal handle)
1760 * We don't do any block allocation in this function. If we have page with
1761 * multiple blocks we need to write those buffer_heads that are mapped. This
1762 * is important for mmaped based write. So if we do with blocksize 1K
1763 * truncate(f, 1024);
1764 * a = mmap(f, 0, 4096);
1766 * truncate(f, 4096);
1767 * we have in the page first buffer_head mapped via page_mkwrite call back
1768 * but other buffer_heads would be unmapped but dirty (dirty done via the
1769 * do_wp_page). So writepage should write the first block. If we modify
1770 * the mmap area beyond 1024 we will again get a page_fault and the
1771 * page_mkwrite callback will do the block allocation and mark the
1772 * buffer_heads mapped.
1774 * We redirty the page if we have any buffer_heads that is either delay or
1775 * unwritten in the page.
1777 * We can get recursively called as show below.
1779 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1782 * But since we don't do any block allocation we should not deadlock.
1783 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1785 static int ext4_writepage(struct page *page,
1786 struct writeback_control *wbc)
1791 struct buffer_head *page_bufs = NULL;
1792 struct inode *inode = page->mapping->host;
1793 struct ext4_io_submit io_submit;
1794 bool keep_towrite = false;
1796 trace_ext4_writepage(page);
1797 size = i_size_read(inode);
1798 if (page->index == size >> PAGE_CACHE_SHIFT)
1799 len = size & ~PAGE_CACHE_MASK;
1801 len = PAGE_CACHE_SIZE;
1803 page_bufs = page_buffers(page);
1805 * We cannot do block allocation or other extent handling in this
1806 * function. If there are buffers needing that, we have to redirty
1807 * the page. But we may reach here when we do a journal commit via
1808 * journal_submit_inode_data_buffers() and in that case we must write
1809 * allocated buffers to achieve data=ordered mode guarantees.
1811 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1812 ext4_bh_delay_or_unwritten)) {
1813 redirty_page_for_writepage(wbc, page);
1814 if (current->flags & PF_MEMALLOC) {
1816 * For memory cleaning there's no point in writing only
1817 * some buffers. So just bail out. Warn if we came here
1818 * from direct reclaim.
1820 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1825 keep_towrite = true;
1828 if (PageChecked(page) && ext4_should_journal_data(inode))
1830 * It's mmapped pagecache. Add buffers and journal it. There
1831 * doesn't seem much point in redirtying the page here.
1833 return __ext4_journalled_writepage(page, len);
1835 ext4_io_submit_init(&io_submit, wbc);
1836 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1837 if (!io_submit.io_end) {
1838 redirty_page_for_writepage(wbc, page);
1842 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1843 ext4_io_submit(&io_submit);
1844 /* Drop io_end reference we got from init */
1845 ext4_put_io_end_defer(io_submit.io_end);
1849 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1852 loff_t size = i_size_read(mpd->inode);
1855 BUG_ON(page->index != mpd->first_page);
1856 if (page->index == size >> PAGE_CACHE_SHIFT)
1857 len = size & ~PAGE_CACHE_MASK;
1859 len = PAGE_CACHE_SIZE;
1860 clear_page_dirty_for_io(page);
1861 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1863 mpd->wbc->nr_to_write--;
1869 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1872 * mballoc gives us at most this number of blocks...
1873 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1874 * The rest of mballoc seems to handle chunks up to full group size.
1876 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1879 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1881 * @mpd - extent of blocks
1882 * @lblk - logical number of the block in the file
1883 * @bh - buffer head we want to add to the extent
1885 * The function is used to collect contig. blocks in the same state. If the
1886 * buffer doesn't require mapping for writeback and we haven't started the
1887 * extent of buffers to map yet, the function returns 'true' immediately - the
1888 * caller can write the buffer right away. Otherwise the function returns true
1889 * if the block has been added to the extent, false if the block couldn't be
1892 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1893 struct buffer_head *bh)
1895 struct ext4_map_blocks *map = &mpd->map;
1897 /* Buffer that doesn't need mapping for writeback? */
1898 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1899 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1900 /* So far no extent to map => we write the buffer right away */
1901 if (map->m_len == 0)
1906 /* First block in the extent? */
1907 if (map->m_len == 0) {
1910 map->m_flags = bh->b_state & BH_FLAGS;
1914 /* Don't go larger than mballoc is willing to allocate */
1915 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
1918 /* Can we merge the block to our big extent? */
1919 if (lblk == map->m_lblk + map->m_len &&
1920 (bh->b_state & BH_FLAGS) == map->m_flags) {
1928 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
1930 * @mpd - extent of blocks for mapping
1931 * @head - the first buffer in the page
1932 * @bh - buffer we should start processing from
1933 * @lblk - logical number of the block in the file corresponding to @bh
1935 * Walk through page buffers from @bh upto @head (exclusive) and either submit
1936 * the page for IO if all buffers in this page were mapped and there's no
1937 * accumulated extent of buffers to map or add buffers in the page to the
1938 * extent of buffers to map. The function returns 1 if the caller can continue
1939 * by processing the next page, 0 if it should stop adding buffers to the
1940 * extent to map because we cannot extend it anymore. It can also return value
1941 * < 0 in case of error during IO submission.
1943 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
1944 struct buffer_head *head,
1945 struct buffer_head *bh,
1948 struct inode *inode = mpd->inode;
1950 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
1951 >> inode->i_blkbits;
1954 BUG_ON(buffer_locked(bh));
1956 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
1957 /* Found extent to map? */
1960 /* Everything mapped so far and we hit EOF */
1963 } while (lblk++, (bh = bh->b_this_page) != head);
1964 /* So far everything mapped? Submit the page for IO. */
1965 if (mpd->map.m_len == 0) {
1966 err = mpage_submit_page(mpd, head->b_page);
1970 return lblk < blocks;
1974 * mpage_map_buffers - update buffers corresponding to changed extent and
1975 * submit fully mapped pages for IO
1977 * @mpd - description of extent to map, on return next extent to map
1979 * Scan buffers corresponding to changed extent (we expect corresponding pages
1980 * to be already locked) and update buffer state according to new extent state.
1981 * We map delalloc buffers to their physical location, clear unwritten bits,
1982 * and mark buffers as uninit when we perform writes to unwritten extents
1983 * and do extent conversion after IO is finished. If the last page is not fully
1984 * mapped, we update @map to the next extent in the last page that needs
1985 * mapping. Otherwise we submit the page for IO.
1987 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
1989 struct pagevec pvec;
1991 struct inode *inode = mpd->inode;
1992 struct buffer_head *head, *bh;
1993 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
1999 start = mpd->map.m_lblk >> bpp_bits;
2000 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2001 lblk = start << bpp_bits;
2002 pblock = mpd->map.m_pblk;
2004 pagevec_init(&pvec, 0);
2005 while (start <= end) {
2006 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2010 for (i = 0; i < nr_pages; i++) {
2011 struct page *page = pvec.pages[i];
2013 if (page->index > end)
2015 /* Up to 'end' pages must be contiguous */
2016 BUG_ON(page->index != start);
2017 bh = head = page_buffers(page);
2019 if (lblk < mpd->map.m_lblk)
2021 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2023 * Buffer after end of mapped extent.
2024 * Find next buffer in the page to map.
2027 mpd->map.m_flags = 0;
2029 * FIXME: If dioread_nolock supports
2030 * blocksize < pagesize, we need to make
2031 * sure we add size mapped so far to
2032 * io_end->size as the following call
2033 * can submit the page for IO.
2035 err = mpage_process_page_bufs(mpd, head,
2037 pagevec_release(&pvec);
2042 if (buffer_delay(bh)) {
2043 clear_buffer_delay(bh);
2044 bh->b_blocknr = pblock++;
2046 clear_buffer_unwritten(bh);
2047 } while (lblk++, (bh = bh->b_this_page) != head);
2050 * FIXME: This is going to break if dioread_nolock
2051 * supports blocksize < pagesize as we will try to
2052 * convert potentially unmapped parts of inode.
2054 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2055 /* Page fully mapped - let IO run! */
2056 err = mpage_submit_page(mpd, page);
2058 pagevec_release(&pvec);
2063 pagevec_release(&pvec);
2065 /* Extent fully mapped and matches with page boundary. We are done. */
2067 mpd->map.m_flags = 0;
2071 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2073 struct inode *inode = mpd->inode;
2074 struct ext4_map_blocks *map = &mpd->map;
2075 int get_blocks_flags;
2076 int err, dioread_nolock;
2078 trace_ext4_da_write_pages_extent(inode, map);
2080 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2081 * to convert an unwritten extent to be initialized (in the case
2082 * where we have written into one or more preallocated blocks). It is
2083 * possible that we're going to need more metadata blocks than
2084 * previously reserved. However we must not fail because we're in
2085 * writeback and there is nothing we can do about it so it might result
2086 * in data loss. So use reserved blocks to allocate metadata if
2089 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2090 * the blocks in question are delalloc blocks. This indicates
2091 * that the blocks and quotas has already been checked when
2092 * the data was copied into the page cache.
2094 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2095 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2096 dioread_nolock = ext4_should_dioread_nolock(inode);
2098 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2099 if (map->m_flags & (1 << BH_Delay))
2100 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2102 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2105 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2106 if (!mpd->io_submit.io_end->handle &&
2107 ext4_handle_valid(handle)) {
2108 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2109 handle->h_rsv_handle = NULL;
2111 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2114 BUG_ON(map->m_len == 0);
2115 if (map->m_flags & EXT4_MAP_NEW) {
2116 struct block_device *bdev = inode->i_sb->s_bdev;
2119 for (i = 0; i < map->m_len; i++)
2120 unmap_underlying_metadata(bdev, map->m_pblk + i);
2126 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2127 * mpd->len and submit pages underlying it for IO
2129 * @handle - handle for journal operations
2130 * @mpd - extent to map
2131 * @give_up_on_write - we set this to true iff there is a fatal error and there
2132 * is no hope of writing the data. The caller should discard
2133 * dirty pages to avoid infinite loops.
2135 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2136 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2137 * them to initialized or split the described range from larger unwritten
2138 * extent. Note that we need not map all the described range since allocation
2139 * can return less blocks or the range is covered by more unwritten extents. We
2140 * cannot map more because we are limited by reserved transaction credits. On
2141 * the other hand we always make sure that the last touched page is fully
2142 * mapped so that it can be written out (and thus forward progress is
2143 * guaranteed). After mapping we submit all mapped pages for IO.
2145 static int mpage_map_and_submit_extent(handle_t *handle,
2146 struct mpage_da_data *mpd,
2147 bool *give_up_on_write)
2149 struct inode *inode = mpd->inode;
2150 struct ext4_map_blocks *map = &mpd->map;
2155 mpd->io_submit.io_end->offset =
2156 ((loff_t)map->m_lblk) << inode->i_blkbits;
2158 err = mpage_map_one_extent(handle, mpd);
2160 struct super_block *sb = inode->i_sb;
2162 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2163 goto invalidate_dirty_pages;
2165 * Let the uper layers retry transient errors.
2166 * In the case of ENOSPC, if ext4_count_free_blocks()
2167 * is non-zero, a commit should free up blocks.
2169 if ((err == -ENOMEM) ||
2170 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2172 goto update_disksize;
2175 ext4_msg(sb, KERN_CRIT,
2176 "Delayed block allocation failed for "
2177 "inode %lu at logical offset %llu with"
2178 " max blocks %u with error %d",
2180 (unsigned long long)map->m_lblk,
2181 (unsigned)map->m_len, -err);
2182 ext4_msg(sb, KERN_CRIT,
2183 "This should not happen!! Data will "
2186 ext4_print_free_blocks(inode);
2187 invalidate_dirty_pages:
2188 *give_up_on_write = true;
2193 * Update buffer state, submit mapped pages, and get us new
2196 err = mpage_map_and_submit_buffers(mpd);
2198 goto update_disksize;
2199 } while (map->m_len);
2203 * Update on-disk size after IO is submitted. Races with
2204 * truncate are avoided by checking i_size under i_data_sem.
2206 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2207 if (disksize > EXT4_I(inode)->i_disksize) {
2211 down_write(&EXT4_I(inode)->i_data_sem);
2212 i_size = i_size_read(inode);
2213 if (disksize > i_size)
2215 if (disksize > EXT4_I(inode)->i_disksize)
2216 EXT4_I(inode)->i_disksize = disksize;
2217 err2 = ext4_mark_inode_dirty(handle, inode);
2218 up_write(&EXT4_I(inode)->i_data_sem);
2220 ext4_error(inode->i_sb,
2221 "Failed to mark inode %lu dirty",
2230 * Calculate the total number of credits to reserve for one writepages
2231 * iteration. This is called from ext4_writepages(). We map an extent of
2232 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2233 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2234 * bpp - 1 blocks in bpp different extents.
2236 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2238 int bpp = ext4_journal_blocks_per_page(inode);
2240 return ext4_meta_trans_blocks(inode,
2241 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2245 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2246 * and underlying extent to map
2248 * @mpd - where to look for pages
2250 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2251 * IO immediately. When we find a page which isn't mapped we start accumulating
2252 * extent of buffers underlying these pages that needs mapping (formed by
2253 * either delayed or unwritten buffers). We also lock the pages containing
2254 * these buffers. The extent found is returned in @mpd structure (starting at
2255 * mpd->lblk with length mpd->len blocks).
2257 * Note that this function can attach bios to one io_end structure which are
2258 * neither logically nor physically contiguous. Although it may seem as an
2259 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2260 * case as we need to track IO to all buffers underlying a page in one io_end.
2262 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2264 struct address_space *mapping = mpd->inode->i_mapping;
2265 struct pagevec pvec;
2266 unsigned int nr_pages;
2267 long left = mpd->wbc->nr_to_write;
2268 pgoff_t index = mpd->first_page;
2269 pgoff_t end = mpd->last_page;
2272 int blkbits = mpd->inode->i_blkbits;
2274 struct buffer_head *head;
2276 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2277 tag = PAGECACHE_TAG_TOWRITE;
2279 tag = PAGECACHE_TAG_DIRTY;
2281 pagevec_init(&pvec, 0);
2283 mpd->next_page = index;
2284 while (index <= end) {
2285 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2286 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2290 for (i = 0; i < nr_pages; i++) {
2291 struct page *page = pvec.pages[i];
2294 * At this point, the page may be truncated or
2295 * invalidated (changing page->mapping to NULL), or
2296 * even swizzled back from swapper_space to tmpfs file
2297 * mapping. However, page->index will not change
2298 * because we have a reference on the page.
2300 if (page->index > end)
2304 * Accumulated enough dirty pages? This doesn't apply
2305 * to WB_SYNC_ALL mode. For integrity sync we have to
2306 * keep going because someone may be concurrently
2307 * dirtying pages, and we might have synced a lot of
2308 * newly appeared dirty pages, but have not synced all
2309 * of the old dirty pages.
2311 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2314 /* If we can't merge this page, we are done. */
2315 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2320 * If the page is no longer dirty, or its mapping no
2321 * longer corresponds to inode we are writing (which
2322 * means it has been truncated or invalidated), or the
2323 * page is already under writeback and we are not doing
2324 * a data integrity writeback, skip the page
2326 if (!PageDirty(page) ||
2327 (PageWriteback(page) &&
2328 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2329 unlikely(page->mapping != mapping)) {
2334 wait_on_page_writeback(page);
2335 BUG_ON(PageWriteback(page));
2337 if (mpd->map.m_len == 0)
2338 mpd->first_page = page->index;
2339 mpd->next_page = page->index + 1;
2340 /* Add all dirty buffers to mpd */
2341 lblk = ((ext4_lblk_t)page->index) <<
2342 (PAGE_CACHE_SHIFT - blkbits);
2343 head = page_buffers(page);
2344 err = mpage_process_page_bufs(mpd, head, head, lblk);
2350 pagevec_release(&pvec);
2355 pagevec_release(&pvec);
2359 static int __writepage(struct page *page, struct writeback_control *wbc,
2362 struct address_space *mapping = data;
2363 int ret = ext4_writepage(page, wbc);
2364 mapping_set_error(mapping, ret);
2368 static int ext4_writepages(struct address_space *mapping,
2369 struct writeback_control *wbc)
2371 pgoff_t writeback_index = 0;
2372 long nr_to_write = wbc->nr_to_write;
2373 int range_whole = 0;
2375 handle_t *handle = NULL;
2376 struct mpage_da_data mpd;
2377 struct inode *inode = mapping->host;
2378 int needed_blocks, rsv_blocks = 0, ret = 0;
2379 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2381 struct blk_plug plug;
2382 bool give_up_on_write = false;
2384 trace_ext4_writepages(inode, wbc);
2387 * No pages to write? This is mainly a kludge to avoid starting
2388 * a transaction for special inodes like journal inode on last iput()
2389 * because that could violate lock ordering on umount
2391 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2392 goto out_writepages;
2394 if (ext4_should_journal_data(inode)) {
2395 struct blk_plug plug;
2397 blk_start_plug(&plug);
2398 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2399 blk_finish_plug(&plug);
2400 goto out_writepages;
2404 * If the filesystem has aborted, it is read-only, so return
2405 * right away instead of dumping stack traces later on that
2406 * will obscure the real source of the problem. We test
2407 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2408 * the latter could be true if the filesystem is mounted
2409 * read-only, and in that case, ext4_writepages should
2410 * *never* be called, so if that ever happens, we would want
2413 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2415 goto out_writepages;
2418 if (ext4_should_dioread_nolock(inode)) {
2420 * We may need to convert up to one extent per block in
2421 * the page and we may dirty the inode.
2423 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2427 * If we have inline data and arrive here, it means that
2428 * we will soon create the block for the 1st page, so
2429 * we'd better clear the inline data here.
2431 if (ext4_has_inline_data(inode)) {
2432 /* Just inode will be modified... */
2433 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2434 if (IS_ERR(handle)) {
2435 ret = PTR_ERR(handle);
2436 goto out_writepages;
2438 BUG_ON(ext4_test_inode_state(inode,
2439 EXT4_STATE_MAY_INLINE_DATA));
2440 ext4_destroy_inline_data(handle, inode);
2441 ext4_journal_stop(handle);
2444 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2447 if (wbc->range_cyclic) {
2448 writeback_index = mapping->writeback_index;
2449 if (writeback_index)
2451 mpd.first_page = writeback_index;
2454 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2455 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2460 ext4_io_submit_init(&mpd.io_submit, wbc);
2462 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2463 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2465 blk_start_plug(&plug);
2466 while (!done && mpd.first_page <= mpd.last_page) {
2467 /* For each extent of pages we use new io_end */
2468 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2469 if (!mpd.io_submit.io_end) {
2475 * We have two constraints: We find one extent to map and we
2476 * must always write out whole page (makes a difference when
2477 * blocksize < pagesize) so that we don't block on IO when we
2478 * try to write out the rest of the page. Journalled mode is
2479 * not supported by delalloc.
2481 BUG_ON(ext4_should_journal_data(inode));
2482 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2484 /* start a new transaction */
2485 handle = ext4_journal_start_with_reserve(inode,
2486 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2487 if (IS_ERR(handle)) {
2488 ret = PTR_ERR(handle);
2489 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2490 "%ld pages, ino %lu; err %d", __func__,
2491 wbc->nr_to_write, inode->i_ino, ret);
2492 /* Release allocated io_end */
2493 ext4_put_io_end(mpd.io_submit.io_end);
2497 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2498 ret = mpage_prepare_extent_to_map(&mpd);
2501 ret = mpage_map_and_submit_extent(handle, &mpd,
2505 * We scanned the whole range (or exhausted
2506 * nr_to_write), submitted what was mapped and
2507 * didn't find anything needing mapping. We are
2513 ext4_journal_stop(handle);
2514 /* Submit prepared bio */
2515 ext4_io_submit(&mpd.io_submit);
2516 /* Unlock pages we didn't use */
2517 mpage_release_unused_pages(&mpd, give_up_on_write);
2518 /* Drop our io_end reference we got from init */
2519 ext4_put_io_end(mpd.io_submit.io_end);
2521 if (ret == -ENOSPC && sbi->s_journal) {
2523 * Commit the transaction which would
2524 * free blocks released in the transaction
2527 jbd2_journal_force_commit_nested(sbi->s_journal);
2531 /* Fatal error - ENOMEM, EIO... */
2535 blk_finish_plug(&plug);
2536 if (!ret && !cycled && wbc->nr_to_write > 0) {
2538 mpd.last_page = writeback_index - 1;
2544 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2546 * Set the writeback_index so that range_cyclic
2547 * mode will write it back later
2549 mapping->writeback_index = mpd.first_page;
2552 trace_ext4_writepages_result(inode, wbc, ret,
2553 nr_to_write - wbc->nr_to_write);
2557 static int ext4_nonda_switch(struct super_block *sb)
2559 s64 free_clusters, dirty_clusters;
2560 struct ext4_sb_info *sbi = EXT4_SB(sb);
2563 * switch to non delalloc mode if we are running low
2564 * on free block. The free block accounting via percpu
2565 * counters can get slightly wrong with percpu_counter_batch getting
2566 * accumulated on each CPU without updating global counters
2567 * Delalloc need an accurate free block accounting. So switch
2568 * to non delalloc when we are near to error range.
2571 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2573 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2575 * Start pushing delalloc when 1/2 of free blocks are dirty.
2577 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2578 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2580 if (2 * free_clusters < 3 * dirty_clusters ||
2581 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2583 * free block count is less than 150% of dirty blocks
2584 * or free blocks is less than watermark
2591 /* We always reserve for an inode update; the superblock could be there too */
2592 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2594 if (likely(EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
2595 EXT4_FEATURE_RO_COMPAT_LARGE_FILE)))
2598 if (pos + len <= 0x7fffffffULL)
2601 /* We might need to update the superblock to set LARGE_FILE */
2605 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2606 loff_t pos, unsigned len, unsigned flags,
2607 struct page **pagep, void **fsdata)
2609 int ret, retries = 0;
2612 struct inode *inode = mapping->host;
2615 index = pos >> PAGE_CACHE_SHIFT;
2617 if (ext4_nonda_switch(inode->i_sb)) {
2618 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2619 return ext4_write_begin(file, mapping, pos,
2620 len, flags, pagep, fsdata);
2622 *fsdata = (void *)0;
2623 trace_ext4_da_write_begin(inode, pos, len, flags);
2625 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2626 ret = ext4_da_write_inline_data_begin(mapping, inode,
2636 * grab_cache_page_write_begin() can take a long time if the
2637 * system is thrashing due to memory pressure, or if the page
2638 * is being written back. So grab it first before we start
2639 * the transaction handle. This also allows us to allocate
2640 * the page (if needed) without using GFP_NOFS.
2643 page = grab_cache_page_write_begin(mapping, index, flags);
2649 * With delayed allocation, we don't log the i_disksize update
2650 * if there is delayed block allocation. But we still need
2651 * to journalling the i_disksize update if writes to the end
2652 * of file which has an already mapped buffer.
2655 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2656 ext4_da_write_credits(inode, pos, len));
2657 if (IS_ERR(handle)) {
2658 page_cache_release(page);
2659 return PTR_ERR(handle);
2663 if (page->mapping != mapping) {
2664 /* The page got truncated from under us */
2666 page_cache_release(page);
2667 ext4_journal_stop(handle);
2670 /* In case writeback began while the page was unlocked */
2671 wait_for_stable_page(page);
2673 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2674 ret = ext4_block_write_begin(page, pos, len,
2675 ext4_da_get_block_prep);
2677 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2681 ext4_journal_stop(handle);
2683 * block_write_begin may have instantiated a few blocks
2684 * outside i_size. Trim these off again. Don't need
2685 * i_size_read because we hold i_mutex.
2687 if (pos + len > inode->i_size)
2688 ext4_truncate_failed_write(inode);
2690 if (ret == -ENOSPC &&
2691 ext4_should_retry_alloc(inode->i_sb, &retries))
2694 page_cache_release(page);
2703 * Check if we should update i_disksize
2704 * when write to the end of file but not require block allocation
2706 static int ext4_da_should_update_i_disksize(struct page *page,
2707 unsigned long offset)
2709 struct buffer_head *bh;
2710 struct inode *inode = page->mapping->host;
2714 bh = page_buffers(page);
2715 idx = offset >> inode->i_blkbits;
2717 for (i = 0; i < idx; i++)
2718 bh = bh->b_this_page;
2720 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2725 static int ext4_da_write_end(struct file *file,
2726 struct address_space *mapping,
2727 loff_t pos, unsigned len, unsigned copied,
2728 struct page *page, void *fsdata)
2730 struct inode *inode = mapping->host;
2732 handle_t *handle = ext4_journal_current_handle();
2734 unsigned long start, end;
2735 int write_mode = (int)(unsigned long)fsdata;
2737 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2738 return ext4_write_end(file, mapping, pos,
2739 len, copied, page, fsdata);
2741 trace_ext4_da_write_end(inode, pos, len, copied);
2742 start = pos & (PAGE_CACHE_SIZE - 1);
2743 end = start + copied - 1;
2746 * generic_write_end() will run mark_inode_dirty() if i_size
2747 * changes. So let's piggyback the i_disksize mark_inode_dirty
2750 new_i_size = pos + copied;
2751 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2752 if (ext4_has_inline_data(inode) ||
2753 ext4_da_should_update_i_disksize(page, end)) {
2754 ext4_update_i_disksize(inode, new_i_size);
2755 /* We need to mark inode dirty even if
2756 * new_i_size is less that inode->i_size
2757 * bu greater than i_disksize.(hint delalloc)
2759 ext4_mark_inode_dirty(handle, inode);
2763 if (write_mode != CONVERT_INLINE_DATA &&
2764 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2765 ext4_has_inline_data(inode))
2766 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2769 ret2 = generic_write_end(file, mapping, pos, len, copied,
2775 ret2 = ext4_journal_stop(handle);
2779 return ret ? ret : copied;
2782 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2783 unsigned int length)
2786 * Drop reserved blocks
2788 BUG_ON(!PageLocked(page));
2789 if (!page_has_buffers(page))
2792 ext4_da_page_release_reservation(page, offset, length);
2795 ext4_invalidatepage(page, offset, length);
2801 * Force all delayed allocation blocks to be allocated for a given inode.
2803 int ext4_alloc_da_blocks(struct inode *inode)
2805 trace_ext4_alloc_da_blocks(inode);
2807 if (!EXT4_I(inode)->i_reserved_data_blocks)
2811 * We do something simple for now. The filemap_flush() will
2812 * also start triggering a write of the data blocks, which is
2813 * not strictly speaking necessary (and for users of
2814 * laptop_mode, not even desirable). However, to do otherwise
2815 * would require replicating code paths in:
2817 * ext4_writepages() ->
2818 * write_cache_pages() ---> (via passed in callback function)
2819 * __mpage_da_writepage() -->
2820 * mpage_add_bh_to_extent()
2821 * mpage_da_map_blocks()
2823 * The problem is that write_cache_pages(), located in
2824 * mm/page-writeback.c, marks pages clean in preparation for
2825 * doing I/O, which is not desirable if we're not planning on
2828 * We could call write_cache_pages(), and then redirty all of
2829 * the pages by calling redirty_page_for_writepage() but that
2830 * would be ugly in the extreme. So instead we would need to
2831 * replicate parts of the code in the above functions,
2832 * simplifying them because we wouldn't actually intend to
2833 * write out the pages, but rather only collect contiguous
2834 * logical block extents, call the multi-block allocator, and
2835 * then update the buffer heads with the block allocations.
2837 * For now, though, we'll cheat by calling filemap_flush(),
2838 * which will map the blocks, and start the I/O, but not
2839 * actually wait for the I/O to complete.
2841 return filemap_flush(inode->i_mapping);
2845 * bmap() is special. It gets used by applications such as lilo and by
2846 * the swapper to find the on-disk block of a specific piece of data.
2848 * Naturally, this is dangerous if the block concerned is still in the
2849 * journal. If somebody makes a swapfile on an ext4 data-journaling
2850 * filesystem and enables swap, then they may get a nasty shock when the
2851 * data getting swapped to that swapfile suddenly gets overwritten by
2852 * the original zero's written out previously to the journal and
2853 * awaiting writeback in the kernel's buffer cache.
2855 * So, if we see any bmap calls here on a modified, data-journaled file,
2856 * take extra steps to flush any blocks which might be in the cache.
2858 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2860 struct inode *inode = mapping->host;
2865 * We can get here for an inline file via the FIBMAP ioctl
2867 if (ext4_has_inline_data(inode))
2870 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2871 test_opt(inode->i_sb, DELALLOC)) {
2873 * With delalloc we want to sync the file
2874 * so that we can make sure we allocate
2877 filemap_write_and_wait(mapping);
2880 if (EXT4_JOURNAL(inode) &&
2881 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2883 * This is a REALLY heavyweight approach, but the use of
2884 * bmap on dirty files is expected to be extremely rare:
2885 * only if we run lilo or swapon on a freshly made file
2886 * do we expect this to happen.
2888 * (bmap requires CAP_SYS_RAWIO so this does not
2889 * represent an unprivileged user DOS attack --- we'd be
2890 * in trouble if mortal users could trigger this path at
2893 * NB. EXT4_STATE_JDATA is not set on files other than
2894 * regular files. If somebody wants to bmap a directory
2895 * or symlink and gets confused because the buffer
2896 * hasn't yet been flushed to disk, they deserve
2897 * everything they get.
2900 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2901 journal = EXT4_JOURNAL(inode);
2902 jbd2_journal_lock_updates(journal);
2903 err = jbd2_journal_flush(journal);
2904 jbd2_journal_unlock_updates(journal);
2910 return generic_block_bmap(mapping, block, ext4_get_block);
2913 static int ext4_readpage(struct file *file, struct page *page)
2916 struct inode *inode = page->mapping->host;
2918 trace_ext4_readpage(page);
2920 if (ext4_has_inline_data(inode))
2921 ret = ext4_readpage_inline(inode, page);
2924 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
2930 ext4_readpages(struct file *file, struct address_space *mapping,
2931 struct list_head *pages, unsigned nr_pages)
2933 struct inode *inode = mapping->host;
2935 /* If the file has inline data, no need to do readpages. */
2936 if (ext4_has_inline_data(inode))
2939 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
2942 static void ext4_invalidatepage(struct page *page, unsigned int offset,
2943 unsigned int length)
2945 trace_ext4_invalidatepage(page, offset, length);
2947 /* No journalling happens on data buffers when this function is used */
2948 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
2950 block_invalidatepage(page, offset, length);
2953 static int __ext4_journalled_invalidatepage(struct page *page,
2954 unsigned int offset,
2955 unsigned int length)
2957 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2959 trace_ext4_journalled_invalidatepage(page, offset, length);
2962 * If it's a full truncate we just forget about the pending dirtying
2964 if (offset == 0 && length == PAGE_CACHE_SIZE)
2965 ClearPageChecked(page);
2967 return jbd2_journal_invalidatepage(journal, page, offset, length);
2970 /* Wrapper for aops... */
2971 static void ext4_journalled_invalidatepage(struct page *page,
2972 unsigned int offset,
2973 unsigned int length)
2975 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
2978 static int ext4_releasepage(struct page *page, gfp_t wait)
2980 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2982 trace_ext4_releasepage(page);
2984 /* Page has dirty journalled data -> cannot release */
2985 if (PageChecked(page))
2988 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2990 return try_to_free_buffers(page);
2994 * ext4_get_block used when preparing for a DIO write or buffer write.
2995 * We allocate an uinitialized extent if blocks haven't been allocated.
2996 * The extent will be converted to initialized after the IO is complete.
2998 int ext4_get_block_write(struct inode *inode, sector_t iblock,
2999 struct buffer_head *bh_result, int create)
3001 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3002 inode->i_ino, create);
3003 return _ext4_get_block(inode, iblock, bh_result,
3004 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3007 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3008 struct buffer_head *bh_result, int create)
3010 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3011 inode->i_ino, create);
3012 return _ext4_get_block(inode, iblock, bh_result,
3013 EXT4_GET_BLOCKS_NO_LOCK);
3016 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3017 ssize_t size, void *private)
3019 ext4_io_end_t *io_end = iocb->private;
3021 /* if not async direct IO just return */
3025 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3026 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3027 iocb->private, io_end->inode->i_ino, iocb, offset,
3030 iocb->private = NULL;
3031 io_end->offset = offset;
3032 io_end->size = size;
3033 ext4_put_io_end(io_end);
3037 * For ext4 extent files, ext4 will do direct-io write to holes,
3038 * preallocated extents, and those write extend the file, no need to
3039 * fall back to buffered IO.
3041 * For holes, we fallocate those blocks, mark them as unwritten
3042 * If those blocks were preallocated, we mark sure they are split, but
3043 * still keep the range to write as unwritten.
3045 * The unwritten extents will be converted to written when DIO is completed.
3046 * For async direct IO, since the IO may still pending when return, we
3047 * set up an end_io call back function, which will do the conversion
3048 * when async direct IO completed.
3050 * If the O_DIRECT write will extend the file then add this inode to the
3051 * orphan list. So recovery will truncate it back to the original size
3052 * if the machine crashes during the write.
3055 static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3058 struct file *file = iocb->ki_filp;
3059 struct inode *inode = file->f_mapping->host;
3061 size_t count = iov_iter_count(iter);
3063 get_block_t *get_block_func = NULL;
3065 loff_t final_size = offset + count;
3066 ext4_io_end_t *io_end = NULL;
3068 /* Use the old path for reads and writes beyond i_size. */
3069 if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size)
3070 return ext4_ind_direct_IO(iocb, iter, offset);
3072 BUG_ON(iocb->private == NULL);
3075 * Make all waiters for direct IO properly wait also for extent
3076 * conversion. This also disallows race between truncate() and
3077 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3079 if (iov_iter_rw(iter) == WRITE)
3080 inode_dio_begin(inode);
3082 /* If we do a overwrite dio, i_mutex locking can be released */
3083 overwrite = *((int *)iocb->private);
3086 down_read(&EXT4_I(inode)->i_data_sem);
3087 mutex_unlock(&inode->i_mutex);
3091 * We could direct write to holes and fallocate.
3093 * Allocated blocks to fill the hole are marked as
3094 * unwritten to prevent parallel buffered read to expose
3095 * the stale data before DIO complete the data IO.
3097 * As to previously fallocated extents, ext4 get_block will
3098 * just simply mark the buffer mapped but still keep the
3099 * extents unwritten.
3101 * For non AIO case, we will convert those unwritten extents
3102 * to written after return back from blockdev_direct_IO.
3104 * For async DIO, the conversion needs to be deferred when the
3105 * IO is completed. The ext4 end_io callback function will be
3106 * called to take care of the conversion work. Here for async
3107 * case, we allocate an io_end structure to hook to the iocb.
3109 iocb->private = NULL;
3110 ext4_inode_aio_set(inode, NULL);
3111 if (!is_sync_kiocb(iocb)) {
3112 io_end = ext4_init_io_end(inode, GFP_NOFS);
3118 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
3120 iocb->private = ext4_get_io_end(io_end);
3122 * we save the io structure for current async direct
3123 * IO, so that later ext4_map_blocks() could flag the
3124 * io structure whether there is a unwritten extents
3125 * needs to be converted when IO is completed.
3127 ext4_inode_aio_set(inode, io_end);
3131 get_block_func = ext4_get_block_write_nolock;
3133 get_block_func = ext4_get_block_write;
3134 dio_flags = DIO_LOCKING;
3136 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3137 BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
3140 ret = dax_do_io(iocb, inode, iter, offset, get_block_func,
3141 ext4_end_io_dio, dio_flags);
3143 ret = __blockdev_direct_IO(iocb, inode,
3144 inode->i_sb->s_bdev, iter, offset,
3146 ext4_end_io_dio, NULL, dio_flags);
3149 * Put our reference to io_end. This can free the io_end structure e.g.
3150 * in sync IO case or in case of error. It can even perform extent
3151 * conversion if all bios we submitted finished before we got here.
3152 * Note that in that case iocb->private can be already set to NULL
3156 ext4_inode_aio_set(inode, NULL);
3157 ext4_put_io_end(io_end);
3159 * When no IO was submitted ext4_end_io_dio() was not
3160 * called so we have to put iocb's reference.
3162 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3163 WARN_ON(iocb->private != io_end);
3164 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3165 ext4_put_io_end(io_end);
3166 iocb->private = NULL;
3169 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3170 EXT4_STATE_DIO_UNWRITTEN)) {
3173 * for non AIO case, since the IO is already
3174 * completed, we could do the conversion right here
3176 err = ext4_convert_unwritten_extents(NULL, inode,
3180 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3184 if (iov_iter_rw(iter) == WRITE)
3185 inode_dio_end(inode);
3186 /* take i_mutex locking again if we do a ovewrite dio */
3188 up_read(&EXT4_I(inode)->i_data_sem);
3189 mutex_lock(&inode->i_mutex);
3195 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3198 struct file *file = iocb->ki_filp;
3199 struct inode *inode = file->f_mapping->host;
3200 size_t count = iov_iter_count(iter);
3203 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3204 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3209 * If we are doing data journalling we don't support O_DIRECT
3211 if (ext4_should_journal_data(inode))
3214 /* Let buffer I/O handle the inline data case. */
3215 if (ext4_has_inline_data(inode))
3218 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3219 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3220 ret = ext4_ext_direct_IO(iocb, iter, offset);
3222 ret = ext4_ind_direct_IO(iocb, iter, offset);
3223 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3228 * Pages can be marked dirty completely asynchronously from ext4's journalling
3229 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3230 * much here because ->set_page_dirty is called under VFS locks. The page is
3231 * not necessarily locked.
3233 * We cannot just dirty the page and leave attached buffers clean, because the
3234 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3235 * or jbddirty because all the journalling code will explode.
3237 * So what we do is to mark the page "pending dirty" and next time writepage
3238 * is called, propagate that into the buffers appropriately.
3240 static int ext4_journalled_set_page_dirty(struct page *page)
3242 SetPageChecked(page);
3243 return __set_page_dirty_nobuffers(page);
3246 static const struct address_space_operations ext4_aops = {
3247 .readpage = ext4_readpage,
3248 .readpages = ext4_readpages,
3249 .writepage = ext4_writepage,
3250 .writepages = ext4_writepages,
3251 .write_begin = ext4_write_begin,
3252 .write_end = ext4_write_end,
3254 .invalidatepage = ext4_invalidatepage,
3255 .releasepage = ext4_releasepage,
3256 .direct_IO = ext4_direct_IO,
3257 .migratepage = buffer_migrate_page,
3258 .is_partially_uptodate = block_is_partially_uptodate,
3259 .error_remove_page = generic_error_remove_page,
3262 static const struct address_space_operations ext4_journalled_aops = {
3263 .readpage = ext4_readpage,
3264 .readpages = ext4_readpages,
3265 .writepage = ext4_writepage,
3266 .writepages = ext4_writepages,
3267 .write_begin = ext4_write_begin,
3268 .write_end = ext4_journalled_write_end,
3269 .set_page_dirty = ext4_journalled_set_page_dirty,
3271 .invalidatepage = ext4_journalled_invalidatepage,
3272 .releasepage = ext4_releasepage,
3273 .direct_IO = ext4_direct_IO,
3274 .is_partially_uptodate = block_is_partially_uptodate,
3275 .error_remove_page = generic_error_remove_page,
3278 static const struct address_space_operations ext4_da_aops = {
3279 .readpage = ext4_readpage,
3280 .readpages = ext4_readpages,
3281 .writepage = ext4_writepage,
3282 .writepages = ext4_writepages,
3283 .write_begin = ext4_da_write_begin,
3284 .write_end = ext4_da_write_end,
3286 .invalidatepage = ext4_da_invalidatepage,
3287 .releasepage = ext4_releasepage,
3288 .direct_IO = ext4_direct_IO,
3289 .migratepage = buffer_migrate_page,
3290 .is_partially_uptodate = block_is_partially_uptodate,
3291 .error_remove_page = generic_error_remove_page,
3294 void ext4_set_aops(struct inode *inode)
3296 switch (ext4_inode_journal_mode(inode)) {
3297 case EXT4_INODE_ORDERED_DATA_MODE:
3298 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3300 case EXT4_INODE_WRITEBACK_DATA_MODE:
3301 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3303 case EXT4_INODE_JOURNAL_DATA_MODE:
3304 inode->i_mapping->a_ops = &ext4_journalled_aops;
3309 if (test_opt(inode->i_sb, DELALLOC))
3310 inode->i_mapping->a_ops = &ext4_da_aops;
3312 inode->i_mapping->a_ops = &ext4_aops;
3315 static int __ext4_block_zero_page_range(handle_t *handle,
3316 struct address_space *mapping, loff_t from, loff_t length)
3318 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3319 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3320 unsigned blocksize, pos;
3322 struct inode *inode = mapping->host;
3323 struct buffer_head *bh;
3327 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3328 mapping_gfp_mask(mapping) & ~__GFP_FS);
3332 blocksize = inode->i_sb->s_blocksize;
3334 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3336 if (!page_has_buffers(page))
3337 create_empty_buffers(page, blocksize, 0);
3339 /* Find the buffer that contains "offset" */
3340 bh = page_buffers(page);
3342 while (offset >= pos) {
3343 bh = bh->b_this_page;
3347 if (buffer_freed(bh)) {
3348 BUFFER_TRACE(bh, "freed: skip");
3351 if (!buffer_mapped(bh)) {
3352 BUFFER_TRACE(bh, "unmapped");
3353 ext4_get_block(inode, iblock, bh, 0);
3354 /* unmapped? It's a hole - nothing to do */
3355 if (!buffer_mapped(bh)) {
3356 BUFFER_TRACE(bh, "still unmapped");
3361 /* Ok, it's mapped. Make sure it's up-to-date */
3362 if (PageUptodate(page))
3363 set_buffer_uptodate(bh);
3365 if (!buffer_uptodate(bh)) {
3367 ll_rw_block(READ, 1, &bh);
3369 /* Uhhuh. Read error. Complain and punt. */
3370 if (!buffer_uptodate(bh))
3372 if (S_ISREG(inode->i_mode) &&
3373 ext4_encrypted_inode(inode)) {
3374 /* We expect the key to be set. */
3375 BUG_ON(!ext4_has_encryption_key(inode));
3376 BUG_ON(blocksize != PAGE_CACHE_SIZE);
3377 WARN_ON_ONCE(ext4_decrypt_one(inode, page));
3380 if (ext4_should_journal_data(inode)) {
3381 BUFFER_TRACE(bh, "get write access");
3382 err = ext4_journal_get_write_access(handle, bh);
3386 zero_user(page, offset, length);
3387 BUFFER_TRACE(bh, "zeroed end of block");
3389 if (ext4_should_journal_data(inode)) {
3390 err = ext4_handle_dirty_metadata(handle, inode, bh);
3393 mark_buffer_dirty(bh);
3394 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3395 err = ext4_jbd2_file_inode(handle, inode);
3400 page_cache_release(page);
3405 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3406 * starting from file offset 'from'. The range to be zero'd must
3407 * be contained with in one block. If the specified range exceeds
3408 * the end of the block it will be shortened to end of the block
3409 * that cooresponds to 'from'
3411 static int ext4_block_zero_page_range(handle_t *handle,
3412 struct address_space *mapping, loff_t from, loff_t length)
3414 struct inode *inode = mapping->host;
3415 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3416 unsigned blocksize = inode->i_sb->s_blocksize;
3417 unsigned max = blocksize - (offset & (blocksize - 1));
3420 * correct length if it does not fall between
3421 * 'from' and the end of the block
3423 if (length > max || length < 0)
3427 return dax_zero_page_range(inode, from, length, ext4_get_block);
3428 return __ext4_block_zero_page_range(handle, mapping, from, length);
3432 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3433 * up to the end of the block which corresponds to `from'.
3434 * This required during truncate. We need to physically zero the tail end
3435 * of that block so it doesn't yield old data if the file is later grown.
3437 static int ext4_block_truncate_page(handle_t *handle,
3438 struct address_space *mapping, loff_t from)
3440 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3443 struct inode *inode = mapping->host;
3445 blocksize = inode->i_sb->s_blocksize;
3446 length = blocksize - (offset & (blocksize - 1));
3448 return ext4_block_zero_page_range(handle, mapping, from, length);
3451 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3452 loff_t lstart, loff_t length)
3454 struct super_block *sb = inode->i_sb;
3455 struct address_space *mapping = inode->i_mapping;
3456 unsigned partial_start, partial_end;
3457 ext4_fsblk_t start, end;
3458 loff_t byte_end = (lstart + length - 1);
3461 partial_start = lstart & (sb->s_blocksize - 1);
3462 partial_end = byte_end & (sb->s_blocksize - 1);
3464 start = lstart >> sb->s_blocksize_bits;
3465 end = byte_end >> sb->s_blocksize_bits;
3467 /* Handle partial zero within the single block */
3469 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3470 err = ext4_block_zero_page_range(handle, mapping,
3474 /* Handle partial zero out on the start of the range */
3475 if (partial_start) {
3476 err = ext4_block_zero_page_range(handle, mapping,
3477 lstart, sb->s_blocksize);
3481 /* Handle partial zero out on the end of the range */
3482 if (partial_end != sb->s_blocksize - 1)
3483 err = ext4_block_zero_page_range(handle, mapping,
3484 byte_end - partial_end,
3489 int ext4_can_truncate(struct inode *inode)
3491 if (S_ISREG(inode->i_mode))
3493 if (S_ISDIR(inode->i_mode))
3495 if (S_ISLNK(inode->i_mode))
3496 return !ext4_inode_is_fast_symlink(inode);
3501 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3502 * associated with the given offset and length
3504 * @inode: File inode
3505 * @offset: The offset where the hole will begin
3506 * @len: The length of the hole
3508 * Returns: 0 on success or negative on failure
3511 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3513 struct super_block *sb = inode->i_sb;
3514 ext4_lblk_t first_block, stop_block;
3515 struct address_space *mapping = inode->i_mapping;
3516 loff_t first_block_offset, last_block_offset;
3518 unsigned int credits;
3521 if (!S_ISREG(inode->i_mode))
3524 trace_ext4_punch_hole(inode, offset, length, 0);
3527 * Write out all dirty pages to avoid race conditions
3528 * Then release them.
3530 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3531 ret = filemap_write_and_wait_range(mapping, offset,
3532 offset + length - 1);
3537 mutex_lock(&inode->i_mutex);
3539 /* No need to punch hole beyond i_size */
3540 if (offset >= inode->i_size)
3544 * If the hole extends beyond i_size, set the hole
3545 * to end after the page that contains i_size
3547 if (offset + length > inode->i_size) {
3548 length = inode->i_size +
3549 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3553 if (offset & (sb->s_blocksize - 1) ||
3554 (offset + length) & (sb->s_blocksize - 1)) {
3556 * Attach jinode to inode for jbd2 if we do any zeroing of
3559 ret = ext4_inode_attach_jinode(inode);
3565 first_block_offset = round_up(offset, sb->s_blocksize);
3566 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3568 /* Now release the pages and zero block aligned part of pages*/
3569 if (last_block_offset > first_block_offset)
3570 truncate_pagecache_range(inode, first_block_offset,
3573 /* Wait all existing dio workers, newcomers will block on i_mutex */
3574 ext4_inode_block_unlocked_dio(inode);
3575 inode_dio_wait(inode);
3577 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3578 credits = ext4_writepage_trans_blocks(inode);
3580 credits = ext4_blocks_for_truncate(inode);
3581 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3582 if (IS_ERR(handle)) {
3583 ret = PTR_ERR(handle);
3584 ext4_std_error(sb, ret);
3588 ret = ext4_zero_partial_blocks(handle, inode, offset,
3593 first_block = (offset + sb->s_blocksize - 1) >>
3594 EXT4_BLOCK_SIZE_BITS(sb);
3595 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3597 /* If there are no blocks to remove, return now */
3598 if (first_block >= stop_block)
3601 down_write(&EXT4_I(inode)->i_data_sem);
3602 ext4_discard_preallocations(inode);
3604 ret = ext4_es_remove_extent(inode, first_block,
3605 stop_block - first_block);
3607 up_write(&EXT4_I(inode)->i_data_sem);
3611 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3612 ret = ext4_ext_remove_space(inode, first_block,
3615 ret = ext4_ind_remove_space(handle, inode, first_block,
3618 up_write(&EXT4_I(inode)->i_data_sem);
3620 ext4_handle_sync(handle);
3622 /* Now release the pages again to reduce race window */
3623 if (last_block_offset > first_block_offset)
3624 truncate_pagecache_range(inode, first_block_offset,
3627 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3628 ext4_mark_inode_dirty(handle, inode);
3630 ext4_journal_stop(handle);
3632 ext4_inode_resume_unlocked_dio(inode);
3634 mutex_unlock(&inode->i_mutex);
3638 int ext4_inode_attach_jinode(struct inode *inode)
3640 struct ext4_inode_info *ei = EXT4_I(inode);
3641 struct jbd2_inode *jinode;
3643 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3646 jinode = jbd2_alloc_inode(GFP_KERNEL);
3647 spin_lock(&inode->i_lock);
3650 spin_unlock(&inode->i_lock);
3653 ei->jinode = jinode;
3654 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3657 spin_unlock(&inode->i_lock);
3658 if (unlikely(jinode != NULL))
3659 jbd2_free_inode(jinode);
3666 * We block out ext4_get_block() block instantiations across the entire
3667 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3668 * simultaneously on behalf of the same inode.
3670 * As we work through the truncate and commit bits of it to the journal there
3671 * is one core, guiding principle: the file's tree must always be consistent on
3672 * disk. We must be able to restart the truncate after a crash.
3674 * The file's tree may be transiently inconsistent in memory (although it
3675 * probably isn't), but whenever we close off and commit a journal transaction,
3676 * the contents of (the filesystem + the journal) must be consistent and
3677 * restartable. It's pretty simple, really: bottom up, right to left (although
3678 * left-to-right works OK too).
3680 * Note that at recovery time, journal replay occurs *before* the restart of
3681 * truncate against the orphan inode list.
3683 * The committed inode has the new, desired i_size (which is the same as
3684 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3685 * that this inode's truncate did not complete and it will again call
3686 * ext4_truncate() to have another go. So there will be instantiated blocks
3687 * to the right of the truncation point in a crashed ext4 filesystem. But
3688 * that's fine - as long as they are linked from the inode, the post-crash
3689 * ext4_truncate() run will find them and release them.
3691 void ext4_truncate(struct inode *inode)
3693 struct ext4_inode_info *ei = EXT4_I(inode);
3694 unsigned int credits;
3696 struct address_space *mapping = inode->i_mapping;
3699 * There is a possibility that we're either freeing the inode
3700 * or it's a completely new inode. In those cases we might not
3701 * have i_mutex locked because it's not necessary.
3703 if (!(inode->i_state & (I_NEW|I_FREEING)))
3704 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3705 trace_ext4_truncate_enter(inode);
3707 if (!ext4_can_truncate(inode))
3710 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3712 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3713 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3715 if (ext4_has_inline_data(inode)) {
3718 ext4_inline_data_truncate(inode, &has_inline);
3723 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3724 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3725 if (ext4_inode_attach_jinode(inode) < 0)
3729 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3730 credits = ext4_writepage_trans_blocks(inode);
3732 credits = ext4_blocks_for_truncate(inode);
3734 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3735 if (IS_ERR(handle)) {
3736 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3740 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3741 ext4_block_truncate_page(handle, mapping, inode->i_size);
3744 * We add the inode to the orphan list, so that if this
3745 * truncate spans multiple transactions, and we crash, we will
3746 * resume the truncate when the filesystem recovers. It also
3747 * marks the inode dirty, to catch the new size.
3749 * Implication: the file must always be in a sane, consistent
3750 * truncatable state while each transaction commits.
3752 if (ext4_orphan_add(handle, inode))
3755 down_write(&EXT4_I(inode)->i_data_sem);
3757 ext4_discard_preallocations(inode);
3759 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3760 ext4_ext_truncate(handle, inode);
3762 ext4_ind_truncate(handle, inode);
3764 up_write(&ei->i_data_sem);
3767 ext4_handle_sync(handle);
3771 * If this was a simple ftruncate() and the file will remain alive,
3772 * then we need to clear up the orphan record which we created above.
3773 * However, if this was a real unlink then we were called by
3774 * ext4_evict_inode(), and we allow that function to clean up the
3775 * orphan info for us.
3778 ext4_orphan_del(handle, inode);
3780 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3781 ext4_mark_inode_dirty(handle, inode);
3782 ext4_journal_stop(handle);
3784 trace_ext4_truncate_exit(inode);
3788 * ext4_get_inode_loc returns with an extra refcount against the inode's
3789 * underlying buffer_head on success. If 'in_mem' is true, we have all
3790 * data in memory that is needed to recreate the on-disk version of this
3793 static int __ext4_get_inode_loc(struct inode *inode,
3794 struct ext4_iloc *iloc, int in_mem)
3796 struct ext4_group_desc *gdp;
3797 struct buffer_head *bh;
3798 struct super_block *sb = inode->i_sb;
3800 int inodes_per_block, inode_offset;
3803 if (!ext4_valid_inum(sb, inode->i_ino))
3806 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3807 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3812 * Figure out the offset within the block group inode table
3814 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3815 inode_offset = ((inode->i_ino - 1) %
3816 EXT4_INODES_PER_GROUP(sb));
3817 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3818 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3820 bh = sb_getblk(sb, block);
3823 if (!buffer_uptodate(bh)) {
3827 * If the buffer has the write error flag, we have failed
3828 * to write out another inode in the same block. In this
3829 * case, we don't have to read the block because we may
3830 * read the old inode data successfully.
3832 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3833 set_buffer_uptodate(bh);
3835 if (buffer_uptodate(bh)) {
3836 /* someone brought it uptodate while we waited */
3842 * If we have all information of the inode in memory and this
3843 * is the only valid inode in the block, we need not read the
3847 struct buffer_head *bitmap_bh;
3850 start = inode_offset & ~(inodes_per_block - 1);
3852 /* Is the inode bitmap in cache? */
3853 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3854 if (unlikely(!bitmap_bh))
3858 * If the inode bitmap isn't in cache then the
3859 * optimisation may end up performing two reads instead
3860 * of one, so skip it.
3862 if (!buffer_uptodate(bitmap_bh)) {
3866 for (i = start; i < start + inodes_per_block; i++) {
3867 if (i == inode_offset)
3869 if (ext4_test_bit(i, bitmap_bh->b_data))
3873 if (i == start + inodes_per_block) {
3874 /* all other inodes are free, so skip I/O */
3875 memset(bh->b_data, 0, bh->b_size);
3876 set_buffer_uptodate(bh);
3884 * If we need to do any I/O, try to pre-readahead extra
3885 * blocks from the inode table.
3887 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3888 ext4_fsblk_t b, end, table;
3890 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3892 table = ext4_inode_table(sb, gdp);
3893 /* s_inode_readahead_blks is always a power of 2 */
3894 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3898 num = EXT4_INODES_PER_GROUP(sb);
3899 if (ext4_has_group_desc_csum(sb))
3900 num -= ext4_itable_unused_count(sb, gdp);
3901 table += num / inodes_per_block;
3905 sb_breadahead(sb, b++);
3909 * There are other valid inodes in the buffer, this inode
3910 * has in-inode xattrs, or we don't have this inode in memory.
3911 * Read the block from disk.
3913 trace_ext4_load_inode(inode);
3915 bh->b_end_io = end_buffer_read_sync;
3916 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3918 if (!buffer_uptodate(bh)) {
3919 EXT4_ERROR_INODE_BLOCK(inode, block,
3920 "unable to read itable block");
3930 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3932 /* We have all inode data except xattrs in memory here. */
3933 return __ext4_get_inode_loc(inode, iloc,
3934 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3937 void ext4_set_inode_flags(struct inode *inode)
3939 unsigned int flags = EXT4_I(inode)->i_flags;
3940 unsigned int new_fl = 0;
3942 if (flags & EXT4_SYNC_FL)
3944 if (flags & EXT4_APPEND_FL)
3946 if (flags & EXT4_IMMUTABLE_FL)
3947 new_fl |= S_IMMUTABLE;
3948 if (flags & EXT4_NOATIME_FL)
3949 new_fl |= S_NOATIME;
3950 if (flags & EXT4_DIRSYNC_FL)
3951 new_fl |= S_DIRSYNC;
3952 if (test_opt(inode->i_sb, DAX))
3954 inode_set_flags(inode, new_fl,
3955 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
3958 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3959 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3961 unsigned int vfs_fl;
3962 unsigned long old_fl, new_fl;
3965 vfs_fl = ei->vfs_inode.i_flags;
3966 old_fl = ei->i_flags;
3967 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3968 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3970 if (vfs_fl & S_SYNC)
3971 new_fl |= EXT4_SYNC_FL;
3972 if (vfs_fl & S_APPEND)
3973 new_fl |= EXT4_APPEND_FL;
3974 if (vfs_fl & S_IMMUTABLE)
3975 new_fl |= EXT4_IMMUTABLE_FL;
3976 if (vfs_fl & S_NOATIME)
3977 new_fl |= EXT4_NOATIME_FL;
3978 if (vfs_fl & S_DIRSYNC)
3979 new_fl |= EXT4_DIRSYNC_FL;
3980 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3983 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3984 struct ext4_inode_info *ei)
3987 struct inode *inode = &(ei->vfs_inode);
3988 struct super_block *sb = inode->i_sb;
3990 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3991 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3992 /* we are using combined 48 bit field */
3993 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3994 le32_to_cpu(raw_inode->i_blocks_lo);
3995 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3996 /* i_blocks represent file system block size */
3997 return i_blocks << (inode->i_blkbits - 9);
4002 return le32_to_cpu(raw_inode->i_blocks_lo);
4006 static inline void ext4_iget_extra_inode(struct inode *inode,
4007 struct ext4_inode *raw_inode,
4008 struct ext4_inode_info *ei)
4010 __le32 *magic = (void *)raw_inode +
4011 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4012 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4013 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4014 ext4_find_inline_data_nolock(inode);
4016 EXT4_I(inode)->i_inline_off = 0;
4019 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4021 struct ext4_iloc iloc;
4022 struct ext4_inode *raw_inode;
4023 struct ext4_inode_info *ei;
4024 struct inode *inode;
4025 journal_t *journal = EXT4_SB(sb)->s_journal;
4031 inode = iget_locked(sb, ino);
4033 return ERR_PTR(-ENOMEM);
4034 if (!(inode->i_state & I_NEW))
4040 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4043 raw_inode = ext4_raw_inode(&iloc);
4045 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4046 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4047 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4048 EXT4_INODE_SIZE(inode->i_sb)) {
4049 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4050 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4051 EXT4_INODE_SIZE(inode->i_sb));
4056 ei->i_extra_isize = 0;
4058 /* Precompute checksum seed for inode metadata */
4059 if (ext4_has_metadata_csum(sb)) {
4060 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4062 __le32 inum = cpu_to_le32(inode->i_ino);
4063 __le32 gen = raw_inode->i_generation;
4064 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4066 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4070 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4071 EXT4_ERROR_INODE(inode, "checksum invalid");
4076 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4077 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4078 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4079 if (!(test_opt(inode->i_sb, NO_UID32))) {
4080 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4081 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4083 i_uid_write(inode, i_uid);
4084 i_gid_write(inode, i_gid);
4085 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4087 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4088 ei->i_inline_off = 0;
4089 ei->i_dir_start_lookup = 0;
4090 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4091 /* We now have enough fields to check if the inode was active or not.
4092 * This is needed because nfsd might try to access dead inodes
4093 * the test is that same one that e2fsck uses
4094 * NeilBrown 1999oct15
4096 if (inode->i_nlink == 0) {
4097 if ((inode->i_mode == 0 ||
4098 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4099 ino != EXT4_BOOT_LOADER_INO) {
4100 /* this inode is deleted */
4104 /* The only unlinked inodes we let through here have
4105 * valid i_mode and are being read by the orphan
4106 * recovery code: that's fine, we're about to complete
4107 * the process of deleting those.
4108 * OR it is the EXT4_BOOT_LOADER_INO which is
4109 * not initialized on a new filesystem. */
4111 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4112 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4113 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4114 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4116 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4117 inode->i_size = ext4_isize(raw_inode);
4118 ei->i_disksize = inode->i_size;
4120 ei->i_reserved_quota = 0;
4122 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4123 ei->i_block_group = iloc.block_group;
4124 ei->i_last_alloc_group = ~0;
4126 * NOTE! The in-memory inode i_data array is in little-endian order
4127 * even on big-endian machines: we do NOT byteswap the block numbers!
4129 for (block = 0; block < EXT4_N_BLOCKS; block++)
4130 ei->i_data[block] = raw_inode->i_block[block];
4131 INIT_LIST_HEAD(&ei->i_orphan);
4134 * Set transaction id's of transactions that have to be committed
4135 * to finish f[data]sync. We set them to currently running transaction
4136 * as we cannot be sure that the inode or some of its metadata isn't
4137 * part of the transaction - the inode could have been reclaimed and
4138 * now it is reread from disk.
4141 transaction_t *transaction;
4144 read_lock(&journal->j_state_lock);
4145 if (journal->j_running_transaction)
4146 transaction = journal->j_running_transaction;
4148 transaction = journal->j_committing_transaction;
4150 tid = transaction->t_tid;
4152 tid = journal->j_commit_sequence;
4153 read_unlock(&journal->j_state_lock);
4154 ei->i_sync_tid = tid;
4155 ei->i_datasync_tid = tid;
4158 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4159 if (ei->i_extra_isize == 0) {
4160 /* The extra space is currently unused. Use it. */
4161 ei->i_extra_isize = sizeof(struct ext4_inode) -
4162 EXT4_GOOD_OLD_INODE_SIZE;
4164 ext4_iget_extra_inode(inode, raw_inode, ei);
4168 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4169 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4170 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4171 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4173 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4174 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4175 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4176 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4178 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4183 if (ei->i_file_acl &&
4184 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4185 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4189 } else if (!ext4_has_inline_data(inode)) {
4190 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4191 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4192 (S_ISLNK(inode->i_mode) &&
4193 !ext4_inode_is_fast_symlink(inode))))
4194 /* Validate extent which is part of inode */
4195 ret = ext4_ext_check_inode(inode);
4196 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4197 (S_ISLNK(inode->i_mode) &&
4198 !ext4_inode_is_fast_symlink(inode))) {
4199 /* Validate block references which are part of inode */
4200 ret = ext4_ind_check_inode(inode);
4206 if (S_ISREG(inode->i_mode)) {
4207 inode->i_op = &ext4_file_inode_operations;
4208 inode->i_fop = &ext4_file_operations;
4209 ext4_set_aops(inode);
4210 } else if (S_ISDIR(inode->i_mode)) {
4211 inode->i_op = &ext4_dir_inode_operations;
4212 inode->i_fop = &ext4_dir_operations;
4213 } else if (S_ISLNK(inode->i_mode)) {
4214 if (ext4_inode_is_fast_symlink(inode) &&
4215 !ext4_encrypted_inode(inode)) {
4216 inode->i_op = &ext4_fast_symlink_inode_operations;
4217 nd_terminate_link(ei->i_data, inode->i_size,
4218 sizeof(ei->i_data) - 1);
4220 inode->i_op = &ext4_symlink_inode_operations;
4221 ext4_set_aops(inode);
4223 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4224 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4225 inode->i_op = &ext4_special_inode_operations;
4226 if (raw_inode->i_block[0])
4227 init_special_inode(inode, inode->i_mode,
4228 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4230 init_special_inode(inode, inode->i_mode,
4231 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4232 } else if (ino == EXT4_BOOT_LOADER_INO) {
4233 make_bad_inode(inode);
4236 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4240 ext4_set_inode_flags(inode);
4241 unlock_new_inode(inode);
4247 return ERR_PTR(ret);
4250 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4252 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4253 return ERR_PTR(-EIO);
4254 return ext4_iget(sb, ino);
4257 static int ext4_inode_blocks_set(handle_t *handle,
4258 struct ext4_inode *raw_inode,
4259 struct ext4_inode_info *ei)
4261 struct inode *inode = &(ei->vfs_inode);
4262 u64 i_blocks = inode->i_blocks;
4263 struct super_block *sb = inode->i_sb;
4265 if (i_blocks <= ~0U) {
4267 * i_blocks can be represented in a 32 bit variable
4268 * as multiple of 512 bytes
4270 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4271 raw_inode->i_blocks_high = 0;
4272 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4275 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4278 if (i_blocks <= 0xffffffffffffULL) {
4280 * i_blocks can be represented in a 48 bit variable
4281 * as multiple of 512 bytes
4283 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4284 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4285 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4287 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4288 /* i_block is stored in file system block size */
4289 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4290 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4291 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4296 struct other_inode {
4297 unsigned long orig_ino;
4298 struct ext4_inode *raw_inode;
4301 static int other_inode_match(struct inode * inode, unsigned long ino,
4304 struct other_inode *oi = (struct other_inode *) data;
4306 if ((inode->i_ino != ino) ||
4307 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4308 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4309 ((inode->i_state & I_DIRTY_TIME) == 0))
4311 spin_lock(&inode->i_lock);
4312 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4313 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4314 (inode->i_state & I_DIRTY_TIME)) {
4315 struct ext4_inode_info *ei = EXT4_I(inode);
4317 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4318 spin_unlock(&inode->i_lock);
4320 spin_lock(&ei->i_raw_lock);
4321 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4322 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4323 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4324 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4325 spin_unlock(&ei->i_raw_lock);
4326 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4329 spin_unlock(&inode->i_lock);
4334 * Opportunistically update the other time fields for other inodes in
4335 * the same inode table block.
4337 static void ext4_update_other_inodes_time(struct super_block *sb,
4338 unsigned long orig_ino, char *buf)
4340 struct other_inode oi;
4342 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4343 int inode_size = EXT4_INODE_SIZE(sb);
4345 oi.orig_ino = orig_ino;
4346 ino = orig_ino & ~(inodes_per_block - 1);
4347 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4348 if (ino == orig_ino)
4350 oi.raw_inode = (struct ext4_inode *) buf;
4351 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4356 * Post the struct inode info into an on-disk inode location in the
4357 * buffer-cache. This gobbles the caller's reference to the
4358 * buffer_head in the inode location struct.
4360 * The caller must have write access to iloc->bh.
4362 static int ext4_do_update_inode(handle_t *handle,
4363 struct inode *inode,
4364 struct ext4_iloc *iloc)
4366 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4367 struct ext4_inode_info *ei = EXT4_I(inode);
4368 struct buffer_head *bh = iloc->bh;
4369 struct super_block *sb = inode->i_sb;
4370 int err = 0, rc, block;
4371 int need_datasync = 0, set_large_file = 0;
4375 spin_lock(&ei->i_raw_lock);
4377 /* For fields not tracked in the in-memory inode,
4378 * initialise them to zero for new inodes. */
4379 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4380 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4382 ext4_get_inode_flags(ei);
4383 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4384 i_uid = i_uid_read(inode);
4385 i_gid = i_gid_read(inode);
4386 if (!(test_opt(inode->i_sb, NO_UID32))) {
4387 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4388 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4390 * Fix up interoperability with old kernels. Otherwise, old inodes get
4391 * re-used with the upper 16 bits of the uid/gid intact
4394 raw_inode->i_uid_high =
4395 cpu_to_le16(high_16_bits(i_uid));
4396 raw_inode->i_gid_high =
4397 cpu_to_le16(high_16_bits(i_gid));
4399 raw_inode->i_uid_high = 0;
4400 raw_inode->i_gid_high = 0;
4403 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4404 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4405 raw_inode->i_uid_high = 0;
4406 raw_inode->i_gid_high = 0;
4408 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4410 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4411 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4412 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4413 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4415 err = ext4_inode_blocks_set(handle, raw_inode, ei);
4417 spin_unlock(&ei->i_raw_lock);
4420 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4421 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4422 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4423 raw_inode->i_file_acl_high =
4424 cpu_to_le16(ei->i_file_acl >> 32);
4425 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4426 if (ei->i_disksize != ext4_isize(raw_inode)) {
4427 ext4_isize_set(raw_inode, ei->i_disksize);
4430 if (ei->i_disksize > 0x7fffffffULL) {
4431 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4432 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4433 EXT4_SB(sb)->s_es->s_rev_level ==
4434 cpu_to_le32(EXT4_GOOD_OLD_REV))
4437 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4438 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4439 if (old_valid_dev(inode->i_rdev)) {
4440 raw_inode->i_block[0] =
4441 cpu_to_le32(old_encode_dev(inode->i_rdev));
4442 raw_inode->i_block[1] = 0;
4444 raw_inode->i_block[0] = 0;
4445 raw_inode->i_block[1] =
4446 cpu_to_le32(new_encode_dev(inode->i_rdev));
4447 raw_inode->i_block[2] = 0;
4449 } else if (!ext4_has_inline_data(inode)) {
4450 for (block = 0; block < EXT4_N_BLOCKS; block++)
4451 raw_inode->i_block[block] = ei->i_data[block];
4454 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4455 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4456 if (ei->i_extra_isize) {
4457 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4458 raw_inode->i_version_hi =
4459 cpu_to_le32(inode->i_version >> 32);
4460 raw_inode->i_extra_isize =
4461 cpu_to_le16(ei->i_extra_isize);
4464 ext4_inode_csum_set(inode, raw_inode, ei);
4465 spin_unlock(&ei->i_raw_lock);
4466 if (inode->i_sb->s_flags & MS_LAZYTIME)
4467 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4470 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4471 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4474 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4475 if (set_large_file) {
4476 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4477 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4480 ext4_update_dynamic_rev(sb);
4481 EXT4_SET_RO_COMPAT_FEATURE(sb,
4482 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4483 ext4_handle_sync(handle);
4484 err = ext4_handle_dirty_super(handle, sb);
4486 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4489 ext4_std_error(inode->i_sb, err);
4494 * ext4_write_inode()
4496 * We are called from a few places:
4498 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4499 * Here, there will be no transaction running. We wait for any running
4500 * transaction to commit.
4502 * - Within flush work (sys_sync(), kupdate and such).
4503 * We wait on commit, if told to.
4505 * - Within iput_final() -> write_inode_now()
4506 * We wait on commit, if told to.
4508 * In all cases it is actually safe for us to return without doing anything,
4509 * because the inode has been copied into a raw inode buffer in
4510 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4513 * Note that we are absolutely dependent upon all inode dirtiers doing the
4514 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4515 * which we are interested.
4517 * It would be a bug for them to not do this. The code:
4519 * mark_inode_dirty(inode)
4521 * inode->i_size = expr;
4523 * is in error because write_inode() could occur while `stuff()' is running,
4524 * and the new i_size will be lost. Plus the inode will no longer be on the
4525 * superblock's dirty inode list.
4527 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4531 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4534 if (EXT4_SB(inode->i_sb)->s_journal) {
4535 if (ext4_journal_current_handle()) {
4536 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4542 * No need to force transaction in WB_SYNC_NONE mode. Also
4543 * ext4_sync_fs() will force the commit after everything is
4546 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4549 err = ext4_force_commit(inode->i_sb);
4551 struct ext4_iloc iloc;
4553 err = __ext4_get_inode_loc(inode, &iloc, 0);
4557 * sync(2) will flush the whole buffer cache. No need to do
4558 * it here separately for each inode.
4560 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4561 sync_dirty_buffer(iloc.bh);
4562 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4563 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4564 "IO error syncing inode");
4573 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4574 * buffers that are attached to a page stradding i_size and are undergoing
4575 * commit. In that case we have to wait for commit to finish and try again.
4577 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4581 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4582 tid_t commit_tid = 0;
4585 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4587 * All buffers in the last page remain valid? Then there's nothing to
4588 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4591 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4594 page = find_lock_page(inode->i_mapping,
4595 inode->i_size >> PAGE_CACHE_SHIFT);
4598 ret = __ext4_journalled_invalidatepage(page, offset,
4599 PAGE_CACHE_SIZE - offset);
4601 page_cache_release(page);
4605 read_lock(&journal->j_state_lock);
4606 if (journal->j_committing_transaction)
4607 commit_tid = journal->j_committing_transaction->t_tid;
4608 read_unlock(&journal->j_state_lock);
4610 jbd2_log_wait_commit(journal, commit_tid);
4617 * Called from notify_change.
4619 * We want to trap VFS attempts to truncate the file as soon as
4620 * possible. In particular, we want to make sure that when the VFS
4621 * shrinks i_size, we put the inode on the orphan list and modify
4622 * i_disksize immediately, so that during the subsequent flushing of
4623 * dirty pages and freeing of disk blocks, we can guarantee that any
4624 * commit will leave the blocks being flushed in an unused state on
4625 * disk. (On recovery, the inode will get truncated and the blocks will
4626 * be freed, so we have a strong guarantee that no future commit will
4627 * leave these blocks visible to the user.)
4629 * Another thing we have to assure is that if we are in ordered mode
4630 * and inode is still attached to the committing transaction, we must
4631 * we start writeout of all the dirty pages which are being truncated.
4632 * This way we are sure that all the data written in the previous
4633 * transaction are already on disk (truncate waits for pages under
4636 * Called with inode->i_mutex down.
4638 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4640 struct inode *inode = d_inode(dentry);
4643 const unsigned int ia_valid = attr->ia_valid;
4645 error = inode_change_ok(inode, attr);
4649 if (is_quota_modification(inode, attr))
4650 dquot_initialize(inode);
4651 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4652 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4655 /* (user+group)*(old+new) structure, inode write (sb,
4656 * inode block, ? - but truncate inode update has it) */
4657 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4658 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4659 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4660 if (IS_ERR(handle)) {
4661 error = PTR_ERR(handle);
4664 error = dquot_transfer(inode, attr);
4666 ext4_journal_stop(handle);
4669 /* Update corresponding info in inode so that everything is in
4670 * one transaction */
4671 if (attr->ia_valid & ATTR_UID)
4672 inode->i_uid = attr->ia_uid;
4673 if (attr->ia_valid & ATTR_GID)
4674 inode->i_gid = attr->ia_gid;
4675 error = ext4_mark_inode_dirty(handle, inode);
4676 ext4_journal_stop(handle);
4679 if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
4682 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4683 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4685 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4689 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4690 inode_inc_iversion(inode);
4692 if (S_ISREG(inode->i_mode) &&
4693 (attr->ia_size < inode->i_size)) {
4694 if (ext4_should_order_data(inode)) {
4695 error = ext4_begin_ordered_truncate(inode,
4700 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4701 if (IS_ERR(handle)) {
4702 error = PTR_ERR(handle);
4705 if (ext4_handle_valid(handle)) {
4706 error = ext4_orphan_add(handle, inode);
4709 down_write(&EXT4_I(inode)->i_data_sem);
4710 EXT4_I(inode)->i_disksize = attr->ia_size;
4711 rc = ext4_mark_inode_dirty(handle, inode);
4715 * We have to update i_size under i_data_sem together
4716 * with i_disksize to avoid races with writeback code
4717 * running ext4_wb_update_i_disksize().
4720 i_size_write(inode, attr->ia_size);
4721 up_write(&EXT4_I(inode)->i_data_sem);
4722 ext4_journal_stop(handle);
4724 ext4_orphan_del(NULL, inode);
4728 loff_t oldsize = inode->i_size;
4730 i_size_write(inode, attr->ia_size);
4731 pagecache_isize_extended(inode, oldsize, inode->i_size);
4735 * Blocks are going to be removed from the inode. Wait
4736 * for dio in flight. Temporarily disable
4737 * dioread_nolock to prevent livelock.
4740 if (!ext4_should_journal_data(inode)) {
4741 ext4_inode_block_unlocked_dio(inode);
4742 inode_dio_wait(inode);
4743 ext4_inode_resume_unlocked_dio(inode);
4745 ext4_wait_for_tail_page_commit(inode);
4748 * Truncate pagecache after we've waited for commit
4749 * in data=journal mode to make pages freeable.
4751 truncate_pagecache(inode, inode->i_size);
4754 * We want to call ext4_truncate() even if attr->ia_size ==
4755 * inode->i_size for cases like truncation of fallocated space
4757 if (attr->ia_valid & ATTR_SIZE)
4758 ext4_truncate(inode);
4761 setattr_copy(inode, attr);
4762 mark_inode_dirty(inode);
4766 * If the call to ext4_truncate failed to get a transaction handle at
4767 * all, we need to clean up the in-core orphan list manually.
4769 if (orphan && inode->i_nlink)
4770 ext4_orphan_del(NULL, inode);
4772 if (!rc && (ia_valid & ATTR_MODE))
4773 rc = posix_acl_chmod(inode, inode->i_mode);
4776 ext4_std_error(inode->i_sb, error);
4782 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4785 struct inode *inode;
4786 unsigned long long delalloc_blocks;
4788 inode = d_inode(dentry);
4789 generic_fillattr(inode, stat);
4792 * If there is inline data in the inode, the inode will normally not
4793 * have data blocks allocated (it may have an external xattr block).
4794 * Report at least one sector for such files, so tools like tar, rsync,
4795 * others doen't incorrectly think the file is completely sparse.
4797 if (unlikely(ext4_has_inline_data(inode)))
4798 stat->blocks += (stat->size + 511) >> 9;
4801 * We can't update i_blocks if the block allocation is delayed
4802 * otherwise in the case of system crash before the real block
4803 * allocation is done, we will have i_blocks inconsistent with
4804 * on-disk file blocks.
4805 * We always keep i_blocks updated together with real
4806 * allocation. But to not confuse with user, stat
4807 * will return the blocks that include the delayed allocation
4808 * blocks for this file.
4810 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4811 EXT4_I(inode)->i_reserved_data_blocks);
4812 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
4816 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4819 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4820 return ext4_ind_trans_blocks(inode, lblocks);
4821 return ext4_ext_index_trans_blocks(inode, pextents);
4825 * Account for index blocks, block groups bitmaps and block group
4826 * descriptor blocks if modify datablocks and index blocks
4827 * worse case, the indexs blocks spread over different block groups
4829 * If datablocks are discontiguous, they are possible to spread over
4830 * different block groups too. If they are contiguous, with flexbg,
4831 * they could still across block group boundary.
4833 * Also account for superblock, inode, quota and xattr blocks
4835 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4838 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4844 * How many index blocks need to touch to map @lblocks logical blocks
4845 * to @pextents physical extents?
4847 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4852 * Now let's see how many group bitmaps and group descriptors need
4855 groups = idxblocks + pextents;
4857 if (groups > ngroups)
4859 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4860 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4862 /* bitmaps and block group descriptor blocks */
4863 ret += groups + gdpblocks;
4865 /* Blocks for super block, inode, quota and xattr blocks */
4866 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4872 * Calculate the total number of credits to reserve to fit
4873 * the modification of a single pages into a single transaction,
4874 * which may include multiple chunks of block allocations.
4876 * This could be called via ext4_write_begin()
4878 * We need to consider the worse case, when
4879 * one new block per extent.
4881 int ext4_writepage_trans_blocks(struct inode *inode)
4883 int bpp = ext4_journal_blocks_per_page(inode);
4886 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4888 /* Account for data blocks for journalled mode */
4889 if (ext4_should_journal_data(inode))
4895 * Calculate the journal credits for a chunk of data modification.
4897 * This is called from DIO, fallocate or whoever calling
4898 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4900 * journal buffers for data blocks are not included here, as DIO
4901 * and fallocate do no need to journal data buffers.
4903 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4905 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4909 * The caller must have previously called ext4_reserve_inode_write().
4910 * Give this, we know that the caller already has write access to iloc->bh.
4912 int ext4_mark_iloc_dirty(handle_t *handle,
4913 struct inode *inode, struct ext4_iloc *iloc)
4917 if (IS_I_VERSION(inode))
4918 inode_inc_iversion(inode);
4920 /* the do_update_inode consumes one bh->b_count */
4923 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4924 err = ext4_do_update_inode(handle, inode, iloc);
4930 * On success, We end up with an outstanding reference count against
4931 * iloc->bh. This _must_ be cleaned up later.
4935 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4936 struct ext4_iloc *iloc)
4940 err = ext4_get_inode_loc(inode, iloc);
4942 BUFFER_TRACE(iloc->bh, "get_write_access");
4943 err = ext4_journal_get_write_access(handle, iloc->bh);
4949 ext4_std_error(inode->i_sb, err);
4954 * Expand an inode by new_extra_isize bytes.
4955 * Returns 0 on success or negative error number on failure.
4957 static int ext4_expand_extra_isize(struct inode *inode,
4958 unsigned int new_extra_isize,
4959 struct ext4_iloc iloc,
4962 struct ext4_inode *raw_inode;
4963 struct ext4_xattr_ibody_header *header;
4965 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4968 raw_inode = ext4_raw_inode(&iloc);
4970 header = IHDR(inode, raw_inode);
4972 /* No extended attributes present */
4973 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4974 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4975 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4977 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4981 /* try to expand with EAs present */
4982 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4987 * What we do here is to mark the in-core inode as clean with respect to inode
4988 * dirtiness (it may still be data-dirty).
4989 * This means that the in-core inode may be reaped by prune_icache
4990 * without having to perform any I/O. This is a very good thing,
4991 * because *any* task may call prune_icache - even ones which
4992 * have a transaction open against a different journal.
4994 * Is this cheating? Not really. Sure, we haven't written the
4995 * inode out, but prune_icache isn't a user-visible syncing function.
4996 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4997 * we start and wait on commits.
4999 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5001 struct ext4_iloc iloc;
5002 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5003 static unsigned int mnt_count;
5007 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5008 err = ext4_reserve_inode_write(handle, inode, &iloc);
5009 if (ext4_handle_valid(handle) &&
5010 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5011 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5013 * We need extra buffer credits since we may write into EA block
5014 * with this same handle. If journal_extend fails, then it will
5015 * only result in a minor loss of functionality for that inode.
5016 * If this is felt to be critical, then e2fsck should be run to
5017 * force a large enough s_min_extra_isize.
5019 if ((jbd2_journal_extend(handle,
5020 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5021 ret = ext4_expand_extra_isize(inode,
5022 sbi->s_want_extra_isize,
5025 ext4_set_inode_state(inode,
5026 EXT4_STATE_NO_EXPAND);
5028 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5029 ext4_warning(inode->i_sb,
5030 "Unable to expand inode %lu. Delete"
5031 " some EAs or run e2fsck.",
5034 le16_to_cpu(sbi->s_es->s_mnt_count);
5040 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5045 * ext4_dirty_inode() is called from __mark_inode_dirty()
5047 * We're really interested in the case where a file is being extended.
5048 * i_size has been changed by generic_commit_write() and we thus need
5049 * to include the updated inode in the current transaction.
5051 * Also, dquot_alloc_block() will always dirty the inode when blocks
5052 * are allocated to the file.
5054 * If the inode is marked synchronous, we don't honour that here - doing
5055 * so would cause a commit on atime updates, which we don't bother doing.
5056 * We handle synchronous inodes at the highest possible level.
5058 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5059 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5060 * to copy into the on-disk inode structure are the timestamp files.
5062 void ext4_dirty_inode(struct inode *inode, int flags)
5066 if (flags == I_DIRTY_TIME)
5068 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5072 ext4_mark_inode_dirty(handle, inode);
5074 ext4_journal_stop(handle);
5081 * Bind an inode's backing buffer_head into this transaction, to prevent
5082 * it from being flushed to disk early. Unlike
5083 * ext4_reserve_inode_write, this leaves behind no bh reference and
5084 * returns no iloc structure, so the caller needs to repeat the iloc
5085 * lookup to mark the inode dirty later.
5087 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5089 struct ext4_iloc iloc;
5093 err = ext4_get_inode_loc(inode, &iloc);
5095 BUFFER_TRACE(iloc.bh, "get_write_access");
5096 err = jbd2_journal_get_write_access(handle, iloc.bh);
5098 err = ext4_handle_dirty_metadata(handle,
5104 ext4_std_error(inode->i_sb, err);
5109 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5116 * We have to be very careful here: changing a data block's
5117 * journaling status dynamically is dangerous. If we write a
5118 * data block to the journal, change the status and then delete
5119 * that block, we risk forgetting to revoke the old log record
5120 * from the journal and so a subsequent replay can corrupt data.
5121 * So, first we make sure that the journal is empty and that
5122 * nobody is changing anything.
5125 journal = EXT4_JOURNAL(inode);
5128 if (is_journal_aborted(journal))
5130 /* We have to allocate physical blocks for delalloc blocks
5131 * before flushing journal. otherwise delalloc blocks can not
5132 * be allocated any more. even more truncate on delalloc blocks
5133 * could trigger BUG by flushing delalloc blocks in journal.
5134 * There is no delalloc block in non-journal data mode.
5136 if (val && test_opt(inode->i_sb, DELALLOC)) {
5137 err = ext4_alloc_da_blocks(inode);
5142 /* Wait for all existing dio workers */
5143 ext4_inode_block_unlocked_dio(inode);
5144 inode_dio_wait(inode);
5146 jbd2_journal_lock_updates(journal);
5149 * OK, there are no updates running now, and all cached data is
5150 * synced to disk. We are now in a completely consistent state
5151 * which doesn't have anything in the journal, and we know that
5152 * no filesystem updates are running, so it is safe to modify
5153 * the inode's in-core data-journaling state flag now.
5157 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5159 err = jbd2_journal_flush(journal);
5161 jbd2_journal_unlock_updates(journal);
5162 ext4_inode_resume_unlocked_dio(inode);
5165 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5167 ext4_set_aops(inode);
5169 jbd2_journal_unlock_updates(journal);
5170 ext4_inode_resume_unlocked_dio(inode);
5172 /* Finally we can mark the inode as dirty. */
5174 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5176 return PTR_ERR(handle);
5178 err = ext4_mark_inode_dirty(handle, inode);
5179 ext4_handle_sync(handle);
5180 ext4_journal_stop(handle);
5181 ext4_std_error(inode->i_sb, err);
5186 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5188 return !buffer_mapped(bh);
5191 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5193 struct page *page = vmf->page;
5197 struct file *file = vma->vm_file;
5198 struct inode *inode = file_inode(file);
5199 struct address_space *mapping = inode->i_mapping;
5201 get_block_t *get_block;
5204 sb_start_pagefault(inode->i_sb);
5205 file_update_time(vma->vm_file);
5206 /* Delalloc case is easy... */
5207 if (test_opt(inode->i_sb, DELALLOC) &&
5208 !ext4_should_journal_data(inode) &&
5209 !ext4_nonda_switch(inode->i_sb)) {
5211 ret = __block_page_mkwrite(vma, vmf,
5212 ext4_da_get_block_prep);
5213 } while (ret == -ENOSPC &&
5214 ext4_should_retry_alloc(inode->i_sb, &retries));
5219 size = i_size_read(inode);
5220 /* Page got truncated from under us? */
5221 if (page->mapping != mapping || page_offset(page) > size) {
5223 ret = VM_FAULT_NOPAGE;
5227 if (page->index == size >> PAGE_CACHE_SHIFT)
5228 len = size & ~PAGE_CACHE_MASK;
5230 len = PAGE_CACHE_SIZE;
5232 * Return if we have all the buffers mapped. This avoids the need to do
5233 * journal_start/journal_stop which can block and take a long time
5235 if (page_has_buffers(page)) {
5236 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5238 ext4_bh_unmapped)) {
5239 /* Wait so that we don't change page under IO */
5240 wait_for_stable_page(page);
5241 ret = VM_FAULT_LOCKED;
5246 /* OK, we need to fill the hole... */
5247 if (ext4_should_dioread_nolock(inode))
5248 get_block = ext4_get_block_write;
5250 get_block = ext4_get_block;
5252 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5253 ext4_writepage_trans_blocks(inode));
5254 if (IS_ERR(handle)) {
5255 ret = VM_FAULT_SIGBUS;
5258 ret = __block_page_mkwrite(vma, vmf, get_block);
5259 if (!ret && ext4_should_journal_data(inode)) {
5260 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5261 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5263 ret = VM_FAULT_SIGBUS;
5264 ext4_journal_stop(handle);
5267 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5269 ext4_journal_stop(handle);
5270 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5273 ret = block_page_mkwrite_return(ret);
5275 sb_end_pagefault(inode->i_sb);