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
21 #include <linux/module.h>
23 #include <linux/time.h>
24 #include <linux/jbd2.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/quotaops.h>
28 #include <linux/string.h>
29 #include <linux/buffer_head.h>
30 #include <linux/writeback.h>
31 #include <linux/pagevec.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/uio.h>
35 #include <linux/bio.h>
36 #include <linux/workqueue.h>
37 #include <linux/kernel.h>
38 #include <linux/printk.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
42 #include "ext4_jbd2.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static inline int ext4_begin_ordered_truncate(struct inode *inode,
54 trace_ext4_begin_ordered_truncate(inode, new_size);
56 * If jinode is zero, then we never opened the file for
57 * writing, so there's no need to call
58 * jbd2_journal_begin_ordered_truncate() since there's no
59 * outstanding writes we need to flush.
61 if (!EXT4_I(inode)->jinode)
63 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
64 EXT4_I(inode)->jinode,
68 static void ext4_invalidatepage(struct page *page, unsigned long offset);
69 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
70 struct buffer_head *bh_result, int create);
71 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
72 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
73 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
74 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
77 * Test whether an inode is a fast symlink.
79 static int ext4_inode_is_fast_symlink(struct inode *inode)
81 int ea_blocks = EXT4_I(inode)->i_file_acl ?
82 (inode->i_sb->s_blocksize >> 9) : 0;
84 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
88 * Restart the transaction associated with *handle. This does a commit,
89 * so before we call here everything must be consistently dirtied against
92 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
98 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
99 * moment, get_block can be called only for blocks inside i_size since
100 * page cache has been already dropped and writes are blocked by
101 * i_mutex. So we can safely drop the i_data_sem here.
103 BUG_ON(EXT4_JOURNAL(inode) == NULL);
104 jbd_debug(2, "restarting handle %p\n", handle);
105 up_write(&EXT4_I(inode)->i_data_sem);
106 ret = ext4_journal_restart(handle, nblocks);
107 down_write(&EXT4_I(inode)->i_data_sem);
108 ext4_discard_preallocations(inode);
114 * Called at the last iput() if i_nlink is zero.
116 void ext4_evict_inode(struct inode *inode)
121 trace_ext4_evict_inode(inode);
123 ext4_ioend_wait(inode);
125 if (inode->i_nlink) {
127 * When journalling data dirty buffers are tracked only in the
128 * journal. So although mm thinks everything is clean and
129 * ready for reaping the inode might still have some pages to
130 * write in the running transaction or waiting to be
131 * checkpointed. Thus calling jbd2_journal_invalidatepage()
132 * (via truncate_inode_pages()) to discard these buffers can
133 * cause data loss. Also even if we did not discard these
134 * buffers, we would have no way to find them after the inode
135 * is reaped and thus user could see stale data if he tries to
136 * read them before the transaction is checkpointed. So be
137 * careful and force everything to disk here... We use
138 * ei->i_datasync_tid to store the newest transaction
139 * containing inode's data.
141 * Note that directories do not have this problem because they
142 * don't use page cache.
144 if (ext4_should_journal_data(inode) &&
145 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
146 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
147 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
149 jbd2_log_start_commit(journal, commit_tid);
150 jbd2_log_wait_commit(journal, commit_tid);
151 filemap_write_and_wait(&inode->i_data);
153 truncate_inode_pages(&inode->i_data, 0);
157 if (!is_bad_inode(inode))
158 dquot_initialize(inode);
160 if (ext4_should_order_data(inode))
161 ext4_begin_ordered_truncate(inode, 0);
162 truncate_inode_pages(&inode->i_data, 0);
164 if (is_bad_inode(inode))
167 handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
168 if (IS_ERR(handle)) {
169 ext4_std_error(inode->i_sb, PTR_ERR(handle));
171 * If we're going to skip the normal cleanup, we still need to
172 * make sure that the in-core orphan linked list is properly
175 ext4_orphan_del(NULL, inode);
180 ext4_handle_sync(handle);
182 err = ext4_mark_inode_dirty(handle, inode);
184 ext4_warning(inode->i_sb,
185 "couldn't mark inode dirty (err %d)", err);
189 ext4_truncate(inode);
192 * ext4_ext_truncate() doesn't reserve any slop when it
193 * restarts journal transactions; therefore there may not be
194 * enough credits left in the handle to remove the inode from
195 * the orphan list and set the dtime field.
197 if (!ext4_handle_has_enough_credits(handle, 3)) {
198 err = ext4_journal_extend(handle, 3);
200 err = ext4_journal_restart(handle, 3);
202 ext4_warning(inode->i_sb,
203 "couldn't extend journal (err %d)", err);
205 ext4_journal_stop(handle);
206 ext4_orphan_del(NULL, inode);
212 * Kill off the orphan record which ext4_truncate created.
213 * AKPM: I think this can be inside the above `if'.
214 * Note that ext4_orphan_del() has to be able to cope with the
215 * deletion of a non-existent orphan - this is because we don't
216 * know if ext4_truncate() actually created an orphan record.
217 * (Well, we could do this if we need to, but heck - it works)
219 ext4_orphan_del(handle, inode);
220 EXT4_I(inode)->i_dtime = get_seconds();
223 * One subtle ordering requirement: if anything has gone wrong
224 * (transaction abort, IO errors, whatever), then we can still
225 * do these next steps (the fs will already have been marked as
226 * having errors), but we can't free the inode if the mark_dirty
229 if (ext4_mark_inode_dirty(handle, inode))
230 /* If that failed, just do the required in-core inode clear. */
231 ext4_clear_inode(inode);
233 ext4_free_inode(handle, inode);
234 ext4_journal_stop(handle);
237 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
241 qsize_t *ext4_get_reserved_space(struct inode *inode)
243 return &EXT4_I(inode)->i_reserved_quota;
248 * Calculate the number of metadata blocks need to reserve
249 * to allocate a block located at @lblock
251 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
253 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
254 return ext4_ext_calc_metadata_amount(inode, lblock);
256 return ext4_ind_calc_metadata_amount(inode, lblock);
260 * Called with i_data_sem down, which is important since we can call
261 * ext4_discard_preallocations() from here.
263 void ext4_da_update_reserve_space(struct inode *inode,
264 int used, int quota_claim)
266 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
267 struct ext4_inode_info *ei = EXT4_I(inode);
269 spin_lock(&ei->i_block_reservation_lock);
270 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
271 if (unlikely(used > ei->i_reserved_data_blocks)) {
272 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
273 "with only %d reserved data blocks\n",
274 __func__, inode->i_ino, used,
275 ei->i_reserved_data_blocks);
277 used = ei->i_reserved_data_blocks;
280 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
281 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, allocated %d "
282 "with only %d reserved metadata blocks\n", __func__,
283 inode->i_ino, ei->i_allocated_meta_blocks,
284 ei->i_reserved_meta_blocks);
286 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
289 /* Update per-inode reservations */
290 ei->i_reserved_data_blocks -= used;
291 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
292 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
293 used + ei->i_allocated_meta_blocks);
294 ei->i_allocated_meta_blocks = 0;
296 if (ei->i_reserved_data_blocks == 0) {
298 * We can release all of the reserved metadata blocks
299 * only when we have written all of the delayed
302 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
303 ei->i_reserved_meta_blocks);
304 ei->i_reserved_meta_blocks = 0;
305 ei->i_da_metadata_calc_len = 0;
307 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
309 /* Update quota subsystem for data blocks */
311 dquot_claim_block(inode, EXT4_C2B(sbi, used));
314 * We did fallocate with an offset that is already delayed
315 * allocated. So on delayed allocated writeback we should
316 * not re-claim the quota for fallocated blocks.
318 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
322 * If we have done all the pending block allocations and if
323 * there aren't any writers on the inode, we can discard the
324 * inode's preallocations.
326 if ((ei->i_reserved_data_blocks == 0) &&
327 (atomic_read(&inode->i_writecount) == 0))
328 ext4_discard_preallocations(inode);
331 static int __check_block_validity(struct inode *inode, const char *func,
333 struct ext4_map_blocks *map)
335 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
337 ext4_error_inode(inode, func, line, map->m_pblk,
338 "lblock %lu mapped to illegal pblock "
339 "(length %d)", (unsigned long) map->m_lblk,
346 #define check_block_validity(inode, map) \
347 __check_block_validity((inode), __func__, __LINE__, (map))
350 * Return the number of contiguous dirty pages in a given inode
351 * starting at page frame idx.
353 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
354 unsigned int max_pages)
356 struct address_space *mapping = inode->i_mapping;
360 int i, nr_pages, done = 0;
364 pagevec_init(&pvec, 0);
367 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
369 (pgoff_t)PAGEVEC_SIZE);
372 for (i = 0; i < nr_pages; i++) {
373 struct page *page = pvec.pages[i];
374 struct buffer_head *bh, *head;
377 if (unlikely(page->mapping != mapping) ||
379 PageWriteback(page) ||
380 page->index != idx) {
385 if (page_has_buffers(page)) {
386 bh = head = page_buffers(page);
388 if (!buffer_delay(bh) &&
389 !buffer_unwritten(bh))
391 bh = bh->b_this_page;
392 } while (!done && (bh != head));
399 if (num >= max_pages) {
404 pagevec_release(&pvec);
410 * Sets the BH_Da_Mapped bit on the buffer heads corresponding to the given map.
412 static void set_buffers_da_mapped(struct inode *inode,
413 struct ext4_map_blocks *map)
415 struct address_space *mapping = inode->i_mapping;
420 index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
421 end = (map->m_lblk + map->m_len - 1) >>
422 (PAGE_CACHE_SHIFT - inode->i_blkbits);
424 pagevec_init(&pvec, 0);
425 while (index <= end) {
426 nr_pages = pagevec_lookup(&pvec, mapping, index,
428 (pgoff_t)PAGEVEC_SIZE));
431 for (i = 0; i < nr_pages; i++) {
432 struct page *page = pvec.pages[i];
433 struct buffer_head *bh, *head;
435 if (unlikely(page->mapping != mapping) ||
439 if (page_has_buffers(page)) {
440 bh = head = page_buffers(page);
442 set_buffer_da_mapped(bh);
443 bh = bh->b_this_page;
444 } while (bh != head);
448 pagevec_release(&pvec);
453 * The ext4_map_blocks() function tries to look up the requested blocks,
454 * and returns if the blocks are already mapped.
456 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
457 * and store the allocated blocks in the result buffer head and mark it
460 * If file type is extents based, it will call ext4_ext_map_blocks(),
461 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
464 * On success, it returns the number of blocks being mapped or allocate.
465 * if create==0 and the blocks are pre-allocated and uninitialized block,
466 * the result buffer head is unmapped. If the create ==1, it will make sure
467 * the buffer head is mapped.
469 * It returns 0 if plain look up failed (blocks have not been allocated), in
470 * that case, buffer head is unmapped
472 * It returns the error in case of allocation failure.
474 int ext4_map_blocks(handle_t *handle, struct inode *inode,
475 struct ext4_map_blocks *map, int flags)
480 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
481 "logical block %lu\n", inode->i_ino, flags, map->m_len,
482 (unsigned long) map->m_lblk);
484 * Try to see if we can get the block without requesting a new
487 down_read((&EXT4_I(inode)->i_data_sem));
488 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
489 retval = ext4_ext_map_blocks(handle, inode, map, flags &
490 EXT4_GET_BLOCKS_KEEP_SIZE);
492 retval = ext4_ind_map_blocks(handle, inode, map, flags &
493 EXT4_GET_BLOCKS_KEEP_SIZE);
495 up_read((&EXT4_I(inode)->i_data_sem));
497 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
498 int ret = check_block_validity(inode, map);
503 /* If it is only a block(s) look up */
504 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
508 * Returns if the blocks have already allocated
510 * Note that if blocks have been preallocated
511 * ext4_ext_get_block() returns the create = 0
512 * with buffer head unmapped.
514 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
518 * When we call get_blocks without the create flag, the
519 * BH_Unwritten flag could have gotten set if the blocks
520 * requested were part of a uninitialized extent. We need to
521 * clear this flag now that we are committed to convert all or
522 * part of the uninitialized extent to be an initialized
523 * extent. This is because we need to avoid the combination
524 * of BH_Unwritten and BH_Mapped flags being simultaneously
525 * set on the buffer_head.
527 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
530 * New blocks allocate and/or writing to uninitialized extent
531 * will possibly result in updating i_data, so we take
532 * the write lock of i_data_sem, and call get_blocks()
533 * with create == 1 flag.
535 down_write((&EXT4_I(inode)->i_data_sem));
538 * if the caller is from delayed allocation writeout path
539 * we have already reserved fs blocks for allocation
540 * let the underlying get_block() function know to
541 * avoid double accounting
543 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
544 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
546 * We need to check for EXT4 here because migrate
547 * could have changed the inode type in between
549 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
550 retval = ext4_ext_map_blocks(handle, inode, map, flags);
552 retval = ext4_ind_map_blocks(handle, inode, map, flags);
554 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
556 * We allocated new blocks which will result in
557 * i_data's format changing. Force the migrate
558 * to fail by clearing migrate flags
560 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
564 * Update reserved blocks/metadata blocks after successful
565 * block allocation which had been deferred till now. We don't
566 * support fallocate for non extent files. So we can update
567 * reserve space here.
570 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
571 ext4_da_update_reserve_space(inode, retval, 1);
573 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
574 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
576 /* If we have successfully mapped the delayed allocated blocks,
577 * set the BH_Da_Mapped bit on them. Its important to do this
578 * under the protection of i_data_sem.
580 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
581 set_buffers_da_mapped(inode, map);
584 up_write((&EXT4_I(inode)->i_data_sem));
585 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
586 int ret = check_block_validity(inode, map);
593 /* Maximum number of blocks we map for direct IO at once. */
594 #define DIO_MAX_BLOCKS 4096
596 static int _ext4_get_block(struct inode *inode, sector_t iblock,
597 struct buffer_head *bh, int flags)
599 handle_t *handle = ext4_journal_current_handle();
600 struct ext4_map_blocks map;
601 int ret = 0, started = 0;
605 map.m_len = bh->b_size >> inode->i_blkbits;
607 if (flags && !handle) {
608 /* Direct IO write... */
609 if (map.m_len > DIO_MAX_BLOCKS)
610 map.m_len = DIO_MAX_BLOCKS;
611 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
612 handle = ext4_journal_start(inode, dio_credits);
613 if (IS_ERR(handle)) {
614 ret = PTR_ERR(handle);
620 ret = ext4_map_blocks(handle, inode, &map, flags);
622 map_bh(bh, inode->i_sb, map.m_pblk);
623 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
624 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
628 ext4_journal_stop(handle);
632 int ext4_get_block(struct inode *inode, sector_t iblock,
633 struct buffer_head *bh, int create)
635 return _ext4_get_block(inode, iblock, bh,
636 create ? EXT4_GET_BLOCKS_CREATE : 0);
640 * `handle' can be NULL if create is zero
642 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
643 ext4_lblk_t block, int create, int *errp)
645 struct ext4_map_blocks map;
646 struct buffer_head *bh;
649 J_ASSERT(handle != NULL || create == 0);
653 err = ext4_map_blocks(handle, inode, &map,
654 create ? EXT4_GET_BLOCKS_CREATE : 0);
662 bh = sb_getblk(inode->i_sb, map.m_pblk);
667 if (map.m_flags & EXT4_MAP_NEW) {
668 J_ASSERT(create != 0);
669 J_ASSERT(handle != NULL);
672 * Now that we do not always journal data, we should
673 * keep in mind whether this should always journal the
674 * new buffer as metadata. For now, regular file
675 * writes use ext4_get_block instead, so it's not a
679 BUFFER_TRACE(bh, "call get_create_access");
680 fatal = ext4_journal_get_create_access(handle, bh);
681 if (!fatal && !buffer_uptodate(bh)) {
682 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
683 set_buffer_uptodate(bh);
686 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
687 err = ext4_handle_dirty_metadata(handle, inode, bh);
691 BUFFER_TRACE(bh, "not a new buffer");
701 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
702 ext4_lblk_t block, int create, int *err)
704 struct buffer_head *bh;
706 bh = ext4_getblk(handle, inode, block, create, err);
709 if (buffer_uptodate(bh))
711 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
713 if (buffer_uptodate(bh))
720 static int walk_page_buffers(handle_t *handle,
721 struct buffer_head *head,
725 int (*fn)(handle_t *handle,
726 struct buffer_head *bh))
728 struct buffer_head *bh;
729 unsigned block_start, block_end;
730 unsigned blocksize = head->b_size;
732 struct buffer_head *next;
734 for (bh = head, block_start = 0;
735 ret == 0 && (bh != head || !block_start);
736 block_start = block_end, bh = next) {
737 next = bh->b_this_page;
738 block_end = block_start + blocksize;
739 if (block_end <= from || block_start >= to) {
740 if (partial && !buffer_uptodate(bh))
744 err = (*fn)(handle, bh);
752 * To preserve ordering, it is essential that the hole instantiation and
753 * the data write be encapsulated in a single transaction. We cannot
754 * close off a transaction and start a new one between the ext4_get_block()
755 * and the commit_write(). So doing the jbd2_journal_start at the start of
756 * prepare_write() is the right place.
758 * Also, this function can nest inside ext4_writepage() ->
759 * block_write_full_page(). In that case, we *know* that ext4_writepage()
760 * has generated enough buffer credits to do the whole page. So we won't
761 * block on the journal in that case, which is good, because the caller may
764 * By accident, ext4 can be reentered when a transaction is open via
765 * quota file writes. If we were to commit the transaction while thus
766 * reentered, there can be a deadlock - we would be holding a quota
767 * lock, and the commit would never complete if another thread had a
768 * transaction open and was blocking on the quota lock - a ranking
771 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
772 * will _not_ run commit under these circumstances because handle->h_ref
773 * is elevated. We'll still have enough credits for the tiny quotafile
776 static int do_journal_get_write_access(handle_t *handle,
777 struct buffer_head *bh)
779 int dirty = buffer_dirty(bh);
782 if (!buffer_mapped(bh) || buffer_freed(bh))
785 * __block_write_begin() could have dirtied some buffers. Clean
786 * the dirty bit as jbd2_journal_get_write_access() could complain
787 * otherwise about fs integrity issues. Setting of the dirty bit
788 * by __block_write_begin() isn't a real problem here as we clear
789 * the bit before releasing a page lock and thus writeback cannot
790 * ever write the buffer.
793 clear_buffer_dirty(bh);
794 ret = ext4_journal_get_write_access(handle, bh);
796 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
800 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
801 struct buffer_head *bh_result, int create);
802 static int ext4_write_begin(struct file *file, struct address_space *mapping,
803 loff_t pos, unsigned len, unsigned flags,
804 struct page **pagep, void **fsdata)
806 struct inode *inode = mapping->host;
807 int ret, needed_blocks;
814 trace_ext4_write_begin(inode, pos, len, flags);
816 * Reserve one block more for addition to orphan list in case
817 * we allocate blocks but write fails for some reason
819 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
820 index = pos >> PAGE_CACHE_SHIFT;
821 from = pos & (PAGE_CACHE_SIZE - 1);
825 handle = ext4_journal_start(inode, needed_blocks);
826 if (IS_ERR(handle)) {
827 ret = PTR_ERR(handle);
831 /* We cannot recurse into the filesystem as the transaction is already
833 flags |= AOP_FLAG_NOFS;
835 page = grab_cache_page_write_begin(mapping, index, flags);
837 ext4_journal_stop(handle);
843 if (ext4_should_dioread_nolock(inode))
844 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
846 ret = __block_write_begin(page, pos, len, ext4_get_block);
848 if (!ret && ext4_should_journal_data(inode)) {
849 ret = walk_page_buffers(handle, page_buffers(page),
850 from, to, NULL, do_journal_get_write_access);
855 page_cache_release(page);
857 * __block_write_begin may have instantiated a few blocks
858 * outside i_size. Trim these off again. Don't need
859 * i_size_read because we hold i_mutex.
861 * Add inode to orphan list in case we crash before
864 if (pos + len > inode->i_size && ext4_can_truncate(inode))
865 ext4_orphan_add(handle, inode);
867 ext4_journal_stop(handle);
868 if (pos + len > inode->i_size) {
869 ext4_truncate_failed_write(inode);
871 * If truncate failed early the inode might
872 * still be on the orphan list; we need to
873 * make sure the inode is removed from the
874 * orphan list in that case.
877 ext4_orphan_del(NULL, inode);
881 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
887 /* For write_end() in data=journal mode */
888 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
890 if (!buffer_mapped(bh) || buffer_freed(bh))
892 set_buffer_uptodate(bh);
893 return ext4_handle_dirty_metadata(handle, NULL, bh);
896 static int ext4_generic_write_end(struct file *file,
897 struct address_space *mapping,
898 loff_t pos, unsigned len, unsigned copied,
899 struct page *page, void *fsdata)
901 int i_size_changed = 0;
902 struct inode *inode = mapping->host;
903 handle_t *handle = ext4_journal_current_handle();
905 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
908 * No need to use i_size_read() here, the i_size
909 * cannot change under us because we hold i_mutex.
911 * But it's important to update i_size while still holding page lock:
912 * page writeout could otherwise come in and zero beyond i_size.
914 if (pos + copied > inode->i_size) {
915 i_size_write(inode, pos + copied);
919 if (pos + copied > EXT4_I(inode)->i_disksize) {
920 /* We need to mark inode dirty even if
921 * new_i_size is less that inode->i_size
922 * bu greater than i_disksize.(hint delalloc)
924 ext4_update_i_disksize(inode, (pos + copied));
928 page_cache_release(page);
931 * Don't mark the inode dirty under page lock. First, it unnecessarily
932 * makes the holding time of page lock longer. Second, it forces lock
933 * ordering of page lock and transaction start for journaling
937 ext4_mark_inode_dirty(handle, inode);
943 * We need to pick up the new inode size which generic_commit_write gave us
944 * `file' can be NULL - eg, when called from page_symlink().
946 * ext4 never places buffers on inode->i_mapping->private_list. metadata
947 * buffers are managed internally.
949 static int ext4_ordered_write_end(struct file *file,
950 struct address_space *mapping,
951 loff_t pos, unsigned len, unsigned copied,
952 struct page *page, void *fsdata)
954 handle_t *handle = ext4_journal_current_handle();
955 struct inode *inode = mapping->host;
958 trace_ext4_ordered_write_end(inode, pos, len, copied);
959 ret = ext4_jbd2_file_inode(handle, inode);
962 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
965 if (pos + len > inode->i_size && ext4_can_truncate(inode))
966 /* if we have allocated more blocks and copied
967 * less. We will have blocks allocated outside
968 * inode->i_size. So truncate them
970 ext4_orphan_add(handle, inode);
975 page_cache_release(page);
978 ret2 = ext4_journal_stop(handle);
982 if (pos + len > inode->i_size) {
983 ext4_truncate_failed_write(inode);
985 * If truncate failed early the inode might still be
986 * on the orphan list; we need to make sure the inode
987 * is removed from the orphan list in that case.
990 ext4_orphan_del(NULL, inode);
994 return ret ? ret : copied;
997 static int ext4_writeback_write_end(struct file *file,
998 struct address_space *mapping,
999 loff_t pos, unsigned len, unsigned copied,
1000 struct page *page, void *fsdata)
1002 handle_t *handle = ext4_journal_current_handle();
1003 struct inode *inode = mapping->host;
1006 trace_ext4_writeback_write_end(inode, pos, len, copied);
1007 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1010 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1011 /* if we have allocated more blocks and copied
1012 * less. We will have blocks allocated outside
1013 * inode->i_size. So truncate them
1015 ext4_orphan_add(handle, inode);
1020 ret2 = ext4_journal_stop(handle);
1024 if (pos + len > inode->i_size) {
1025 ext4_truncate_failed_write(inode);
1027 * If truncate failed early the inode might still be
1028 * on the orphan list; we need to make sure the inode
1029 * is removed from the orphan list in that case.
1032 ext4_orphan_del(NULL, inode);
1035 return ret ? ret : copied;
1038 static int ext4_journalled_write_end(struct file *file,
1039 struct address_space *mapping,
1040 loff_t pos, unsigned len, unsigned copied,
1041 struct page *page, void *fsdata)
1043 handle_t *handle = ext4_journal_current_handle();
1044 struct inode *inode = mapping->host;
1050 trace_ext4_journalled_write_end(inode, pos, len, copied);
1051 from = pos & (PAGE_CACHE_SIZE - 1);
1054 BUG_ON(!ext4_handle_valid(handle));
1057 if (!PageUptodate(page))
1059 page_zero_new_buffers(page, from+copied, to);
1062 ret = walk_page_buffers(handle, page_buffers(page), from,
1063 to, &partial, write_end_fn);
1065 SetPageUptodate(page);
1066 new_i_size = pos + copied;
1067 if (new_i_size > inode->i_size)
1068 i_size_write(inode, pos+copied);
1069 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1070 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1071 if (new_i_size > EXT4_I(inode)->i_disksize) {
1072 ext4_update_i_disksize(inode, new_i_size);
1073 ret2 = ext4_mark_inode_dirty(handle, inode);
1079 page_cache_release(page);
1080 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1081 /* if we have allocated more blocks and copied
1082 * less. We will have blocks allocated outside
1083 * inode->i_size. So truncate them
1085 ext4_orphan_add(handle, inode);
1087 ret2 = ext4_journal_stop(handle);
1090 if (pos + len > inode->i_size) {
1091 ext4_truncate_failed_write(inode);
1093 * If truncate failed early the inode might still be
1094 * on the orphan list; we need to make sure the inode
1095 * is removed from the orphan list in that case.
1098 ext4_orphan_del(NULL, inode);
1101 return ret ? ret : copied;
1105 * Reserve a single cluster located at lblock
1107 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1110 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1111 struct ext4_inode_info *ei = EXT4_I(inode);
1112 unsigned int md_needed;
1114 ext4_lblk_t save_last_lblock;
1118 * We will charge metadata quota at writeout time; this saves
1119 * us from metadata over-estimation, though we may go over by
1120 * a small amount in the end. Here we just reserve for data.
1122 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1127 * recalculate the amount of metadata blocks to reserve
1128 * in order to allocate nrblocks
1129 * worse case is one extent per block
1132 spin_lock(&ei->i_block_reservation_lock);
1134 * ext4_calc_metadata_amount() has side effects, which we have
1135 * to be prepared undo if we fail to claim space.
1137 save_len = ei->i_da_metadata_calc_len;
1138 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1139 md_needed = EXT4_NUM_B2C(sbi,
1140 ext4_calc_metadata_amount(inode, lblock));
1141 trace_ext4_da_reserve_space(inode, md_needed);
1144 * We do still charge estimated metadata to the sb though;
1145 * we cannot afford to run out of free blocks.
1147 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1148 ei->i_da_metadata_calc_len = save_len;
1149 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1150 spin_unlock(&ei->i_block_reservation_lock);
1151 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1155 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1158 ei->i_reserved_data_blocks++;
1159 ei->i_reserved_meta_blocks += md_needed;
1160 spin_unlock(&ei->i_block_reservation_lock);
1162 return 0; /* success */
1165 static void ext4_da_release_space(struct inode *inode, int to_free)
1167 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1168 struct ext4_inode_info *ei = EXT4_I(inode);
1171 return; /* Nothing to release, exit */
1173 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1175 trace_ext4_da_release_space(inode, to_free);
1176 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1178 * if there aren't enough reserved blocks, then the
1179 * counter is messed up somewhere. Since this
1180 * function is called from invalidate page, it's
1181 * harmless to return without any action.
1183 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1184 "ino %lu, to_free %d with only %d reserved "
1185 "data blocks\n", inode->i_ino, to_free,
1186 ei->i_reserved_data_blocks);
1188 to_free = ei->i_reserved_data_blocks;
1190 ei->i_reserved_data_blocks -= to_free;
1192 if (ei->i_reserved_data_blocks == 0) {
1194 * We can release all of the reserved metadata blocks
1195 * only when we have written all of the delayed
1196 * allocation blocks.
1197 * Note that in case of bigalloc, i_reserved_meta_blocks,
1198 * i_reserved_data_blocks, etc. refer to number of clusters.
1200 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1201 ei->i_reserved_meta_blocks);
1202 ei->i_reserved_meta_blocks = 0;
1203 ei->i_da_metadata_calc_len = 0;
1206 /* update fs dirty data blocks counter */
1207 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1209 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1211 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1214 static void ext4_da_page_release_reservation(struct page *page,
1215 unsigned long offset)
1218 struct buffer_head *head, *bh;
1219 unsigned int curr_off = 0;
1220 struct inode *inode = page->mapping->host;
1221 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1224 head = page_buffers(page);
1227 unsigned int next_off = curr_off + bh->b_size;
1229 if ((offset <= curr_off) && (buffer_delay(bh))) {
1231 clear_buffer_delay(bh);
1232 clear_buffer_da_mapped(bh);
1234 curr_off = next_off;
1235 } while ((bh = bh->b_this_page) != head);
1237 /* If we have released all the blocks belonging to a cluster, then we
1238 * need to release the reserved space for that cluster. */
1239 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1240 while (num_clusters > 0) {
1242 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1243 ((num_clusters - 1) << sbi->s_cluster_bits);
1244 if (sbi->s_cluster_ratio == 1 ||
1245 !ext4_find_delalloc_cluster(inode, lblk, 1))
1246 ext4_da_release_space(inode, 1);
1253 * Delayed allocation stuff
1257 * mpage_da_submit_io - walks through extent of pages and try to write
1258 * them with writepage() call back
1260 * @mpd->inode: inode
1261 * @mpd->first_page: first page of the extent
1262 * @mpd->next_page: page after the last page of the extent
1264 * By the time mpage_da_submit_io() is called we expect all blocks
1265 * to be allocated. this may be wrong if allocation failed.
1267 * As pages are already locked by write_cache_pages(), we can't use it
1269 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1270 struct ext4_map_blocks *map)
1272 struct pagevec pvec;
1273 unsigned long index, end;
1274 int ret = 0, err, nr_pages, i;
1275 struct inode *inode = mpd->inode;
1276 struct address_space *mapping = inode->i_mapping;
1277 loff_t size = i_size_read(inode);
1278 unsigned int len, block_start;
1279 struct buffer_head *bh, *page_bufs = NULL;
1280 int journal_data = ext4_should_journal_data(inode);
1281 sector_t pblock = 0, cur_logical = 0;
1282 struct ext4_io_submit io_submit;
1284 BUG_ON(mpd->next_page <= mpd->first_page);
1285 memset(&io_submit, 0, sizeof(io_submit));
1287 * We need to start from the first_page to the next_page - 1
1288 * to make sure we also write the mapped dirty buffer_heads.
1289 * If we look at mpd->b_blocknr we would only be looking
1290 * at the currently mapped buffer_heads.
1292 index = mpd->first_page;
1293 end = mpd->next_page - 1;
1295 pagevec_init(&pvec, 0);
1296 while (index <= end) {
1297 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1300 for (i = 0; i < nr_pages; i++) {
1301 int commit_write = 0, skip_page = 0;
1302 struct page *page = pvec.pages[i];
1304 index = page->index;
1308 if (index == size >> PAGE_CACHE_SHIFT)
1309 len = size & ~PAGE_CACHE_MASK;
1311 len = PAGE_CACHE_SIZE;
1313 cur_logical = index << (PAGE_CACHE_SHIFT -
1315 pblock = map->m_pblk + (cur_logical -
1320 BUG_ON(!PageLocked(page));
1321 BUG_ON(PageWriteback(page));
1324 * If the page does not have buffers (for
1325 * whatever reason), try to create them using
1326 * __block_write_begin. If this fails,
1327 * skip the page and move on.
1329 if (!page_has_buffers(page)) {
1330 if (__block_write_begin(page, 0, len,
1331 noalloc_get_block_write)) {
1339 bh = page_bufs = page_buffers(page);
1344 if (map && (cur_logical >= map->m_lblk) &&
1345 (cur_logical <= (map->m_lblk +
1346 (map->m_len - 1)))) {
1347 if (buffer_delay(bh)) {
1348 clear_buffer_delay(bh);
1349 bh->b_blocknr = pblock;
1351 if (buffer_da_mapped(bh))
1352 clear_buffer_da_mapped(bh);
1353 if (buffer_unwritten(bh) ||
1355 BUG_ON(bh->b_blocknr != pblock);
1356 if (map->m_flags & EXT4_MAP_UNINIT)
1357 set_buffer_uninit(bh);
1358 clear_buffer_unwritten(bh);
1362 * skip page if block allocation undone and
1365 if (ext4_bh_delay_or_unwritten(NULL, bh))
1367 bh = bh->b_this_page;
1368 block_start += bh->b_size;
1371 } while (bh != page_bufs);
1377 /* mark the buffer_heads as dirty & uptodate */
1378 block_commit_write(page, 0, len);
1380 clear_page_dirty_for_io(page);
1382 * Delalloc doesn't support data journalling,
1383 * but eventually maybe we'll lift this
1386 if (unlikely(journal_data && PageChecked(page)))
1387 err = __ext4_journalled_writepage(page, len);
1388 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1389 err = ext4_bio_write_page(&io_submit, page,
1391 else if (buffer_uninit(page_bufs)) {
1392 ext4_set_bh_endio(page_bufs, inode);
1393 err = block_write_full_page_endio(page,
1394 noalloc_get_block_write,
1395 mpd->wbc, ext4_end_io_buffer_write);
1397 err = block_write_full_page(page,
1398 noalloc_get_block_write, mpd->wbc);
1401 mpd->pages_written++;
1403 * In error case, we have to continue because
1404 * remaining pages are still locked
1409 pagevec_release(&pvec);
1411 ext4_io_submit(&io_submit);
1415 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1419 struct pagevec pvec;
1420 struct inode *inode = mpd->inode;
1421 struct address_space *mapping = inode->i_mapping;
1423 index = mpd->first_page;
1424 end = mpd->next_page - 1;
1425 while (index <= end) {
1426 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1429 for (i = 0; i < nr_pages; i++) {
1430 struct page *page = pvec.pages[i];
1431 if (page->index > end)
1433 BUG_ON(!PageLocked(page));
1434 BUG_ON(PageWriteback(page));
1435 block_invalidatepage(page, 0);
1436 ClearPageUptodate(page);
1439 index = pvec.pages[nr_pages - 1]->index + 1;
1440 pagevec_release(&pvec);
1445 static void ext4_print_free_blocks(struct inode *inode)
1447 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1448 printk(KERN_CRIT "Total free blocks count %lld\n",
1449 EXT4_C2B(EXT4_SB(inode->i_sb),
1450 ext4_count_free_clusters(inode->i_sb)));
1451 printk(KERN_CRIT "Free/Dirty block details\n");
1452 printk(KERN_CRIT "free_blocks=%lld\n",
1453 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1454 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1455 printk(KERN_CRIT "dirty_blocks=%lld\n",
1456 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1457 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1458 printk(KERN_CRIT "Block reservation details\n");
1459 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1460 EXT4_I(inode)->i_reserved_data_blocks);
1461 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1462 EXT4_I(inode)->i_reserved_meta_blocks);
1467 * mpage_da_map_and_submit - go through given space, map them
1468 * if necessary, and then submit them for I/O
1470 * @mpd - bh describing space
1472 * The function skips space we know is already mapped to disk blocks.
1475 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1477 int err, blks, get_blocks_flags;
1478 struct ext4_map_blocks map, *mapp = NULL;
1479 sector_t next = mpd->b_blocknr;
1480 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1481 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1482 handle_t *handle = NULL;
1485 * If the blocks are mapped already, or we couldn't accumulate
1486 * any blocks, then proceed immediately to the submission stage.
1488 if ((mpd->b_size == 0) ||
1489 ((mpd->b_state & (1 << BH_Mapped)) &&
1490 !(mpd->b_state & (1 << BH_Delay)) &&
1491 !(mpd->b_state & (1 << BH_Unwritten))))
1494 handle = ext4_journal_current_handle();
1498 * Call ext4_map_blocks() to allocate any delayed allocation
1499 * blocks, or to convert an uninitialized extent to be
1500 * initialized (in the case where we have written into
1501 * one or more preallocated blocks).
1503 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1504 * indicate that we are on the delayed allocation path. This
1505 * affects functions in many different parts of the allocation
1506 * call path. This flag exists primarily because we don't
1507 * want to change *many* call functions, so ext4_map_blocks()
1508 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1509 * inode's allocation semaphore is taken.
1511 * If the blocks in questions were delalloc blocks, set
1512 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1513 * variables are updated after the blocks have been allocated.
1516 map.m_len = max_blocks;
1517 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1518 if (ext4_should_dioread_nolock(mpd->inode))
1519 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1520 if (mpd->b_state & (1 << BH_Delay))
1521 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1523 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1525 struct super_block *sb = mpd->inode->i_sb;
1529 * If get block returns EAGAIN or ENOSPC and there
1530 * appears to be free blocks we will just let
1531 * mpage_da_submit_io() unlock all of the pages.
1536 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1542 * get block failure will cause us to loop in
1543 * writepages, because a_ops->writepage won't be able
1544 * to make progress. The page will be redirtied by
1545 * writepage and writepages will again try to write
1548 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1549 ext4_msg(sb, KERN_CRIT,
1550 "delayed block allocation failed for inode %lu "
1551 "at logical offset %llu with max blocks %zd "
1552 "with error %d", mpd->inode->i_ino,
1553 (unsigned long long) next,
1554 mpd->b_size >> mpd->inode->i_blkbits, err);
1555 ext4_msg(sb, KERN_CRIT,
1556 "This should not happen!! Data will be lost\n");
1558 ext4_print_free_blocks(mpd->inode);
1560 /* invalidate all the pages */
1561 ext4_da_block_invalidatepages(mpd);
1563 /* Mark this page range as having been completed */
1570 if (map.m_flags & EXT4_MAP_NEW) {
1571 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1574 for (i = 0; i < map.m_len; i++)
1575 unmap_underlying_metadata(bdev, map.m_pblk + i);
1577 if (ext4_should_order_data(mpd->inode)) {
1578 err = ext4_jbd2_file_inode(handle, mpd->inode);
1580 /* Only if the journal is aborted */
1588 * Update on-disk size along with block allocation.
1590 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1591 if (disksize > i_size_read(mpd->inode))
1592 disksize = i_size_read(mpd->inode);
1593 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1594 ext4_update_i_disksize(mpd->inode, disksize);
1595 err = ext4_mark_inode_dirty(handle, mpd->inode);
1597 ext4_error(mpd->inode->i_sb,
1598 "Failed to mark inode %lu dirty",
1603 mpage_da_submit_io(mpd, mapp);
1607 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1608 (1 << BH_Delay) | (1 << BH_Unwritten))
1611 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1613 * @mpd->lbh - extent of blocks
1614 * @logical - logical number of the block in the file
1615 * @bh - bh of the block (used to access block's state)
1617 * the function is used to collect contig. blocks in same state
1619 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1620 sector_t logical, size_t b_size,
1621 unsigned long b_state)
1624 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1627 * XXX Don't go larger than mballoc is willing to allocate
1628 * This is a stopgap solution. We eventually need to fold
1629 * mpage_da_submit_io() into this function and then call
1630 * ext4_map_blocks() multiple times in a loop
1632 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1635 /* check if thereserved journal credits might overflow */
1636 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1637 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1639 * With non-extent format we are limited by the journal
1640 * credit available. Total credit needed to insert
1641 * nrblocks contiguous blocks is dependent on the
1642 * nrblocks. So limit nrblocks.
1645 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1646 EXT4_MAX_TRANS_DATA) {
1648 * Adding the new buffer_head would make it cross the
1649 * allowed limit for which we have journal credit
1650 * reserved. So limit the new bh->b_size
1652 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1653 mpd->inode->i_blkbits;
1654 /* we will do mpage_da_submit_io in the next loop */
1658 * First block in the extent
1660 if (mpd->b_size == 0) {
1661 mpd->b_blocknr = logical;
1662 mpd->b_size = b_size;
1663 mpd->b_state = b_state & BH_FLAGS;
1667 next = mpd->b_blocknr + nrblocks;
1669 * Can we merge the block to our big extent?
1671 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1672 mpd->b_size += b_size;
1678 * We couldn't merge the block to our extent, so we
1679 * need to flush current extent and start new one
1681 mpage_da_map_and_submit(mpd);
1685 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1687 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1691 * This function is grabs code from the very beginning of
1692 * ext4_map_blocks, but assumes that the caller is from delayed write
1693 * time. This function looks up the requested blocks and sets the
1694 * buffer delay bit under the protection of i_data_sem.
1696 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1697 struct ext4_map_blocks *map,
1698 struct buffer_head *bh)
1701 sector_t invalid_block = ~((sector_t) 0xffff);
1703 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1707 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1708 "logical block %lu\n", inode->i_ino, map->m_len,
1709 (unsigned long) map->m_lblk);
1711 * Try to see if we can get the block without requesting a new
1712 * file system block.
1714 down_read((&EXT4_I(inode)->i_data_sem));
1715 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1716 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1718 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1722 * XXX: __block_prepare_write() unmaps passed block,
1725 /* If the block was allocated from previously allocated cluster,
1726 * then we dont need to reserve it again. */
1727 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1728 retval = ext4_da_reserve_space(inode, iblock);
1730 /* not enough space to reserve */
1734 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1735 * and it should not appear on the bh->b_state.
1737 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1739 map_bh(bh, inode->i_sb, invalid_block);
1741 set_buffer_delay(bh);
1745 up_read((&EXT4_I(inode)->i_data_sem));
1751 * This is a special get_blocks_t callback which is used by
1752 * ext4_da_write_begin(). It will either return mapped block or
1753 * reserve space for a single block.
1755 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1756 * We also have b_blocknr = -1 and b_bdev initialized properly
1758 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1759 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1760 * initialized properly.
1762 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1763 struct buffer_head *bh, int create)
1765 struct ext4_map_blocks map;
1768 BUG_ON(create == 0);
1769 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1771 map.m_lblk = iblock;
1775 * first, we need to know whether the block is allocated already
1776 * preallocated blocks are unmapped but should treated
1777 * the same as allocated blocks.
1779 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1783 map_bh(bh, inode->i_sb, map.m_pblk);
1784 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1786 if (buffer_unwritten(bh)) {
1787 /* A delayed write to unwritten bh should be marked
1788 * new and mapped. Mapped ensures that we don't do
1789 * get_block multiple times when we write to the same
1790 * offset and new ensures that we do proper zero out
1791 * for partial write.
1794 set_buffer_mapped(bh);
1800 * This function is used as a standard get_block_t calback function
1801 * when there is no desire to allocate any blocks. It is used as a
1802 * callback function for block_write_begin() and block_write_full_page().
1803 * These functions should only try to map a single block at a time.
1805 * Since this function doesn't do block allocations even if the caller
1806 * requests it by passing in create=1, it is critically important that
1807 * any caller checks to make sure that any buffer heads are returned
1808 * by this function are either all already mapped or marked for
1809 * delayed allocation before calling block_write_full_page(). Otherwise,
1810 * b_blocknr could be left unitialized, and the page write functions will
1811 * be taken by surprise.
1813 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1814 struct buffer_head *bh_result, int create)
1816 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1817 return _ext4_get_block(inode, iblock, bh_result, 0);
1820 static int bget_one(handle_t *handle, struct buffer_head *bh)
1826 static int bput_one(handle_t *handle, struct buffer_head *bh)
1832 static int __ext4_journalled_writepage(struct page *page,
1835 struct address_space *mapping = page->mapping;
1836 struct inode *inode = mapping->host;
1837 struct buffer_head *page_bufs;
1838 handle_t *handle = NULL;
1842 ClearPageChecked(page);
1843 page_bufs = page_buffers(page);
1845 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1846 /* As soon as we unlock the page, it can go away, but we have
1847 * references to buffers so we are safe */
1850 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1851 if (IS_ERR(handle)) {
1852 ret = PTR_ERR(handle);
1856 BUG_ON(!ext4_handle_valid(handle));
1858 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1859 do_journal_get_write_access);
1861 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1865 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1866 err = ext4_journal_stop(handle);
1870 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1871 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1876 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1877 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1880 * Note that we don't need to start a transaction unless we're journaling data
1881 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1882 * need to file the inode to the transaction's list in ordered mode because if
1883 * we are writing back data added by write(), the inode is already there and if
1884 * we are writing back data modified via mmap(), no one guarantees in which
1885 * transaction the data will hit the disk. In case we are journaling data, we
1886 * cannot start transaction directly because transaction start ranks above page
1887 * lock so we have to do some magic.
1889 * This function can get called via...
1890 * - ext4_da_writepages after taking page lock (have journal handle)
1891 * - journal_submit_inode_data_buffers (no journal handle)
1892 * - shrink_page_list via pdflush (no journal handle)
1893 * - grab_page_cache when doing write_begin (have journal handle)
1895 * We don't do any block allocation in this function. If we have page with
1896 * multiple blocks we need to write those buffer_heads that are mapped. This
1897 * is important for mmaped based write. So if we do with blocksize 1K
1898 * truncate(f, 1024);
1899 * a = mmap(f, 0, 4096);
1901 * truncate(f, 4096);
1902 * we have in the page first buffer_head mapped via page_mkwrite call back
1903 * but other bufer_heads would be unmapped but dirty(dirty done via the
1904 * do_wp_page). So writepage should write the first block. If we modify
1905 * the mmap area beyond 1024 we will again get a page_fault and the
1906 * page_mkwrite callback will do the block allocation and mark the
1907 * buffer_heads mapped.
1909 * We redirty the page if we have any buffer_heads that is either delay or
1910 * unwritten in the page.
1912 * We can get recursively called as show below.
1914 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1917 * But since we don't do any block allocation we should not deadlock.
1918 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1920 static int ext4_writepage(struct page *page,
1921 struct writeback_control *wbc)
1923 int ret = 0, commit_write = 0;
1926 struct buffer_head *page_bufs = NULL;
1927 struct inode *inode = page->mapping->host;
1929 trace_ext4_writepage(page);
1930 size = i_size_read(inode);
1931 if (page->index == size >> PAGE_CACHE_SHIFT)
1932 len = size & ~PAGE_CACHE_MASK;
1934 len = PAGE_CACHE_SIZE;
1937 * If the page does not have buffers (for whatever reason),
1938 * try to create them using __block_write_begin. If this
1939 * fails, redirty the page and move on.
1941 if (!page_has_buffers(page)) {
1942 if (__block_write_begin(page, 0, len,
1943 noalloc_get_block_write)) {
1945 redirty_page_for_writepage(wbc, page);
1951 page_bufs = page_buffers(page);
1952 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1953 ext4_bh_delay_or_unwritten)) {
1955 * We don't want to do block allocation, so redirty
1956 * the page and return. We may reach here when we do
1957 * a journal commit via journal_submit_inode_data_buffers.
1958 * We can also reach here via shrink_page_list but it
1959 * should never be for direct reclaim so warn if that
1962 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1967 /* now mark the buffer_heads as dirty and uptodate */
1968 block_commit_write(page, 0, len);
1970 if (PageChecked(page) && ext4_should_journal_data(inode))
1972 * It's mmapped pagecache. Add buffers and journal it. There
1973 * doesn't seem much point in redirtying the page here.
1975 return __ext4_journalled_writepage(page, len);
1977 if (buffer_uninit(page_bufs)) {
1978 ext4_set_bh_endio(page_bufs, inode);
1979 ret = block_write_full_page_endio(page, noalloc_get_block_write,
1980 wbc, ext4_end_io_buffer_write);
1982 ret = block_write_full_page(page, noalloc_get_block_write,
1989 * This is called via ext4_da_writepages() to
1990 * calculate the total number of credits to reserve to fit
1991 * a single extent allocation into a single transaction,
1992 * ext4_da_writpeages() will loop calling this before
1993 * the block allocation.
1996 static int ext4_da_writepages_trans_blocks(struct inode *inode)
1998 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2001 * With non-extent format the journal credit needed to
2002 * insert nrblocks contiguous block is dependent on
2003 * number of contiguous block. So we will limit
2004 * number of contiguous block to a sane value
2006 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2007 (max_blocks > EXT4_MAX_TRANS_DATA))
2008 max_blocks = EXT4_MAX_TRANS_DATA;
2010 return ext4_chunk_trans_blocks(inode, max_blocks);
2014 * write_cache_pages_da - walk the list of dirty pages of the given
2015 * address space and accumulate pages that need writing, and call
2016 * mpage_da_map_and_submit to map a single contiguous memory region
2017 * and then write them.
2019 static int write_cache_pages_da(struct address_space *mapping,
2020 struct writeback_control *wbc,
2021 struct mpage_da_data *mpd,
2022 pgoff_t *done_index)
2024 struct buffer_head *bh, *head;
2025 struct inode *inode = mapping->host;
2026 struct pagevec pvec;
2027 unsigned int nr_pages;
2030 long nr_to_write = wbc->nr_to_write;
2031 int i, tag, ret = 0;
2033 memset(mpd, 0, sizeof(struct mpage_da_data));
2036 pagevec_init(&pvec, 0);
2037 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2038 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2040 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2041 tag = PAGECACHE_TAG_TOWRITE;
2043 tag = PAGECACHE_TAG_DIRTY;
2045 *done_index = index;
2046 while (index <= end) {
2047 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2048 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2052 for (i = 0; i < nr_pages; i++) {
2053 struct page *page = pvec.pages[i];
2056 * At this point, the page may be truncated or
2057 * invalidated (changing page->mapping to NULL), or
2058 * even swizzled back from swapper_space to tmpfs file
2059 * mapping. However, page->index will not change
2060 * because we have a reference on the page.
2062 if (page->index > end)
2065 *done_index = page->index + 1;
2068 * If we can't merge this page, and we have
2069 * accumulated an contiguous region, write it
2071 if ((mpd->next_page != page->index) &&
2072 (mpd->next_page != mpd->first_page)) {
2073 mpage_da_map_and_submit(mpd);
2074 goto ret_extent_tail;
2080 * If the page is no longer dirty, or its
2081 * mapping no longer corresponds to inode we
2082 * are writing (which means it has been
2083 * truncated or invalidated), or the page is
2084 * already under writeback and we are not
2085 * doing a data integrity writeback, skip the page
2087 if (!PageDirty(page) ||
2088 (PageWriteback(page) &&
2089 (wbc->sync_mode == WB_SYNC_NONE)) ||
2090 unlikely(page->mapping != mapping)) {
2095 wait_on_page_writeback(page);
2096 BUG_ON(PageWriteback(page));
2098 if (mpd->next_page != page->index)
2099 mpd->first_page = page->index;
2100 mpd->next_page = page->index + 1;
2101 logical = (sector_t) page->index <<
2102 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2104 if (!page_has_buffers(page)) {
2105 mpage_add_bh_to_extent(mpd, logical,
2107 (1 << BH_Dirty) | (1 << BH_Uptodate));
2109 goto ret_extent_tail;
2112 * Page with regular buffer heads,
2113 * just add all dirty ones
2115 head = page_buffers(page);
2118 BUG_ON(buffer_locked(bh));
2120 * We need to try to allocate
2121 * unmapped blocks in the same page.
2122 * Otherwise we won't make progress
2123 * with the page in ext4_writepage
2125 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2126 mpage_add_bh_to_extent(mpd, logical,
2130 goto ret_extent_tail;
2131 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2133 * mapped dirty buffer. We need
2134 * to update the b_state
2135 * because we look at b_state
2136 * in mpage_da_map_blocks. We
2137 * don't update b_size because
2138 * if we find an unmapped
2139 * buffer_head later we need to
2140 * use the b_state flag of that
2143 if (mpd->b_size == 0)
2144 mpd->b_state = bh->b_state & BH_FLAGS;
2147 } while ((bh = bh->b_this_page) != head);
2150 if (nr_to_write > 0) {
2152 if (nr_to_write == 0 &&
2153 wbc->sync_mode == WB_SYNC_NONE)
2155 * We stop writing back only if we are
2156 * not doing integrity sync. In case of
2157 * integrity sync we have to keep going
2158 * because someone may be concurrently
2159 * dirtying pages, and we might have
2160 * synced a lot of newly appeared dirty
2161 * pages, but have not synced all of the
2167 pagevec_release(&pvec);
2172 ret = MPAGE_DA_EXTENT_TAIL;
2174 pagevec_release(&pvec);
2180 static int ext4_da_writepages(struct address_space *mapping,
2181 struct writeback_control *wbc)
2184 int range_whole = 0;
2185 handle_t *handle = NULL;
2186 struct mpage_da_data mpd;
2187 struct inode *inode = mapping->host;
2188 int pages_written = 0;
2189 unsigned int max_pages;
2190 int range_cyclic, cycled = 1, io_done = 0;
2191 int needed_blocks, ret = 0;
2192 long desired_nr_to_write, nr_to_writebump = 0;
2193 loff_t range_start = wbc->range_start;
2194 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2195 pgoff_t done_index = 0;
2197 struct blk_plug plug;
2199 trace_ext4_da_writepages(inode, wbc);
2202 * No pages to write? This is mainly a kludge to avoid starting
2203 * a transaction for special inodes like journal inode on last iput()
2204 * because that could violate lock ordering on umount
2206 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2210 * If the filesystem has aborted, it is read-only, so return
2211 * right away instead of dumping stack traces later on that
2212 * will obscure the real source of the problem. We test
2213 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2214 * the latter could be true if the filesystem is mounted
2215 * read-only, and in that case, ext4_da_writepages should
2216 * *never* be called, so if that ever happens, we would want
2219 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2222 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2225 range_cyclic = wbc->range_cyclic;
2226 if (wbc->range_cyclic) {
2227 index = mapping->writeback_index;
2230 wbc->range_start = index << PAGE_CACHE_SHIFT;
2231 wbc->range_end = LLONG_MAX;
2232 wbc->range_cyclic = 0;
2235 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2236 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2240 * This works around two forms of stupidity. The first is in
2241 * the writeback code, which caps the maximum number of pages
2242 * written to be 1024 pages. This is wrong on multiple
2243 * levels; different architectues have a different page size,
2244 * which changes the maximum amount of data which gets
2245 * written. Secondly, 4 megabytes is way too small. XFS
2246 * forces this value to be 16 megabytes by multiplying
2247 * nr_to_write parameter by four, and then relies on its
2248 * allocator to allocate larger extents to make them
2249 * contiguous. Unfortunately this brings us to the second
2250 * stupidity, which is that ext4's mballoc code only allocates
2251 * at most 2048 blocks. So we force contiguous writes up to
2252 * the number of dirty blocks in the inode, or
2253 * sbi->max_writeback_mb_bump whichever is smaller.
2255 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2256 if (!range_cyclic && range_whole) {
2257 if (wbc->nr_to_write == LONG_MAX)
2258 desired_nr_to_write = wbc->nr_to_write;
2260 desired_nr_to_write = wbc->nr_to_write * 8;
2262 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2264 if (desired_nr_to_write > max_pages)
2265 desired_nr_to_write = max_pages;
2267 if (wbc->nr_to_write < desired_nr_to_write) {
2268 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2269 wbc->nr_to_write = desired_nr_to_write;
2273 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2274 tag_pages_for_writeback(mapping, index, end);
2276 blk_start_plug(&plug);
2277 while (!ret && wbc->nr_to_write > 0) {
2280 * we insert one extent at a time. So we need
2281 * credit needed for single extent allocation.
2282 * journalled mode is currently not supported
2285 BUG_ON(ext4_should_journal_data(inode));
2286 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2288 /* start a new transaction*/
2289 handle = ext4_journal_start(inode, needed_blocks);
2290 if (IS_ERR(handle)) {
2291 ret = PTR_ERR(handle);
2292 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2293 "%ld pages, ino %lu; err %d", __func__,
2294 wbc->nr_to_write, inode->i_ino, ret);
2295 blk_finish_plug(&plug);
2296 goto out_writepages;
2300 * Now call write_cache_pages_da() to find the next
2301 * contiguous region of logical blocks that need
2302 * blocks to be allocated by ext4 and submit them.
2304 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2306 * If we have a contiguous extent of pages and we
2307 * haven't done the I/O yet, map the blocks and submit
2310 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2311 mpage_da_map_and_submit(&mpd);
2312 ret = MPAGE_DA_EXTENT_TAIL;
2314 trace_ext4_da_write_pages(inode, &mpd);
2315 wbc->nr_to_write -= mpd.pages_written;
2317 ext4_journal_stop(handle);
2319 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2320 /* commit the transaction which would
2321 * free blocks released in the transaction
2324 jbd2_journal_force_commit_nested(sbi->s_journal);
2326 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2328 * Got one extent now try with rest of the pages.
2329 * If mpd.retval is set -EIO, journal is aborted.
2330 * So we don't need to write any more.
2332 pages_written += mpd.pages_written;
2335 } else if (wbc->nr_to_write)
2337 * There is no more writeout needed
2338 * or we requested for a noblocking writeout
2339 * and we found the device congested
2343 blk_finish_plug(&plug);
2344 if (!io_done && !cycled) {
2347 wbc->range_start = index << PAGE_CACHE_SHIFT;
2348 wbc->range_end = mapping->writeback_index - 1;
2353 wbc->range_cyclic = range_cyclic;
2354 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2356 * set the writeback_index so that range_cyclic
2357 * mode will write it back later
2359 mapping->writeback_index = done_index;
2362 wbc->nr_to_write -= nr_to_writebump;
2363 wbc->range_start = range_start;
2364 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2368 #define FALL_BACK_TO_NONDELALLOC 1
2369 static int ext4_nonda_switch(struct super_block *sb)
2371 s64 free_blocks, dirty_blocks;
2372 struct ext4_sb_info *sbi = EXT4_SB(sb);
2375 * switch to non delalloc mode if we are running low
2376 * on free block. The free block accounting via percpu
2377 * counters can get slightly wrong with percpu_counter_batch getting
2378 * accumulated on each CPU without updating global counters
2379 * Delalloc need an accurate free block accounting. So switch
2380 * to non delalloc when we are near to error range.
2382 free_blocks = EXT4_C2B(sbi,
2383 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2384 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2386 * Start pushing delalloc when 1/2 of free blocks are dirty.
2388 if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
2389 !writeback_in_progress(sb->s_bdi) &&
2390 down_read_trylock(&sb->s_umount)) {
2391 writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2392 up_read(&sb->s_umount);
2395 if (2 * free_blocks < 3 * dirty_blocks ||
2396 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2398 * free block count is less than 150% of dirty blocks
2399 * or free blocks is less than watermark
2406 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2407 loff_t pos, unsigned len, unsigned flags,
2408 struct page **pagep, void **fsdata)
2410 int ret, retries = 0;
2413 struct inode *inode = mapping->host;
2416 index = pos >> PAGE_CACHE_SHIFT;
2418 if (ext4_nonda_switch(inode->i_sb)) {
2419 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2420 return ext4_write_begin(file, mapping, pos,
2421 len, flags, pagep, fsdata);
2423 *fsdata = (void *)0;
2424 trace_ext4_da_write_begin(inode, pos, len, flags);
2427 * With delayed allocation, we don't log the i_disksize update
2428 * if there is delayed block allocation. But we still need
2429 * to journalling the i_disksize update if writes to the end
2430 * of file which has an already mapped buffer.
2432 handle = ext4_journal_start(inode, 1);
2433 if (IS_ERR(handle)) {
2434 ret = PTR_ERR(handle);
2437 /* We cannot recurse into the filesystem as the transaction is already
2439 flags |= AOP_FLAG_NOFS;
2441 page = grab_cache_page_write_begin(mapping, index, flags);
2443 ext4_journal_stop(handle);
2449 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2452 ext4_journal_stop(handle);
2453 page_cache_release(page);
2455 * block_write_begin may have instantiated a few blocks
2456 * outside i_size. Trim these off again. Don't need
2457 * i_size_read because we hold i_mutex.
2459 if (pos + len > inode->i_size)
2460 ext4_truncate_failed_write(inode);
2463 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2470 * Check if we should update i_disksize
2471 * when write to the end of file but not require block allocation
2473 static int ext4_da_should_update_i_disksize(struct page *page,
2474 unsigned long offset)
2476 struct buffer_head *bh;
2477 struct inode *inode = page->mapping->host;
2481 bh = page_buffers(page);
2482 idx = offset >> inode->i_blkbits;
2484 for (i = 0; i < idx; i++)
2485 bh = bh->b_this_page;
2487 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2492 static int ext4_da_write_end(struct file *file,
2493 struct address_space *mapping,
2494 loff_t pos, unsigned len, unsigned copied,
2495 struct page *page, void *fsdata)
2497 struct inode *inode = mapping->host;
2499 handle_t *handle = ext4_journal_current_handle();
2501 unsigned long start, end;
2502 int write_mode = (int)(unsigned long)fsdata;
2504 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2505 switch (ext4_inode_journal_mode(inode)) {
2506 case EXT4_INODE_ORDERED_DATA_MODE:
2507 return ext4_ordered_write_end(file, mapping, pos,
2508 len, copied, page, fsdata);
2509 case EXT4_INODE_WRITEBACK_DATA_MODE:
2510 return ext4_writeback_write_end(file, mapping, pos,
2511 len, copied, page, fsdata);
2517 trace_ext4_da_write_end(inode, pos, len, copied);
2518 start = pos & (PAGE_CACHE_SIZE - 1);
2519 end = start + copied - 1;
2522 * generic_write_end() will run mark_inode_dirty() if i_size
2523 * changes. So let's piggyback the i_disksize mark_inode_dirty
2527 new_i_size = pos + copied;
2528 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2529 if (ext4_da_should_update_i_disksize(page, end)) {
2530 down_write(&EXT4_I(inode)->i_data_sem);
2531 if (new_i_size > EXT4_I(inode)->i_disksize) {
2533 * Updating i_disksize when extending file
2534 * without needing block allocation
2536 if (ext4_should_order_data(inode))
2537 ret = ext4_jbd2_file_inode(handle,
2540 EXT4_I(inode)->i_disksize = new_i_size;
2542 up_write(&EXT4_I(inode)->i_data_sem);
2543 /* We need to mark inode dirty even if
2544 * new_i_size is less that inode->i_size
2545 * bu greater than i_disksize.(hint delalloc)
2547 ext4_mark_inode_dirty(handle, inode);
2550 ret2 = generic_write_end(file, mapping, pos, len, copied,
2555 ret2 = ext4_journal_stop(handle);
2559 return ret ? ret : copied;
2562 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2565 * Drop reserved blocks
2567 BUG_ON(!PageLocked(page));
2568 if (!page_has_buffers(page))
2571 ext4_da_page_release_reservation(page, offset);
2574 ext4_invalidatepage(page, offset);
2580 * Force all delayed allocation blocks to be allocated for a given inode.
2582 int ext4_alloc_da_blocks(struct inode *inode)
2584 trace_ext4_alloc_da_blocks(inode);
2586 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2587 !EXT4_I(inode)->i_reserved_meta_blocks)
2591 * We do something simple for now. The filemap_flush() will
2592 * also start triggering a write of the data blocks, which is
2593 * not strictly speaking necessary (and for users of
2594 * laptop_mode, not even desirable). However, to do otherwise
2595 * would require replicating code paths in:
2597 * ext4_da_writepages() ->
2598 * write_cache_pages() ---> (via passed in callback function)
2599 * __mpage_da_writepage() -->
2600 * mpage_add_bh_to_extent()
2601 * mpage_da_map_blocks()
2603 * The problem is that write_cache_pages(), located in
2604 * mm/page-writeback.c, marks pages clean in preparation for
2605 * doing I/O, which is not desirable if we're not planning on
2608 * We could call write_cache_pages(), and then redirty all of
2609 * the pages by calling redirty_page_for_writepage() but that
2610 * would be ugly in the extreme. So instead we would need to
2611 * replicate parts of the code in the above functions,
2612 * simplifying them because we wouldn't actually intend to
2613 * write out the pages, but rather only collect contiguous
2614 * logical block extents, call the multi-block allocator, and
2615 * then update the buffer heads with the block allocations.
2617 * For now, though, we'll cheat by calling filemap_flush(),
2618 * which will map the blocks, and start the I/O, but not
2619 * actually wait for the I/O to complete.
2621 return filemap_flush(inode->i_mapping);
2625 * bmap() is special. It gets used by applications such as lilo and by
2626 * the swapper to find the on-disk block of a specific piece of data.
2628 * Naturally, this is dangerous if the block concerned is still in the
2629 * journal. If somebody makes a swapfile on an ext4 data-journaling
2630 * filesystem and enables swap, then they may get a nasty shock when the
2631 * data getting swapped to that swapfile suddenly gets overwritten by
2632 * the original zero's written out previously to the journal and
2633 * awaiting writeback in the kernel's buffer cache.
2635 * So, if we see any bmap calls here on a modified, data-journaled file,
2636 * take extra steps to flush any blocks which might be in the cache.
2638 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2640 struct inode *inode = mapping->host;
2644 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2645 test_opt(inode->i_sb, DELALLOC)) {
2647 * With delalloc we want to sync the file
2648 * so that we can make sure we allocate
2651 filemap_write_and_wait(mapping);
2654 if (EXT4_JOURNAL(inode) &&
2655 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2657 * This is a REALLY heavyweight approach, but the use of
2658 * bmap on dirty files is expected to be extremely rare:
2659 * only if we run lilo or swapon on a freshly made file
2660 * do we expect this to happen.
2662 * (bmap requires CAP_SYS_RAWIO so this does not
2663 * represent an unprivileged user DOS attack --- we'd be
2664 * in trouble if mortal users could trigger this path at
2667 * NB. EXT4_STATE_JDATA is not set on files other than
2668 * regular files. If somebody wants to bmap a directory
2669 * or symlink and gets confused because the buffer
2670 * hasn't yet been flushed to disk, they deserve
2671 * everything they get.
2674 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2675 journal = EXT4_JOURNAL(inode);
2676 jbd2_journal_lock_updates(journal);
2677 err = jbd2_journal_flush(journal);
2678 jbd2_journal_unlock_updates(journal);
2684 return generic_block_bmap(mapping, block, ext4_get_block);
2687 static int ext4_readpage(struct file *file, struct page *page)
2689 trace_ext4_readpage(page);
2690 return mpage_readpage(page, ext4_get_block);
2694 ext4_readpages(struct file *file, struct address_space *mapping,
2695 struct list_head *pages, unsigned nr_pages)
2697 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2700 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2702 struct buffer_head *head, *bh;
2703 unsigned int curr_off = 0;
2705 if (!page_has_buffers(page))
2707 head = bh = page_buffers(page);
2709 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2711 ext4_free_io_end(bh->b_private);
2712 bh->b_private = NULL;
2713 bh->b_end_io = NULL;
2715 curr_off = curr_off + bh->b_size;
2716 bh = bh->b_this_page;
2717 } while (bh != head);
2720 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2722 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2724 trace_ext4_invalidatepage(page, offset);
2727 * free any io_end structure allocated for buffers to be discarded
2729 if (ext4_should_dioread_nolock(page->mapping->host))
2730 ext4_invalidatepage_free_endio(page, offset);
2732 * If it's a full truncate we just forget about the pending dirtying
2735 ClearPageChecked(page);
2738 jbd2_journal_invalidatepage(journal, page, offset);
2740 block_invalidatepage(page, offset);
2743 static int ext4_releasepage(struct page *page, gfp_t wait)
2745 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2747 trace_ext4_releasepage(page);
2749 WARN_ON(PageChecked(page));
2750 if (!page_has_buffers(page))
2753 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2755 return try_to_free_buffers(page);
2759 * ext4_get_block used when preparing for a DIO write or buffer write.
2760 * We allocate an uinitialized extent if blocks haven't been allocated.
2761 * The extent will be converted to initialized after the IO is complete.
2763 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2764 struct buffer_head *bh_result, int create)
2766 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2767 inode->i_ino, create);
2768 return _ext4_get_block(inode, iblock, bh_result,
2769 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2772 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2773 ssize_t size, void *private, int ret,
2776 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2777 ext4_io_end_t *io_end = iocb->private;
2778 struct workqueue_struct *wq;
2779 unsigned long flags;
2780 struct ext4_inode_info *ei;
2782 /* if not async direct IO or dio with 0 bytes write, just return */
2783 if (!io_end || !size)
2786 ext_debug("ext4_end_io_dio(): io_end 0x%p"
2787 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2788 iocb->private, io_end->inode->i_ino, iocb, offset,
2791 iocb->private = NULL;
2793 /* if not aio dio with unwritten extents, just free io and return */
2794 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2795 ext4_free_io_end(io_end);
2798 aio_complete(iocb, ret, 0);
2799 inode_dio_done(inode);
2803 io_end->offset = offset;
2804 io_end->size = size;
2806 io_end->iocb = iocb;
2807 io_end->result = ret;
2809 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2811 /* Add the io_end to per-inode completed aio dio list*/
2812 ei = EXT4_I(io_end->inode);
2813 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2814 list_add_tail(&io_end->list, &ei->i_completed_io_list);
2815 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2817 /* queue the work to convert unwritten extents to written */
2818 queue_work(wq, &io_end->work);
2821 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2823 ext4_io_end_t *io_end = bh->b_private;
2824 struct workqueue_struct *wq;
2825 struct inode *inode;
2826 unsigned long flags;
2828 if (!test_clear_buffer_uninit(bh) || !io_end)
2831 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2832 printk("sb umounted, discard end_io request for inode %lu\n",
2833 io_end->inode->i_ino);
2834 ext4_free_io_end(io_end);
2839 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2840 * but being more careful is always safe for the future change.
2842 inode = io_end->inode;
2843 ext4_set_io_unwritten_flag(inode, io_end);
2845 /* Add the io_end to per-inode completed io list*/
2846 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2847 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2848 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2850 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2851 /* queue the work to convert unwritten extents to written */
2852 queue_work(wq, &io_end->work);
2854 bh->b_private = NULL;
2855 bh->b_end_io = NULL;
2856 clear_buffer_uninit(bh);
2857 end_buffer_async_write(bh, uptodate);
2860 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2862 ext4_io_end_t *io_end;
2863 struct page *page = bh->b_page;
2864 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2865 size_t size = bh->b_size;
2868 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2870 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2874 io_end->offset = offset;
2875 io_end->size = size;
2877 * We need to hold a reference to the page to make sure it
2878 * doesn't get evicted before ext4_end_io_work() has a chance
2879 * to convert the extent from written to unwritten.
2881 io_end->page = page;
2882 get_page(io_end->page);
2884 bh->b_private = io_end;
2885 bh->b_end_io = ext4_end_io_buffer_write;
2890 * For ext4 extent files, ext4 will do direct-io write to holes,
2891 * preallocated extents, and those write extend the file, no need to
2892 * fall back to buffered IO.
2894 * For holes, we fallocate those blocks, mark them as uninitialized
2895 * If those blocks were preallocated, we mark sure they are splited, but
2896 * still keep the range to write as uninitialized.
2898 * The unwrritten extents will be converted to written when DIO is completed.
2899 * For async direct IO, since the IO may still pending when return, we
2900 * set up an end_io call back function, which will do the conversion
2901 * when async direct IO completed.
2903 * If the O_DIRECT write will extend the file then add this inode to the
2904 * orphan list. So recovery will truncate it back to the original size
2905 * if the machine crashes during the write.
2908 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2909 const struct iovec *iov, loff_t offset,
2910 unsigned long nr_segs)
2912 struct file *file = iocb->ki_filp;
2913 struct inode *inode = file->f_mapping->host;
2915 size_t count = iov_length(iov, nr_segs);
2917 loff_t final_size = offset + count;
2918 if (rw == WRITE && final_size <= inode->i_size) {
2920 * We could direct write to holes and fallocate.
2922 * Allocated blocks to fill the hole are marked as uninitialized
2923 * to prevent parallel buffered read to expose the stale data
2924 * before DIO complete the data IO.
2926 * As to previously fallocated extents, ext4 get_block
2927 * will just simply mark the buffer mapped but still
2928 * keep the extents uninitialized.
2930 * for non AIO case, we will convert those unwritten extents
2931 * to written after return back from blockdev_direct_IO.
2933 * for async DIO, the conversion needs to be defered when
2934 * the IO is completed. The ext4 end_io callback function
2935 * will be called to take care of the conversion work.
2936 * Here for async case, we allocate an io_end structure to
2939 iocb->private = NULL;
2940 EXT4_I(inode)->cur_aio_dio = NULL;
2941 if (!is_sync_kiocb(iocb)) {
2942 ext4_io_end_t *io_end =
2943 ext4_init_io_end(inode, GFP_NOFS);
2946 io_end->flag |= EXT4_IO_END_DIRECT;
2947 iocb->private = io_end;
2949 * we save the io structure for current async
2950 * direct IO, so that later ext4_map_blocks()
2951 * could flag the io structure whether there
2952 * is a unwritten extents needs to be converted
2953 * when IO is completed.
2955 EXT4_I(inode)->cur_aio_dio = iocb->private;
2958 ret = __blockdev_direct_IO(rw, iocb, inode,
2959 inode->i_sb->s_bdev, iov,
2961 ext4_get_block_write,
2964 DIO_LOCKING | DIO_SKIP_HOLES);
2966 EXT4_I(inode)->cur_aio_dio = NULL;
2968 * The io_end structure takes a reference to the inode,
2969 * that structure needs to be destroyed and the
2970 * reference to the inode need to be dropped, when IO is
2971 * complete, even with 0 byte write, or failed.
2973 * In the successful AIO DIO case, the io_end structure will be
2974 * desctroyed and the reference to the inode will be dropped
2975 * after the end_io call back function is called.
2977 * In the case there is 0 byte write, or error case, since
2978 * VFS direct IO won't invoke the end_io call back function,
2979 * we need to free the end_io structure here.
2981 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
2982 ext4_free_io_end(iocb->private);
2983 iocb->private = NULL;
2984 } else if (ret > 0 && ext4_test_inode_state(inode,
2985 EXT4_STATE_DIO_UNWRITTEN)) {
2988 * for non AIO case, since the IO is already
2989 * completed, we could do the conversion right here
2991 err = ext4_convert_unwritten_extents(inode,
2995 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3000 /* for write the the end of file case, we fall back to old way */
3001 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3004 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3005 const struct iovec *iov, loff_t offset,
3006 unsigned long nr_segs)
3008 struct file *file = iocb->ki_filp;
3009 struct inode *inode = file->f_mapping->host;
3013 * If we are doing data journalling we don't support O_DIRECT
3015 if (ext4_should_journal_data(inode))
3018 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3019 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3020 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3022 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3023 trace_ext4_direct_IO_exit(inode, offset,
3024 iov_length(iov, nr_segs), rw, ret);
3029 * Pages can be marked dirty completely asynchronously from ext4's journalling
3030 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3031 * much here because ->set_page_dirty is called under VFS locks. The page is
3032 * not necessarily locked.
3034 * We cannot just dirty the page and leave attached buffers clean, because the
3035 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3036 * or jbddirty because all the journalling code will explode.
3038 * So what we do is to mark the page "pending dirty" and next time writepage
3039 * is called, propagate that into the buffers appropriately.
3041 static int ext4_journalled_set_page_dirty(struct page *page)
3043 SetPageChecked(page);
3044 return __set_page_dirty_nobuffers(page);
3047 static const struct address_space_operations ext4_ordered_aops = {
3048 .readpage = ext4_readpage,
3049 .readpages = ext4_readpages,
3050 .writepage = ext4_writepage,
3051 .write_begin = ext4_write_begin,
3052 .write_end = ext4_ordered_write_end,
3054 .invalidatepage = ext4_invalidatepage,
3055 .releasepage = ext4_releasepage,
3056 .direct_IO = ext4_direct_IO,
3057 .migratepage = buffer_migrate_page,
3058 .is_partially_uptodate = block_is_partially_uptodate,
3059 .error_remove_page = generic_error_remove_page,
3062 static const struct address_space_operations ext4_writeback_aops = {
3063 .readpage = ext4_readpage,
3064 .readpages = ext4_readpages,
3065 .writepage = ext4_writepage,
3066 .write_begin = ext4_write_begin,
3067 .write_end = ext4_writeback_write_end,
3069 .invalidatepage = ext4_invalidatepage,
3070 .releasepage = ext4_releasepage,
3071 .direct_IO = ext4_direct_IO,
3072 .migratepage = buffer_migrate_page,
3073 .is_partially_uptodate = block_is_partially_uptodate,
3074 .error_remove_page = generic_error_remove_page,
3077 static const struct address_space_operations ext4_journalled_aops = {
3078 .readpage = ext4_readpage,
3079 .readpages = ext4_readpages,
3080 .writepage = ext4_writepage,
3081 .write_begin = ext4_write_begin,
3082 .write_end = ext4_journalled_write_end,
3083 .set_page_dirty = ext4_journalled_set_page_dirty,
3085 .invalidatepage = ext4_invalidatepage,
3086 .releasepage = ext4_releasepage,
3087 .direct_IO = ext4_direct_IO,
3088 .is_partially_uptodate = block_is_partially_uptodate,
3089 .error_remove_page = generic_error_remove_page,
3092 static const struct address_space_operations ext4_da_aops = {
3093 .readpage = ext4_readpage,
3094 .readpages = ext4_readpages,
3095 .writepage = ext4_writepage,
3096 .writepages = ext4_da_writepages,
3097 .write_begin = ext4_da_write_begin,
3098 .write_end = ext4_da_write_end,
3100 .invalidatepage = ext4_da_invalidatepage,
3101 .releasepage = ext4_releasepage,
3102 .direct_IO = ext4_direct_IO,
3103 .migratepage = buffer_migrate_page,
3104 .is_partially_uptodate = block_is_partially_uptodate,
3105 .error_remove_page = generic_error_remove_page,
3108 void ext4_set_aops(struct inode *inode)
3110 switch (ext4_inode_journal_mode(inode)) {
3111 case EXT4_INODE_ORDERED_DATA_MODE:
3112 if (test_opt(inode->i_sb, DELALLOC))
3113 inode->i_mapping->a_ops = &ext4_da_aops;
3115 inode->i_mapping->a_ops = &ext4_ordered_aops;
3117 case EXT4_INODE_WRITEBACK_DATA_MODE:
3118 if (test_opt(inode->i_sb, DELALLOC))
3119 inode->i_mapping->a_ops = &ext4_da_aops;
3121 inode->i_mapping->a_ops = &ext4_writeback_aops;
3123 case EXT4_INODE_JOURNAL_DATA_MODE:
3124 inode->i_mapping->a_ops = &ext4_journalled_aops;
3133 * ext4_discard_partial_page_buffers()
3134 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3135 * This function finds and locks the page containing the offset
3136 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3137 * Calling functions that already have the page locked should call
3138 * ext4_discard_partial_page_buffers_no_lock directly.
3140 int ext4_discard_partial_page_buffers(handle_t *handle,
3141 struct address_space *mapping, loff_t from,
3142 loff_t length, int flags)
3144 struct inode *inode = mapping->host;
3148 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3149 mapping_gfp_mask(mapping) & ~__GFP_FS);
3153 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3154 from, length, flags);
3157 page_cache_release(page);
3162 * ext4_discard_partial_page_buffers_no_lock()
3163 * Zeros a page range of length 'length' starting from offset 'from'.
3164 * Buffer heads that correspond to the block aligned regions of the
3165 * zeroed range will be unmapped. Unblock aligned regions
3166 * will have the corresponding buffer head mapped if needed so that
3167 * that region of the page can be updated with the partial zero out.
3169 * This function assumes that the page has already been locked. The
3170 * The range to be discarded must be contained with in the given page.
3171 * If the specified range exceeds the end of the page it will be shortened
3172 * to the end of the page that corresponds to 'from'. This function is
3173 * appropriate for updating a page and it buffer heads to be unmapped and
3174 * zeroed for blocks that have been either released, or are going to be
3177 * handle: The journal handle
3178 * inode: The files inode
3179 * page: A locked page that contains the offset "from"
3180 * from: The starting byte offset (from the begining of the file)
3181 * to begin discarding
3182 * len: The length of bytes to discard
3183 * flags: Optional flags that may be used:
3185 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3186 * Only zero the regions of the page whose buffer heads
3187 * have already been unmapped. This flag is appropriate
3188 * for updateing the contents of a page whose blocks may
3189 * have already been released, and we only want to zero
3190 * out the regions that correspond to those released blocks.
3192 * Returns zero on sucess or negative on failure.
3194 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3195 struct inode *inode, struct page *page, loff_t from,
3196 loff_t length, int flags)
3198 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3199 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3200 unsigned int blocksize, max, pos;
3202 struct buffer_head *bh;
3205 blocksize = inode->i_sb->s_blocksize;
3206 max = PAGE_CACHE_SIZE - offset;
3208 if (index != page->index)
3212 * correct length if it does not fall between
3213 * 'from' and the end of the page
3215 if (length > max || length < 0)
3218 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3220 if (!page_has_buffers(page))
3221 create_empty_buffers(page, blocksize, 0);
3223 /* Find the buffer that contains "offset" */
3224 bh = page_buffers(page);
3226 while (offset >= pos) {
3227 bh = bh->b_this_page;
3233 while (pos < offset + length) {
3234 unsigned int end_of_block, range_to_discard;
3238 /* The length of space left to zero and unmap */
3239 range_to_discard = offset + length - pos;
3241 /* The length of space until the end of the block */
3242 end_of_block = blocksize - (pos & (blocksize-1));
3245 * Do not unmap or zero past end of block
3246 * for this buffer head
3248 if (range_to_discard > end_of_block)
3249 range_to_discard = end_of_block;
3253 * Skip this buffer head if we are only zeroing unampped
3254 * regions of the page
3256 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3260 /* If the range is block aligned, unmap */
3261 if (range_to_discard == blocksize) {
3262 clear_buffer_dirty(bh);
3264 clear_buffer_mapped(bh);
3265 clear_buffer_req(bh);
3266 clear_buffer_new(bh);
3267 clear_buffer_delay(bh);
3268 clear_buffer_unwritten(bh);
3269 clear_buffer_uptodate(bh);
3270 zero_user(page, pos, range_to_discard);
3271 BUFFER_TRACE(bh, "Buffer discarded");
3276 * If this block is not completely contained in the range
3277 * to be discarded, then it is not going to be released. Because
3278 * we need to keep this block, we need to make sure this part
3279 * of the page is uptodate before we modify it by writeing
3280 * partial zeros on it.
3282 if (!buffer_mapped(bh)) {
3284 * Buffer head must be mapped before we can read
3287 BUFFER_TRACE(bh, "unmapped");
3288 ext4_get_block(inode, iblock, bh, 0);
3289 /* unmapped? It's a hole - nothing to do */
3290 if (!buffer_mapped(bh)) {
3291 BUFFER_TRACE(bh, "still unmapped");
3296 /* Ok, it's mapped. Make sure it's up-to-date */
3297 if (PageUptodate(page))
3298 set_buffer_uptodate(bh);
3300 if (!buffer_uptodate(bh)) {
3302 ll_rw_block(READ, 1, &bh);
3304 /* Uhhuh. Read error. Complain and punt.*/
3305 if (!buffer_uptodate(bh))
3309 if (ext4_should_journal_data(inode)) {
3310 BUFFER_TRACE(bh, "get write access");
3311 err = ext4_journal_get_write_access(handle, bh);
3316 zero_user(page, pos, range_to_discard);
3319 if (ext4_should_journal_data(inode)) {
3320 err = ext4_handle_dirty_metadata(handle, inode, bh);
3322 mark_buffer_dirty(bh);
3324 BUFFER_TRACE(bh, "Partial buffer zeroed");
3326 bh = bh->b_this_page;
3328 pos += range_to_discard;
3335 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3336 * up to the end of the block which corresponds to `from'.
3337 * This required during truncate. We need to physically zero the tail end
3338 * of that block so it doesn't yield old data if the file is later grown.
3340 int ext4_block_truncate_page(handle_t *handle,
3341 struct address_space *mapping, loff_t from)
3343 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3346 struct inode *inode = mapping->host;
3348 blocksize = inode->i_sb->s_blocksize;
3349 length = blocksize - (offset & (blocksize - 1));
3351 return ext4_block_zero_page_range(handle, mapping, from, length);
3355 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3356 * starting from file offset 'from'. The range to be zero'd must
3357 * be contained with in one block. If the specified range exceeds
3358 * the end of the block it will be shortened to end of the block
3359 * that cooresponds to 'from'
3361 int ext4_block_zero_page_range(handle_t *handle,
3362 struct address_space *mapping, loff_t from, loff_t length)
3364 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3365 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3366 unsigned blocksize, max, pos;
3368 struct inode *inode = mapping->host;
3369 struct buffer_head *bh;
3373 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3374 mapping_gfp_mask(mapping) & ~__GFP_FS);
3378 blocksize = inode->i_sb->s_blocksize;
3379 max = blocksize - (offset & (blocksize - 1));
3382 * correct length if it does not fall between
3383 * 'from' and the end of the block
3385 if (length > max || length < 0)
3388 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3390 if (!page_has_buffers(page))
3391 create_empty_buffers(page, blocksize, 0);
3393 /* Find the buffer that contains "offset" */
3394 bh = page_buffers(page);
3396 while (offset >= pos) {
3397 bh = bh->b_this_page;
3403 if (buffer_freed(bh)) {
3404 BUFFER_TRACE(bh, "freed: skip");
3408 if (!buffer_mapped(bh)) {
3409 BUFFER_TRACE(bh, "unmapped");
3410 ext4_get_block(inode, iblock, bh, 0);
3411 /* unmapped? It's a hole - nothing to do */
3412 if (!buffer_mapped(bh)) {
3413 BUFFER_TRACE(bh, "still unmapped");
3418 /* Ok, it's mapped. Make sure it's up-to-date */
3419 if (PageUptodate(page))
3420 set_buffer_uptodate(bh);
3422 if (!buffer_uptodate(bh)) {
3424 ll_rw_block(READ, 1, &bh);
3426 /* Uhhuh. Read error. Complain and punt. */
3427 if (!buffer_uptodate(bh))
3431 if (ext4_should_journal_data(inode)) {
3432 BUFFER_TRACE(bh, "get write access");
3433 err = ext4_journal_get_write_access(handle, bh);
3438 zero_user(page, offset, length);
3440 BUFFER_TRACE(bh, "zeroed end of block");
3443 if (ext4_should_journal_data(inode)) {
3444 err = ext4_handle_dirty_metadata(handle, inode, bh);
3446 mark_buffer_dirty(bh);
3450 page_cache_release(page);
3454 int ext4_can_truncate(struct inode *inode)
3456 if (S_ISREG(inode->i_mode))
3458 if (S_ISDIR(inode->i_mode))
3460 if (S_ISLNK(inode->i_mode))
3461 return !ext4_inode_is_fast_symlink(inode);
3466 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3467 * associated with the given offset and length
3469 * @inode: File inode
3470 * @offset: The offset where the hole will begin
3471 * @len: The length of the hole
3473 * Returns: 0 on sucess or negative on failure
3476 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3478 struct inode *inode = file->f_path.dentry->d_inode;
3479 if (!S_ISREG(inode->i_mode))
3482 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3483 /* TODO: Add support for non extent hole punching */
3487 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3488 /* TODO: Add support for bigalloc file systems */
3492 return ext4_ext_punch_hole(file, offset, length);
3498 * We block out ext4_get_block() block instantiations across the entire
3499 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3500 * simultaneously on behalf of the same inode.
3502 * As we work through the truncate and commmit bits of it to the journal there
3503 * is one core, guiding principle: the file's tree must always be consistent on
3504 * disk. We must be able to restart the truncate after a crash.
3506 * The file's tree may be transiently inconsistent in memory (although it
3507 * probably isn't), but whenever we close off and commit a journal transaction,
3508 * the contents of (the filesystem + the journal) must be consistent and
3509 * restartable. It's pretty simple, really: bottom up, right to left (although
3510 * left-to-right works OK too).
3512 * Note that at recovery time, journal replay occurs *before* the restart of
3513 * truncate against the orphan inode list.
3515 * The committed inode has the new, desired i_size (which is the same as
3516 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3517 * that this inode's truncate did not complete and it will again call
3518 * ext4_truncate() to have another go. So there will be instantiated blocks
3519 * to the right of the truncation point in a crashed ext4 filesystem. But
3520 * that's fine - as long as they are linked from the inode, the post-crash
3521 * ext4_truncate() run will find them and release them.
3523 void ext4_truncate(struct inode *inode)
3525 trace_ext4_truncate_enter(inode);
3527 if (!ext4_can_truncate(inode))
3530 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3532 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3533 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3535 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3536 ext4_ext_truncate(inode);
3538 ext4_ind_truncate(inode);
3540 trace_ext4_truncate_exit(inode);
3544 * ext4_get_inode_loc returns with an extra refcount against the inode's
3545 * underlying buffer_head on success. If 'in_mem' is true, we have all
3546 * data in memory that is needed to recreate the on-disk version of this
3549 static int __ext4_get_inode_loc(struct inode *inode,
3550 struct ext4_iloc *iloc, int in_mem)
3552 struct ext4_group_desc *gdp;
3553 struct buffer_head *bh;
3554 struct super_block *sb = inode->i_sb;
3556 int inodes_per_block, inode_offset;
3559 if (!ext4_valid_inum(sb, inode->i_ino))
3562 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3563 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3568 * Figure out the offset within the block group inode table
3570 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3571 inode_offset = ((inode->i_ino - 1) %
3572 EXT4_INODES_PER_GROUP(sb));
3573 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3574 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3576 bh = sb_getblk(sb, block);
3578 EXT4_ERROR_INODE_BLOCK(inode, block,
3579 "unable to read itable block");
3582 if (!buffer_uptodate(bh)) {
3586 * If the buffer has the write error flag, we have failed
3587 * to write out another inode in the same block. In this
3588 * case, we don't have to read the block because we may
3589 * read the old inode data successfully.
3591 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3592 set_buffer_uptodate(bh);
3594 if (buffer_uptodate(bh)) {
3595 /* someone brought it uptodate while we waited */
3601 * If we have all information of the inode in memory and this
3602 * is the only valid inode in the block, we need not read the
3606 struct buffer_head *bitmap_bh;
3609 start = inode_offset & ~(inodes_per_block - 1);
3611 /* Is the inode bitmap in cache? */
3612 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3617 * If the inode bitmap isn't in cache then the
3618 * optimisation may end up performing two reads instead
3619 * of one, so skip it.
3621 if (!buffer_uptodate(bitmap_bh)) {
3625 for (i = start; i < start + inodes_per_block; i++) {
3626 if (i == inode_offset)
3628 if (ext4_test_bit(i, bitmap_bh->b_data))
3632 if (i == start + inodes_per_block) {
3633 /* all other inodes are free, so skip I/O */
3634 memset(bh->b_data, 0, bh->b_size);
3635 set_buffer_uptodate(bh);
3643 * If we need to do any I/O, try to pre-readahead extra
3644 * blocks from the inode table.
3646 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3647 ext4_fsblk_t b, end, table;
3650 table = ext4_inode_table(sb, gdp);
3651 /* s_inode_readahead_blks is always a power of 2 */
3652 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3655 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3656 num = EXT4_INODES_PER_GROUP(sb);
3657 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3658 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3659 num -= ext4_itable_unused_count(sb, gdp);
3660 table += num / inodes_per_block;
3664 sb_breadahead(sb, b++);
3668 * There are other valid inodes in the buffer, this inode
3669 * has in-inode xattrs, or we don't have this inode in memory.
3670 * Read the block from disk.
3672 trace_ext4_load_inode(inode);
3674 bh->b_end_io = end_buffer_read_sync;
3675 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3677 if (!buffer_uptodate(bh)) {
3678 EXT4_ERROR_INODE_BLOCK(inode, block,
3679 "unable to read itable block");
3689 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3691 /* We have all inode data except xattrs in memory here. */
3692 return __ext4_get_inode_loc(inode, iloc,
3693 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3696 void ext4_set_inode_flags(struct inode *inode)
3698 unsigned int flags = EXT4_I(inode)->i_flags;
3700 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3701 if (flags & EXT4_SYNC_FL)
3702 inode->i_flags |= S_SYNC;
3703 if (flags & EXT4_APPEND_FL)
3704 inode->i_flags |= S_APPEND;
3705 if (flags & EXT4_IMMUTABLE_FL)
3706 inode->i_flags |= S_IMMUTABLE;
3707 if (flags & EXT4_NOATIME_FL)
3708 inode->i_flags |= S_NOATIME;
3709 if (flags & EXT4_DIRSYNC_FL)
3710 inode->i_flags |= S_DIRSYNC;
3713 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3714 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3716 unsigned int vfs_fl;
3717 unsigned long old_fl, new_fl;
3720 vfs_fl = ei->vfs_inode.i_flags;
3721 old_fl = ei->i_flags;
3722 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3723 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3725 if (vfs_fl & S_SYNC)
3726 new_fl |= EXT4_SYNC_FL;
3727 if (vfs_fl & S_APPEND)
3728 new_fl |= EXT4_APPEND_FL;
3729 if (vfs_fl & S_IMMUTABLE)
3730 new_fl |= EXT4_IMMUTABLE_FL;
3731 if (vfs_fl & S_NOATIME)
3732 new_fl |= EXT4_NOATIME_FL;
3733 if (vfs_fl & S_DIRSYNC)
3734 new_fl |= EXT4_DIRSYNC_FL;
3735 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3738 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3739 struct ext4_inode_info *ei)
3742 struct inode *inode = &(ei->vfs_inode);
3743 struct super_block *sb = inode->i_sb;
3745 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3746 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3747 /* we are using combined 48 bit field */
3748 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3749 le32_to_cpu(raw_inode->i_blocks_lo);
3750 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3751 /* i_blocks represent file system block size */
3752 return i_blocks << (inode->i_blkbits - 9);
3757 return le32_to_cpu(raw_inode->i_blocks_lo);
3761 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3763 struct ext4_iloc iloc;
3764 struct ext4_inode *raw_inode;
3765 struct ext4_inode_info *ei;
3766 struct inode *inode;
3767 journal_t *journal = EXT4_SB(sb)->s_journal;
3771 inode = iget_locked(sb, ino);
3773 return ERR_PTR(-ENOMEM);
3774 if (!(inode->i_state & I_NEW))
3780 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3783 raw_inode = ext4_raw_inode(&iloc);
3784 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3785 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3786 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3787 if (!(test_opt(inode->i_sb, NO_UID32))) {
3788 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3789 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3791 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3793 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3794 ei->i_dir_start_lookup = 0;
3795 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3796 /* We now have enough fields to check if the inode was active or not.
3797 * This is needed because nfsd might try to access dead inodes
3798 * the test is that same one that e2fsck uses
3799 * NeilBrown 1999oct15
3801 if (inode->i_nlink == 0) {
3802 if (inode->i_mode == 0 ||
3803 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3804 /* this inode is deleted */
3808 /* The only unlinked inodes we let through here have
3809 * valid i_mode and are being read by the orphan
3810 * recovery code: that's fine, we're about to complete
3811 * the process of deleting those. */
3813 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3814 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3815 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3816 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3818 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3819 inode->i_size = ext4_isize(raw_inode);
3820 ei->i_disksize = inode->i_size;
3822 ei->i_reserved_quota = 0;
3824 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3825 ei->i_block_group = iloc.block_group;
3826 ei->i_last_alloc_group = ~0;
3828 * NOTE! The in-memory inode i_data array is in little-endian order
3829 * even on big-endian machines: we do NOT byteswap the block numbers!
3831 for (block = 0; block < EXT4_N_BLOCKS; block++)
3832 ei->i_data[block] = raw_inode->i_block[block];
3833 INIT_LIST_HEAD(&ei->i_orphan);
3836 * Set transaction id's of transactions that have to be committed
3837 * to finish f[data]sync. We set them to currently running transaction
3838 * as we cannot be sure that the inode or some of its metadata isn't
3839 * part of the transaction - the inode could have been reclaimed and
3840 * now it is reread from disk.
3843 transaction_t *transaction;
3846 read_lock(&journal->j_state_lock);
3847 if (journal->j_running_transaction)
3848 transaction = journal->j_running_transaction;
3850 transaction = journal->j_committing_transaction;
3852 tid = transaction->t_tid;
3854 tid = journal->j_commit_sequence;
3855 read_unlock(&journal->j_state_lock);
3856 ei->i_sync_tid = tid;
3857 ei->i_datasync_tid = tid;
3860 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3861 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3862 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3863 EXT4_INODE_SIZE(inode->i_sb)) {
3867 if (ei->i_extra_isize == 0) {
3868 /* The extra space is currently unused. Use it. */
3869 ei->i_extra_isize = sizeof(struct ext4_inode) -
3870 EXT4_GOOD_OLD_INODE_SIZE;
3872 __le32 *magic = (void *)raw_inode +
3873 EXT4_GOOD_OLD_INODE_SIZE +
3875 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3876 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3879 ei->i_extra_isize = 0;
3881 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3882 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3883 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3884 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3886 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3887 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3888 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3890 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3894 if (ei->i_file_acl &&
3895 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3896 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3900 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3901 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3902 (S_ISLNK(inode->i_mode) &&
3903 !ext4_inode_is_fast_symlink(inode)))
3904 /* Validate extent which is part of inode */
3905 ret = ext4_ext_check_inode(inode);
3906 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3907 (S_ISLNK(inode->i_mode) &&
3908 !ext4_inode_is_fast_symlink(inode))) {
3909 /* Validate block references which are part of inode */
3910 ret = ext4_ind_check_inode(inode);
3915 if (S_ISREG(inode->i_mode)) {
3916 inode->i_op = &ext4_file_inode_operations;
3917 inode->i_fop = &ext4_file_operations;
3918 ext4_set_aops(inode);
3919 } else if (S_ISDIR(inode->i_mode)) {
3920 inode->i_op = &ext4_dir_inode_operations;
3921 inode->i_fop = &ext4_dir_operations;
3922 } else if (S_ISLNK(inode->i_mode)) {
3923 if (ext4_inode_is_fast_symlink(inode)) {
3924 inode->i_op = &ext4_fast_symlink_inode_operations;
3925 nd_terminate_link(ei->i_data, inode->i_size,
3926 sizeof(ei->i_data) - 1);
3928 inode->i_op = &ext4_symlink_inode_operations;
3929 ext4_set_aops(inode);
3931 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3932 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3933 inode->i_op = &ext4_special_inode_operations;
3934 if (raw_inode->i_block[0])
3935 init_special_inode(inode, inode->i_mode,
3936 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3938 init_special_inode(inode, inode->i_mode,
3939 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3942 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3946 ext4_set_inode_flags(inode);
3947 unlock_new_inode(inode);
3953 return ERR_PTR(ret);
3956 static int ext4_inode_blocks_set(handle_t *handle,
3957 struct ext4_inode *raw_inode,
3958 struct ext4_inode_info *ei)
3960 struct inode *inode = &(ei->vfs_inode);
3961 u64 i_blocks = inode->i_blocks;
3962 struct super_block *sb = inode->i_sb;
3964 if (i_blocks <= ~0U) {
3966 * i_blocks can be represnted in a 32 bit variable
3967 * as multiple of 512 bytes
3969 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3970 raw_inode->i_blocks_high = 0;
3971 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3974 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3977 if (i_blocks <= 0xffffffffffffULL) {
3979 * i_blocks can be represented in a 48 bit variable
3980 * as multiple of 512 bytes
3982 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3983 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3984 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3986 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3987 /* i_block is stored in file system block size */
3988 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3989 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3990 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3996 * Post the struct inode info into an on-disk inode location in the
3997 * buffer-cache. This gobbles the caller's reference to the
3998 * buffer_head in the inode location struct.
4000 * The caller must have write access to iloc->bh.
4002 static int ext4_do_update_inode(handle_t *handle,
4003 struct inode *inode,
4004 struct ext4_iloc *iloc)
4006 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4007 struct ext4_inode_info *ei = EXT4_I(inode);
4008 struct buffer_head *bh = iloc->bh;
4009 int err = 0, rc, block;
4011 /* For fields not not tracking in the in-memory inode,
4012 * initialise them to zero for new inodes. */
4013 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4014 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4016 ext4_get_inode_flags(ei);
4017 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4018 if (!(test_opt(inode->i_sb, NO_UID32))) {
4019 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4020 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4022 * Fix up interoperability with old kernels. Otherwise, old inodes get
4023 * re-used with the upper 16 bits of the uid/gid intact
4026 raw_inode->i_uid_high =
4027 cpu_to_le16(high_16_bits(inode->i_uid));
4028 raw_inode->i_gid_high =
4029 cpu_to_le16(high_16_bits(inode->i_gid));
4031 raw_inode->i_uid_high = 0;
4032 raw_inode->i_gid_high = 0;
4035 raw_inode->i_uid_low =
4036 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4037 raw_inode->i_gid_low =
4038 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4039 raw_inode->i_uid_high = 0;
4040 raw_inode->i_gid_high = 0;
4042 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4044 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4045 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4046 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4047 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4049 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4051 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4052 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4053 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4054 cpu_to_le32(EXT4_OS_HURD))
4055 raw_inode->i_file_acl_high =
4056 cpu_to_le16(ei->i_file_acl >> 32);
4057 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4058 ext4_isize_set(raw_inode, ei->i_disksize);
4059 if (ei->i_disksize > 0x7fffffffULL) {
4060 struct super_block *sb = inode->i_sb;
4061 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4062 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4063 EXT4_SB(sb)->s_es->s_rev_level ==
4064 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4065 /* If this is the first large file
4066 * created, add a flag to the superblock.
4068 err = ext4_journal_get_write_access(handle,
4069 EXT4_SB(sb)->s_sbh);
4072 ext4_update_dynamic_rev(sb);
4073 EXT4_SET_RO_COMPAT_FEATURE(sb,
4074 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4076 ext4_handle_sync(handle);
4077 err = ext4_handle_dirty_metadata(handle, NULL,
4078 EXT4_SB(sb)->s_sbh);
4081 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4082 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4083 if (old_valid_dev(inode->i_rdev)) {
4084 raw_inode->i_block[0] =
4085 cpu_to_le32(old_encode_dev(inode->i_rdev));
4086 raw_inode->i_block[1] = 0;
4088 raw_inode->i_block[0] = 0;
4089 raw_inode->i_block[1] =
4090 cpu_to_le32(new_encode_dev(inode->i_rdev));
4091 raw_inode->i_block[2] = 0;
4094 for (block = 0; block < EXT4_N_BLOCKS; block++)
4095 raw_inode->i_block[block] = ei->i_data[block];
4097 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4098 if (ei->i_extra_isize) {
4099 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4100 raw_inode->i_version_hi =
4101 cpu_to_le32(inode->i_version >> 32);
4102 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4105 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4106 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4109 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4111 ext4_update_inode_fsync_trans(handle, inode, 0);
4114 ext4_std_error(inode->i_sb, err);
4119 * ext4_write_inode()
4121 * We are called from a few places:
4123 * - Within generic_file_write() for O_SYNC files.
4124 * Here, there will be no transaction running. We wait for any running
4125 * trasnaction to commit.
4127 * - Within sys_sync(), kupdate and such.
4128 * We wait on commit, if tol to.
4130 * - Within prune_icache() (PF_MEMALLOC == true)
4131 * Here we simply return. We can't afford to block kswapd on the
4134 * In all cases it is actually safe for us to return without doing anything,
4135 * because the inode has been copied into a raw inode buffer in
4136 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4139 * Note that we are absolutely dependent upon all inode dirtiers doing the
4140 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4141 * which we are interested.
4143 * It would be a bug for them to not do this. The code:
4145 * mark_inode_dirty(inode)
4147 * inode->i_size = expr;
4149 * is in error because a kswapd-driven write_inode() could occur while
4150 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4151 * will no longer be on the superblock's dirty inode list.
4153 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4157 if (current->flags & PF_MEMALLOC)
4160 if (EXT4_SB(inode->i_sb)->s_journal) {
4161 if (ext4_journal_current_handle()) {
4162 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4167 if (wbc->sync_mode != WB_SYNC_ALL)
4170 err = ext4_force_commit(inode->i_sb);
4172 struct ext4_iloc iloc;
4174 err = __ext4_get_inode_loc(inode, &iloc, 0);
4177 if (wbc->sync_mode == WB_SYNC_ALL)
4178 sync_dirty_buffer(iloc.bh);
4179 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4180 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4181 "IO error syncing inode");
4192 * Called from notify_change.
4194 * We want to trap VFS attempts to truncate the file as soon as
4195 * possible. In particular, we want to make sure that when the VFS
4196 * shrinks i_size, we put the inode on the orphan list and modify
4197 * i_disksize immediately, so that during the subsequent flushing of
4198 * dirty pages and freeing of disk blocks, we can guarantee that any
4199 * commit will leave the blocks being flushed in an unused state on
4200 * disk. (On recovery, the inode will get truncated and the blocks will
4201 * be freed, so we have a strong guarantee that no future commit will
4202 * leave these blocks visible to the user.)
4204 * Another thing we have to assure is that if we are in ordered mode
4205 * and inode is still attached to the committing transaction, we must
4206 * we start writeout of all the dirty pages which are being truncated.
4207 * This way we are sure that all the data written in the previous
4208 * transaction are already on disk (truncate waits for pages under
4211 * Called with inode->i_mutex down.
4213 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4215 struct inode *inode = dentry->d_inode;
4218 const unsigned int ia_valid = attr->ia_valid;
4220 error = inode_change_ok(inode, attr);
4224 if (is_quota_modification(inode, attr))
4225 dquot_initialize(inode);
4226 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4227 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4230 /* (user+group)*(old+new) structure, inode write (sb,
4231 * inode block, ? - but truncate inode update has it) */
4232 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4233 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4234 if (IS_ERR(handle)) {
4235 error = PTR_ERR(handle);
4238 error = dquot_transfer(inode, attr);
4240 ext4_journal_stop(handle);
4243 /* Update corresponding info in inode so that everything is in
4244 * one transaction */
4245 if (attr->ia_valid & ATTR_UID)
4246 inode->i_uid = attr->ia_uid;
4247 if (attr->ia_valid & ATTR_GID)
4248 inode->i_gid = attr->ia_gid;
4249 error = ext4_mark_inode_dirty(handle, inode);
4250 ext4_journal_stop(handle);
4253 if (attr->ia_valid & ATTR_SIZE) {
4254 inode_dio_wait(inode);
4256 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4257 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4259 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4264 if (S_ISREG(inode->i_mode) &&
4265 attr->ia_valid & ATTR_SIZE &&
4266 (attr->ia_size < inode->i_size)) {
4269 handle = ext4_journal_start(inode, 3);
4270 if (IS_ERR(handle)) {
4271 error = PTR_ERR(handle);
4274 if (ext4_handle_valid(handle)) {
4275 error = ext4_orphan_add(handle, inode);
4278 EXT4_I(inode)->i_disksize = attr->ia_size;
4279 rc = ext4_mark_inode_dirty(handle, inode);
4282 ext4_journal_stop(handle);
4284 if (ext4_should_order_data(inode)) {
4285 error = ext4_begin_ordered_truncate(inode,
4288 /* Do as much error cleanup as possible */
4289 handle = ext4_journal_start(inode, 3);
4290 if (IS_ERR(handle)) {
4291 ext4_orphan_del(NULL, inode);
4294 ext4_orphan_del(handle, inode);
4296 ext4_journal_stop(handle);
4302 if (attr->ia_valid & ATTR_SIZE) {
4303 if (attr->ia_size != i_size_read(inode)) {
4304 truncate_setsize(inode, attr->ia_size);
4305 ext4_truncate(inode);
4306 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4307 ext4_truncate(inode);
4311 setattr_copy(inode, attr);
4312 mark_inode_dirty(inode);
4316 * If the call to ext4_truncate failed to get a transaction handle at
4317 * all, we need to clean up the in-core orphan list manually.
4319 if (orphan && inode->i_nlink)
4320 ext4_orphan_del(NULL, inode);
4322 if (!rc && (ia_valid & ATTR_MODE))
4323 rc = ext4_acl_chmod(inode);
4326 ext4_std_error(inode->i_sb, error);
4332 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4335 struct inode *inode;
4336 unsigned long delalloc_blocks;
4338 inode = dentry->d_inode;
4339 generic_fillattr(inode, stat);
4342 * We can't update i_blocks if the block allocation is delayed
4343 * otherwise in the case of system crash before the real block
4344 * allocation is done, we will have i_blocks inconsistent with
4345 * on-disk file blocks.
4346 * We always keep i_blocks updated together with real
4347 * allocation. But to not confuse with user, stat
4348 * will return the blocks that include the delayed allocation
4349 * blocks for this file.
4351 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4353 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4357 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4359 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4360 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4361 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4365 * Account for index blocks, block groups bitmaps and block group
4366 * descriptor blocks if modify datablocks and index blocks
4367 * worse case, the indexs blocks spread over different block groups
4369 * If datablocks are discontiguous, they are possible to spread over
4370 * different block groups too. If they are contiuguous, with flexbg,
4371 * they could still across block group boundary.
4373 * Also account for superblock, inode, quota and xattr blocks
4375 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4377 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4383 * How many index blocks need to touch to modify nrblocks?
4384 * The "Chunk" flag indicating whether the nrblocks is
4385 * physically contiguous on disk
4387 * For Direct IO and fallocate, they calls get_block to allocate
4388 * one single extent at a time, so they could set the "Chunk" flag
4390 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4395 * Now let's see how many group bitmaps and group descriptors need
4405 if (groups > ngroups)
4407 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4408 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4410 /* bitmaps and block group descriptor blocks */
4411 ret += groups + gdpblocks;
4413 /* Blocks for super block, inode, quota and xattr blocks */
4414 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4420 * Calculate the total number of credits to reserve to fit
4421 * the modification of a single pages into a single transaction,
4422 * which may include multiple chunks of block allocations.
4424 * This could be called via ext4_write_begin()
4426 * We need to consider the worse case, when
4427 * one new block per extent.
4429 int ext4_writepage_trans_blocks(struct inode *inode)
4431 int bpp = ext4_journal_blocks_per_page(inode);
4434 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4436 /* Account for data blocks for journalled mode */
4437 if (ext4_should_journal_data(inode))
4443 * Calculate the journal credits for a chunk of data modification.
4445 * This is called from DIO, fallocate or whoever calling
4446 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4448 * journal buffers for data blocks are not included here, as DIO
4449 * and fallocate do no need to journal data buffers.
4451 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4453 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4457 * The caller must have previously called ext4_reserve_inode_write().
4458 * Give this, we know that the caller already has write access to iloc->bh.
4460 int ext4_mark_iloc_dirty(handle_t *handle,
4461 struct inode *inode, struct ext4_iloc *iloc)
4465 if (test_opt(inode->i_sb, I_VERSION))
4466 inode_inc_iversion(inode);
4468 /* the do_update_inode consumes one bh->b_count */
4471 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4472 err = ext4_do_update_inode(handle, inode, iloc);
4478 * On success, We end up with an outstanding reference count against
4479 * iloc->bh. This _must_ be cleaned up later.
4483 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4484 struct ext4_iloc *iloc)
4488 err = ext4_get_inode_loc(inode, iloc);
4490 BUFFER_TRACE(iloc->bh, "get_write_access");
4491 err = ext4_journal_get_write_access(handle, iloc->bh);
4497 ext4_std_error(inode->i_sb, err);
4502 * Expand an inode by new_extra_isize bytes.
4503 * Returns 0 on success or negative error number on failure.
4505 static int ext4_expand_extra_isize(struct inode *inode,
4506 unsigned int new_extra_isize,
4507 struct ext4_iloc iloc,
4510 struct ext4_inode *raw_inode;
4511 struct ext4_xattr_ibody_header *header;
4513 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4516 raw_inode = ext4_raw_inode(&iloc);
4518 header = IHDR(inode, raw_inode);
4520 /* No extended attributes present */
4521 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4522 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4523 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4525 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4529 /* try to expand with EAs present */
4530 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4535 * What we do here is to mark the in-core inode as clean with respect to inode
4536 * dirtiness (it may still be data-dirty).
4537 * This means that the in-core inode may be reaped by prune_icache
4538 * without having to perform any I/O. This is a very good thing,
4539 * because *any* task may call prune_icache - even ones which
4540 * have a transaction open against a different journal.
4542 * Is this cheating? Not really. Sure, we haven't written the
4543 * inode out, but prune_icache isn't a user-visible syncing function.
4544 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4545 * we start and wait on commits.
4547 * Is this efficient/effective? Well, we're being nice to the system
4548 * by cleaning up our inodes proactively so they can be reaped
4549 * without I/O. But we are potentially leaving up to five seconds'
4550 * worth of inodes floating about which prune_icache wants us to
4551 * write out. One way to fix that would be to get prune_icache()
4552 * to do a write_super() to free up some memory. It has the desired
4555 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4557 struct ext4_iloc iloc;
4558 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4559 static unsigned int mnt_count;
4563 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4564 err = ext4_reserve_inode_write(handle, inode, &iloc);
4565 if (ext4_handle_valid(handle) &&
4566 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4567 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4569 * We need extra buffer credits since we may write into EA block
4570 * with this same handle. If journal_extend fails, then it will
4571 * only result in a minor loss of functionality for that inode.
4572 * If this is felt to be critical, then e2fsck should be run to
4573 * force a large enough s_min_extra_isize.
4575 if ((jbd2_journal_extend(handle,
4576 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4577 ret = ext4_expand_extra_isize(inode,
4578 sbi->s_want_extra_isize,
4581 ext4_set_inode_state(inode,
4582 EXT4_STATE_NO_EXPAND);
4584 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4585 ext4_warning(inode->i_sb,
4586 "Unable to expand inode %lu. Delete"
4587 " some EAs or run e2fsck.",
4590 le16_to_cpu(sbi->s_es->s_mnt_count);
4596 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4601 * ext4_dirty_inode() is called from __mark_inode_dirty()
4603 * We're really interested in the case where a file is being extended.
4604 * i_size has been changed by generic_commit_write() and we thus need
4605 * to include the updated inode in the current transaction.
4607 * Also, dquot_alloc_block() will always dirty the inode when blocks
4608 * are allocated to the file.
4610 * If the inode is marked synchronous, we don't honour that here - doing
4611 * so would cause a commit on atime updates, which we don't bother doing.
4612 * We handle synchronous inodes at the highest possible level.
4614 void ext4_dirty_inode(struct inode *inode, int flags)
4618 handle = ext4_journal_start(inode, 2);
4622 ext4_mark_inode_dirty(handle, inode);
4624 ext4_journal_stop(handle);
4631 * Bind an inode's backing buffer_head into this transaction, to prevent
4632 * it from being flushed to disk early. Unlike
4633 * ext4_reserve_inode_write, this leaves behind no bh reference and
4634 * returns no iloc structure, so the caller needs to repeat the iloc
4635 * lookup to mark the inode dirty later.
4637 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4639 struct ext4_iloc iloc;
4643 err = ext4_get_inode_loc(inode, &iloc);
4645 BUFFER_TRACE(iloc.bh, "get_write_access");
4646 err = jbd2_journal_get_write_access(handle, iloc.bh);
4648 err = ext4_handle_dirty_metadata(handle,
4654 ext4_std_error(inode->i_sb, err);
4659 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4666 * We have to be very careful here: changing a data block's
4667 * journaling status dynamically is dangerous. If we write a
4668 * data block to the journal, change the status and then delete
4669 * that block, we risk forgetting to revoke the old log record
4670 * from the journal and so a subsequent replay can corrupt data.
4671 * So, first we make sure that the journal is empty and that
4672 * nobody is changing anything.
4675 journal = EXT4_JOURNAL(inode);
4678 if (is_journal_aborted(journal))
4681 jbd2_journal_lock_updates(journal);
4682 jbd2_journal_flush(journal);
4685 * OK, there are no updates running now, and all cached data is
4686 * synced to disk. We are now in a completely consistent state
4687 * which doesn't have anything in the journal, and we know that
4688 * no filesystem updates are running, so it is safe to modify
4689 * the inode's in-core data-journaling state flag now.
4693 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4695 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4696 ext4_set_aops(inode);
4698 jbd2_journal_unlock_updates(journal);
4700 /* Finally we can mark the inode as dirty. */
4702 handle = ext4_journal_start(inode, 1);
4704 return PTR_ERR(handle);
4706 err = ext4_mark_inode_dirty(handle, inode);
4707 ext4_handle_sync(handle);
4708 ext4_journal_stop(handle);
4709 ext4_std_error(inode->i_sb, err);
4714 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4716 return !buffer_mapped(bh);
4719 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4721 struct page *page = vmf->page;
4725 struct file *file = vma->vm_file;
4726 struct inode *inode = file->f_path.dentry->d_inode;
4727 struct address_space *mapping = inode->i_mapping;
4729 get_block_t *get_block;
4733 * This check is racy but catches the common case. We rely on
4734 * __block_page_mkwrite() to do a reliable check.
4736 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4737 /* Delalloc case is easy... */
4738 if (test_opt(inode->i_sb, DELALLOC) &&
4739 !ext4_should_journal_data(inode) &&
4740 !ext4_nonda_switch(inode->i_sb)) {
4742 ret = __block_page_mkwrite(vma, vmf,
4743 ext4_da_get_block_prep);
4744 } while (ret == -ENOSPC &&
4745 ext4_should_retry_alloc(inode->i_sb, &retries));
4750 size = i_size_read(inode);
4751 /* Page got truncated from under us? */
4752 if (page->mapping != mapping || page_offset(page) > size) {
4754 ret = VM_FAULT_NOPAGE;
4758 if (page->index == size >> PAGE_CACHE_SHIFT)
4759 len = size & ~PAGE_CACHE_MASK;
4761 len = PAGE_CACHE_SIZE;
4763 * Return if we have all the buffers mapped. This avoids the need to do
4764 * journal_start/journal_stop which can block and take a long time
4766 if (page_has_buffers(page)) {
4767 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4768 ext4_bh_unmapped)) {
4769 /* Wait so that we don't change page under IO */
4770 wait_on_page_writeback(page);
4771 ret = VM_FAULT_LOCKED;
4776 /* OK, we need to fill the hole... */
4777 if (ext4_should_dioread_nolock(inode))
4778 get_block = ext4_get_block_write;
4780 get_block = ext4_get_block;
4782 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4783 if (IS_ERR(handle)) {
4784 ret = VM_FAULT_SIGBUS;
4787 ret = __block_page_mkwrite(vma, vmf, get_block);
4788 if (!ret && ext4_should_journal_data(inode)) {
4789 if (walk_page_buffers(handle, page_buffers(page), 0,
4790 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4792 ret = VM_FAULT_SIGBUS;
4793 ext4_journal_stop(handle);
4796 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4798 ext4_journal_stop(handle);
4799 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4802 ret = block_page_mkwrite_return(ret);