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>
41 #include <linux/bitops.h>
43 #include "ext4_jbd2.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static inline int ext4_begin_ordered_truncate(struct inode *inode,
55 trace_ext4_begin_ordered_truncate(inode, new_size);
57 * If jinode is zero, then we never opened the file for
58 * writing, so there's no need to call
59 * jbd2_journal_begin_ordered_truncate() since there's no
60 * outstanding writes we need to flush.
62 if (!EXT4_I(inode)->jinode)
64 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
65 EXT4_I(inode)->jinode,
69 static void ext4_invalidatepage(struct page *page, unsigned long offset);
70 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
71 struct buffer_head *bh_result, int create);
72 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
73 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
74 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
75 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
78 * Test whether an inode is a fast symlink.
80 static int ext4_inode_is_fast_symlink(struct inode *inode)
82 int ea_blocks = EXT4_I(inode)->i_file_acl ?
83 (inode->i_sb->s_blocksize >> 9) : 0;
85 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
89 * Restart the transaction associated with *handle. This does a commit,
90 * so before we call here everything must be consistently dirtied against
93 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
99 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
100 * moment, get_block can be called only for blocks inside i_size since
101 * page cache has been already dropped and writes are blocked by
102 * i_mutex. So we can safely drop the i_data_sem here.
104 BUG_ON(EXT4_JOURNAL(inode) == NULL);
105 jbd_debug(2, "restarting handle %p\n", handle);
106 up_write(&EXT4_I(inode)->i_data_sem);
107 ret = ext4_journal_restart(handle, nblocks);
108 down_write(&EXT4_I(inode)->i_data_sem);
109 ext4_discard_preallocations(inode);
115 * Called at the last iput() if i_nlink is zero.
117 void ext4_evict_inode(struct inode *inode)
122 trace_ext4_evict_inode(inode);
124 ext4_ioend_wait(inode);
126 if (inode->i_nlink) {
128 * When journalling data dirty buffers are tracked only in the
129 * journal. So although mm thinks everything is clean and
130 * ready for reaping the inode might still have some pages to
131 * write in the running transaction or waiting to be
132 * checkpointed. Thus calling jbd2_journal_invalidatepage()
133 * (via truncate_inode_pages()) to discard these buffers can
134 * cause data loss. Also even if we did not discard these
135 * buffers, we would have no way to find them after the inode
136 * is reaped and thus user could see stale data if he tries to
137 * read them before the transaction is checkpointed. So be
138 * careful and force everything to disk here... We use
139 * ei->i_datasync_tid to store the newest transaction
140 * containing inode's data.
142 * Note that directories do not have this problem because they
143 * don't use page cache.
145 if (ext4_should_journal_data(inode) &&
146 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
147 inode->i_ino != EXT4_JOURNAL_INO) {
148 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
149 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
151 jbd2_complete_transaction(journal, commit_tid);
152 filemap_write_and_wait(&inode->i_data);
154 truncate_inode_pages(&inode->i_data, 0);
158 if (!is_bad_inode(inode))
159 dquot_initialize(inode);
161 if (ext4_should_order_data(inode))
162 ext4_begin_ordered_truncate(inode, 0);
163 truncate_inode_pages(&inode->i_data, 0);
165 if (is_bad_inode(inode))
168 handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
169 if (IS_ERR(handle)) {
170 ext4_std_error(inode->i_sb, PTR_ERR(handle));
172 * If we're going to skip the normal cleanup, we still need to
173 * make sure that the in-core orphan linked list is properly
176 ext4_orphan_del(NULL, inode);
181 ext4_handle_sync(handle);
183 err = ext4_mark_inode_dirty(handle, inode);
185 ext4_warning(inode->i_sb,
186 "couldn't mark inode dirty (err %d)", err);
190 ext4_truncate(inode);
193 * ext4_ext_truncate() doesn't reserve any slop when it
194 * restarts journal transactions; therefore there may not be
195 * enough credits left in the handle to remove the inode from
196 * the orphan list and set the dtime field.
198 if (!ext4_handle_has_enough_credits(handle, 3)) {
199 err = ext4_journal_extend(handle, 3);
201 err = ext4_journal_restart(handle, 3);
203 ext4_warning(inode->i_sb,
204 "couldn't extend journal (err %d)", err);
206 ext4_journal_stop(handle);
207 ext4_orphan_del(NULL, inode);
213 * Kill off the orphan record which ext4_truncate created.
214 * AKPM: I think this can be inside the above `if'.
215 * Note that ext4_orphan_del() has to be able to cope with the
216 * deletion of a non-existent orphan - this is because we don't
217 * know if ext4_truncate() actually created an orphan record.
218 * (Well, we could do this if we need to, but heck - it works)
220 ext4_orphan_del(handle, inode);
221 EXT4_I(inode)->i_dtime = get_seconds();
224 * One subtle ordering requirement: if anything has gone wrong
225 * (transaction abort, IO errors, whatever), then we can still
226 * do these next steps (the fs will already have been marked as
227 * having errors), but we can't free the inode if the mark_dirty
230 if (ext4_mark_inode_dirty(handle, inode))
231 /* If that failed, just do the required in-core inode clear. */
232 ext4_clear_inode(inode);
234 ext4_free_inode(handle, inode);
235 ext4_journal_stop(handle);
238 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
242 qsize_t *ext4_get_reserved_space(struct inode *inode)
244 return &EXT4_I(inode)->i_reserved_quota;
249 * Calculate the number of metadata blocks need to reserve
250 * to allocate a block located at @lblock
252 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
254 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
255 return ext4_ext_calc_metadata_amount(inode, lblock);
257 return ext4_ind_calc_metadata_amount(inode, lblock);
261 * Called with i_data_sem down, which is important since we can call
262 * ext4_discard_preallocations() from here.
264 void ext4_da_update_reserve_space(struct inode *inode,
265 int used, int quota_claim)
267 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
268 struct ext4_inode_info *ei = EXT4_I(inode);
270 spin_lock(&ei->i_block_reservation_lock);
271 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
272 if (unlikely(used > ei->i_reserved_data_blocks)) {
273 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
274 "with only %d reserved data blocks\n",
275 __func__, inode->i_ino, used,
276 ei->i_reserved_data_blocks);
278 used = ei->i_reserved_data_blocks;
281 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
282 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, allocated %d "
283 "with only %d reserved metadata blocks\n", __func__,
284 inode->i_ino, ei->i_allocated_meta_blocks,
285 ei->i_reserved_meta_blocks);
287 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
290 /* Update per-inode reservations */
291 ei->i_reserved_data_blocks -= used;
292 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
293 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
294 used + ei->i_allocated_meta_blocks);
295 ei->i_allocated_meta_blocks = 0;
297 if (ei->i_reserved_data_blocks == 0) {
299 * We can release all of the reserved metadata blocks
300 * only when we have written all of the delayed
303 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
304 ei->i_reserved_meta_blocks);
305 ei->i_reserved_meta_blocks = 0;
306 ei->i_da_metadata_calc_len = 0;
308 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
310 /* Update quota subsystem for data blocks */
312 dquot_claim_block(inode, EXT4_C2B(sbi, used));
315 * We did fallocate with an offset that is already delayed
316 * allocated. So on delayed allocated writeback we should
317 * not re-claim the quota for fallocated blocks.
319 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
323 * If we have done all the pending block allocations and if
324 * there aren't any writers on the inode, we can discard the
325 * inode's preallocations.
327 if ((ei->i_reserved_data_blocks == 0) &&
328 (atomic_read(&inode->i_writecount) == 0))
329 ext4_discard_preallocations(inode);
332 static int __check_block_validity(struct inode *inode, const char *func,
334 struct ext4_map_blocks *map)
336 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
338 ext4_error_inode(inode, func, line, map->m_pblk,
339 "lblock %lu mapped to illegal pblock "
340 "(length %d)", (unsigned long) map->m_lblk,
347 #define check_block_validity(inode, map) \
348 __check_block_validity((inode), __func__, __LINE__, (map))
351 * Return the number of contiguous dirty pages in a given inode
352 * starting at page frame idx.
354 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
355 unsigned int max_pages)
357 struct address_space *mapping = inode->i_mapping;
361 int i, nr_pages, done = 0;
365 pagevec_init(&pvec, 0);
368 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
370 (pgoff_t)PAGEVEC_SIZE);
373 for (i = 0; i < nr_pages; i++) {
374 struct page *page = pvec.pages[i];
375 struct buffer_head *bh, *head;
378 if (unlikely(page->mapping != mapping) ||
380 PageWriteback(page) ||
381 page->index != idx) {
386 if (page_has_buffers(page)) {
387 bh = head = page_buffers(page);
389 if (!buffer_delay(bh) &&
390 !buffer_unwritten(bh))
392 bh = bh->b_this_page;
393 } while (!done && (bh != head));
400 if (num >= max_pages) {
405 pagevec_release(&pvec);
411 * Sets the BH_Da_Mapped bit on the buffer heads corresponding to the given map.
413 static void set_buffers_da_mapped(struct inode *inode,
414 struct ext4_map_blocks *map)
416 struct address_space *mapping = inode->i_mapping;
421 index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
422 end = (map->m_lblk + map->m_len - 1) >>
423 (PAGE_CACHE_SHIFT - inode->i_blkbits);
425 pagevec_init(&pvec, 0);
426 while (index <= end) {
427 nr_pages = pagevec_lookup(&pvec, mapping, index,
429 (pgoff_t)PAGEVEC_SIZE));
432 for (i = 0; i < nr_pages; i++) {
433 struct page *page = pvec.pages[i];
434 struct buffer_head *bh, *head;
436 if (unlikely(page->mapping != mapping) ||
440 if (page_has_buffers(page)) {
441 bh = head = page_buffers(page);
443 set_buffer_da_mapped(bh);
444 bh = bh->b_this_page;
445 } while (bh != head);
449 pagevec_release(&pvec);
454 * The ext4_map_blocks() function tries to look up the requested blocks,
455 * and returns if the blocks are already mapped.
457 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
458 * and store the allocated blocks in the result buffer head and mark it
461 * If file type is extents based, it will call ext4_ext_map_blocks(),
462 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
465 * On success, it returns the number of blocks being mapped or allocate.
466 * if create==0 and the blocks are pre-allocated and uninitialized block,
467 * the result buffer head is unmapped. If the create ==1, it will make sure
468 * the buffer head is mapped.
470 * It returns 0 if plain look up failed (blocks have not been allocated), in
471 * that case, buffer head is unmapped
473 * It returns the error in case of allocation failure.
475 int ext4_map_blocks(handle_t *handle, struct inode *inode,
476 struct ext4_map_blocks *map, int flags)
481 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
482 "logical block %lu\n", inode->i_ino, flags, map->m_len,
483 (unsigned long) map->m_lblk);
485 /* We can handle the block number less than EXT_MAX_BLOCKS */
486 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
490 * Try to see if we can get the block without requesting a new
493 down_read((&EXT4_I(inode)->i_data_sem));
494 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
495 retval = ext4_ext_map_blocks(handle, inode, map, flags &
496 EXT4_GET_BLOCKS_KEEP_SIZE);
498 retval = ext4_ind_map_blocks(handle, inode, map, flags &
499 EXT4_GET_BLOCKS_KEEP_SIZE);
501 up_read((&EXT4_I(inode)->i_data_sem));
503 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
504 int ret = check_block_validity(inode, map);
509 /* If it is only a block(s) look up */
510 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
514 * Returns if the blocks have already allocated
516 * Note that if blocks have been preallocated
517 * ext4_ext_get_block() returns the create = 0
518 * with buffer head unmapped.
520 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
524 * When we call get_blocks without the create flag, the
525 * BH_Unwritten flag could have gotten set if the blocks
526 * requested were part of a uninitialized extent. We need to
527 * clear this flag now that we are committed to convert all or
528 * part of the uninitialized extent to be an initialized
529 * extent. This is because we need to avoid the combination
530 * of BH_Unwritten and BH_Mapped flags being simultaneously
531 * set on the buffer_head.
533 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
536 * New blocks allocate and/or writing to uninitialized extent
537 * will possibly result in updating i_data, so we take
538 * the write lock of i_data_sem, and call get_blocks()
539 * with create == 1 flag.
541 down_write((&EXT4_I(inode)->i_data_sem));
544 * if the caller is from delayed allocation writeout path
545 * we have already reserved fs blocks for allocation
546 * let the underlying get_block() function know to
547 * avoid double accounting
549 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
550 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
552 * We need to check for EXT4 here because migrate
553 * could have changed the inode type in between
555 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
556 retval = ext4_ext_map_blocks(handle, inode, map, flags);
558 retval = ext4_ind_map_blocks(handle, inode, map, flags);
560 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
562 * We allocated new blocks which will result in
563 * i_data's format changing. Force the migrate
564 * to fail by clearing migrate flags
566 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
570 * Update reserved blocks/metadata blocks after successful
571 * block allocation which had been deferred till now. We don't
572 * support fallocate for non extent files. So we can update
573 * reserve space here.
576 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
577 ext4_da_update_reserve_space(inode, retval, 1);
579 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
580 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
582 /* If we have successfully mapped the delayed allocated blocks,
583 * set the BH_Da_Mapped bit on them. Its important to do this
584 * under the protection of i_data_sem.
586 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
587 set_buffers_da_mapped(inode, map);
590 up_write((&EXT4_I(inode)->i_data_sem));
591 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
592 int ret = check_block_validity(inode, map);
599 /* Maximum number of blocks we map for direct IO at once. */
600 #define DIO_MAX_BLOCKS 4096
602 static int _ext4_get_block(struct inode *inode, sector_t iblock,
603 struct buffer_head *bh, int flags)
605 handle_t *handle = ext4_journal_current_handle();
606 struct ext4_map_blocks map;
607 int ret = 0, started = 0;
611 map.m_len = bh->b_size >> inode->i_blkbits;
613 if (flags && !handle) {
614 /* Direct IO write... */
615 if (map.m_len > DIO_MAX_BLOCKS)
616 map.m_len = DIO_MAX_BLOCKS;
617 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
618 handle = ext4_journal_start(inode, dio_credits);
619 if (IS_ERR(handle)) {
620 ret = PTR_ERR(handle);
626 ret = ext4_map_blocks(handle, inode, &map, flags);
628 map_bh(bh, inode->i_sb, map.m_pblk);
629 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
630 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
634 ext4_journal_stop(handle);
638 int ext4_get_block(struct inode *inode, sector_t iblock,
639 struct buffer_head *bh, int create)
641 return _ext4_get_block(inode, iblock, bh,
642 create ? EXT4_GET_BLOCKS_CREATE : 0);
646 * `handle' can be NULL if create is zero
648 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
649 ext4_lblk_t block, int create, int *errp)
651 struct ext4_map_blocks map;
652 struct buffer_head *bh;
655 J_ASSERT(handle != NULL || create == 0);
659 err = ext4_map_blocks(handle, inode, &map,
660 create ? EXT4_GET_BLOCKS_CREATE : 0);
668 bh = sb_getblk(inode->i_sb, map.m_pblk);
673 if (map.m_flags & EXT4_MAP_NEW) {
674 J_ASSERT(create != 0);
675 J_ASSERT(handle != NULL);
678 * Now that we do not always journal data, we should
679 * keep in mind whether this should always journal the
680 * new buffer as metadata. For now, regular file
681 * writes use ext4_get_block instead, so it's not a
685 BUFFER_TRACE(bh, "call get_create_access");
686 fatal = ext4_journal_get_create_access(handle, bh);
687 if (!fatal && !buffer_uptodate(bh)) {
688 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
689 set_buffer_uptodate(bh);
692 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
693 err = ext4_handle_dirty_metadata(handle, inode, bh);
697 BUFFER_TRACE(bh, "not a new buffer");
707 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
708 ext4_lblk_t block, int create, int *err)
710 struct buffer_head *bh;
712 bh = ext4_getblk(handle, inode, block, create, err);
715 if (buffer_uptodate(bh))
717 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
719 if (buffer_uptodate(bh))
726 static int walk_page_buffers(handle_t *handle,
727 struct buffer_head *head,
731 int (*fn)(handle_t *handle,
732 struct buffer_head *bh))
734 struct buffer_head *bh;
735 unsigned block_start, block_end;
736 unsigned blocksize = head->b_size;
738 struct buffer_head *next;
740 for (bh = head, block_start = 0;
741 ret == 0 && (bh != head || !block_start);
742 block_start = block_end, bh = next) {
743 next = bh->b_this_page;
744 block_end = block_start + blocksize;
745 if (block_end <= from || block_start >= to) {
746 if (partial && !buffer_uptodate(bh))
750 err = (*fn)(handle, bh);
758 * To preserve ordering, it is essential that the hole instantiation and
759 * the data write be encapsulated in a single transaction. We cannot
760 * close off a transaction and start a new one between the ext4_get_block()
761 * and the commit_write(). So doing the jbd2_journal_start at the start of
762 * prepare_write() is the right place.
764 * Also, this function can nest inside ext4_writepage() ->
765 * block_write_full_page(). In that case, we *know* that ext4_writepage()
766 * has generated enough buffer credits to do the whole page. So we won't
767 * block on the journal in that case, which is good, because the caller may
770 * By accident, ext4 can be reentered when a transaction is open via
771 * quota file writes. If we were to commit the transaction while thus
772 * reentered, there can be a deadlock - we would be holding a quota
773 * lock, and the commit would never complete if another thread had a
774 * transaction open and was blocking on the quota lock - a ranking
777 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
778 * will _not_ run commit under these circumstances because handle->h_ref
779 * is elevated. We'll still have enough credits for the tiny quotafile
782 static int do_journal_get_write_access(handle_t *handle,
783 struct buffer_head *bh)
785 int dirty = buffer_dirty(bh);
788 if (!buffer_mapped(bh) || buffer_freed(bh))
791 * __block_write_begin() could have dirtied some buffers. Clean
792 * the dirty bit as jbd2_journal_get_write_access() could complain
793 * otherwise about fs integrity issues. Setting of the dirty bit
794 * by __block_write_begin() isn't a real problem here as we clear
795 * the bit before releasing a page lock and thus writeback cannot
796 * ever write the buffer.
799 clear_buffer_dirty(bh);
800 ret = ext4_journal_get_write_access(handle, bh);
802 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
806 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
807 struct buffer_head *bh_result, int create);
808 static int ext4_write_begin(struct file *file, struct address_space *mapping,
809 loff_t pos, unsigned len, unsigned flags,
810 struct page **pagep, void **fsdata)
812 struct inode *inode = mapping->host;
813 int ret, needed_blocks;
820 trace_ext4_write_begin(inode, pos, len, flags);
822 * Reserve one block more for addition to orphan list in case
823 * we allocate blocks but write fails for some reason
825 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
826 index = pos >> PAGE_CACHE_SHIFT;
827 from = pos & (PAGE_CACHE_SIZE - 1);
831 handle = ext4_journal_start(inode, needed_blocks);
832 if (IS_ERR(handle)) {
833 ret = PTR_ERR(handle);
837 /* We cannot recurse into the filesystem as the transaction is already
839 flags |= AOP_FLAG_NOFS;
841 page = grab_cache_page_write_begin(mapping, index, flags);
843 ext4_journal_stop(handle);
849 if (ext4_should_dioread_nolock(inode))
850 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
852 ret = __block_write_begin(page, pos, len, ext4_get_block);
854 if (!ret && ext4_should_journal_data(inode)) {
855 ret = walk_page_buffers(handle, page_buffers(page),
856 from, to, NULL, do_journal_get_write_access);
861 page_cache_release(page);
863 * __block_write_begin may have instantiated a few blocks
864 * outside i_size. Trim these off again. Don't need
865 * i_size_read because we hold i_mutex.
867 * Add inode to orphan list in case we crash before
870 if (pos + len > inode->i_size && ext4_can_truncate(inode))
871 ext4_orphan_add(handle, inode);
873 ext4_journal_stop(handle);
874 if (pos + len > inode->i_size) {
875 ext4_truncate_failed_write(inode);
877 * If truncate failed early the inode might
878 * still be on the orphan list; we need to
879 * make sure the inode is removed from the
880 * orphan list in that case.
883 ext4_orphan_del(NULL, inode);
887 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
893 /* For write_end() in data=journal mode */
894 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
896 if (!buffer_mapped(bh) || buffer_freed(bh))
898 set_buffer_uptodate(bh);
899 return ext4_handle_dirty_metadata(handle, NULL, bh);
902 static int ext4_generic_write_end(struct file *file,
903 struct address_space *mapping,
904 loff_t pos, unsigned len, unsigned copied,
905 struct page *page, void *fsdata)
907 int i_size_changed = 0;
908 struct inode *inode = mapping->host;
909 handle_t *handle = ext4_journal_current_handle();
911 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
914 * No need to use i_size_read() here, the i_size
915 * cannot change under us because we hold i_mutex.
917 * But it's important to update i_size while still holding page lock:
918 * page writeout could otherwise come in and zero beyond i_size.
920 if (pos + copied > inode->i_size) {
921 i_size_write(inode, pos + copied);
925 if (pos + copied > EXT4_I(inode)->i_disksize) {
926 /* We need to mark inode dirty even if
927 * new_i_size is less that inode->i_size
928 * bu greater than i_disksize.(hint delalloc)
930 ext4_update_i_disksize(inode, (pos + copied));
934 page_cache_release(page);
937 * Don't mark the inode dirty under page lock. First, it unnecessarily
938 * makes the holding time of page lock longer. Second, it forces lock
939 * ordering of page lock and transaction start for journaling
943 ext4_mark_inode_dirty(handle, inode);
949 * We need to pick up the new inode size which generic_commit_write gave us
950 * `file' can be NULL - eg, when called from page_symlink().
952 * ext4 never places buffers on inode->i_mapping->private_list. metadata
953 * buffers are managed internally.
955 static int ext4_ordered_write_end(struct file *file,
956 struct address_space *mapping,
957 loff_t pos, unsigned len, unsigned copied,
958 struct page *page, void *fsdata)
960 handle_t *handle = ext4_journal_current_handle();
961 struct inode *inode = mapping->host;
964 trace_ext4_ordered_write_end(inode, pos, len, copied);
965 ret = ext4_jbd2_file_inode(handle, inode);
968 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
971 if (pos + len > inode->i_size && ext4_can_truncate(inode))
972 /* if we have allocated more blocks and copied
973 * less. We will have blocks allocated outside
974 * inode->i_size. So truncate them
976 ext4_orphan_add(handle, inode);
981 page_cache_release(page);
984 ret2 = ext4_journal_stop(handle);
988 if (pos + len > inode->i_size) {
989 ext4_truncate_failed_write(inode);
991 * If truncate failed early the inode might still be
992 * on the orphan list; we need to make sure the inode
993 * is removed from the orphan list in that case.
996 ext4_orphan_del(NULL, inode);
1000 return ret ? ret : copied;
1003 static int ext4_writeback_write_end(struct file *file,
1004 struct address_space *mapping,
1005 loff_t pos, unsigned len, unsigned copied,
1006 struct page *page, void *fsdata)
1008 handle_t *handle = ext4_journal_current_handle();
1009 struct inode *inode = mapping->host;
1012 trace_ext4_writeback_write_end(inode, pos, len, copied);
1013 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1016 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1017 /* if we have allocated more blocks and copied
1018 * less. We will have blocks allocated outside
1019 * inode->i_size. So truncate them
1021 ext4_orphan_add(handle, inode);
1026 ret2 = ext4_journal_stop(handle);
1030 if (pos + len > inode->i_size) {
1031 ext4_truncate_failed_write(inode);
1033 * If truncate failed early the inode might still be
1034 * on the orphan list; we need to make sure the inode
1035 * is removed from the orphan list in that case.
1038 ext4_orphan_del(NULL, inode);
1041 return ret ? ret : copied;
1044 static int ext4_journalled_write_end(struct file *file,
1045 struct address_space *mapping,
1046 loff_t pos, unsigned len, unsigned copied,
1047 struct page *page, void *fsdata)
1049 handle_t *handle = ext4_journal_current_handle();
1050 struct inode *inode = mapping->host;
1056 trace_ext4_journalled_write_end(inode, pos, len, copied);
1057 from = pos & (PAGE_CACHE_SIZE - 1);
1060 BUG_ON(!ext4_handle_valid(handle));
1063 if (!PageUptodate(page))
1065 page_zero_new_buffers(page, from+copied, to);
1068 ret = walk_page_buffers(handle, page_buffers(page), from,
1069 to, &partial, write_end_fn);
1071 SetPageUptodate(page);
1072 new_i_size = pos + copied;
1073 if (new_i_size > inode->i_size)
1074 i_size_write(inode, pos+copied);
1075 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1076 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1077 if (new_i_size > EXT4_I(inode)->i_disksize) {
1078 ext4_update_i_disksize(inode, new_i_size);
1079 ret2 = ext4_mark_inode_dirty(handle, inode);
1085 page_cache_release(page);
1086 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1087 /* if we have allocated more blocks and copied
1088 * less. We will have blocks allocated outside
1089 * inode->i_size. So truncate them
1091 ext4_orphan_add(handle, inode);
1093 ret2 = ext4_journal_stop(handle);
1096 if (pos + len > inode->i_size) {
1097 ext4_truncate_failed_write(inode);
1099 * If truncate failed early the inode might still be
1100 * on the orphan list; we need to make sure the inode
1101 * is removed from the orphan list in that case.
1104 ext4_orphan_del(NULL, inode);
1107 return ret ? ret : copied;
1111 * Reserve a single cluster located at lblock
1113 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1116 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1117 struct ext4_inode_info *ei = EXT4_I(inode);
1118 unsigned int md_needed;
1120 ext4_lblk_t save_last_lblock;
1124 * We will charge metadata quota at writeout time; this saves
1125 * us from metadata over-estimation, though we may go over by
1126 * a small amount in the end. Here we just reserve for data.
1128 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1133 * recalculate the amount of metadata blocks to reserve
1134 * in order to allocate nrblocks
1135 * worse case is one extent per block
1138 spin_lock(&ei->i_block_reservation_lock);
1140 * ext4_calc_metadata_amount() has side effects, which we have
1141 * to be prepared undo if we fail to claim space.
1143 save_len = ei->i_da_metadata_calc_len;
1144 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1145 md_needed = EXT4_NUM_B2C(sbi,
1146 ext4_calc_metadata_amount(inode, lblock));
1147 trace_ext4_da_reserve_space(inode, md_needed);
1150 * We do still charge estimated metadata to the sb though;
1151 * we cannot afford to run out of free blocks.
1153 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1154 ei->i_da_metadata_calc_len = save_len;
1155 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1156 spin_unlock(&ei->i_block_reservation_lock);
1157 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1161 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1164 ei->i_reserved_data_blocks++;
1165 ei->i_reserved_meta_blocks += md_needed;
1166 spin_unlock(&ei->i_block_reservation_lock);
1168 return 0; /* success */
1171 static void ext4_da_release_space(struct inode *inode, int to_free)
1173 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1174 struct ext4_inode_info *ei = EXT4_I(inode);
1177 return; /* Nothing to release, exit */
1179 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1181 trace_ext4_da_release_space(inode, to_free);
1182 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1184 * if there aren't enough reserved blocks, then the
1185 * counter is messed up somewhere. Since this
1186 * function is called from invalidate page, it's
1187 * harmless to return without any action.
1189 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1190 "ino %lu, to_free %d with only %d reserved "
1191 "data blocks\n", inode->i_ino, to_free,
1192 ei->i_reserved_data_blocks);
1194 to_free = ei->i_reserved_data_blocks;
1196 ei->i_reserved_data_blocks -= to_free;
1198 if (ei->i_reserved_data_blocks == 0) {
1200 * We can release all of the reserved metadata blocks
1201 * only when we have written all of the delayed
1202 * allocation blocks.
1203 * Note that in case of bigalloc, i_reserved_meta_blocks,
1204 * i_reserved_data_blocks, etc. refer to number of clusters.
1206 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1207 ei->i_reserved_meta_blocks);
1208 ei->i_reserved_meta_blocks = 0;
1209 ei->i_da_metadata_calc_len = 0;
1212 /* update fs dirty data blocks counter */
1213 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1215 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1217 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1220 static void ext4_da_page_release_reservation(struct page *page,
1221 unsigned long offset)
1224 struct buffer_head *head, *bh;
1225 unsigned int curr_off = 0;
1226 struct inode *inode = page->mapping->host;
1227 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1230 head = page_buffers(page);
1233 unsigned int next_off = curr_off + bh->b_size;
1235 if ((offset <= curr_off) && (buffer_delay(bh))) {
1237 clear_buffer_delay(bh);
1238 clear_buffer_da_mapped(bh);
1240 curr_off = next_off;
1241 } while ((bh = bh->b_this_page) != head);
1243 /* If we have released all the blocks belonging to a cluster, then we
1244 * need to release the reserved space for that cluster. */
1245 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1246 while (num_clusters > 0) {
1248 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1249 ((num_clusters - 1) << sbi->s_cluster_bits);
1250 if (sbi->s_cluster_ratio == 1 ||
1251 !ext4_find_delalloc_cluster(inode, lblk, 1))
1252 ext4_da_release_space(inode, 1);
1259 * Delayed allocation stuff
1263 * mpage_da_submit_io - walks through extent of pages and try to write
1264 * them with writepage() call back
1266 * @mpd->inode: inode
1267 * @mpd->first_page: first page of the extent
1268 * @mpd->next_page: page after the last page of the extent
1270 * By the time mpage_da_submit_io() is called we expect all blocks
1271 * to be allocated. this may be wrong if allocation failed.
1273 * As pages are already locked by write_cache_pages(), we can't use it
1275 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1276 struct ext4_map_blocks *map)
1278 struct pagevec pvec;
1279 unsigned long index, end;
1280 int ret = 0, err, nr_pages, i;
1281 struct inode *inode = mpd->inode;
1282 struct address_space *mapping = inode->i_mapping;
1283 loff_t size = i_size_read(inode);
1284 unsigned int len, block_start;
1285 struct buffer_head *bh, *page_bufs = NULL;
1286 int journal_data = ext4_should_journal_data(inode);
1287 sector_t pblock = 0, cur_logical = 0;
1288 struct ext4_io_submit io_submit;
1290 BUG_ON(mpd->next_page <= mpd->first_page);
1291 memset(&io_submit, 0, sizeof(io_submit));
1293 * We need to start from the first_page to the next_page - 1
1294 * to make sure we also write the mapped dirty buffer_heads.
1295 * If we look at mpd->b_blocknr we would only be looking
1296 * at the currently mapped buffer_heads.
1298 index = mpd->first_page;
1299 end = mpd->next_page - 1;
1301 pagevec_init(&pvec, 0);
1302 while (index <= end) {
1303 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1306 for (i = 0; i < nr_pages; i++) {
1307 int commit_write = 0, skip_page = 0;
1308 struct page *page = pvec.pages[i];
1310 index = page->index;
1314 if (index == size >> PAGE_CACHE_SHIFT)
1315 len = size & ~PAGE_CACHE_MASK;
1317 len = PAGE_CACHE_SIZE;
1319 cur_logical = index << (PAGE_CACHE_SHIFT -
1321 pblock = map->m_pblk + (cur_logical -
1326 BUG_ON(!PageLocked(page));
1327 BUG_ON(PageWriteback(page));
1330 * If the page does not have buffers (for
1331 * whatever reason), try to create them using
1332 * __block_write_begin. If this fails,
1333 * skip the page and move on.
1335 if (!page_has_buffers(page)) {
1336 if (__block_write_begin(page, 0, len,
1337 noalloc_get_block_write)) {
1345 bh = page_bufs = page_buffers(page);
1350 if (map && (cur_logical >= map->m_lblk) &&
1351 (cur_logical <= (map->m_lblk +
1352 (map->m_len - 1)))) {
1353 if (buffer_delay(bh)) {
1354 clear_buffer_delay(bh);
1355 bh->b_blocknr = pblock;
1357 if (buffer_da_mapped(bh))
1358 clear_buffer_da_mapped(bh);
1359 if (buffer_unwritten(bh) ||
1361 BUG_ON(bh->b_blocknr != pblock);
1362 if (map->m_flags & EXT4_MAP_UNINIT)
1363 set_buffer_uninit(bh);
1364 clear_buffer_unwritten(bh);
1368 * skip page if block allocation undone and
1371 if (ext4_bh_delay_or_unwritten(NULL, bh))
1373 bh = bh->b_this_page;
1374 block_start += bh->b_size;
1377 } while (bh != page_bufs);
1383 /* mark the buffer_heads as dirty & uptodate */
1384 block_commit_write(page, 0, len);
1386 clear_page_dirty_for_io(page);
1388 * Delalloc doesn't support data journalling,
1389 * but eventually maybe we'll lift this
1392 if (unlikely(journal_data && PageChecked(page)))
1393 err = __ext4_journalled_writepage(page, len);
1394 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1395 err = ext4_bio_write_page(&io_submit, page,
1397 else if (buffer_uninit(page_bufs)) {
1398 ext4_set_bh_endio(page_bufs, inode);
1399 err = block_write_full_page_endio(page,
1400 noalloc_get_block_write,
1401 mpd->wbc, ext4_end_io_buffer_write);
1403 err = block_write_full_page(page,
1404 noalloc_get_block_write, mpd->wbc);
1407 mpd->pages_written++;
1409 * In error case, we have to continue because
1410 * remaining pages are still locked
1415 pagevec_release(&pvec);
1417 ext4_io_submit(&io_submit);
1421 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1425 struct pagevec pvec;
1426 struct inode *inode = mpd->inode;
1427 struct address_space *mapping = inode->i_mapping;
1429 index = mpd->first_page;
1430 end = mpd->next_page - 1;
1431 pagevec_init(&pvec, 0);
1432 while (index <= end) {
1433 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1436 for (i = 0; i < nr_pages; i++) {
1437 struct page *page = pvec.pages[i];
1438 if (page->index > end)
1440 BUG_ON(!PageLocked(page));
1441 BUG_ON(PageWriteback(page));
1442 block_invalidatepage(page, 0);
1443 ClearPageUptodate(page);
1446 index = pvec.pages[nr_pages - 1]->index + 1;
1447 pagevec_release(&pvec);
1452 static void ext4_print_free_blocks(struct inode *inode)
1454 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1455 printk(KERN_CRIT "Total free blocks count %lld\n",
1456 EXT4_C2B(EXT4_SB(inode->i_sb),
1457 ext4_count_free_clusters(inode->i_sb)));
1458 printk(KERN_CRIT "Free/Dirty block details\n");
1459 printk(KERN_CRIT "free_blocks=%lld\n",
1460 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1461 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1462 printk(KERN_CRIT "dirty_blocks=%lld\n",
1463 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1464 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1465 printk(KERN_CRIT "Block reservation details\n");
1466 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1467 EXT4_I(inode)->i_reserved_data_blocks);
1468 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1469 EXT4_I(inode)->i_reserved_meta_blocks);
1474 * mpage_da_map_and_submit - go through given space, map them
1475 * if necessary, and then submit them for I/O
1477 * @mpd - bh describing space
1479 * The function skips space we know is already mapped to disk blocks.
1482 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1484 int err, blks, get_blocks_flags;
1485 struct ext4_map_blocks map, *mapp = NULL;
1486 sector_t next = mpd->b_blocknr;
1487 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1488 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1489 handle_t *handle = NULL;
1492 * If the blocks are mapped already, or we couldn't accumulate
1493 * any blocks, then proceed immediately to the submission stage.
1495 if ((mpd->b_size == 0) ||
1496 ((mpd->b_state & (1 << BH_Mapped)) &&
1497 !(mpd->b_state & (1 << BH_Delay)) &&
1498 !(mpd->b_state & (1 << BH_Unwritten))))
1501 handle = ext4_journal_current_handle();
1505 * Call ext4_map_blocks() to allocate any delayed allocation
1506 * blocks, or to convert an uninitialized extent to be
1507 * initialized (in the case where we have written into
1508 * one or more preallocated blocks).
1510 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1511 * indicate that we are on the delayed allocation path. This
1512 * affects functions in many different parts of the allocation
1513 * call path. This flag exists primarily because we don't
1514 * want to change *many* call functions, so ext4_map_blocks()
1515 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1516 * inode's allocation semaphore is taken.
1518 * If the blocks in questions were delalloc blocks, set
1519 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1520 * variables are updated after the blocks have been allocated.
1523 map.m_len = max_blocks;
1524 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1525 if (ext4_should_dioread_nolock(mpd->inode))
1526 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1527 if (mpd->b_state & (1 << BH_Delay))
1528 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1530 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1532 struct super_block *sb = mpd->inode->i_sb;
1536 * If get block returns EAGAIN or ENOSPC and there
1537 * appears to be free blocks we will just let
1538 * mpage_da_submit_io() unlock all of the pages.
1543 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1549 * get block failure will cause us to loop in
1550 * writepages, because a_ops->writepage won't be able
1551 * to make progress. The page will be redirtied by
1552 * writepage and writepages will again try to write
1555 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1556 ext4_msg(sb, KERN_CRIT,
1557 "delayed block allocation failed for inode %lu "
1558 "at logical offset %llu with max blocks %zd "
1559 "with error %d", mpd->inode->i_ino,
1560 (unsigned long long) next,
1561 mpd->b_size >> mpd->inode->i_blkbits, err);
1562 ext4_msg(sb, KERN_CRIT,
1563 "This should not happen!! Data will be lost\n");
1565 ext4_print_free_blocks(mpd->inode);
1567 /* invalidate all the pages */
1568 ext4_da_block_invalidatepages(mpd);
1570 /* Mark this page range as having been completed */
1577 if (map.m_flags & EXT4_MAP_NEW) {
1578 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1581 for (i = 0; i < map.m_len; i++)
1582 unmap_underlying_metadata(bdev, map.m_pblk + i);
1584 if (ext4_should_order_data(mpd->inode)) {
1585 err = ext4_jbd2_file_inode(handle, mpd->inode);
1587 /* Only if the journal is aborted */
1595 * Update on-disk size along with block allocation.
1597 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1598 if (disksize > i_size_read(mpd->inode))
1599 disksize = i_size_read(mpd->inode);
1600 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1601 ext4_update_i_disksize(mpd->inode, disksize);
1602 err = ext4_mark_inode_dirty(handle, mpd->inode);
1604 ext4_error(mpd->inode->i_sb,
1605 "Failed to mark inode %lu dirty",
1610 mpage_da_submit_io(mpd, mapp);
1614 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1615 (1 << BH_Delay) | (1 << BH_Unwritten))
1618 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1620 * @mpd->lbh - extent of blocks
1621 * @logical - logical number of the block in the file
1622 * @bh - bh of the block (used to access block's state)
1624 * the function is used to collect contig. blocks in same state
1626 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1627 sector_t logical, size_t b_size,
1628 unsigned long b_state)
1631 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1634 * XXX Don't go larger than mballoc is willing to allocate
1635 * This is a stopgap solution. We eventually need to fold
1636 * mpage_da_submit_io() into this function and then call
1637 * ext4_map_blocks() multiple times in a loop
1639 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1642 /* check if thereserved journal credits might overflow */
1643 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1644 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1646 * With non-extent format we are limited by the journal
1647 * credit available. Total credit needed to insert
1648 * nrblocks contiguous blocks is dependent on the
1649 * nrblocks. So limit nrblocks.
1652 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1653 EXT4_MAX_TRANS_DATA) {
1655 * Adding the new buffer_head would make it cross the
1656 * allowed limit for which we have journal credit
1657 * reserved. So limit the new bh->b_size
1659 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1660 mpd->inode->i_blkbits;
1661 /* we will do mpage_da_submit_io in the next loop */
1665 * First block in the extent
1667 if (mpd->b_size == 0) {
1668 mpd->b_blocknr = logical;
1669 mpd->b_size = b_size;
1670 mpd->b_state = b_state & BH_FLAGS;
1674 next = mpd->b_blocknr + nrblocks;
1676 * Can we merge the block to our big extent?
1678 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1679 mpd->b_size += b_size;
1685 * We couldn't merge the block to our extent, so we
1686 * need to flush current extent and start new one
1688 mpage_da_map_and_submit(mpd);
1692 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1694 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1698 * This function is grabs code from the very beginning of
1699 * ext4_map_blocks, but assumes that the caller is from delayed write
1700 * time. This function looks up the requested blocks and sets the
1701 * buffer delay bit under the protection of i_data_sem.
1703 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1704 struct ext4_map_blocks *map,
1705 struct buffer_head *bh)
1708 sector_t invalid_block = ~((sector_t) 0xffff);
1710 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1714 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1715 "logical block %lu\n", inode->i_ino, map->m_len,
1716 (unsigned long) map->m_lblk);
1718 * Try to see if we can get the block without requesting a new
1719 * file system block.
1721 down_read((&EXT4_I(inode)->i_data_sem));
1722 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1723 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1725 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1729 * XXX: __block_prepare_write() unmaps passed block,
1732 /* If the block was allocated from previously allocated cluster,
1733 * then we dont need to reserve it again. */
1734 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1735 retval = ext4_da_reserve_space(inode, iblock);
1737 /* not enough space to reserve */
1741 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1742 * and it should not appear on the bh->b_state.
1744 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1746 map_bh(bh, inode->i_sb, invalid_block);
1748 set_buffer_delay(bh);
1752 up_read((&EXT4_I(inode)->i_data_sem));
1758 * This is a special get_blocks_t callback which is used by
1759 * ext4_da_write_begin(). It will either return mapped block or
1760 * reserve space for a single block.
1762 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1763 * We also have b_blocknr = -1 and b_bdev initialized properly
1765 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1766 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1767 * initialized properly.
1769 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1770 struct buffer_head *bh, int create)
1772 struct ext4_map_blocks map;
1775 BUG_ON(create == 0);
1776 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1778 map.m_lblk = iblock;
1782 * first, we need to know whether the block is allocated already
1783 * preallocated blocks are unmapped but should treated
1784 * the same as allocated blocks.
1786 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1790 map_bh(bh, inode->i_sb, map.m_pblk);
1791 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1793 if (buffer_unwritten(bh)) {
1794 /* A delayed write to unwritten bh should be marked
1795 * new and mapped. Mapped ensures that we don't do
1796 * get_block multiple times when we write to the same
1797 * offset and new ensures that we do proper zero out
1798 * for partial write.
1801 set_buffer_mapped(bh);
1807 * This function is used as a standard get_block_t calback function
1808 * when there is no desire to allocate any blocks. It is used as a
1809 * callback function for block_write_begin() and block_write_full_page().
1810 * These functions should only try to map a single block at a time.
1812 * Since this function doesn't do block allocations even if the caller
1813 * requests it by passing in create=1, it is critically important that
1814 * any caller checks to make sure that any buffer heads are returned
1815 * by this function are either all already mapped or marked for
1816 * delayed allocation before calling block_write_full_page(). Otherwise,
1817 * b_blocknr could be left unitialized, and the page write functions will
1818 * be taken by surprise.
1820 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1821 struct buffer_head *bh_result, int create)
1823 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1824 return _ext4_get_block(inode, iblock, bh_result, 0);
1827 static int bget_one(handle_t *handle, struct buffer_head *bh)
1833 static int bput_one(handle_t *handle, struct buffer_head *bh)
1839 static int __ext4_journalled_writepage(struct page *page,
1842 struct address_space *mapping = page->mapping;
1843 struct inode *inode = mapping->host;
1844 struct buffer_head *page_bufs;
1845 handle_t *handle = NULL;
1849 ClearPageChecked(page);
1850 page_bufs = page_buffers(page);
1852 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1853 /* As soon as we unlock the page, it can go away, but we have
1854 * references to buffers so we are safe */
1857 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1858 if (IS_ERR(handle)) {
1859 ret = PTR_ERR(handle);
1863 BUG_ON(!ext4_handle_valid(handle));
1865 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1866 do_journal_get_write_access);
1868 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1872 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1873 err = ext4_journal_stop(handle);
1877 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1878 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1883 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1884 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1887 * Note that we don't need to start a transaction unless we're journaling data
1888 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1889 * need to file the inode to the transaction's list in ordered mode because if
1890 * we are writing back data added by write(), the inode is already there and if
1891 * we are writing back data modified via mmap(), no one guarantees in which
1892 * transaction the data will hit the disk. In case we are journaling data, we
1893 * cannot start transaction directly because transaction start ranks above page
1894 * lock so we have to do some magic.
1896 * This function can get called via...
1897 * - ext4_da_writepages after taking page lock (have journal handle)
1898 * - journal_submit_inode_data_buffers (no journal handle)
1899 * - shrink_page_list via pdflush (no journal handle)
1900 * - grab_page_cache when doing write_begin (have journal handle)
1902 * We don't do any block allocation in this function. If we have page with
1903 * multiple blocks we need to write those buffer_heads that are mapped. This
1904 * is important for mmaped based write. So if we do with blocksize 1K
1905 * truncate(f, 1024);
1906 * a = mmap(f, 0, 4096);
1908 * truncate(f, 4096);
1909 * we have in the page first buffer_head mapped via page_mkwrite call back
1910 * but other bufer_heads would be unmapped but dirty(dirty done via the
1911 * do_wp_page). So writepage should write the first block. If we modify
1912 * the mmap area beyond 1024 we will again get a page_fault and the
1913 * page_mkwrite callback will do the block allocation and mark the
1914 * buffer_heads mapped.
1916 * We redirty the page if we have any buffer_heads that is either delay or
1917 * unwritten in the page.
1919 * We can get recursively called as show below.
1921 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1924 * But since we don't do any block allocation we should not deadlock.
1925 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1927 static int ext4_writepage(struct page *page,
1928 struct writeback_control *wbc)
1930 int ret = 0, commit_write = 0;
1933 struct buffer_head *page_bufs = NULL;
1934 struct inode *inode = page->mapping->host;
1936 trace_ext4_writepage(page);
1937 size = i_size_read(inode);
1938 if (page->index == size >> PAGE_CACHE_SHIFT)
1939 len = size & ~PAGE_CACHE_MASK;
1941 len = PAGE_CACHE_SIZE;
1944 * If the page does not have buffers (for whatever reason),
1945 * try to create them using __block_write_begin. If this
1946 * fails, redirty the page and move on.
1948 if (!page_has_buffers(page)) {
1949 if (__block_write_begin(page, 0, len,
1950 noalloc_get_block_write)) {
1952 redirty_page_for_writepage(wbc, page);
1958 page_bufs = page_buffers(page);
1959 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1960 ext4_bh_delay_or_unwritten)) {
1962 * We don't want to do block allocation, so redirty
1963 * the page and return. We may reach here when we do
1964 * a journal commit via journal_submit_inode_data_buffers.
1965 * We can also reach here via shrink_page_list but it
1966 * should never be for direct reclaim so warn if that
1969 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1974 /* now mark the buffer_heads as dirty and uptodate */
1975 block_commit_write(page, 0, len);
1977 if (PageChecked(page) && ext4_should_journal_data(inode))
1979 * It's mmapped pagecache. Add buffers and journal it. There
1980 * doesn't seem much point in redirtying the page here.
1982 return __ext4_journalled_writepage(page, len);
1984 if (buffer_uninit(page_bufs)) {
1985 ext4_set_bh_endio(page_bufs, inode);
1986 ret = block_write_full_page_endio(page, noalloc_get_block_write,
1987 wbc, ext4_end_io_buffer_write);
1989 ret = block_write_full_page(page, noalloc_get_block_write,
1996 * This is called via ext4_da_writepages() to
1997 * calculate the total number of credits to reserve to fit
1998 * a single extent allocation into a single transaction,
1999 * ext4_da_writpeages() will loop calling this before
2000 * the block allocation.
2003 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2005 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2008 * With non-extent format the journal credit needed to
2009 * insert nrblocks contiguous block is dependent on
2010 * number of contiguous block. So we will limit
2011 * number of contiguous block to a sane value
2013 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2014 (max_blocks > EXT4_MAX_TRANS_DATA))
2015 max_blocks = EXT4_MAX_TRANS_DATA;
2017 return ext4_chunk_trans_blocks(inode, max_blocks);
2021 * write_cache_pages_da - walk the list of dirty pages of the given
2022 * address space and accumulate pages that need writing, and call
2023 * mpage_da_map_and_submit to map a single contiguous memory region
2024 * and then write them.
2026 static int write_cache_pages_da(struct address_space *mapping,
2027 struct writeback_control *wbc,
2028 struct mpage_da_data *mpd,
2029 pgoff_t *done_index)
2031 struct buffer_head *bh, *head;
2032 struct inode *inode = mapping->host;
2033 struct pagevec pvec;
2034 unsigned int nr_pages;
2037 long nr_to_write = wbc->nr_to_write;
2038 int i, tag, ret = 0;
2040 memset(mpd, 0, sizeof(struct mpage_da_data));
2043 pagevec_init(&pvec, 0);
2044 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2045 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2047 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2048 tag = PAGECACHE_TAG_TOWRITE;
2050 tag = PAGECACHE_TAG_DIRTY;
2052 *done_index = index;
2053 while (index <= end) {
2054 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2055 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2059 for (i = 0; i < nr_pages; i++) {
2060 struct page *page = pvec.pages[i];
2063 * At this point, the page may be truncated or
2064 * invalidated (changing page->mapping to NULL), or
2065 * even swizzled back from swapper_space to tmpfs file
2066 * mapping. However, page->index will not change
2067 * because we have a reference on the page.
2069 if (page->index > end)
2072 *done_index = page->index + 1;
2075 * If we can't merge this page, and we have
2076 * accumulated an contiguous region, write it
2078 if ((mpd->next_page != page->index) &&
2079 (mpd->next_page != mpd->first_page)) {
2080 mpage_da_map_and_submit(mpd);
2081 goto ret_extent_tail;
2087 * If the page is no longer dirty, or its
2088 * mapping no longer corresponds to inode we
2089 * are writing (which means it has been
2090 * truncated or invalidated), or the page is
2091 * already under writeback and we are not
2092 * doing a data integrity writeback, skip the page
2094 if (!PageDirty(page) ||
2095 (PageWriteback(page) &&
2096 (wbc->sync_mode == WB_SYNC_NONE)) ||
2097 unlikely(page->mapping != mapping)) {
2102 wait_on_page_writeback(page);
2103 BUG_ON(PageWriteback(page));
2105 if (mpd->next_page != page->index)
2106 mpd->first_page = page->index;
2107 mpd->next_page = page->index + 1;
2108 logical = (sector_t) page->index <<
2109 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2111 if (!page_has_buffers(page)) {
2112 mpage_add_bh_to_extent(mpd, logical,
2114 (1 << BH_Dirty) | (1 << BH_Uptodate));
2116 goto ret_extent_tail;
2119 * Page with regular buffer heads,
2120 * just add all dirty ones
2122 head = page_buffers(page);
2125 BUG_ON(buffer_locked(bh));
2127 * We need to try to allocate
2128 * unmapped blocks in the same page.
2129 * Otherwise we won't make progress
2130 * with the page in ext4_writepage
2132 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2133 mpage_add_bh_to_extent(mpd, logical,
2137 goto ret_extent_tail;
2138 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2140 * mapped dirty buffer. We need
2141 * to update the b_state
2142 * because we look at b_state
2143 * in mpage_da_map_blocks. We
2144 * don't update b_size because
2145 * if we find an unmapped
2146 * buffer_head later we need to
2147 * use the b_state flag of that
2150 if (mpd->b_size == 0)
2151 mpd->b_state = bh->b_state & BH_FLAGS;
2154 } while ((bh = bh->b_this_page) != head);
2157 if (nr_to_write > 0) {
2159 if (nr_to_write == 0 &&
2160 wbc->sync_mode == WB_SYNC_NONE)
2162 * We stop writing back only if we are
2163 * not doing integrity sync. In case of
2164 * integrity sync we have to keep going
2165 * because someone may be concurrently
2166 * dirtying pages, and we might have
2167 * synced a lot of newly appeared dirty
2168 * pages, but have not synced all of the
2174 pagevec_release(&pvec);
2179 ret = MPAGE_DA_EXTENT_TAIL;
2181 pagevec_release(&pvec);
2187 static int ext4_da_writepages(struct address_space *mapping,
2188 struct writeback_control *wbc)
2191 int range_whole = 0;
2192 handle_t *handle = NULL;
2193 struct mpage_da_data mpd;
2194 struct inode *inode = mapping->host;
2195 int pages_written = 0;
2196 unsigned int max_pages;
2197 int range_cyclic, cycled = 1, io_done = 0;
2198 int needed_blocks, ret = 0;
2199 long desired_nr_to_write, nr_to_writebump = 0;
2200 loff_t range_start = wbc->range_start;
2201 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2202 pgoff_t done_index = 0;
2204 struct blk_plug plug;
2206 trace_ext4_da_writepages(inode, wbc);
2209 * No pages to write? This is mainly a kludge to avoid starting
2210 * a transaction for special inodes like journal inode on last iput()
2211 * because that could violate lock ordering on umount
2213 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2217 * If the filesystem has aborted, it is read-only, so return
2218 * right away instead of dumping stack traces later on that
2219 * will obscure the real source of the problem. We test
2220 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2221 * the latter could be true if the filesystem is mounted
2222 * read-only, and in that case, ext4_da_writepages should
2223 * *never* be called, so if that ever happens, we would want
2226 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2229 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2232 range_cyclic = wbc->range_cyclic;
2233 if (wbc->range_cyclic) {
2234 index = mapping->writeback_index;
2237 wbc->range_start = index << PAGE_CACHE_SHIFT;
2238 wbc->range_end = LLONG_MAX;
2239 wbc->range_cyclic = 0;
2242 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2243 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2247 * This works around two forms of stupidity. The first is in
2248 * the writeback code, which caps the maximum number of pages
2249 * written to be 1024 pages. This is wrong on multiple
2250 * levels; different architectues have a different page size,
2251 * which changes the maximum amount of data which gets
2252 * written. Secondly, 4 megabytes is way too small. XFS
2253 * forces this value to be 16 megabytes by multiplying
2254 * nr_to_write parameter by four, and then relies on its
2255 * allocator to allocate larger extents to make them
2256 * contiguous. Unfortunately this brings us to the second
2257 * stupidity, which is that ext4's mballoc code only allocates
2258 * at most 2048 blocks. So we force contiguous writes up to
2259 * the number of dirty blocks in the inode, or
2260 * sbi->max_writeback_mb_bump whichever is smaller.
2262 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2263 if (!range_cyclic && range_whole) {
2264 if (wbc->nr_to_write == LONG_MAX)
2265 desired_nr_to_write = wbc->nr_to_write;
2267 desired_nr_to_write = wbc->nr_to_write * 8;
2269 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2271 if (desired_nr_to_write > max_pages)
2272 desired_nr_to_write = max_pages;
2274 if (wbc->nr_to_write < desired_nr_to_write) {
2275 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2276 wbc->nr_to_write = desired_nr_to_write;
2280 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2281 tag_pages_for_writeback(mapping, index, end);
2283 blk_start_plug(&plug);
2284 while (!ret && wbc->nr_to_write > 0) {
2287 * we insert one extent at a time. So we need
2288 * credit needed for single extent allocation.
2289 * journalled mode is currently not supported
2292 BUG_ON(ext4_should_journal_data(inode));
2293 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2295 /* start a new transaction*/
2296 handle = ext4_journal_start(inode, needed_blocks);
2297 if (IS_ERR(handle)) {
2298 ret = PTR_ERR(handle);
2299 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2300 "%ld pages, ino %lu; err %d", __func__,
2301 wbc->nr_to_write, inode->i_ino, ret);
2302 blk_finish_plug(&plug);
2303 goto out_writepages;
2307 * Now call write_cache_pages_da() to find the next
2308 * contiguous region of logical blocks that need
2309 * blocks to be allocated by ext4 and submit them.
2311 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2313 * If we have a contiguous extent of pages and we
2314 * haven't done the I/O yet, map the blocks and submit
2317 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2318 mpage_da_map_and_submit(&mpd);
2319 ret = MPAGE_DA_EXTENT_TAIL;
2321 trace_ext4_da_write_pages(inode, &mpd);
2322 wbc->nr_to_write -= mpd.pages_written;
2324 ext4_journal_stop(handle);
2326 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2327 /* commit the transaction which would
2328 * free blocks released in the transaction
2331 jbd2_journal_force_commit_nested(sbi->s_journal);
2333 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2335 * Got one extent now try with rest of the pages.
2336 * If mpd.retval is set -EIO, journal is aborted.
2337 * So we don't need to write any more.
2339 pages_written += mpd.pages_written;
2342 } else if (wbc->nr_to_write)
2344 * There is no more writeout needed
2345 * or we requested for a noblocking writeout
2346 * and we found the device congested
2350 blk_finish_plug(&plug);
2351 if (!io_done && !cycled) {
2354 wbc->range_start = index << PAGE_CACHE_SHIFT;
2355 wbc->range_end = mapping->writeback_index - 1;
2360 wbc->range_cyclic = range_cyclic;
2361 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2363 * set the writeback_index so that range_cyclic
2364 * mode will write it back later
2366 mapping->writeback_index = done_index;
2369 wbc->nr_to_write -= nr_to_writebump;
2370 wbc->range_start = range_start;
2371 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2375 #define FALL_BACK_TO_NONDELALLOC 1
2376 static int ext4_nonda_switch(struct super_block *sb)
2378 s64 free_blocks, dirty_blocks;
2379 struct ext4_sb_info *sbi = EXT4_SB(sb);
2382 * switch to non delalloc mode if we are running low
2383 * on free block. The free block accounting via percpu
2384 * counters can get slightly wrong with percpu_counter_batch getting
2385 * accumulated on each CPU without updating global counters
2386 * Delalloc need an accurate free block accounting. So switch
2387 * to non delalloc when we are near to error range.
2389 free_blocks = EXT4_C2B(sbi,
2390 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2391 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2393 * Start pushing delalloc when 1/2 of free blocks are dirty.
2395 if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
2396 !writeback_in_progress(sb->s_bdi) &&
2397 down_read_trylock(&sb->s_umount)) {
2398 writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2399 up_read(&sb->s_umount);
2402 if (2 * free_blocks < 3 * dirty_blocks ||
2403 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2405 * free block count is less than 150% of dirty blocks
2406 * or free blocks is less than watermark
2413 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2414 loff_t pos, unsigned len, unsigned flags,
2415 struct page **pagep, void **fsdata)
2417 int ret, retries = 0;
2420 struct inode *inode = mapping->host;
2423 index = pos >> PAGE_CACHE_SHIFT;
2425 if (ext4_nonda_switch(inode->i_sb)) {
2426 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2427 return ext4_write_begin(file, mapping, pos,
2428 len, flags, pagep, fsdata);
2430 *fsdata = (void *)0;
2431 trace_ext4_da_write_begin(inode, pos, len, flags);
2434 * With delayed allocation, we don't log the i_disksize update
2435 * if there is delayed block allocation. But we still need
2436 * to journalling the i_disksize update if writes to the end
2437 * of file which has an already mapped buffer.
2439 handle = ext4_journal_start(inode, 1);
2440 if (IS_ERR(handle)) {
2441 ret = PTR_ERR(handle);
2444 /* We cannot recurse into the filesystem as the transaction is already
2446 flags |= AOP_FLAG_NOFS;
2448 page = grab_cache_page_write_begin(mapping, index, flags);
2450 ext4_journal_stop(handle);
2456 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2459 ext4_journal_stop(handle);
2460 page_cache_release(page);
2462 * block_write_begin may have instantiated a few blocks
2463 * outside i_size. Trim these off again. Don't need
2464 * i_size_read because we hold i_mutex.
2466 if (pos + len > inode->i_size)
2467 ext4_truncate_failed_write(inode);
2470 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2477 * Check if we should update i_disksize
2478 * when write to the end of file but not require block allocation
2480 static int ext4_da_should_update_i_disksize(struct page *page,
2481 unsigned long offset)
2483 struct buffer_head *bh;
2484 struct inode *inode = page->mapping->host;
2488 bh = page_buffers(page);
2489 idx = offset >> inode->i_blkbits;
2491 for (i = 0; i < idx; i++)
2492 bh = bh->b_this_page;
2494 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2499 static int ext4_da_write_end(struct file *file,
2500 struct address_space *mapping,
2501 loff_t pos, unsigned len, unsigned copied,
2502 struct page *page, void *fsdata)
2504 struct inode *inode = mapping->host;
2506 handle_t *handle = ext4_journal_current_handle();
2508 unsigned long start, end;
2509 int write_mode = (int)(unsigned long)fsdata;
2511 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2512 switch (ext4_inode_journal_mode(inode)) {
2513 case EXT4_INODE_ORDERED_DATA_MODE:
2514 return ext4_ordered_write_end(file, mapping, pos,
2515 len, copied, page, fsdata);
2516 case EXT4_INODE_WRITEBACK_DATA_MODE:
2517 return ext4_writeback_write_end(file, mapping, pos,
2518 len, copied, page, fsdata);
2524 trace_ext4_da_write_end(inode, pos, len, copied);
2525 start = pos & (PAGE_CACHE_SIZE - 1);
2526 end = start + copied - 1;
2529 * generic_write_end() will run mark_inode_dirty() if i_size
2530 * changes. So let's piggyback the i_disksize mark_inode_dirty
2534 new_i_size = pos + copied;
2535 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2536 if (ext4_da_should_update_i_disksize(page, end)) {
2537 down_write(&EXT4_I(inode)->i_data_sem);
2538 if (new_i_size > EXT4_I(inode)->i_disksize) {
2540 * Updating i_disksize when extending file
2541 * without needing block allocation
2543 if (ext4_should_order_data(inode))
2544 ret = ext4_jbd2_file_inode(handle,
2547 EXT4_I(inode)->i_disksize = new_i_size;
2549 up_write(&EXT4_I(inode)->i_data_sem);
2550 /* We need to mark inode dirty even if
2551 * new_i_size is less that inode->i_size
2552 * bu greater than i_disksize.(hint delalloc)
2554 ext4_mark_inode_dirty(handle, inode);
2557 ret2 = generic_write_end(file, mapping, pos, len, copied,
2562 ret2 = ext4_journal_stop(handle);
2566 return ret ? ret : copied;
2569 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2572 * Drop reserved blocks
2574 BUG_ON(!PageLocked(page));
2575 if (!page_has_buffers(page))
2578 ext4_da_page_release_reservation(page, offset);
2581 ext4_invalidatepage(page, offset);
2587 * Force all delayed allocation blocks to be allocated for a given inode.
2589 int ext4_alloc_da_blocks(struct inode *inode)
2591 trace_ext4_alloc_da_blocks(inode);
2593 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2594 !EXT4_I(inode)->i_reserved_meta_blocks)
2598 * We do something simple for now. The filemap_flush() will
2599 * also start triggering a write of the data blocks, which is
2600 * not strictly speaking necessary (and for users of
2601 * laptop_mode, not even desirable). However, to do otherwise
2602 * would require replicating code paths in:
2604 * ext4_da_writepages() ->
2605 * write_cache_pages() ---> (via passed in callback function)
2606 * __mpage_da_writepage() -->
2607 * mpage_add_bh_to_extent()
2608 * mpage_da_map_blocks()
2610 * The problem is that write_cache_pages(), located in
2611 * mm/page-writeback.c, marks pages clean in preparation for
2612 * doing I/O, which is not desirable if we're not planning on
2615 * We could call write_cache_pages(), and then redirty all of
2616 * the pages by calling redirty_page_for_writepage() but that
2617 * would be ugly in the extreme. So instead we would need to
2618 * replicate parts of the code in the above functions,
2619 * simplifying them because we wouldn't actually intend to
2620 * write out the pages, but rather only collect contiguous
2621 * logical block extents, call the multi-block allocator, and
2622 * then update the buffer heads with the block allocations.
2624 * For now, though, we'll cheat by calling filemap_flush(),
2625 * which will map the blocks, and start the I/O, but not
2626 * actually wait for the I/O to complete.
2628 return filemap_flush(inode->i_mapping);
2632 * bmap() is special. It gets used by applications such as lilo and by
2633 * the swapper to find the on-disk block of a specific piece of data.
2635 * Naturally, this is dangerous if the block concerned is still in the
2636 * journal. If somebody makes a swapfile on an ext4 data-journaling
2637 * filesystem and enables swap, then they may get a nasty shock when the
2638 * data getting swapped to that swapfile suddenly gets overwritten by
2639 * the original zero's written out previously to the journal and
2640 * awaiting writeback in the kernel's buffer cache.
2642 * So, if we see any bmap calls here on a modified, data-journaled file,
2643 * take extra steps to flush any blocks which might be in the cache.
2645 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2647 struct inode *inode = mapping->host;
2651 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2652 test_opt(inode->i_sb, DELALLOC)) {
2654 * With delalloc we want to sync the file
2655 * so that we can make sure we allocate
2658 filemap_write_and_wait(mapping);
2661 if (EXT4_JOURNAL(inode) &&
2662 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2664 * This is a REALLY heavyweight approach, but the use of
2665 * bmap on dirty files is expected to be extremely rare:
2666 * only if we run lilo or swapon on a freshly made file
2667 * do we expect this to happen.
2669 * (bmap requires CAP_SYS_RAWIO so this does not
2670 * represent an unprivileged user DOS attack --- we'd be
2671 * in trouble if mortal users could trigger this path at
2674 * NB. EXT4_STATE_JDATA is not set on files other than
2675 * regular files. If somebody wants to bmap a directory
2676 * or symlink and gets confused because the buffer
2677 * hasn't yet been flushed to disk, they deserve
2678 * everything they get.
2681 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2682 journal = EXT4_JOURNAL(inode);
2683 jbd2_journal_lock_updates(journal);
2684 err = jbd2_journal_flush(journal);
2685 jbd2_journal_unlock_updates(journal);
2691 return generic_block_bmap(mapping, block, ext4_get_block);
2694 static int ext4_readpage(struct file *file, struct page *page)
2696 trace_ext4_readpage(page);
2697 return mpage_readpage(page, ext4_get_block);
2701 ext4_readpages(struct file *file, struct address_space *mapping,
2702 struct list_head *pages, unsigned nr_pages)
2704 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2707 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2709 struct buffer_head *head, *bh;
2710 unsigned int curr_off = 0;
2712 if (!page_has_buffers(page))
2714 head = bh = page_buffers(page);
2716 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2718 ext4_free_io_end(bh->b_private);
2719 bh->b_private = NULL;
2720 bh->b_end_io = NULL;
2722 curr_off = curr_off + bh->b_size;
2723 bh = bh->b_this_page;
2724 } while (bh != head);
2727 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2729 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2731 trace_ext4_invalidatepage(page, offset);
2734 * free any io_end structure allocated for buffers to be discarded
2736 if (ext4_should_dioread_nolock(page->mapping->host))
2737 ext4_invalidatepage_free_endio(page, offset);
2739 * If it's a full truncate we just forget about the pending dirtying
2742 ClearPageChecked(page);
2745 jbd2_journal_invalidatepage(journal, page, offset);
2747 block_invalidatepage(page, offset);
2750 static int ext4_releasepage(struct page *page, gfp_t wait)
2752 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2754 trace_ext4_releasepage(page);
2756 WARN_ON(PageChecked(page));
2757 if (!page_has_buffers(page))
2760 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2762 return try_to_free_buffers(page);
2766 * ext4_get_block used when preparing for a DIO write or buffer write.
2767 * We allocate an uinitialized extent if blocks haven't been allocated.
2768 * The extent will be converted to initialized after the IO is complete.
2770 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2771 struct buffer_head *bh_result, int create)
2773 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2774 inode->i_ino, create);
2775 return _ext4_get_block(inode, iblock, bh_result,
2776 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2779 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2780 ssize_t size, void *private, int ret,
2783 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2784 ext4_io_end_t *io_end = iocb->private;
2785 struct workqueue_struct *wq;
2786 unsigned long flags;
2787 struct ext4_inode_info *ei;
2789 /* if not async direct IO or dio with 0 bytes write, just return */
2790 if (!io_end || !size)
2793 ext_debug("ext4_end_io_dio(): io_end 0x%p"
2794 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2795 iocb->private, io_end->inode->i_ino, iocb, offset,
2798 iocb->private = NULL;
2800 /* if not aio dio with unwritten extents, just free io and return */
2801 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2802 ext4_free_io_end(io_end);
2804 inode_dio_done(inode);
2806 aio_complete(iocb, ret, 0);
2810 io_end->offset = offset;
2811 io_end->size = size;
2813 io_end->iocb = iocb;
2814 io_end->result = ret;
2816 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2818 /* Add the io_end to per-inode completed aio dio list*/
2819 ei = EXT4_I(io_end->inode);
2820 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2821 list_add_tail(&io_end->list, &ei->i_completed_io_list);
2822 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2824 /* queue the work to convert unwritten extents to written */
2825 queue_work(wq, &io_end->work);
2828 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2830 ext4_io_end_t *io_end = bh->b_private;
2831 struct workqueue_struct *wq;
2832 struct inode *inode;
2833 unsigned long flags;
2835 if (!test_clear_buffer_uninit(bh) || !io_end)
2838 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2839 printk("sb umounted, discard end_io request for inode %lu\n",
2840 io_end->inode->i_ino);
2841 ext4_free_io_end(io_end);
2846 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2847 * but being more careful is always safe for the future change.
2849 inode = io_end->inode;
2850 ext4_set_io_unwritten_flag(inode, io_end);
2852 /* Add the io_end to per-inode completed io list*/
2853 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2854 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2855 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2857 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2858 /* queue the work to convert unwritten extents to written */
2859 queue_work(wq, &io_end->work);
2861 bh->b_private = NULL;
2862 bh->b_end_io = NULL;
2863 clear_buffer_uninit(bh);
2864 end_buffer_async_write(bh, uptodate);
2867 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2869 ext4_io_end_t *io_end;
2870 struct page *page = bh->b_page;
2871 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2872 size_t size = bh->b_size;
2875 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2877 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2881 io_end->offset = offset;
2882 io_end->size = size;
2884 * We need to hold a reference to the page to make sure it
2885 * doesn't get evicted before ext4_end_io_work() has a chance
2886 * to convert the extent from written to unwritten.
2888 io_end->page = page;
2889 get_page(io_end->page);
2891 bh->b_private = io_end;
2892 bh->b_end_io = ext4_end_io_buffer_write;
2897 * For ext4 extent files, ext4 will do direct-io write to holes,
2898 * preallocated extents, and those write extend the file, no need to
2899 * fall back to buffered IO.
2901 * For holes, we fallocate those blocks, mark them as uninitialized
2902 * If those blocks were preallocated, we mark sure they are splited, but
2903 * still keep the range to write as uninitialized.
2905 * The unwrritten extents will be converted to written when DIO is completed.
2906 * For async direct IO, since the IO may still pending when return, we
2907 * set up an end_io call back function, which will do the conversion
2908 * when async direct IO completed.
2910 * If the O_DIRECT write will extend the file then add this inode to the
2911 * orphan list. So recovery will truncate it back to the original size
2912 * if the machine crashes during the write.
2915 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2916 const struct iovec *iov, loff_t offset,
2917 unsigned long nr_segs)
2919 struct file *file = iocb->ki_filp;
2920 struct inode *inode = file->f_mapping->host;
2922 size_t count = iov_length(iov, nr_segs);
2924 loff_t final_size = offset + count;
2925 if (rw == WRITE && final_size <= inode->i_size) {
2927 * We could direct write to holes and fallocate.
2929 * Allocated blocks to fill the hole are marked as uninitialized
2930 * to prevent parallel buffered read to expose the stale data
2931 * before DIO complete the data IO.
2933 * As to previously fallocated extents, ext4 get_block
2934 * will just simply mark the buffer mapped but still
2935 * keep the extents uninitialized.
2937 * for non AIO case, we will convert those unwritten extents
2938 * to written after return back from blockdev_direct_IO.
2940 * for async DIO, the conversion needs to be defered when
2941 * the IO is completed. The ext4 end_io callback function
2942 * will be called to take care of the conversion work.
2943 * Here for async case, we allocate an io_end structure to
2946 iocb->private = NULL;
2947 EXT4_I(inode)->cur_aio_dio = NULL;
2948 if (!is_sync_kiocb(iocb)) {
2949 ext4_io_end_t *io_end =
2950 ext4_init_io_end(inode, GFP_NOFS);
2953 io_end->flag |= EXT4_IO_END_DIRECT;
2954 iocb->private = io_end;
2956 * we save the io structure for current async
2957 * direct IO, so that later ext4_map_blocks()
2958 * could flag the io structure whether there
2959 * is a unwritten extents needs to be converted
2960 * when IO is completed.
2962 EXT4_I(inode)->cur_aio_dio = iocb->private;
2965 ret = __blockdev_direct_IO(rw, iocb, inode,
2966 inode->i_sb->s_bdev, iov,
2968 ext4_get_block_write,
2971 DIO_LOCKING | DIO_SKIP_HOLES);
2973 EXT4_I(inode)->cur_aio_dio = NULL;
2975 * The io_end structure takes a reference to the inode,
2976 * that structure needs to be destroyed and the
2977 * reference to the inode need to be dropped, when IO is
2978 * complete, even with 0 byte write, or failed.
2980 * In the successful AIO DIO case, the io_end structure will be
2981 * desctroyed and the reference to the inode will be dropped
2982 * after the end_io call back function is called.
2984 * In the case there is 0 byte write, or error case, since
2985 * VFS direct IO won't invoke the end_io call back function,
2986 * we need to free the end_io structure here.
2988 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
2989 ext4_free_io_end(iocb->private);
2990 iocb->private = NULL;
2991 } else if (ret > 0 && ext4_test_inode_state(inode,
2992 EXT4_STATE_DIO_UNWRITTEN)) {
2995 * for non AIO case, since the IO is already
2996 * completed, we could do the conversion right here
2998 err = ext4_convert_unwritten_extents(inode,
3002 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3007 /* for write the the end of file case, we fall back to old way */
3008 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3011 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3012 const struct iovec *iov, loff_t offset,
3013 unsigned long nr_segs)
3015 struct file *file = iocb->ki_filp;
3016 struct inode *inode = file->f_mapping->host;
3020 * If we are doing data journalling we don't support O_DIRECT
3022 if (ext4_should_journal_data(inode))
3025 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3026 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3027 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3029 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3030 trace_ext4_direct_IO_exit(inode, offset,
3031 iov_length(iov, nr_segs), rw, ret);
3036 * Pages can be marked dirty completely asynchronously from ext4's journalling
3037 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3038 * much here because ->set_page_dirty is called under VFS locks. The page is
3039 * not necessarily locked.
3041 * We cannot just dirty the page and leave attached buffers clean, because the
3042 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3043 * or jbddirty because all the journalling code will explode.
3045 * So what we do is to mark the page "pending dirty" and next time writepage
3046 * is called, propagate that into the buffers appropriately.
3048 static int ext4_journalled_set_page_dirty(struct page *page)
3050 SetPageChecked(page);
3051 return __set_page_dirty_nobuffers(page);
3054 static const struct address_space_operations ext4_ordered_aops = {
3055 .readpage = ext4_readpage,
3056 .readpages = ext4_readpages,
3057 .writepage = ext4_writepage,
3058 .write_begin = ext4_write_begin,
3059 .write_end = ext4_ordered_write_end,
3061 .invalidatepage = ext4_invalidatepage,
3062 .releasepage = ext4_releasepage,
3063 .direct_IO = ext4_direct_IO,
3064 .migratepage = buffer_migrate_page,
3065 .is_partially_uptodate = block_is_partially_uptodate,
3066 .error_remove_page = generic_error_remove_page,
3069 static const struct address_space_operations ext4_writeback_aops = {
3070 .readpage = ext4_readpage,
3071 .readpages = ext4_readpages,
3072 .writepage = ext4_writepage,
3073 .write_begin = ext4_write_begin,
3074 .write_end = ext4_writeback_write_end,
3076 .invalidatepage = ext4_invalidatepage,
3077 .releasepage = ext4_releasepage,
3078 .direct_IO = ext4_direct_IO,
3079 .migratepage = buffer_migrate_page,
3080 .is_partially_uptodate = block_is_partially_uptodate,
3081 .error_remove_page = generic_error_remove_page,
3084 static const struct address_space_operations ext4_journalled_aops = {
3085 .readpage = ext4_readpage,
3086 .readpages = ext4_readpages,
3087 .writepage = ext4_writepage,
3088 .write_begin = ext4_write_begin,
3089 .write_end = ext4_journalled_write_end,
3090 .set_page_dirty = ext4_journalled_set_page_dirty,
3092 .invalidatepage = ext4_invalidatepage,
3093 .releasepage = ext4_releasepage,
3094 .direct_IO = ext4_direct_IO,
3095 .is_partially_uptodate = block_is_partially_uptodate,
3096 .error_remove_page = generic_error_remove_page,
3099 static const struct address_space_operations ext4_da_aops = {
3100 .readpage = ext4_readpage,
3101 .readpages = ext4_readpages,
3102 .writepage = ext4_writepage,
3103 .writepages = ext4_da_writepages,
3104 .write_begin = ext4_da_write_begin,
3105 .write_end = ext4_da_write_end,
3107 .invalidatepage = ext4_da_invalidatepage,
3108 .releasepage = ext4_releasepage,
3109 .direct_IO = ext4_direct_IO,
3110 .migratepage = buffer_migrate_page,
3111 .is_partially_uptodate = block_is_partially_uptodate,
3112 .error_remove_page = generic_error_remove_page,
3115 void ext4_set_aops(struct inode *inode)
3117 switch (ext4_inode_journal_mode(inode)) {
3118 case EXT4_INODE_ORDERED_DATA_MODE:
3119 if (test_opt(inode->i_sb, DELALLOC))
3120 inode->i_mapping->a_ops = &ext4_da_aops;
3122 inode->i_mapping->a_ops = &ext4_ordered_aops;
3124 case EXT4_INODE_WRITEBACK_DATA_MODE:
3125 if (test_opt(inode->i_sb, DELALLOC))
3126 inode->i_mapping->a_ops = &ext4_da_aops;
3128 inode->i_mapping->a_ops = &ext4_writeback_aops;
3130 case EXT4_INODE_JOURNAL_DATA_MODE:
3131 inode->i_mapping->a_ops = &ext4_journalled_aops;
3140 * ext4_discard_partial_page_buffers()
3141 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3142 * This function finds and locks the page containing the offset
3143 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3144 * Calling functions that already have the page locked should call
3145 * ext4_discard_partial_page_buffers_no_lock directly.
3147 int ext4_discard_partial_page_buffers(handle_t *handle,
3148 struct address_space *mapping, loff_t from,
3149 loff_t length, int flags)
3151 struct inode *inode = mapping->host;
3155 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3156 mapping_gfp_mask(mapping) & ~__GFP_FS);
3160 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3161 from, length, flags);
3164 page_cache_release(page);
3169 * ext4_discard_partial_page_buffers_no_lock()
3170 * Zeros a page range of length 'length' starting from offset 'from'.
3171 * Buffer heads that correspond to the block aligned regions of the
3172 * zeroed range will be unmapped. Unblock aligned regions
3173 * will have the corresponding buffer head mapped if needed so that
3174 * that region of the page can be updated with the partial zero out.
3176 * This function assumes that the page has already been locked. The
3177 * The range to be discarded must be contained with in the given page.
3178 * If the specified range exceeds the end of the page it will be shortened
3179 * to the end of the page that corresponds to 'from'. This function is
3180 * appropriate for updating a page and it buffer heads to be unmapped and
3181 * zeroed for blocks that have been either released, or are going to be
3184 * handle: The journal handle
3185 * inode: The files inode
3186 * page: A locked page that contains the offset "from"
3187 * from: The starting byte offset (from the begining of the file)
3188 * to begin discarding
3189 * len: The length of bytes to discard
3190 * flags: Optional flags that may be used:
3192 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3193 * Only zero the regions of the page whose buffer heads
3194 * have already been unmapped. This flag is appropriate
3195 * for updateing the contents of a page whose blocks may
3196 * have already been released, and we only want to zero
3197 * out the regions that correspond to those released blocks.
3199 * Returns zero on sucess or negative on failure.
3201 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3202 struct inode *inode, struct page *page, loff_t from,
3203 loff_t length, int flags)
3205 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3206 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3207 unsigned int blocksize, max, pos;
3209 struct buffer_head *bh;
3212 blocksize = inode->i_sb->s_blocksize;
3213 max = PAGE_CACHE_SIZE - offset;
3215 if (index != page->index)
3219 * correct length if it does not fall between
3220 * 'from' and the end of the page
3222 if (length > max || length < 0)
3225 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3227 if (!page_has_buffers(page))
3228 create_empty_buffers(page, blocksize, 0);
3230 /* Find the buffer that contains "offset" */
3231 bh = page_buffers(page);
3233 while (offset >= pos) {
3234 bh = bh->b_this_page;
3240 while (pos < offset + length) {
3241 unsigned int end_of_block, range_to_discard;
3245 /* The length of space left to zero and unmap */
3246 range_to_discard = offset + length - pos;
3248 /* The length of space until the end of the block */
3249 end_of_block = blocksize - (pos & (blocksize-1));
3252 * Do not unmap or zero past end of block
3253 * for this buffer head
3255 if (range_to_discard > end_of_block)
3256 range_to_discard = end_of_block;
3260 * Skip this buffer head if we are only zeroing unampped
3261 * regions of the page
3263 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3267 /* If the range is block aligned, unmap */
3268 if (range_to_discard == blocksize) {
3269 clear_buffer_dirty(bh);
3271 clear_buffer_mapped(bh);
3272 clear_buffer_req(bh);
3273 clear_buffer_new(bh);
3274 clear_buffer_delay(bh);
3275 clear_buffer_unwritten(bh);
3276 clear_buffer_uptodate(bh);
3277 zero_user(page, pos, range_to_discard);
3278 BUFFER_TRACE(bh, "Buffer discarded");
3283 * If this block is not completely contained in the range
3284 * to be discarded, then it is not going to be released. Because
3285 * we need to keep this block, we need to make sure this part
3286 * of the page is uptodate before we modify it by writeing
3287 * partial zeros on it.
3289 if (!buffer_mapped(bh)) {
3291 * Buffer head must be mapped before we can read
3294 BUFFER_TRACE(bh, "unmapped");
3295 ext4_get_block(inode, iblock, bh, 0);
3296 /* unmapped? It's a hole - nothing to do */
3297 if (!buffer_mapped(bh)) {
3298 BUFFER_TRACE(bh, "still unmapped");
3303 /* Ok, it's mapped. Make sure it's up-to-date */
3304 if (PageUptodate(page))
3305 set_buffer_uptodate(bh);
3307 if (!buffer_uptodate(bh)) {
3309 ll_rw_block(READ, 1, &bh);
3311 /* Uhhuh. Read error. Complain and punt.*/
3312 if (!buffer_uptodate(bh))
3316 if (ext4_should_journal_data(inode)) {
3317 BUFFER_TRACE(bh, "get write access");
3318 err = ext4_journal_get_write_access(handle, bh);
3323 zero_user(page, pos, range_to_discard);
3326 if (ext4_should_journal_data(inode)) {
3327 err = ext4_handle_dirty_metadata(handle, inode, bh);
3329 mark_buffer_dirty(bh);
3331 BUFFER_TRACE(bh, "Partial buffer zeroed");
3333 bh = bh->b_this_page;
3335 pos += range_to_discard;
3342 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3343 * up to the end of the block which corresponds to `from'.
3344 * This required during truncate. We need to physically zero the tail end
3345 * of that block so it doesn't yield old data if the file is later grown.
3347 int ext4_block_truncate_page(handle_t *handle,
3348 struct address_space *mapping, loff_t from)
3350 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3353 struct inode *inode = mapping->host;
3355 blocksize = inode->i_sb->s_blocksize;
3356 length = blocksize - (offset & (blocksize - 1));
3358 return ext4_block_zero_page_range(handle, mapping, from, length);
3362 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3363 * starting from file offset 'from'. The range to be zero'd must
3364 * be contained with in one block. If the specified range exceeds
3365 * the end of the block it will be shortened to end of the block
3366 * that cooresponds to 'from'
3368 int ext4_block_zero_page_range(handle_t *handle,
3369 struct address_space *mapping, loff_t from, loff_t length)
3371 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3372 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3373 unsigned blocksize, max, pos;
3375 struct inode *inode = mapping->host;
3376 struct buffer_head *bh;
3380 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3381 mapping_gfp_mask(mapping) & ~__GFP_FS);
3385 blocksize = inode->i_sb->s_blocksize;
3386 max = blocksize - (offset & (blocksize - 1));
3389 * correct length if it does not fall between
3390 * 'from' and the end of the block
3392 if (length > max || length < 0)
3395 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3397 if (!page_has_buffers(page))
3398 create_empty_buffers(page, blocksize, 0);
3400 /* Find the buffer that contains "offset" */
3401 bh = page_buffers(page);
3403 while (offset >= pos) {
3404 bh = bh->b_this_page;
3410 if (buffer_freed(bh)) {
3411 BUFFER_TRACE(bh, "freed: skip");
3415 if (!buffer_mapped(bh)) {
3416 BUFFER_TRACE(bh, "unmapped");
3417 ext4_get_block(inode, iblock, bh, 0);
3418 /* unmapped? It's a hole - nothing to do */
3419 if (!buffer_mapped(bh)) {
3420 BUFFER_TRACE(bh, "still unmapped");
3425 /* Ok, it's mapped. Make sure it's up-to-date */
3426 if (PageUptodate(page))
3427 set_buffer_uptodate(bh);
3429 if (!buffer_uptodate(bh)) {
3431 ll_rw_block(READ, 1, &bh);
3433 /* Uhhuh. Read error. Complain and punt. */
3434 if (!buffer_uptodate(bh))
3438 if (ext4_should_journal_data(inode)) {
3439 BUFFER_TRACE(bh, "get write access");
3440 err = ext4_journal_get_write_access(handle, bh);
3445 zero_user(page, offset, length);
3447 BUFFER_TRACE(bh, "zeroed end of block");
3450 if (ext4_should_journal_data(inode)) {
3451 err = ext4_handle_dirty_metadata(handle, inode, bh);
3453 mark_buffer_dirty(bh);
3457 page_cache_release(page);
3461 int ext4_can_truncate(struct inode *inode)
3463 if (S_ISREG(inode->i_mode))
3465 if (S_ISDIR(inode->i_mode))
3467 if (S_ISLNK(inode->i_mode))
3468 return !ext4_inode_is_fast_symlink(inode);
3473 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3474 * associated with the given offset and length
3476 * @inode: File inode
3477 * @offset: The offset where the hole will begin
3478 * @len: The length of the hole
3480 * Returns: 0 on sucess or negative on failure
3483 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3485 struct inode *inode = file->f_path.dentry->d_inode;
3486 if (!S_ISREG(inode->i_mode))
3489 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3490 /* TODO: Add support for non extent hole punching */
3494 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3495 /* TODO: Add support for bigalloc file systems */
3499 return ext4_ext_punch_hole(file, offset, length);
3505 * We block out ext4_get_block() block instantiations across the entire
3506 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3507 * simultaneously on behalf of the same inode.
3509 * As we work through the truncate and commmit bits of it to the journal there
3510 * is one core, guiding principle: the file's tree must always be consistent on
3511 * disk. We must be able to restart the truncate after a crash.
3513 * The file's tree may be transiently inconsistent in memory (although it
3514 * probably isn't), but whenever we close off and commit a journal transaction,
3515 * the contents of (the filesystem + the journal) must be consistent and
3516 * restartable. It's pretty simple, really: bottom up, right to left (although
3517 * left-to-right works OK too).
3519 * Note that at recovery time, journal replay occurs *before* the restart of
3520 * truncate against the orphan inode list.
3522 * The committed inode has the new, desired i_size (which is the same as
3523 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3524 * that this inode's truncate did not complete and it will again call
3525 * ext4_truncate() to have another go. So there will be instantiated blocks
3526 * to the right of the truncation point in a crashed ext4 filesystem. But
3527 * that's fine - as long as they are linked from the inode, the post-crash
3528 * ext4_truncate() run will find them and release them.
3530 void ext4_truncate(struct inode *inode)
3532 trace_ext4_truncate_enter(inode);
3534 if (!ext4_can_truncate(inode))
3537 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3539 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3540 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3542 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3543 ext4_ext_truncate(inode);
3545 ext4_ind_truncate(inode);
3547 trace_ext4_truncate_exit(inode);
3551 * ext4_get_inode_loc returns with an extra refcount against the inode's
3552 * underlying buffer_head on success. If 'in_mem' is true, we have all
3553 * data in memory that is needed to recreate the on-disk version of this
3556 static int __ext4_get_inode_loc(struct inode *inode,
3557 struct ext4_iloc *iloc, int in_mem)
3559 struct ext4_group_desc *gdp;
3560 struct buffer_head *bh;
3561 struct super_block *sb = inode->i_sb;
3563 int inodes_per_block, inode_offset;
3566 if (!ext4_valid_inum(sb, inode->i_ino))
3569 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3570 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3575 * Figure out the offset within the block group inode table
3577 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3578 inode_offset = ((inode->i_ino - 1) %
3579 EXT4_INODES_PER_GROUP(sb));
3580 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3581 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3583 bh = sb_getblk(sb, block);
3586 if (!buffer_uptodate(bh)) {
3590 * If the buffer has the write error flag, we have failed
3591 * to write out another inode in the same block. In this
3592 * case, we don't have to read the block because we may
3593 * read the old inode data successfully.
3595 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3596 set_buffer_uptodate(bh);
3598 if (buffer_uptodate(bh)) {
3599 /* someone brought it uptodate while we waited */
3605 * If we have all information of the inode in memory and this
3606 * is the only valid inode in the block, we need not read the
3610 struct buffer_head *bitmap_bh;
3613 start = inode_offset & ~(inodes_per_block - 1);
3615 /* Is the inode bitmap in cache? */
3616 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3621 * If the inode bitmap isn't in cache then the
3622 * optimisation may end up performing two reads instead
3623 * of one, so skip it.
3625 if (!buffer_uptodate(bitmap_bh)) {
3629 for (i = start; i < start + inodes_per_block; i++) {
3630 if (i == inode_offset)
3632 if (ext4_test_bit(i, bitmap_bh->b_data))
3636 if (i == start + inodes_per_block) {
3637 /* all other inodes are free, so skip I/O */
3638 memset(bh->b_data, 0, bh->b_size);
3639 set_buffer_uptodate(bh);
3647 * If we need to do any I/O, try to pre-readahead extra
3648 * blocks from the inode table.
3650 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3651 ext4_fsblk_t b, end, table;
3654 table = ext4_inode_table(sb, gdp);
3655 /* s_inode_readahead_blks is always a power of 2 */
3656 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3659 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3660 num = EXT4_INODES_PER_GROUP(sb);
3661 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3662 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3663 num -= ext4_itable_unused_count(sb, gdp);
3664 table += num / inodes_per_block;
3668 sb_breadahead(sb, b++);
3672 * There are other valid inodes in the buffer, this inode
3673 * has in-inode xattrs, or we don't have this inode in memory.
3674 * Read the block from disk.
3676 trace_ext4_load_inode(inode);
3678 bh->b_end_io = end_buffer_read_sync;
3679 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3681 if (!buffer_uptodate(bh)) {
3682 EXT4_ERROR_INODE_BLOCK(inode, block,
3683 "unable to read itable block");
3693 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3695 /* We have all inode data except xattrs in memory here. */
3696 return __ext4_get_inode_loc(inode, iloc,
3697 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3700 void ext4_set_inode_flags(struct inode *inode)
3702 unsigned int flags = EXT4_I(inode)->i_flags;
3703 unsigned int new_fl = 0;
3705 if (flags & EXT4_SYNC_FL)
3707 if (flags & EXT4_APPEND_FL)
3709 if (flags & EXT4_IMMUTABLE_FL)
3710 new_fl |= S_IMMUTABLE;
3711 if (flags & EXT4_NOATIME_FL)
3712 new_fl |= S_NOATIME;
3713 if (flags & EXT4_DIRSYNC_FL)
3714 new_fl |= S_DIRSYNC;
3715 set_mask_bits(&inode->i_flags,
3716 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC, new_fl);
3719 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3720 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3722 unsigned int vfs_fl;
3723 unsigned long old_fl, new_fl;
3726 vfs_fl = ei->vfs_inode.i_flags;
3727 old_fl = ei->i_flags;
3728 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3729 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3731 if (vfs_fl & S_SYNC)
3732 new_fl |= EXT4_SYNC_FL;
3733 if (vfs_fl & S_APPEND)
3734 new_fl |= EXT4_APPEND_FL;
3735 if (vfs_fl & S_IMMUTABLE)
3736 new_fl |= EXT4_IMMUTABLE_FL;
3737 if (vfs_fl & S_NOATIME)
3738 new_fl |= EXT4_NOATIME_FL;
3739 if (vfs_fl & S_DIRSYNC)
3740 new_fl |= EXT4_DIRSYNC_FL;
3741 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3744 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3745 struct ext4_inode_info *ei)
3748 struct inode *inode = &(ei->vfs_inode);
3749 struct super_block *sb = inode->i_sb;
3751 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3752 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3753 /* we are using combined 48 bit field */
3754 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3755 le32_to_cpu(raw_inode->i_blocks_lo);
3756 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3757 /* i_blocks represent file system block size */
3758 return i_blocks << (inode->i_blkbits - 9);
3763 return le32_to_cpu(raw_inode->i_blocks_lo);
3767 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3769 struct ext4_iloc iloc;
3770 struct ext4_inode *raw_inode;
3771 struct ext4_inode_info *ei;
3772 struct inode *inode;
3773 journal_t *journal = EXT4_SB(sb)->s_journal;
3777 inode = iget_locked(sb, ino);
3779 return ERR_PTR(-ENOMEM);
3780 if (!(inode->i_state & I_NEW))
3786 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3789 raw_inode = ext4_raw_inode(&iloc);
3790 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3791 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3792 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3793 if (!(test_opt(inode->i_sb, NO_UID32))) {
3794 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3795 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3797 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3799 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3800 ei->i_dir_start_lookup = 0;
3801 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3802 /* We now have enough fields to check if the inode was active or not.
3803 * This is needed because nfsd might try to access dead inodes
3804 * the test is that same one that e2fsck uses
3805 * NeilBrown 1999oct15
3807 if (inode->i_nlink == 0) {
3808 if (inode->i_mode == 0 ||
3809 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3810 /* this inode is deleted */
3814 /* The only unlinked inodes we let through here have
3815 * valid i_mode and are being read by the orphan
3816 * recovery code: that's fine, we're about to complete
3817 * the process of deleting those. */
3819 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3820 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3821 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3822 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3824 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3825 inode->i_size = ext4_isize(raw_inode);
3826 ei->i_disksize = inode->i_size;
3828 ei->i_reserved_quota = 0;
3830 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3831 ei->i_block_group = iloc.block_group;
3832 ei->i_last_alloc_group = ~0;
3834 * NOTE! The in-memory inode i_data array is in little-endian order
3835 * even on big-endian machines: we do NOT byteswap the block numbers!
3837 for (block = 0; block < EXT4_N_BLOCKS; block++)
3838 ei->i_data[block] = raw_inode->i_block[block];
3839 INIT_LIST_HEAD(&ei->i_orphan);
3842 * Set transaction id's of transactions that have to be committed
3843 * to finish f[data]sync. We set them to currently running transaction
3844 * as we cannot be sure that the inode or some of its metadata isn't
3845 * part of the transaction - the inode could have been reclaimed and
3846 * now it is reread from disk.
3849 transaction_t *transaction;
3852 read_lock(&journal->j_state_lock);
3853 if (journal->j_running_transaction)
3854 transaction = journal->j_running_transaction;
3856 transaction = journal->j_committing_transaction;
3858 tid = transaction->t_tid;
3860 tid = journal->j_commit_sequence;
3861 read_unlock(&journal->j_state_lock);
3862 ei->i_sync_tid = tid;
3863 ei->i_datasync_tid = tid;
3866 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3867 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3868 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3869 EXT4_INODE_SIZE(inode->i_sb)) {
3873 if (ei->i_extra_isize == 0) {
3874 /* The extra space is currently unused. Use it. */
3875 ei->i_extra_isize = sizeof(struct ext4_inode) -
3876 EXT4_GOOD_OLD_INODE_SIZE;
3878 __le32 *magic = (void *)raw_inode +
3879 EXT4_GOOD_OLD_INODE_SIZE +
3881 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3882 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3885 ei->i_extra_isize = 0;
3887 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3888 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3889 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3890 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3892 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3893 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3894 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3896 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3900 if (ei->i_file_acl &&
3901 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3902 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3906 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3907 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3908 (S_ISLNK(inode->i_mode) &&
3909 !ext4_inode_is_fast_symlink(inode)))
3910 /* Validate extent which is part of inode */
3911 ret = ext4_ext_check_inode(inode);
3912 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3913 (S_ISLNK(inode->i_mode) &&
3914 !ext4_inode_is_fast_symlink(inode))) {
3915 /* Validate block references which are part of inode */
3916 ret = ext4_ind_check_inode(inode);
3921 if (S_ISREG(inode->i_mode)) {
3922 inode->i_op = &ext4_file_inode_operations;
3923 inode->i_fop = &ext4_file_operations;
3924 ext4_set_aops(inode);
3925 } else if (S_ISDIR(inode->i_mode)) {
3926 inode->i_op = &ext4_dir_inode_operations;
3927 inode->i_fop = &ext4_dir_operations;
3928 } else if (S_ISLNK(inode->i_mode)) {
3929 if (ext4_inode_is_fast_symlink(inode)) {
3930 inode->i_op = &ext4_fast_symlink_inode_operations;
3931 nd_terminate_link(ei->i_data, inode->i_size,
3932 sizeof(ei->i_data) - 1);
3934 inode->i_op = &ext4_symlink_inode_operations;
3935 ext4_set_aops(inode);
3937 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3938 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3939 inode->i_op = &ext4_special_inode_operations;
3940 if (raw_inode->i_block[0])
3941 init_special_inode(inode, inode->i_mode,
3942 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3944 init_special_inode(inode, inode->i_mode,
3945 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3948 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3952 ext4_set_inode_flags(inode);
3953 unlock_new_inode(inode);
3959 return ERR_PTR(ret);
3962 static int ext4_inode_blocks_set(handle_t *handle,
3963 struct ext4_inode *raw_inode,
3964 struct ext4_inode_info *ei)
3966 struct inode *inode = &(ei->vfs_inode);
3967 u64 i_blocks = inode->i_blocks;
3968 struct super_block *sb = inode->i_sb;
3970 if (i_blocks <= ~0U) {
3972 * i_blocks can be represnted in a 32 bit variable
3973 * as multiple of 512 bytes
3975 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3976 raw_inode->i_blocks_high = 0;
3977 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3980 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3983 if (i_blocks <= 0xffffffffffffULL) {
3985 * i_blocks can be represented in a 48 bit variable
3986 * as multiple of 512 bytes
3988 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3989 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3990 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3992 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3993 /* i_block is stored in file system block size */
3994 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3995 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3996 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4002 * Post the struct inode info into an on-disk inode location in the
4003 * buffer-cache. This gobbles the caller's reference to the
4004 * buffer_head in the inode location struct.
4006 * The caller must have write access to iloc->bh.
4008 static int ext4_do_update_inode(handle_t *handle,
4009 struct inode *inode,
4010 struct ext4_iloc *iloc)
4012 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4013 struct ext4_inode_info *ei = EXT4_I(inode);
4014 struct buffer_head *bh = iloc->bh;
4015 int err = 0, rc, block;
4016 int need_datasync = 0;
4018 /* For fields not not tracking in the in-memory inode,
4019 * initialise them to zero for new inodes. */
4020 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4021 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4023 ext4_get_inode_flags(ei);
4024 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4025 if (!(test_opt(inode->i_sb, NO_UID32))) {
4026 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4027 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4029 * Fix up interoperability with old kernels. Otherwise, old inodes get
4030 * re-used with the upper 16 bits of the uid/gid intact
4033 raw_inode->i_uid_high =
4034 cpu_to_le16(high_16_bits(inode->i_uid));
4035 raw_inode->i_gid_high =
4036 cpu_to_le16(high_16_bits(inode->i_gid));
4038 raw_inode->i_uid_high = 0;
4039 raw_inode->i_gid_high = 0;
4042 raw_inode->i_uid_low =
4043 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4044 raw_inode->i_gid_low =
4045 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4046 raw_inode->i_uid_high = 0;
4047 raw_inode->i_gid_high = 0;
4049 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4051 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4052 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4053 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4054 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4056 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4058 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4059 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4060 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4061 cpu_to_le32(EXT4_OS_HURD))
4062 raw_inode->i_file_acl_high =
4063 cpu_to_le16(ei->i_file_acl >> 32);
4064 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4065 if (ei->i_disksize != ext4_isize(raw_inode)) {
4066 ext4_isize_set(raw_inode, ei->i_disksize);
4069 if (ei->i_disksize > 0x7fffffffULL) {
4070 struct super_block *sb = inode->i_sb;
4071 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4072 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4073 EXT4_SB(sb)->s_es->s_rev_level ==
4074 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4075 /* If this is the first large file
4076 * created, add a flag to the superblock.
4078 err = ext4_journal_get_write_access(handle,
4079 EXT4_SB(sb)->s_sbh);
4082 ext4_update_dynamic_rev(sb);
4083 EXT4_SET_RO_COMPAT_FEATURE(sb,
4084 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4086 ext4_handle_sync(handle);
4087 err = ext4_handle_dirty_metadata(handle, NULL,
4088 EXT4_SB(sb)->s_sbh);
4091 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4092 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4093 if (old_valid_dev(inode->i_rdev)) {
4094 raw_inode->i_block[0] =
4095 cpu_to_le32(old_encode_dev(inode->i_rdev));
4096 raw_inode->i_block[1] = 0;
4098 raw_inode->i_block[0] = 0;
4099 raw_inode->i_block[1] =
4100 cpu_to_le32(new_encode_dev(inode->i_rdev));
4101 raw_inode->i_block[2] = 0;
4104 for (block = 0; block < EXT4_N_BLOCKS; block++)
4105 raw_inode->i_block[block] = ei->i_data[block];
4107 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4108 if (ei->i_extra_isize) {
4109 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4110 raw_inode->i_version_hi =
4111 cpu_to_le32(inode->i_version >> 32);
4112 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4115 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4116 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4119 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4121 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4124 ext4_std_error(inode->i_sb, err);
4129 * ext4_write_inode()
4131 * We are called from a few places:
4133 * - Within generic_file_write() for O_SYNC files.
4134 * Here, there will be no transaction running. We wait for any running
4135 * trasnaction to commit.
4137 * - Within sys_sync(), kupdate and such.
4138 * We wait on commit, if tol to.
4140 * - Within prune_icache() (PF_MEMALLOC == true)
4141 * Here we simply return. We can't afford to block kswapd on the
4144 * In all cases it is actually safe for us to return without doing anything,
4145 * because the inode has been copied into a raw inode buffer in
4146 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4149 * Note that we are absolutely dependent upon all inode dirtiers doing the
4150 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4151 * which we are interested.
4153 * It would be a bug for them to not do this. The code:
4155 * mark_inode_dirty(inode)
4157 * inode->i_size = expr;
4159 * is in error because a kswapd-driven write_inode() could occur while
4160 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4161 * will no longer be on the superblock's dirty inode list.
4163 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4167 if (current->flags & PF_MEMALLOC)
4170 if (EXT4_SB(inode->i_sb)->s_journal) {
4171 if (ext4_journal_current_handle()) {
4172 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4177 if (wbc->sync_mode != WB_SYNC_ALL)
4180 err = ext4_force_commit(inode->i_sb);
4182 struct ext4_iloc iloc;
4184 err = __ext4_get_inode_loc(inode, &iloc, 0);
4187 if (wbc->sync_mode == WB_SYNC_ALL)
4188 sync_dirty_buffer(iloc.bh);
4189 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4190 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4191 "IO error syncing inode");
4202 * Called from notify_change.
4204 * We want to trap VFS attempts to truncate the file as soon as
4205 * possible. In particular, we want to make sure that when the VFS
4206 * shrinks i_size, we put the inode on the orphan list and modify
4207 * i_disksize immediately, so that during the subsequent flushing of
4208 * dirty pages and freeing of disk blocks, we can guarantee that any
4209 * commit will leave the blocks being flushed in an unused state on
4210 * disk. (On recovery, the inode will get truncated and the blocks will
4211 * be freed, so we have a strong guarantee that no future commit will
4212 * leave these blocks visible to the user.)
4214 * Another thing we have to assure is that if we are in ordered mode
4215 * and inode is still attached to the committing transaction, we must
4216 * we start writeout of all the dirty pages which are being truncated.
4217 * This way we are sure that all the data written in the previous
4218 * transaction are already on disk (truncate waits for pages under
4221 * Called with inode->i_mutex down.
4223 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4225 struct inode *inode = dentry->d_inode;
4228 const unsigned int ia_valid = attr->ia_valid;
4230 error = inode_change_ok(inode, attr);
4234 if (is_quota_modification(inode, attr))
4235 dquot_initialize(inode);
4236 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4237 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4240 /* (user+group)*(old+new) structure, inode write (sb,
4241 * inode block, ? - but truncate inode update has it) */
4242 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4243 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4244 if (IS_ERR(handle)) {
4245 error = PTR_ERR(handle);
4248 error = dquot_transfer(inode, attr);
4250 ext4_journal_stop(handle);
4253 /* Update corresponding info in inode so that everything is in
4254 * one transaction */
4255 if (attr->ia_valid & ATTR_UID)
4256 inode->i_uid = attr->ia_uid;
4257 if (attr->ia_valid & ATTR_GID)
4258 inode->i_gid = attr->ia_gid;
4259 error = ext4_mark_inode_dirty(handle, inode);
4260 ext4_journal_stop(handle);
4263 if (attr->ia_valid & ATTR_SIZE) {
4264 inode_dio_wait(inode);
4266 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4267 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4269 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4274 if (S_ISREG(inode->i_mode) &&
4275 attr->ia_valid & ATTR_SIZE &&
4276 (attr->ia_size < inode->i_size)) {
4279 handle = ext4_journal_start(inode, 3);
4280 if (IS_ERR(handle)) {
4281 error = PTR_ERR(handle);
4284 if (ext4_handle_valid(handle)) {
4285 error = ext4_orphan_add(handle, inode);
4288 EXT4_I(inode)->i_disksize = attr->ia_size;
4289 rc = ext4_mark_inode_dirty(handle, inode);
4292 ext4_journal_stop(handle);
4294 if (ext4_should_order_data(inode)) {
4295 error = ext4_begin_ordered_truncate(inode,
4298 /* Do as much error cleanup as possible */
4299 handle = ext4_journal_start(inode, 3);
4300 if (IS_ERR(handle)) {
4301 ext4_orphan_del(NULL, inode);
4304 ext4_orphan_del(handle, inode);
4306 ext4_journal_stop(handle);
4312 if (attr->ia_valid & ATTR_SIZE) {
4313 if (attr->ia_size != i_size_read(inode)) {
4314 truncate_setsize(inode, attr->ia_size);
4315 ext4_truncate(inode);
4316 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4317 ext4_truncate(inode);
4321 setattr_copy(inode, attr);
4322 mark_inode_dirty(inode);
4326 * If the call to ext4_truncate failed to get a transaction handle at
4327 * all, we need to clean up the in-core orphan list manually.
4329 if (orphan && inode->i_nlink)
4330 ext4_orphan_del(NULL, inode);
4332 if (!rc && (ia_valid & ATTR_MODE))
4333 rc = ext4_acl_chmod(inode);
4336 ext4_std_error(inode->i_sb, error);
4342 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4345 struct inode *inode;
4346 unsigned long long delalloc_blocks;
4348 inode = dentry->d_inode;
4349 generic_fillattr(inode, stat);
4352 * We can't update i_blocks if the block allocation is delayed
4353 * otherwise in the case of system crash before the real block
4354 * allocation is done, we will have i_blocks inconsistent with
4355 * on-disk file blocks.
4356 * We always keep i_blocks updated together with real
4357 * allocation. But to not confuse with user, stat
4358 * will return the blocks that include the delayed allocation
4359 * blocks for this file.
4361 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4363 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
4367 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4369 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4370 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4371 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4375 * Account for index blocks, block groups bitmaps and block group
4376 * descriptor blocks if modify datablocks and index blocks
4377 * worse case, the indexs blocks spread over different block groups
4379 * If datablocks are discontiguous, they are possible to spread over
4380 * different block groups too. If they are contiuguous, with flexbg,
4381 * they could still across block group boundary.
4383 * Also account for superblock, inode, quota and xattr blocks
4385 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4387 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4393 * How many index blocks need to touch to modify nrblocks?
4394 * The "Chunk" flag indicating whether the nrblocks is
4395 * physically contiguous on disk
4397 * For Direct IO and fallocate, they calls get_block to allocate
4398 * one single extent at a time, so they could set the "Chunk" flag
4400 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4405 * Now let's see how many group bitmaps and group descriptors need
4415 if (groups > ngroups)
4417 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4418 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4420 /* bitmaps and block group descriptor blocks */
4421 ret += groups + gdpblocks;
4423 /* Blocks for super block, inode, quota and xattr blocks */
4424 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4430 * Calculate the total number of credits to reserve to fit
4431 * the modification of a single pages into a single transaction,
4432 * which may include multiple chunks of block allocations.
4434 * This could be called via ext4_write_begin()
4436 * We need to consider the worse case, when
4437 * one new block per extent.
4439 int ext4_writepage_trans_blocks(struct inode *inode)
4441 int bpp = ext4_journal_blocks_per_page(inode);
4444 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4446 /* Account for data blocks for journalled mode */
4447 if (ext4_should_journal_data(inode))
4453 * Calculate the journal credits for a chunk of data modification.
4455 * This is called from DIO, fallocate or whoever calling
4456 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4458 * journal buffers for data blocks are not included here, as DIO
4459 * and fallocate do no need to journal data buffers.
4461 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4463 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4467 * The caller must have previously called ext4_reserve_inode_write().
4468 * Give this, we know that the caller already has write access to iloc->bh.
4470 int ext4_mark_iloc_dirty(handle_t *handle,
4471 struct inode *inode, struct ext4_iloc *iloc)
4475 if (test_opt(inode->i_sb, I_VERSION))
4476 inode_inc_iversion(inode);
4478 /* the do_update_inode consumes one bh->b_count */
4481 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4482 err = ext4_do_update_inode(handle, inode, iloc);
4488 * On success, We end up with an outstanding reference count against
4489 * iloc->bh. This _must_ be cleaned up later.
4493 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4494 struct ext4_iloc *iloc)
4498 err = ext4_get_inode_loc(inode, iloc);
4500 BUFFER_TRACE(iloc->bh, "get_write_access");
4501 err = ext4_journal_get_write_access(handle, iloc->bh);
4507 ext4_std_error(inode->i_sb, err);
4512 * Expand an inode by new_extra_isize bytes.
4513 * Returns 0 on success or negative error number on failure.
4515 static int ext4_expand_extra_isize(struct inode *inode,
4516 unsigned int new_extra_isize,
4517 struct ext4_iloc iloc,
4520 struct ext4_inode *raw_inode;
4521 struct ext4_xattr_ibody_header *header;
4523 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4526 raw_inode = ext4_raw_inode(&iloc);
4528 header = IHDR(inode, raw_inode);
4530 /* No extended attributes present */
4531 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4532 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4533 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4535 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4539 /* try to expand with EAs present */
4540 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4545 * What we do here is to mark the in-core inode as clean with respect to inode
4546 * dirtiness (it may still be data-dirty).
4547 * This means that the in-core inode may be reaped by prune_icache
4548 * without having to perform any I/O. This is a very good thing,
4549 * because *any* task may call prune_icache - even ones which
4550 * have a transaction open against a different journal.
4552 * Is this cheating? Not really. Sure, we haven't written the
4553 * inode out, but prune_icache isn't a user-visible syncing function.
4554 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4555 * we start and wait on commits.
4557 * Is this efficient/effective? Well, we're being nice to the system
4558 * by cleaning up our inodes proactively so they can be reaped
4559 * without I/O. But we are potentially leaving up to five seconds'
4560 * worth of inodes floating about which prune_icache wants us to
4561 * write out. One way to fix that would be to get prune_icache()
4562 * to do a write_super() to free up some memory. It has the desired
4565 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4567 struct ext4_iloc iloc;
4568 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4569 static unsigned int mnt_count;
4573 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4574 err = ext4_reserve_inode_write(handle, inode, &iloc);
4575 if (ext4_handle_valid(handle) &&
4576 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4577 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4579 * We need extra buffer credits since we may write into EA block
4580 * with this same handle. If journal_extend fails, then it will
4581 * only result in a minor loss of functionality for that inode.
4582 * If this is felt to be critical, then e2fsck should be run to
4583 * force a large enough s_min_extra_isize.
4585 if ((jbd2_journal_extend(handle,
4586 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4587 ret = ext4_expand_extra_isize(inode,
4588 sbi->s_want_extra_isize,
4591 ext4_set_inode_state(inode,
4592 EXT4_STATE_NO_EXPAND);
4594 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4595 ext4_warning(inode->i_sb,
4596 "Unable to expand inode %lu. Delete"
4597 " some EAs or run e2fsck.",
4600 le16_to_cpu(sbi->s_es->s_mnt_count);
4606 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4611 * ext4_dirty_inode() is called from __mark_inode_dirty()
4613 * We're really interested in the case where a file is being extended.
4614 * i_size has been changed by generic_commit_write() and we thus need
4615 * to include the updated inode in the current transaction.
4617 * Also, dquot_alloc_block() will always dirty the inode when blocks
4618 * are allocated to the file.
4620 * If the inode is marked synchronous, we don't honour that here - doing
4621 * so would cause a commit on atime updates, which we don't bother doing.
4622 * We handle synchronous inodes at the highest possible level.
4624 void ext4_dirty_inode(struct inode *inode, int flags)
4628 handle = ext4_journal_start(inode, 2);
4632 ext4_mark_inode_dirty(handle, inode);
4634 ext4_journal_stop(handle);
4641 * Bind an inode's backing buffer_head into this transaction, to prevent
4642 * it from being flushed to disk early. Unlike
4643 * ext4_reserve_inode_write, this leaves behind no bh reference and
4644 * returns no iloc structure, so the caller needs to repeat the iloc
4645 * lookup to mark the inode dirty later.
4647 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4649 struct ext4_iloc iloc;
4653 err = ext4_get_inode_loc(inode, &iloc);
4655 BUFFER_TRACE(iloc.bh, "get_write_access");
4656 err = jbd2_journal_get_write_access(handle, iloc.bh);
4658 err = ext4_handle_dirty_metadata(handle,
4664 ext4_std_error(inode->i_sb, err);
4669 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4676 * We have to be very careful here: changing a data block's
4677 * journaling status dynamically is dangerous. If we write a
4678 * data block to the journal, change the status and then delete
4679 * that block, we risk forgetting to revoke the old log record
4680 * from the journal and so a subsequent replay can corrupt data.
4681 * So, first we make sure that the journal is empty and that
4682 * nobody is changing anything.
4685 journal = EXT4_JOURNAL(inode);
4688 if (is_journal_aborted(journal))
4691 jbd2_journal_lock_updates(journal);
4692 jbd2_journal_flush(journal);
4695 * OK, there are no updates running now, and all cached data is
4696 * synced to disk. We are now in a completely consistent state
4697 * which doesn't have anything in the journal, and we know that
4698 * no filesystem updates are running, so it is safe to modify
4699 * the inode's in-core data-journaling state flag now.
4703 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4705 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4706 ext4_set_aops(inode);
4708 jbd2_journal_unlock_updates(journal);
4710 /* Finally we can mark the inode as dirty. */
4712 handle = ext4_journal_start(inode, 1);
4714 return PTR_ERR(handle);
4716 err = ext4_mark_inode_dirty(handle, inode);
4717 ext4_handle_sync(handle);
4718 ext4_journal_stop(handle);
4719 ext4_std_error(inode->i_sb, err);
4724 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4726 return !buffer_mapped(bh);
4729 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4731 struct page *page = vmf->page;
4735 struct file *file = vma->vm_file;
4736 struct inode *inode = file->f_path.dentry->d_inode;
4737 struct address_space *mapping = inode->i_mapping;
4739 get_block_t *get_block;
4743 * This check is racy but catches the common case. We rely on
4744 * __block_page_mkwrite() to do a reliable check.
4746 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4747 /* Delalloc case is easy... */
4748 if (test_opt(inode->i_sb, DELALLOC) &&
4749 !ext4_should_journal_data(inode) &&
4750 !ext4_nonda_switch(inode->i_sb)) {
4752 ret = __block_page_mkwrite(vma, vmf,
4753 ext4_da_get_block_prep);
4754 } while (ret == -ENOSPC &&
4755 ext4_should_retry_alloc(inode->i_sb, &retries));
4760 size = i_size_read(inode);
4761 /* Page got truncated from under us? */
4762 if (page->mapping != mapping || page_offset(page) > size) {
4764 ret = VM_FAULT_NOPAGE;
4768 if (page->index == size >> PAGE_CACHE_SHIFT)
4769 len = size & ~PAGE_CACHE_MASK;
4771 len = PAGE_CACHE_SIZE;
4773 * Return if we have all the buffers mapped. This avoids the need to do
4774 * journal_start/journal_stop which can block and take a long time
4776 if (page_has_buffers(page)) {
4777 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4778 ext4_bh_unmapped)) {
4779 /* Wait so that we don't change page under IO */
4780 wait_on_page_writeback(page);
4781 ret = VM_FAULT_LOCKED;
4786 /* OK, we need to fill the hole... */
4787 if (ext4_should_dioread_nolock(inode))
4788 get_block = ext4_get_block_write;
4790 get_block = ext4_get_block;
4792 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4793 if (IS_ERR(handle)) {
4794 ret = VM_FAULT_SIGBUS;
4797 ret = __block_page_mkwrite(vma, vmf, get_block);
4798 if (!ret && ext4_should_journal_data(inode)) {
4799 if (walk_page_buffers(handle, page_buffers(page), 0,
4800 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4802 ret = VM_FAULT_SIGBUS;
4803 ext4_journal_stop(handle);
4806 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4808 ext4_journal_stop(handle);
4809 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4812 ret = block_page_mkwrite_return(ret);