2 * linux/fs/ext4/inode.c
4 * Copyright (C) 1992, 1993, 1994, 1995
5 * Remy Card (card@masi.ibp.fr)
6 * Laboratoire MASI - Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
22 #include <linux/time.h>
23 #include <linux/jbd2.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
41 #include "ext4_jbd2.h"
46 #include <trace/events/ext4.h>
48 #define MPAGE_DA_EXTENT_TAIL 0x01
50 static inline int ext4_begin_ordered_truncate(struct inode *inode,
53 trace_ext4_begin_ordered_truncate(inode, new_size);
55 * If jinode is zero, then we never opened the file for
56 * writing, so there's no need to call
57 * jbd2_journal_begin_ordered_truncate() since there's no
58 * outstanding writes we need to flush.
60 if (!EXT4_I(inode)->jinode)
62 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
63 EXT4_I(inode)->jinode,
67 static void ext4_invalidatepage(struct page *page, unsigned long offset);
68 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
69 struct buffer_head *bh_result, int create);
70 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
71 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
72 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
73 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
76 * Test whether an inode is a fast symlink.
78 static int ext4_inode_is_fast_symlink(struct inode *inode)
80 int ea_blocks = EXT4_I(inode)->i_file_acl ?
81 (inode->i_sb->s_blocksize >> 9) : 0;
83 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
87 * Restart the transaction associated with *handle. This does a commit,
88 * so before we call here everything must be consistently dirtied against
91 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
97 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
98 * moment, get_block can be called only for blocks inside i_size since
99 * page cache has been already dropped and writes are blocked by
100 * i_mutex. So we can safely drop the i_data_sem here.
102 BUG_ON(EXT4_JOURNAL(inode) == NULL);
103 jbd_debug(2, "restarting handle %p\n", handle);
104 up_write(&EXT4_I(inode)->i_data_sem);
105 ret = ext4_journal_restart(handle, nblocks);
106 down_write(&EXT4_I(inode)->i_data_sem);
107 ext4_discard_preallocations(inode);
113 * Called at the last iput() if i_nlink is zero.
115 void ext4_evict_inode(struct inode *inode)
120 trace_ext4_evict_inode(inode);
122 ext4_ioend_wait(inode);
124 if (inode->i_nlink) {
126 * When journalling data dirty buffers are tracked only in the
127 * journal. So although mm thinks everything is clean and
128 * ready for reaping the inode might still have some pages to
129 * write in the running transaction or waiting to be
130 * checkpointed. Thus calling jbd2_journal_invalidatepage()
131 * (via truncate_inode_pages()) to discard these buffers can
132 * cause data loss. Also even if we did not discard these
133 * buffers, we would have no way to find them after the inode
134 * is reaped and thus user could see stale data if he tries to
135 * read them before the transaction is checkpointed. So be
136 * careful and force everything to disk here... We use
137 * ei->i_datasync_tid to store the newest transaction
138 * containing inode's data.
140 * Note that directories do not have this problem because they
141 * don't use page cache.
143 if (ext4_should_journal_data(inode) &&
144 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
145 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
146 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
148 jbd2_log_start_commit(journal, commit_tid);
149 jbd2_log_wait_commit(journal, commit_tid);
150 filemap_write_and_wait(&inode->i_data);
152 truncate_inode_pages(&inode->i_data, 0);
156 if (!is_bad_inode(inode))
157 dquot_initialize(inode);
159 if (ext4_should_order_data(inode))
160 ext4_begin_ordered_truncate(inode, 0);
161 truncate_inode_pages(&inode->i_data, 0);
163 if (is_bad_inode(inode))
166 handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
167 if (IS_ERR(handle)) {
168 ext4_std_error(inode->i_sb, PTR_ERR(handle));
170 * If we're going to skip the normal cleanup, we still need to
171 * make sure that the in-core orphan linked list is properly
174 ext4_orphan_del(NULL, inode);
179 ext4_handle_sync(handle);
181 err = ext4_mark_inode_dirty(handle, inode);
183 ext4_warning(inode->i_sb,
184 "couldn't mark inode dirty (err %d)", err);
188 ext4_truncate(inode);
191 * ext4_ext_truncate() doesn't reserve any slop when it
192 * restarts journal transactions; therefore there may not be
193 * enough credits left in the handle to remove the inode from
194 * the orphan list and set the dtime field.
196 if (!ext4_handle_has_enough_credits(handle, 3)) {
197 err = ext4_journal_extend(handle, 3);
199 err = ext4_journal_restart(handle, 3);
201 ext4_warning(inode->i_sb,
202 "couldn't extend journal (err %d)", err);
204 ext4_journal_stop(handle);
205 ext4_orphan_del(NULL, inode);
211 * Kill off the orphan record which ext4_truncate created.
212 * AKPM: I think this can be inside the above `if'.
213 * Note that ext4_orphan_del() has to be able to cope with the
214 * deletion of a non-existent orphan - this is because we don't
215 * know if ext4_truncate() actually created an orphan record.
216 * (Well, we could do this if we need to, but heck - it works)
218 ext4_orphan_del(handle, inode);
219 EXT4_I(inode)->i_dtime = get_seconds();
222 * One subtle ordering requirement: if anything has gone wrong
223 * (transaction abort, IO errors, whatever), then we can still
224 * do these next steps (the fs will already have been marked as
225 * having errors), but we can't free the inode if the mark_dirty
228 if (ext4_mark_inode_dirty(handle, inode))
229 /* If that failed, just do the required in-core inode clear. */
230 ext4_clear_inode(inode);
232 ext4_free_inode(handle, inode);
233 ext4_journal_stop(handle);
236 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
240 qsize_t *ext4_get_reserved_space(struct inode *inode)
242 return &EXT4_I(inode)->i_reserved_quota;
247 * Calculate the number of metadata blocks need to reserve
248 * to allocate a block located at @lblock
250 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
252 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
253 return ext4_ext_calc_metadata_amount(inode, lblock);
255 return ext4_ind_calc_metadata_amount(inode, lblock);
259 * Called with i_data_sem down, which is important since we can call
260 * ext4_discard_preallocations() from here.
262 void ext4_da_update_reserve_space(struct inode *inode,
263 int used, int quota_claim)
265 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
266 struct ext4_inode_info *ei = EXT4_I(inode);
268 spin_lock(&ei->i_block_reservation_lock);
269 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
270 if (unlikely(used > ei->i_reserved_data_blocks)) {
271 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
272 "with only %d reserved data blocks\n",
273 __func__, inode->i_ino, used,
274 ei->i_reserved_data_blocks);
276 used = ei->i_reserved_data_blocks;
279 /* Update per-inode reservations */
280 ei->i_reserved_data_blocks -= used;
281 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
282 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
283 used + ei->i_allocated_meta_blocks);
284 ei->i_allocated_meta_blocks = 0;
286 if (ei->i_reserved_data_blocks == 0) {
288 * We can release all of the reserved metadata blocks
289 * only when we have written all of the delayed
292 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
293 ei->i_reserved_meta_blocks);
294 ei->i_reserved_meta_blocks = 0;
295 ei->i_da_metadata_calc_len = 0;
297 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
299 /* Update quota subsystem for data blocks */
301 dquot_claim_block(inode, EXT4_C2B(sbi, used));
304 * We did fallocate with an offset that is already delayed
305 * allocated. So on delayed allocated writeback we should
306 * not re-claim the quota for fallocated blocks.
308 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
312 * If we have done all the pending block allocations and if
313 * there aren't any writers on the inode, we can discard the
314 * inode's preallocations.
316 if ((ei->i_reserved_data_blocks == 0) &&
317 (atomic_read(&inode->i_writecount) == 0))
318 ext4_discard_preallocations(inode);
321 static int __check_block_validity(struct inode *inode, const char *func,
323 struct ext4_map_blocks *map)
325 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
327 ext4_error_inode(inode, func, line, map->m_pblk,
328 "lblock %lu mapped to illegal pblock "
329 "(length %d)", (unsigned long) map->m_lblk,
336 #define check_block_validity(inode, map) \
337 __check_block_validity((inode), __func__, __LINE__, (map))
340 * Return the number of contiguous dirty pages in a given inode
341 * starting at page frame idx.
343 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
344 unsigned int max_pages)
346 struct address_space *mapping = inode->i_mapping;
350 int i, nr_pages, done = 0;
354 pagevec_init(&pvec, 0);
357 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
359 (pgoff_t)PAGEVEC_SIZE);
362 for (i = 0; i < nr_pages; i++) {
363 struct page *page = pvec.pages[i];
364 struct buffer_head *bh, *head;
367 if (unlikely(page->mapping != mapping) ||
369 PageWriteback(page) ||
370 page->index != idx) {
375 if (page_has_buffers(page)) {
376 bh = head = page_buffers(page);
378 if (!buffer_delay(bh) &&
379 !buffer_unwritten(bh))
381 bh = bh->b_this_page;
382 } while (!done && (bh != head));
389 if (num >= max_pages) {
394 pagevec_release(&pvec);
400 * Sets the BH_Da_Mapped bit on the buffer heads corresponding to the given map.
402 static void set_buffers_da_mapped(struct inode *inode,
403 struct ext4_map_blocks *map)
405 struct address_space *mapping = inode->i_mapping;
410 index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
411 end = (map->m_lblk + map->m_len - 1) >>
412 (PAGE_CACHE_SHIFT - inode->i_blkbits);
414 pagevec_init(&pvec, 0);
415 while (index <= end) {
416 nr_pages = pagevec_lookup(&pvec, mapping, index,
418 (pgoff_t)PAGEVEC_SIZE));
421 for (i = 0; i < nr_pages; i++) {
422 struct page *page = pvec.pages[i];
423 struct buffer_head *bh, *head;
425 if (unlikely(page->mapping != mapping) ||
429 if (page_has_buffers(page)) {
430 bh = head = page_buffers(page);
432 set_buffer_da_mapped(bh);
433 bh = bh->b_this_page;
434 } while (bh != head);
438 pagevec_release(&pvec);
443 * The ext4_map_blocks() function tries to look up the requested blocks,
444 * and returns if the blocks are already mapped.
446 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
447 * and store the allocated blocks in the result buffer head and mark it
450 * If file type is extents based, it will call ext4_ext_map_blocks(),
451 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
454 * On success, it returns the number of blocks being mapped or allocate.
455 * if create==0 and the blocks are pre-allocated and uninitialized block,
456 * the result buffer head is unmapped. If the create ==1, it will make sure
457 * the buffer head is mapped.
459 * It returns 0 if plain look up failed (blocks have not been allocated), in
460 * that case, buffer head is unmapped
462 * It returns the error in case of allocation failure.
464 int ext4_map_blocks(handle_t *handle, struct inode *inode,
465 struct ext4_map_blocks *map, int flags)
470 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
471 "logical block %lu\n", inode->i_ino, flags, map->m_len,
472 (unsigned long) map->m_lblk);
474 * Try to see if we can get the block without requesting a new
477 down_read((&EXT4_I(inode)->i_data_sem));
478 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
479 retval = ext4_ext_map_blocks(handle, inode, map, flags &
480 EXT4_GET_BLOCKS_KEEP_SIZE);
482 retval = ext4_ind_map_blocks(handle, inode, map, flags &
483 EXT4_GET_BLOCKS_KEEP_SIZE);
485 up_read((&EXT4_I(inode)->i_data_sem));
487 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
488 int ret = check_block_validity(inode, map);
493 /* If it is only a block(s) look up */
494 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
498 * Returns if the blocks have already allocated
500 * Note that if blocks have been preallocated
501 * ext4_ext_get_block() returns the create = 0
502 * with buffer head unmapped.
504 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
508 * When we call get_blocks without the create flag, the
509 * BH_Unwritten flag could have gotten set if the blocks
510 * requested were part of a uninitialized extent. We need to
511 * clear this flag now that we are committed to convert all or
512 * part of the uninitialized extent to be an initialized
513 * extent. This is because we need to avoid the combination
514 * of BH_Unwritten and BH_Mapped flags being simultaneously
515 * set on the buffer_head.
517 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
520 * New blocks allocate and/or writing to uninitialized extent
521 * will possibly result in updating i_data, so we take
522 * the write lock of i_data_sem, and call get_blocks()
523 * with create == 1 flag.
525 down_write((&EXT4_I(inode)->i_data_sem));
528 * if the caller is from delayed allocation writeout path
529 * we have already reserved fs blocks for allocation
530 * let the underlying get_block() function know to
531 * avoid double accounting
533 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
534 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
536 * We need to check for EXT4 here because migrate
537 * could have changed the inode type in between
539 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
540 retval = ext4_ext_map_blocks(handle, inode, map, flags);
542 retval = ext4_ind_map_blocks(handle, inode, map, flags);
544 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
546 * We allocated new blocks which will result in
547 * i_data's format changing. Force the migrate
548 * to fail by clearing migrate flags
550 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
554 * Update reserved blocks/metadata blocks after successful
555 * block allocation which had been deferred till now. We don't
556 * support fallocate for non extent files. So we can update
557 * reserve space here.
560 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
561 ext4_da_update_reserve_space(inode, retval, 1);
563 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
564 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
566 /* If we have successfully mapped the delayed allocated blocks,
567 * set the BH_Da_Mapped bit on them. Its important to do this
568 * under the protection of i_data_sem.
570 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
571 set_buffers_da_mapped(inode, map);
574 up_write((&EXT4_I(inode)->i_data_sem));
575 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
576 int ret = check_block_validity(inode, map);
583 /* Maximum number of blocks we map for direct IO at once. */
584 #define DIO_MAX_BLOCKS 4096
586 static int _ext4_get_block(struct inode *inode, sector_t iblock,
587 struct buffer_head *bh, int flags)
589 handle_t *handle = ext4_journal_current_handle();
590 struct ext4_map_blocks map;
591 int ret = 0, started = 0;
595 map.m_len = bh->b_size >> inode->i_blkbits;
597 if (flags && !handle) {
598 /* Direct IO write... */
599 if (map.m_len > DIO_MAX_BLOCKS)
600 map.m_len = DIO_MAX_BLOCKS;
601 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
602 handle = ext4_journal_start(inode, dio_credits);
603 if (IS_ERR(handle)) {
604 ret = PTR_ERR(handle);
610 ret = ext4_map_blocks(handle, inode, &map, flags);
612 map_bh(bh, inode->i_sb, map.m_pblk);
613 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
614 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
618 ext4_journal_stop(handle);
622 int ext4_get_block(struct inode *inode, sector_t iblock,
623 struct buffer_head *bh, int create)
625 return _ext4_get_block(inode, iblock, bh,
626 create ? EXT4_GET_BLOCKS_CREATE : 0);
630 * `handle' can be NULL if create is zero
632 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
633 ext4_lblk_t block, int create, int *errp)
635 struct ext4_map_blocks map;
636 struct buffer_head *bh;
639 J_ASSERT(handle != NULL || create == 0);
643 err = ext4_map_blocks(handle, inode, &map,
644 create ? EXT4_GET_BLOCKS_CREATE : 0);
652 bh = sb_getblk(inode->i_sb, map.m_pblk);
657 if (map.m_flags & EXT4_MAP_NEW) {
658 J_ASSERT(create != 0);
659 J_ASSERT(handle != NULL);
662 * Now that we do not always journal data, we should
663 * keep in mind whether this should always journal the
664 * new buffer as metadata. For now, regular file
665 * writes use ext4_get_block instead, so it's not a
669 BUFFER_TRACE(bh, "call get_create_access");
670 fatal = ext4_journal_get_create_access(handle, bh);
671 if (!fatal && !buffer_uptodate(bh)) {
672 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
673 set_buffer_uptodate(bh);
676 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
677 err = ext4_handle_dirty_metadata(handle, inode, bh);
681 BUFFER_TRACE(bh, "not a new buffer");
691 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
692 ext4_lblk_t block, int create, int *err)
694 struct buffer_head *bh;
696 bh = ext4_getblk(handle, inode, block, create, err);
699 if (buffer_uptodate(bh))
701 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
703 if (buffer_uptodate(bh))
710 static int walk_page_buffers(handle_t *handle,
711 struct buffer_head *head,
715 int (*fn)(handle_t *handle,
716 struct buffer_head *bh))
718 struct buffer_head *bh;
719 unsigned block_start, block_end;
720 unsigned blocksize = head->b_size;
722 struct buffer_head *next;
724 for (bh = head, block_start = 0;
725 ret == 0 && (bh != head || !block_start);
726 block_start = block_end, bh = next) {
727 next = bh->b_this_page;
728 block_end = block_start + blocksize;
729 if (block_end <= from || block_start >= to) {
730 if (partial && !buffer_uptodate(bh))
734 err = (*fn)(handle, bh);
742 * To preserve ordering, it is essential that the hole instantiation and
743 * the data write be encapsulated in a single transaction. We cannot
744 * close off a transaction and start a new one between the ext4_get_block()
745 * and the commit_write(). So doing the jbd2_journal_start at the start of
746 * prepare_write() is the right place.
748 * Also, this function can nest inside ext4_writepage() ->
749 * block_write_full_page(). In that case, we *know* that ext4_writepage()
750 * has generated enough buffer credits to do the whole page. So we won't
751 * block on the journal in that case, which is good, because the caller may
754 * By accident, ext4 can be reentered when a transaction is open via
755 * quota file writes. If we were to commit the transaction while thus
756 * reentered, there can be a deadlock - we would be holding a quota
757 * lock, and the commit would never complete if another thread had a
758 * transaction open and was blocking on the quota lock - a ranking
761 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
762 * will _not_ run commit under these circumstances because handle->h_ref
763 * is elevated. We'll still have enough credits for the tiny quotafile
766 static int do_journal_get_write_access(handle_t *handle,
767 struct buffer_head *bh)
769 int dirty = buffer_dirty(bh);
772 if (!buffer_mapped(bh) || buffer_freed(bh))
775 * __block_write_begin() could have dirtied some buffers. Clean
776 * the dirty bit as jbd2_journal_get_write_access() could complain
777 * otherwise about fs integrity issues. Setting of the dirty bit
778 * by __block_write_begin() isn't a real problem here as we clear
779 * the bit before releasing a page lock and thus writeback cannot
780 * ever write the buffer.
783 clear_buffer_dirty(bh);
784 ret = ext4_journal_get_write_access(handle, bh);
786 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
790 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
791 struct buffer_head *bh_result, int create);
792 static int ext4_write_begin(struct file *file, struct address_space *mapping,
793 loff_t pos, unsigned len, unsigned flags,
794 struct page **pagep, void **fsdata)
796 struct inode *inode = mapping->host;
797 int ret, needed_blocks;
804 trace_ext4_write_begin(inode, pos, len, flags);
806 * Reserve one block more for addition to orphan list in case
807 * we allocate blocks but write fails for some reason
809 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
810 index = pos >> PAGE_CACHE_SHIFT;
811 from = pos & (PAGE_CACHE_SIZE - 1);
815 handle = ext4_journal_start(inode, needed_blocks);
816 if (IS_ERR(handle)) {
817 ret = PTR_ERR(handle);
821 /* We cannot recurse into the filesystem as the transaction is already
823 flags |= AOP_FLAG_NOFS;
825 page = grab_cache_page_write_begin(mapping, index, flags);
827 ext4_journal_stop(handle);
833 if (ext4_should_dioread_nolock(inode))
834 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
836 ret = __block_write_begin(page, pos, len, ext4_get_block);
838 if (!ret && ext4_should_journal_data(inode)) {
839 ret = walk_page_buffers(handle, page_buffers(page),
840 from, to, NULL, do_journal_get_write_access);
845 page_cache_release(page);
847 * __block_write_begin may have instantiated a few blocks
848 * outside i_size. Trim these off again. Don't need
849 * i_size_read because we hold i_mutex.
851 * Add inode to orphan list in case we crash before
854 if (pos + len > inode->i_size && ext4_can_truncate(inode))
855 ext4_orphan_add(handle, inode);
857 ext4_journal_stop(handle);
858 if (pos + len > inode->i_size) {
859 ext4_truncate_failed_write(inode);
861 * If truncate failed early the inode might
862 * still be on the orphan list; we need to
863 * make sure the inode is removed from the
864 * orphan list in that case.
867 ext4_orphan_del(NULL, inode);
871 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
877 /* For write_end() in data=journal mode */
878 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
880 if (!buffer_mapped(bh) || buffer_freed(bh))
882 set_buffer_uptodate(bh);
883 return ext4_handle_dirty_metadata(handle, NULL, bh);
886 static int ext4_generic_write_end(struct file *file,
887 struct address_space *mapping,
888 loff_t pos, unsigned len, unsigned copied,
889 struct page *page, void *fsdata)
891 int i_size_changed = 0;
892 struct inode *inode = mapping->host;
893 handle_t *handle = ext4_journal_current_handle();
895 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
898 * No need to use i_size_read() here, the i_size
899 * cannot change under us because we hold i_mutex.
901 * But it's important to update i_size while still holding page lock:
902 * page writeout could otherwise come in and zero beyond i_size.
904 if (pos + copied > inode->i_size) {
905 i_size_write(inode, pos + copied);
909 if (pos + copied > EXT4_I(inode)->i_disksize) {
910 /* We need to mark inode dirty even if
911 * new_i_size is less that inode->i_size
912 * bu greater than i_disksize.(hint delalloc)
914 ext4_update_i_disksize(inode, (pos + copied));
918 page_cache_release(page);
921 * Don't mark the inode dirty under page lock. First, it unnecessarily
922 * makes the holding time of page lock longer. Second, it forces lock
923 * ordering of page lock and transaction start for journaling
927 ext4_mark_inode_dirty(handle, inode);
933 * We need to pick up the new inode size which generic_commit_write gave us
934 * `file' can be NULL - eg, when called from page_symlink().
936 * ext4 never places buffers on inode->i_mapping->private_list. metadata
937 * buffers are managed internally.
939 static int ext4_ordered_write_end(struct file *file,
940 struct address_space *mapping,
941 loff_t pos, unsigned len, unsigned copied,
942 struct page *page, void *fsdata)
944 handle_t *handle = ext4_journal_current_handle();
945 struct inode *inode = mapping->host;
948 trace_ext4_ordered_write_end(inode, pos, len, copied);
949 ret = ext4_jbd2_file_inode(handle, inode);
952 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
955 if (pos + len > inode->i_size && ext4_can_truncate(inode))
956 /* if we have allocated more blocks and copied
957 * less. We will have blocks allocated outside
958 * inode->i_size. So truncate them
960 ext4_orphan_add(handle, inode);
965 page_cache_release(page);
968 ret2 = ext4_journal_stop(handle);
972 if (pos + len > inode->i_size) {
973 ext4_truncate_failed_write(inode);
975 * If truncate failed early the inode might still be
976 * on the orphan list; we need to make sure the inode
977 * is removed from the orphan list in that case.
980 ext4_orphan_del(NULL, inode);
984 return ret ? ret : copied;
987 static int ext4_writeback_write_end(struct file *file,
988 struct address_space *mapping,
989 loff_t pos, unsigned len, unsigned copied,
990 struct page *page, void *fsdata)
992 handle_t *handle = ext4_journal_current_handle();
993 struct inode *inode = mapping->host;
996 trace_ext4_writeback_write_end(inode, pos, len, copied);
997 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1000 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1001 /* if we have allocated more blocks and copied
1002 * less. We will have blocks allocated outside
1003 * inode->i_size. So truncate them
1005 ext4_orphan_add(handle, inode);
1010 ret2 = ext4_journal_stop(handle);
1014 if (pos + len > inode->i_size) {
1015 ext4_truncate_failed_write(inode);
1017 * If truncate failed early the inode might still be
1018 * on the orphan list; we need to make sure the inode
1019 * is removed from the orphan list in that case.
1022 ext4_orphan_del(NULL, inode);
1025 return ret ? ret : copied;
1028 static int ext4_journalled_write_end(struct file *file,
1029 struct address_space *mapping,
1030 loff_t pos, unsigned len, unsigned copied,
1031 struct page *page, void *fsdata)
1033 handle_t *handle = ext4_journal_current_handle();
1034 struct inode *inode = mapping->host;
1040 trace_ext4_journalled_write_end(inode, pos, len, copied);
1041 from = pos & (PAGE_CACHE_SIZE - 1);
1044 BUG_ON(!ext4_handle_valid(handle));
1047 if (!PageUptodate(page))
1049 page_zero_new_buffers(page, from+copied, to);
1052 ret = walk_page_buffers(handle, page_buffers(page), from,
1053 to, &partial, write_end_fn);
1055 SetPageUptodate(page);
1056 new_i_size = pos + copied;
1057 if (new_i_size > inode->i_size)
1058 i_size_write(inode, pos+copied);
1059 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1060 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1061 if (new_i_size > EXT4_I(inode)->i_disksize) {
1062 ext4_update_i_disksize(inode, new_i_size);
1063 ret2 = ext4_mark_inode_dirty(handle, inode);
1069 page_cache_release(page);
1070 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1071 /* if we have allocated more blocks and copied
1072 * less. We will have blocks allocated outside
1073 * inode->i_size. So truncate them
1075 ext4_orphan_add(handle, inode);
1077 ret2 = ext4_journal_stop(handle);
1080 if (pos + len > inode->i_size) {
1081 ext4_truncate_failed_write(inode);
1083 * If truncate failed early the inode might still be
1084 * on the orphan list; we need to make sure the inode
1085 * is removed from the orphan list in that case.
1088 ext4_orphan_del(NULL, inode);
1091 return ret ? ret : copied;
1095 * Reserve a single cluster located at lblock
1097 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1100 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1101 struct ext4_inode_info *ei = EXT4_I(inode);
1102 unsigned int md_needed;
1106 * recalculate the amount of metadata blocks to reserve
1107 * in order to allocate nrblocks
1108 * worse case is one extent per block
1111 spin_lock(&ei->i_block_reservation_lock);
1112 md_needed = EXT4_NUM_B2C(sbi,
1113 ext4_calc_metadata_amount(inode, lblock));
1114 trace_ext4_da_reserve_space(inode, md_needed);
1115 spin_unlock(&ei->i_block_reservation_lock);
1118 * We will charge metadata quota at writeout time; this saves
1119 * us from metadata over-estimation, though we may go over by
1120 * a small amount in the end. Here we just reserve for data.
1122 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1126 * We do still charge estimated metadata to the sb though;
1127 * we cannot afford to run out of free blocks.
1129 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1130 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1131 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1137 spin_lock(&ei->i_block_reservation_lock);
1138 ei->i_reserved_data_blocks++;
1139 ei->i_reserved_meta_blocks += md_needed;
1140 spin_unlock(&ei->i_block_reservation_lock);
1142 return 0; /* success */
1145 static void ext4_da_release_space(struct inode *inode, int to_free)
1147 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1148 struct ext4_inode_info *ei = EXT4_I(inode);
1151 return; /* Nothing to release, exit */
1153 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1155 trace_ext4_da_release_space(inode, to_free);
1156 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1158 * if there aren't enough reserved blocks, then the
1159 * counter is messed up somewhere. Since this
1160 * function is called from invalidate page, it's
1161 * harmless to return without any action.
1163 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1164 "ino %lu, to_free %d with only %d reserved "
1165 "data blocks\n", inode->i_ino, to_free,
1166 ei->i_reserved_data_blocks);
1168 to_free = ei->i_reserved_data_blocks;
1170 ei->i_reserved_data_blocks -= to_free;
1172 if (ei->i_reserved_data_blocks == 0) {
1174 * We can release all of the reserved metadata blocks
1175 * only when we have written all of the delayed
1176 * allocation blocks.
1177 * Note that in case of bigalloc, i_reserved_meta_blocks,
1178 * i_reserved_data_blocks, etc. refer to number of clusters.
1180 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1181 ei->i_reserved_meta_blocks);
1182 ei->i_reserved_meta_blocks = 0;
1183 ei->i_da_metadata_calc_len = 0;
1186 /* update fs dirty data blocks counter */
1187 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1189 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1191 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1194 static void ext4_da_page_release_reservation(struct page *page,
1195 unsigned long offset)
1198 struct buffer_head *head, *bh;
1199 unsigned int curr_off = 0;
1200 struct inode *inode = page->mapping->host;
1201 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1204 head = page_buffers(page);
1207 unsigned int next_off = curr_off + bh->b_size;
1209 if ((offset <= curr_off) && (buffer_delay(bh))) {
1211 clear_buffer_delay(bh);
1212 clear_buffer_da_mapped(bh);
1214 curr_off = next_off;
1215 } while ((bh = bh->b_this_page) != head);
1217 /* If we have released all the blocks belonging to a cluster, then we
1218 * need to release the reserved space for that cluster. */
1219 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1220 while (num_clusters > 0) {
1222 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1223 ((num_clusters - 1) << sbi->s_cluster_bits);
1224 if (sbi->s_cluster_ratio == 1 ||
1225 !ext4_find_delalloc_cluster(inode, lblk, 1))
1226 ext4_da_release_space(inode, 1);
1233 * Delayed allocation stuff
1237 * mpage_da_submit_io - walks through extent of pages and try to write
1238 * them with writepage() call back
1240 * @mpd->inode: inode
1241 * @mpd->first_page: first page of the extent
1242 * @mpd->next_page: page after the last page of the extent
1244 * By the time mpage_da_submit_io() is called we expect all blocks
1245 * to be allocated. this may be wrong if allocation failed.
1247 * As pages are already locked by write_cache_pages(), we can't use it
1249 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1250 struct ext4_map_blocks *map)
1252 struct pagevec pvec;
1253 unsigned long index, end;
1254 int ret = 0, err, nr_pages, i;
1255 struct inode *inode = mpd->inode;
1256 struct address_space *mapping = inode->i_mapping;
1257 loff_t size = i_size_read(inode);
1258 unsigned int len, block_start;
1259 struct buffer_head *bh, *page_bufs = NULL;
1260 int journal_data = ext4_should_journal_data(inode);
1261 sector_t pblock = 0, cur_logical = 0;
1262 struct ext4_io_submit io_submit;
1264 BUG_ON(mpd->next_page <= mpd->first_page);
1265 memset(&io_submit, 0, sizeof(io_submit));
1267 * We need to start from the first_page to the next_page - 1
1268 * to make sure we also write the mapped dirty buffer_heads.
1269 * If we look at mpd->b_blocknr we would only be looking
1270 * at the currently mapped buffer_heads.
1272 index = mpd->first_page;
1273 end = mpd->next_page - 1;
1275 pagevec_init(&pvec, 0);
1276 while (index <= end) {
1277 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1280 for (i = 0; i < nr_pages; i++) {
1281 int commit_write = 0, skip_page = 0;
1282 struct page *page = pvec.pages[i];
1284 index = page->index;
1288 if (index == size >> PAGE_CACHE_SHIFT)
1289 len = size & ~PAGE_CACHE_MASK;
1291 len = PAGE_CACHE_SIZE;
1293 cur_logical = index << (PAGE_CACHE_SHIFT -
1295 pblock = map->m_pblk + (cur_logical -
1300 BUG_ON(!PageLocked(page));
1301 BUG_ON(PageWriteback(page));
1304 * If the page does not have buffers (for
1305 * whatever reason), try to create them using
1306 * __block_write_begin. If this fails,
1307 * skip the page and move on.
1309 if (!page_has_buffers(page)) {
1310 if (__block_write_begin(page, 0, len,
1311 noalloc_get_block_write)) {
1319 bh = page_bufs = page_buffers(page);
1324 if (map && (cur_logical >= map->m_lblk) &&
1325 (cur_logical <= (map->m_lblk +
1326 (map->m_len - 1)))) {
1327 if (buffer_delay(bh)) {
1328 clear_buffer_delay(bh);
1329 bh->b_blocknr = pblock;
1331 if (buffer_da_mapped(bh))
1332 clear_buffer_da_mapped(bh);
1333 if (buffer_unwritten(bh) ||
1335 BUG_ON(bh->b_blocknr != pblock);
1336 if (map->m_flags & EXT4_MAP_UNINIT)
1337 set_buffer_uninit(bh);
1338 clear_buffer_unwritten(bh);
1341 /* skip page if block allocation undone */
1342 if (buffer_delay(bh) || buffer_unwritten(bh))
1344 bh = bh->b_this_page;
1345 block_start += bh->b_size;
1348 } while (bh != page_bufs);
1354 /* mark the buffer_heads as dirty & uptodate */
1355 block_commit_write(page, 0, len);
1357 clear_page_dirty_for_io(page);
1359 * Delalloc doesn't support data journalling,
1360 * but eventually maybe we'll lift this
1363 if (unlikely(journal_data && PageChecked(page)))
1364 err = __ext4_journalled_writepage(page, len);
1365 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1366 err = ext4_bio_write_page(&io_submit, page,
1368 else if (buffer_uninit(page_bufs)) {
1369 ext4_set_bh_endio(page_bufs, inode);
1370 err = block_write_full_page_endio(page,
1371 noalloc_get_block_write,
1372 mpd->wbc, ext4_end_io_buffer_write);
1374 err = block_write_full_page(page,
1375 noalloc_get_block_write, mpd->wbc);
1378 mpd->pages_written++;
1380 * In error case, we have to continue because
1381 * remaining pages are still locked
1386 pagevec_release(&pvec);
1388 ext4_io_submit(&io_submit);
1392 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1396 struct pagevec pvec;
1397 struct inode *inode = mpd->inode;
1398 struct address_space *mapping = inode->i_mapping;
1400 index = mpd->first_page;
1401 end = mpd->next_page - 1;
1402 while (index <= end) {
1403 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1406 for (i = 0; i < nr_pages; i++) {
1407 struct page *page = pvec.pages[i];
1408 if (page->index > end)
1410 BUG_ON(!PageLocked(page));
1411 BUG_ON(PageWriteback(page));
1412 block_invalidatepage(page, 0);
1413 ClearPageUptodate(page);
1416 index = pvec.pages[nr_pages - 1]->index + 1;
1417 pagevec_release(&pvec);
1422 static void ext4_print_free_blocks(struct inode *inode)
1424 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1425 printk(KERN_CRIT "Total free blocks count %lld\n",
1426 EXT4_C2B(EXT4_SB(inode->i_sb),
1427 ext4_count_free_clusters(inode->i_sb)));
1428 printk(KERN_CRIT "Free/Dirty block details\n");
1429 printk(KERN_CRIT "free_blocks=%lld\n",
1430 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1431 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1432 printk(KERN_CRIT "dirty_blocks=%lld\n",
1433 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1434 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1435 printk(KERN_CRIT "Block reservation details\n");
1436 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1437 EXT4_I(inode)->i_reserved_data_blocks);
1438 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1439 EXT4_I(inode)->i_reserved_meta_blocks);
1444 * mpage_da_map_and_submit - go through given space, map them
1445 * if necessary, and then submit them for I/O
1447 * @mpd - bh describing space
1449 * The function skips space we know is already mapped to disk blocks.
1452 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1454 int err, blks, get_blocks_flags;
1455 struct ext4_map_blocks map, *mapp = NULL;
1456 sector_t next = mpd->b_blocknr;
1457 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1458 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1459 handle_t *handle = NULL;
1462 * If the blocks are mapped already, or we couldn't accumulate
1463 * any blocks, then proceed immediately to the submission stage.
1465 if ((mpd->b_size == 0) ||
1466 ((mpd->b_state & (1 << BH_Mapped)) &&
1467 !(mpd->b_state & (1 << BH_Delay)) &&
1468 !(mpd->b_state & (1 << BH_Unwritten))))
1471 handle = ext4_journal_current_handle();
1475 * Call ext4_map_blocks() to allocate any delayed allocation
1476 * blocks, or to convert an uninitialized extent to be
1477 * initialized (in the case where we have written into
1478 * one or more preallocated blocks).
1480 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1481 * indicate that we are on the delayed allocation path. This
1482 * affects functions in many different parts of the allocation
1483 * call path. This flag exists primarily because we don't
1484 * want to change *many* call functions, so ext4_map_blocks()
1485 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1486 * inode's allocation semaphore is taken.
1488 * If the blocks in questions were delalloc blocks, set
1489 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1490 * variables are updated after the blocks have been allocated.
1493 map.m_len = max_blocks;
1494 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1495 if (ext4_should_dioread_nolock(mpd->inode))
1496 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1497 if (mpd->b_state & (1 << BH_Delay))
1498 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1500 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1502 struct super_block *sb = mpd->inode->i_sb;
1506 * If get block returns EAGAIN or ENOSPC and there
1507 * appears to be free blocks we will just let
1508 * mpage_da_submit_io() unlock all of the pages.
1513 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1519 * get block failure will cause us to loop in
1520 * writepages, because a_ops->writepage won't be able
1521 * to make progress. The page will be redirtied by
1522 * writepage and writepages will again try to write
1525 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1526 ext4_msg(sb, KERN_CRIT,
1527 "delayed block allocation failed for inode %lu "
1528 "at logical offset %llu with max blocks %zd "
1529 "with error %d", mpd->inode->i_ino,
1530 (unsigned long long) next,
1531 mpd->b_size >> mpd->inode->i_blkbits, err);
1532 ext4_msg(sb, KERN_CRIT,
1533 "This should not happen!! Data will be lost\n");
1535 ext4_print_free_blocks(mpd->inode);
1537 /* invalidate all the pages */
1538 ext4_da_block_invalidatepages(mpd);
1540 /* Mark this page range as having been completed */
1547 if (map.m_flags & EXT4_MAP_NEW) {
1548 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1551 for (i = 0; i < map.m_len; i++)
1552 unmap_underlying_metadata(bdev, map.m_pblk + i);
1554 if (ext4_should_order_data(mpd->inode)) {
1555 err = ext4_jbd2_file_inode(handle, mpd->inode);
1557 /* Only if the journal is aborted */
1565 * Update on-disk size along with block allocation.
1567 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1568 if (disksize > i_size_read(mpd->inode))
1569 disksize = i_size_read(mpd->inode);
1570 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1571 ext4_update_i_disksize(mpd->inode, disksize);
1572 err = ext4_mark_inode_dirty(handle, mpd->inode);
1574 ext4_error(mpd->inode->i_sb,
1575 "Failed to mark inode %lu dirty",
1580 mpage_da_submit_io(mpd, mapp);
1584 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1585 (1 << BH_Delay) | (1 << BH_Unwritten))
1588 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1590 * @mpd->lbh - extent of blocks
1591 * @logical - logical number of the block in the file
1592 * @bh - bh of the block (used to access block's state)
1594 * the function is used to collect contig. blocks in same state
1596 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1597 sector_t logical, size_t b_size,
1598 unsigned long b_state)
1601 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1604 * XXX Don't go larger than mballoc is willing to allocate
1605 * This is a stopgap solution. We eventually need to fold
1606 * mpage_da_submit_io() into this function and then call
1607 * ext4_map_blocks() multiple times in a loop
1609 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1612 /* check if thereserved journal credits might overflow */
1613 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1614 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1616 * With non-extent format we are limited by the journal
1617 * credit available. Total credit needed to insert
1618 * nrblocks contiguous blocks is dependent on the
1619 * nrblocks. So limit nrblocks.
1622 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1623 EXT4_MAX_TRANS_DATA) {
1625 * Adding the new buffer_head would make it cross the
1626 * allowed limit for which we have journal credit
1627 * reserved. So limit the new bh->b_size
1629 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1630 mpd->inode->i_blkbits;
1631 /* we will do mpage_da_submit_io in the next loop */
1635 * First block in the extent
1637 if (mpd->b_size == 0) {
1638 mpd->b_blocknr = logical;
1639 mpd->b_size = b_size;
1640 mpd->b_state = b_state & BH_FLAGS;
1644 next = mpd->b_blocknr + nrblocks;
1646 * Can we merge the block to our big extent?
1648 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1649 mpd->b_size += b_size;
1655 * We couldn't merge the block to our extent, so we
1656 * need to flush current extent and start new one
1658 mpage_da_map_and_submit(mpd);
1662 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1664 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1668 * This function is grabs code from the very beginning of
1669 * ext4_map_blocks, but assumes that the caller is from delayed write
1670 * time. This function looks up the requested blocks and sets the
1671 * buffer delay bit under the protection of i_data_sem.
1673 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1674 struct ext4_map_blocks *map,
1675 struct buffer_head *bh)
1678 sector_t invalid_block = ~((sector_t) 0xffff);
1680 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1684 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1685 "logical block %lu\n", inode->i_ino, map->m_len,
1686 (unsigned long) map->m_lblk);
1688 * Try to see if we can get the block without requesting a new
1689 * file system block.
1691 down_read((&EXT4_I(inode)->i_data_sem));
1692 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1693 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1695 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1699 * XXX: __block_prepare_write() unmaps passed block,
1702 /* If the block was allocated from previously allocated cluster,
1703 * then we dont need to reserve it again. */
1704 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1705 retval = ext4_da_reserve_space(inode, iblock);
1707 /* not enough space to reserve */
1711 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1712 * and it should not appear on the bh->b_state.
1714 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1716 map_bh(bh, inode->i_sb, invalid_block);
1718 set_buffer_delay(bh);
1722 up_read((&EXT4_I(inode)->i_data_sem));
1728 * This is a special get_blocks_t callback which is used by
1729 * ext4_da_write_begin(). It will either return mapped block or
1730 * reserve space for a single block.
1732 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1733 * We also have b_blocknr = -1 and b_bdev initialized properly
1735 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1736 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1737 * initialized properly.
1739 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1740 struct buffer_head *bh, int create)
1742 struct ext4_map_blocks map;
1745 BUG_ON(create == 0);
1746 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1748 map.m_lblk = iblock;
1752 * first, we need to know whether the block is allocated already
1753 * preallocated blocks are unmapped but should treated
1754 * the same as allocated blocks.
1756 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1760 map_bh(bh, inode->i_sb, map.m_pblk);
1761 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1763 if (buffer_unwritten(bh)) {
1764 /* A delayed write to unwritten bh should be marked
1765 * new and mapped. Mapped ensures that we don't do
1766 * get_block multiple times when we write to the same
1767 * offset and new ensures that we do proper zero out
1768 * for partial write.
1771 set_buffer_mapped(bh);
1777 * This function is used as a standard get_block_t calback function
1778 * when there is no desire to allocate any blocks. It is used as a
1779 * callback function for block_write_begin() and block_write_full_page().
1780 * These functions should only try to map a single block at a time.
1782 * Since this function doesn't do block allocations even if the caller
1783 * requests it by passing in create=1, it is critically important that
1784 * any caller checks to make sure that any buffer heads are returned
1785 * by this function are either all already mapped or marked for
1786 * delayed allocation before calling block_write_full_page(). Otherwise,
1787 * b_blocknr could be left unitialized, and the page write functions will
1788 * be taken by surprise.
1790 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1791 struct buffer_head *bh_result, int create)
1793 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1794 return _ext4_get_block(inode, iblock, bh_result, 0);
1797 static int bget_one(handle_t *handle, struct buffer_head *bh)
1803 static int bput_one(handle_t *handle, struct buffer_head *bh)
1809 static int __ext4_journalled_writepage(struct page *page,
1812 struct address_space *mapping = page->mapping;
1813 struct inode *inode = mapping->host;
1814 struct buffer_head *page_bufs;
1815 handle_t *handle = NULL;
1819 ClearPageChecked(page);
1820 page_bufs = page_buffers(page);
1822 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1823 /* As soon as we unlock the page, it can go away, but we have
1824 * references to buffers so we are safe */
1827 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1828 if (IS_ERR(handle)) {
1829 ret = PTR_ERR(handle);
1833 BUG_ON(!ext4_handle_valid(handle));
1835 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1836 do_journal_get_write_access);
1838 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1842 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1843 err = ext4_journal_stop(handle);
1847 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1848 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1853 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1854 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1857 * Note that we don't need to start a transaction unless we're journaling data
1858 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1859 * need to file the inode to the transaction's list in ordered mode because if
1860 * we are writing back data added by write(), the inode is already there and if
1861 * we are writing back data modified via mmap(), no one guarantees in which
1862 * transaction the data will hit the disk. In case we are journaling data, we
1863 * cannot start transaction directly because transaction start ranks above page
1864 * lock so we have to do some magic.
1866 * This function can get called via...
1867 * - ext4_da_writepages after taking page lock (have journal handle)
1868 * - journal_submit_inode_data_buffers (no journal handle)
1869 * - shrink_page_list via pdflush (no journal handle)
1870 * - grab_page_cache when doing write_begin (have journal handle)
1872 * We don't do any block allocation in this function. If we have page with
1873 * multiple blocks we need to write those buffer_heads that are mapped. This
1874 * is important for mmaped based write. So if we do with blocksize 1K
1875 * truncate(f, 1024);
1876 * a = mmap(f, 0, 4096);
1878 * truncate(f, 4096);
1879 * we have in the page first buffer_head mapped via page_mkwrite call back
1880 * but other bufer_heads would be unmapped but dirty(dirty done via the
1881 * do_wp_page). So writepage should write the first block. If we modify
1882 * the mmap area beyond 1024 we will again get a page_fault and the
1883 * page_mkwrite callback will do the block allocation and mark the
1884 * buffer_heads mapped.
1886 * We redirty the page if we have any buffer_heads that is either delay or
1887 * unwritten in the page.
1889 * We can get recursively called as show below.
1891 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1894 * But since we don't do any block allocation we should not deadlock.
1895 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1897 static int ext4_writepage(struct page *page,
1898 struct writeback_control *wbc)
1900 int ret = 0, commit_write = 0;
1903 struct buffer_head *page_bufs = NULL;
1904 struct inode *inode = page->mapping->host;
1906 trace_ext4_writepage(page);
1907 size = i_size_read(inode);
1908 if (page->index == size >> PAGE_CACHE_SHIFT)
1909 len = size & ~PAGE_CACHE_MASK;
1911 len = PAGE_CACHE_SIZE;
1914 * If the page does not have buffers (for whatever reason),
1915 * try to create them using __block_write_begin. If this
1916 * fails, redirty the page and move on.
1918 if (!page_has_buffers(page)) {
1919 if (__block_write_begin(page, 0, len,
1920 noalloc_get_block_write)) {
1922 redirty_page_for_writepage(wbc, page);
1928 page_bufs = page_buffers(page);
1929 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1930 ext4_bh_delay_or_unwritten)) {
1932 * We don't want to do block allocation, so redirty
1933 * the page and return. We may reach here when we do
1934 * a journal commit via journal_submit_inode_data_buffers.
1935 * We can also reach here via shrink_page_list but it
1936 * should never be for direct reclaim so warn if that
1939 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1944 /* now mark the buffer_heads as dirty and uptodate */
1945 block_commit_write(page, 0, len);
1947 if (PageChecked(page) && ext4_should_journal_data(inode))
1949 * It's mmapped pagecache. Add buffers and journal it. There
1950 * doesn't seem much point in redirtying the page here.
1952 return __ext4_journalled_writepage(page, len);
1954 if (buffer_uninit(page_bufs)) {
1955 ext4_set_bh_endio(page_bufs, inode);
1956 ret = block_write_full_page_endio(page, noalloc_get_block_write,
1957 wbc, ext4_end_io_buffer_write);
1959 ret = block_write_full_page(page, noalloc_get_block_write,
1966 * This is called via ext4_da_writepages() to
1967 * calculate the total number of credits to reserve to fit
1968 * a single extent allocation into a single transaction,
1969 * ext4_da_writpeages() will loop calling this before
1970 * the block allocation.
1973 static int ext4_da_writepages_trans_blocks(struct inode *inode)
1975 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
1978 * With non-extent format the journal credit needed to
1979 * insert nrblocks contiguous block is dependent on
1980 * number of contiguous block. So we will limit
1981 * number of contiguous block to a sane value
1983 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
1984 (max_blocks > EXT4_MAX_TRANS_DATA))
1985 max_blocks = EXT4_MAX_TRANS_DATA;
1987 return ext4_chunk_trans_blocks(inode, max_blocks);
1991 * write_cache_pages_da - walk the list of dirty pages of the given
1992 * address space and accumulate pages that need writing, and call
1993 * mpage_da_map_and_submit to map a single contiguous memory region
1994 * and then write them.
1996 static int write_cache_pages_da(struct address_space *mapping,
1997 struct writeback_control *wbc,
1998 struct mpage_da_data *mpd,
1999 pgoff_t *done_index)
2001 struct buffer_head *bh, *head;
2002 struct inode *inode = mapping->host;
2003 struct pagevec pvec;
2004 unsigned int nr_pages;
2007 long nr_to_write = wbc->nr_to_write;
2008 int i, tag, ret = 0;
2010 memset(mpd, 0, sizeof(struct mpage_da_data));
2013 pagevec_init(&pvec, 0);
2014 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2015 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2017 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2018 tag = PAGECACHE_TAG_TOWRITE;
2020 tag = PAGECACHE_TAG_DIRTY;
2022 *done_index = index;
2023 while (index <= end) {
2024 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2025 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2029 for (i = 0; i < nr_pages; i++) {
2030 struct page *page = pvec.pages[i];
2033 * At this point, the page may be truncated or
2034 * invalidated (changing page->mapping to NULL), or
2035 * even swizzled back from swapper_space to tmpfs file
2036 * mapping. However, page->index will not change
2037 * because we have a reference on the page.
2039 if (page->index > end)
2042 *done_index = page->index + 1;
2045 * If we can't merge this page, and we have
2046 * accumulated an contiguous region, write it
2048 if ((mpd->next_page != page->index) &&
2049 (mpd->next_page != mpd->first_page)) {
2050 mpage_da_map_and_submit(mpd);
2051 goto ret_extent_tail;
2057 * If the page is no longer dirty, or its
2058 * mapping no longer corresponds to inode we
2059 * are writing (which means it has been
2060 * truncated or invalidated), or the page is
2061 * already under writeback and we are not
2062 * doing a data integrity writeback, skip the page
2064 if (!PageDirty(page) ||
2065 (PageWriteback(page) &&
2066 (wbc->sync_mode == WB_SYNC_NONE)) ||
2067 unlikely(page->mapping != mapping)) {
2072 wait_on_page_writeback(page);
2073 BUG_ON(PageWriteback(page));
2075 if (mpd->next_page != page->index)
2076 mpd->first_page = page->index;
2077 mpd->next_page = page->index + 1;
2078 logical = (sector_t) page->index <<
2079 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2081 if (!page_has_buffers(page)) {
2082 mpage_add_bh_to_extent(mpd, logical,
2084 (1 << BH_Dirty) | (1 << BH_Uptodate));
2086 goto ret_extent_tail;
2089 * Page with regular buffer heads,
2090 * just add all dirty ones
2092 head = page_buffers(page);
2095 BUG_ON(buffer_locked(bh));
2097 * We need to try to allocate
2098 * unmapped blocks in the same page.
2099 * Otherwise we won't make progress
2100 * with the page in ext4_writepage
2102 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2103 mpage_add_bh_to_extent(mpd, logical,
2107 goto ret_extent_tail;
2108 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2110 * mapped dirty buffer. We need
2111 * to update the b_state
2112 * because we look at b_state
2113 * in mpage_da_map_blocks. We
2114 * don't update b_size because
2115 * if we find an unmapped
2116 * buffer_head later we need to
2117 * use the b_state flag of that
2120 if (mpd->b_size == 0)
2121 mpd->b_state = bh->b_state & BH_FLAGS;
2124 } while ((bh = bh->b_this_page) != head);
2127 if (nr_to_write > 0) {
2129 if (nr_to_write == 0 &&
2130 wbc->sync_mode == WB_SYNC_NONE)
2132 * We stop writing back only if we are
2133 * not doing integrity sync. In case of
2134 * integrity sync we have to keep going
2135 * because someone may be concurrently
2136 * dirtying pages, and we might have
2137 * synced a lot of newly appeared dirty
2138 * pages, but have not synced all of the
2144 pagevec_release(&pvec);
2149 ret = MPAGE_DA_EXTENT_TAIL;
2151 pagevec_release(&pvec);
2157 static int ext4_da_writepages(struct address_space *mapping,
2158 struct writeback_control *wbc)
2161 int range_whole = 0;
2162 handle_t *handle = NULL;
2163 struct mpage_da_data mpd;
2164 struct inode *inode = mapping->host;
2165 int pages_written = 0;
2166 unsigned int max_pages;
2167 int range_cyclic, cycled = 1, io_done = 0;
2168 int needed_blocks, ret = 0;
2169 long desired_nr_to_write, nr_to_writebump = 0;
2170 loff_t range_start = wbc->range_start;
2171 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2172 pgoff_t done_index = 0;
2174 struct blk_plug plug;
2176 trace_ext4_da_writepages(inode, wbc);
2179 * No pages to write? This is mainly a kludge to avoid starting
2180 * a transaction for special inodes like journal inode on last iput()
2181 * because that could violate lock ordering on umount
2183 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2187 * If the filesystem has aborted, it is read-only, so return
2188 * right away instead of dumping stack traces later on that
2189 * will obscure the real source of the problem. We test
2190 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2191 * the latter could be true if the filesystem is mounted
2192 * read-only, and in that case, ext4_da_writepages should
2193 * *never* be called, so if that ever happens, we would want
2196 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2199 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2202 range_cyclic = wbc->range_cyclic;
2203 if (wbc->range_cyclic) {
2204 index = mapping->writeback_index;
2207 wbc->range_start = index << PAGE_CACHE_SHIFT;
2208 wbc->range_end = LLONG_MAX;
2209 wbc->range_cyclic = 0;
2212 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2213 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2217 * This works around two forms of stupidity. The first is in
2218 * the writeback code, which caps the maximum number of pages
2219 * written to be 1024 pages. This is wrong on multiple
2220 * levels; different architectues have a different page size,
2221 * which changes the maximum amount of data which gets
2222 * written. Secondly, 4 megabytes is way too small. XFS
2223 * forces this value to be 16 megabytes by multiplying
2224 * nr_to_write parameter by four, and then relies on its
2225 * allocator to allocate larger extents to make them
2226 * contiguous. Unfortunately this brings us to the second
2227 * stupidity, which is that ext4's mballoc code only allocates
2228 * at most 2048 blocks. So we force contiguous writes up to
2229 * the number of dirty blocks in the inode, or
2230 * sbi->max_writeback_mb_bump whichever is smaller.
2232 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2233 if (!range_cyclic && range_whole) {
2234 if (wbc->nr_to_write == LONG_MAX)
2235 desired_nr_to_write = wbc->nr_to_write;
2237 desired_nr_to_write = wbc->nr_to_write * 8;
2239 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2241 if (desired_nr_to_write > max_pages)
2242 desired_nr_to_write = max_pages;
2244 if (wbc->nr_to_write < desired_nr_to_write) {
2245 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2246 wbc->nr_to_write = desired_nr_to_write;
2250 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2251 tag_pages_for_writeback(mapping, index, end);
2253 blk_start_plug(&plug);
2254 while (!ret && wbc->nr_to_write > 0) {
2257 * we insert one extent at a time. So we need
2258 * credit needed for single extent allocation.
2259 * journalled mode is currently not supported
2262 BUG_ON(ext4_should_journal_data(inode));
2263 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2265 /* start a new transaction*/
2266 handle = ext4_journal_start(inode, needed_blocks);
2267 if (IS_ERR(handle)) {
2268 ret = PTR_ERR(handle);
2269 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2270 "%ld pages, ino %lu; err %d", __func__,
2271 wbc->nr_to_write, inode->i_ino, ret);
2272 goto out_writepages;
2276 * Now call write_cache_pages_da() to find the next
2277 * contiguous region of logical blocks that need
2278 * blocks to be allocated by ext4 and submit them.
2280 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2282 * If we have a contiguous extent of pages and we
2283 * haven't done the I/O yet, map the blocks and submit
2286 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2287 mpage_da_map_and_submit(&mpd);
2288 ret = MPAGE_DA_EXTENT_TAIL;
2290 trace_ext4_da_write_pages(inode, &mpd);
2291 wbc->nr_to_write -= mpd.pages_written;
2293 ext4_journal_stop(handle);
2295 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2296 /* commit the transaction which would
2297 * free blocks released in the transaction
2300 jbd2_journal_force_commit_nested(sbi->s_journal);
2302 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2304 * Got one extent now try with rest of the pages.
2305 * If mpd.retval is set -EIO, journal is aborted.
2306 * So we don't need to write any more.
2308 pages_written += mpd.pages_written;
2311 } else if (wbc->nr_to_write)
2313 * There is no more writeout needed
2314 * or we requested for a noblocking writeout
2315 * and we found the device congested
2319 blk_finish_plug(&plug);
2320 if (!io_done && !cycled) {
2323 wbc->range_start = index << PAGE_CACHE_SHIFT;
2324 wbc->range_end = mapping->writeback_index - 1;
2329 wbc->range_cyclic = range_cyclic;
2330 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2332 * set the writeback_index so that range_cyclic
2333 * mode will write it back later
2335 mapping->writeback_index = done_index;
2338 wbc->nr_to_write -= nr_to_writebump;
2339 wbc->range_start = range_start;
2340 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2344 #define FALL_BACK_TO_NONDELALLOC 1
2345 static int ext4_nonda_switch(struct super_block *sb)
2347 s64 free_blocks, dirty_blocks;
2348 struct ext4_sb_info *sbi = EXT4_SB(sb);
2351 * switch to non delalloc mode if we are running low
2352 * on free block. The free block accounting via percpu
2353 * counters can get slightly wrong with percpu_counter_batch getting
2354 * accumulated on each CPU without updating global counters
2355 * Delalloc need an accurate free block accounting. So switch
2356 * to non delalloc when we are near to error range.
2358 free_blocks = EXT4_C2B(sbi,
2359 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2360 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2361 if (2 * free_blocks < 3 * dirty_blocks ||
2362 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2364 * free block count is less than 150% of dirty blocks
2365 * or free blocks is less than watermark
2370 * Even if we don't switch but are nearing capacity,
2371 * start pushing delalloc when 1/2 of free blocks are dirty.
2373 if (free_blocks < 2 * dirty_blocks)
2374 writeback_inodes_sb_if_idle(sb, WB_REASON_FS_FREE_SPACE);
2379 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2380 loff_t pos, unsigned len, unsigned flags,
2381 struct page **pagep, void **fsdata)
2383 int ret, retries = 0;
2386 struct inode *inode = mapping->host;
2390 index = pos >> PAGE_CACHE_SHIFT;
2392 if (ext4_nonda_switch(inode->i_sb)) {
2393 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2394 return ext4_write_begin(file, mapping, pos,
2395 len, flags, pagep, fsdata);
2397 *fsdata = (void *)0;
2398 trace_ext4_da_write_begin(inode, pos, len, flags);
2401 * With delayed allocation, we don't log the i_disksize update
2402 * if there is delayed block allocation. But we still need
2403 * to journalling the i_disksize update if writes to the end
2404 * of file which has an already mapped buffer.
2406 handle = ext4_journal_start(inode, 1);
2407 if (IS_ERR(handle)) {
2408 ret = PTR_ERR(handle);
2411 /* We cannot recurse into the filesystem as the transaction is already
2413 flags |= AOP_FLAG_NOFS;
2415 page = grab_cache_page_write_begin(mapping, index, flags);
2417 ext4_journal_stop(handle);
2423 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2426 ext4_journal_stop(handle);
2427 page_cache_release(page);
2429 * block_write_begin may have instantiated a few blocks
2430 * outside i_size. Trim these off again. Don't need
2431 * i_size_read because we hold i_mutex.
2433 if (pos + len > inode->i_size)
2434 ext4_truncate_failed_write(inode);
2436 page_len = pos & (PAGE_CACHE_SIZE - 1);
2438 ret = ext4_discard_partial_page_buffers_no_lock(handle,
2439 inode, page, pos - page_len, page_len,
2440 EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED);
2444 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2451 * Check if we should update i_disksize
2452 * when write to the end of file but not require block allocation
2454 static int ext4_da_should_update_i_disksize(struct page *page,
2455 unsigned long offset)
2457 struct buffer_head *bh;
2458 struct inode *inode = page->mapping->host;
2462 bh = page_buffers(page);
2463 idx = offset >> inode->i_blkbits;
2465 for (i = 0; i < idx; i++)
2466 bh = bh->b_this_page;
2468 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2473 static int ext4_da_write_end(struct file *file,
2474 struct address_space *mapping,
2475 loff_t pos, unsigned len, unsigned copied,
2476 struct page *page, void *fsdata)
2478 struct inode *inode = mapping->host;
2480 handle_t *handle = ext4_journal_current_handle();
2482 unsigned long start, end;
2483 int write_mode = (int)(unsigned long)fsdata;
2486 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2487 if (ext4_should_order_data(inode)) {
2488 return ext4_ordered_write_end(file, mapping, pos,
2489 len, copied, page, fsdata);
2490 } else if (ext4_should_writeback_data(inode)) {
2491 return ext4_writeback_write_end(file, mapping, pos,
2492 len, copied, page, fsdata);
2498 trace_ext4_da_write_end(inode, pos, len, copied);
2499 start = pos & (PAGE_CACHE_SIZE - 1);
2500 end = start + copied - 1;
2503 * generic_write_end() will run mark_inode_dirty() if i_size
2504 * changes. So let's piggyback the i_disksize mark_inode_dirty
2508 new_i_size = pos + copied;
2509 if (new_i_size > EXT4_I(inode)->i_disksize) {
2510 if (ext4_da_should_update_i_disksize(page, end)) {
2511 down_write(&EXT4_I(inode)->i_data_sem);
2512 if (new_i_size > EXT4_I(inode)->i_disksize) {
2514 * Updating i_disksize when extending file
2515 * without needing block allocation
2517 if (ext4_should_order_data(inode))
2518 ret = ext4_jbd2_file_inode(handle,
2521 EXT4_I(inode)->i_disksize = new_i_size;
2523 up_write(&EXT4_I(inode)->i_data_sem);
2524 /* We need to mark inode dirty even if
2525 * new_i_size is less that inode->i_size
2526 * bu greater than i_disksize.(hint delalloc)
2528 ext4_mark_inode_dirty(handle, inode);
2531 ret2 = generic_write_end(file, mapping, pos, len, copied,
2534 page_len = PAGE_CACHE_SIZE -
2535 ((pos + copied - 1) & (PAGE_CACHE_SIZE - 1));
2538 ret = ext4_discard_partial_page_buffers_no_lock(handle,
2539 inode, page, pos + copied - 1, page_len,
2540 EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED);
2546 ret2 = ext4_journal_stop(handle);
2550 return ret ? ret : copied;
2553 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2556 * Drop reserved blocks
2558 BUG_ON(!PageLocked(page));
2559 if (!page_has_buffers(page))
2562 ext4_da_page_release_reservation(page, offset);
2565 ext4_invalidatepage(page, offset);
2571 * Force all delayed allocation blocks to be allocated for a given inode.
2573 int ext4_alloc_da_blocks(struct inode *inode)
2575 trace_ext4_alloc_da_blocks(inode);
2577 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2578 !EXT4_I(inode)->i_reserved_meta_blocks)
2582 * We do something simple for now. The filemap_flush() will
2583 * also start triggering a write of the data blocks, which is
2584 * not strictly speaking necessary (and for users of
2585 * laptop_mode, not even desirable). However, to do otherwise
2586 * would require replicating code paths in:
2588 * ext4_da_writepages() ->
2589 * write_cache_pages() ---> (via passed in callback function)
2590 * __mpage_da_writepage() -->
2591 * mpage_add_bh_to_extent()
2592 * mpage_da_map_blocks()
2594 * The problem is that write_cache_pages(), located in
2595 * mm/page-writeback.c, marks pages clean in preparation for
2596 * doing I/O, which is not desirable if we're not planning on
2599 * We could call write_cache_pages(), and then redirty all of
2600 * the pages by calling redirty_page_for_writepage() but that
2601 * would be ugly in the extreme. So instead we would need to
2602 * replicate parts of the code in the above functions,
2603 * simplifying them because we wouldn't actually intend to
2604 * write out the pages, but rather only collect contiguous
2605 * logical block extents, call the multi-block allocator, and
2606 * then update the buffer heads with the block allocations.
2608 * For now, though, we'll cheat by calling filemap_flush(),
2609 * which will map the blocks, and start the I/O, but not
2610 * actually wait for the I/O to complete.
2612 return filemap_flush(inode->i_mapping);
2616 * bmap() is special. It gets used by applications such as lilo and by
2617 * the swapper to find the on-disk block of a specific piece of data.
2619 * Naturally, this is dangerous if the block concerned is still in the
2620 * journal. If somebody makes a swapfile on an ext4 data-journaling
2621 * filesystem and enables swap, then they may get a nasty shock when the
2622 * data getting swapped to that swapfile suddenly gets overwritten by
2623 * the original zero's written out previously to the journal and
2624 * awaiting writeback in the kernel's buffer cache.
2626 * So, if we see any bmap calls here on a modified, data-journaled file,
2627 * take extra steps to flush any blocks which might be in the cache.
2629 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2631 struct inode *inode = mapping->host;
2635 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2636 test_opt(inode->i_sb, DELALLOC)) {
2638 * With delalloc we want to sync the file
2639 * so that we can make sure we allocate
2642 filemap_write_and_wait(mapping);
2645 if (EXT4_JOURNAL(inode) &&
2646 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2648 * This is a REALLY heavyweight approach, but the use of
2649 * bmap on dirty files is expected to be extremely rare:
2650 * only if we run lilo or swapon on a freshly made file
2651 * do we expect this to happen.
2653 * (bmap requires CAP_SYS_RAWIO so this does not
2654 * represent an unprivileged user DOS attack --- we'd be
2655 * in trouble if mortal users could trigger this path at
2658 * NB. EXT4_STATE_JDATA is not set on files other than
2659 * regular files. If somebody wants to bmap a directory
2660 * or symlink and gets confused because the buffer
2661 * hasn't yet been flushed to disk, they deserve
2662 * everything they get.
2665 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2666 journal = EXT4_JOURNAL(inode);
2667 jbd2_journal_lock_updates(journal);
2668 err = jbd2_journal_flush(journal);
2669 jbd2_journal_unlock_updates(journal);
2675 return generic_block_bmap(mapping, block, ext4_get_block);
2678 static int ext4_readpage(struct file *file, struct page *page)
2680 trace_ext4_readpage(page);
2681 return mpage_readpage(page, ext4_get_block);
2685 ext4_readpages(struct file *file, struct address_space *mapping,
2686 struct list_head *pages, unsigned nr_pages)
2688 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2691 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2693 struct buffer_head *head, *bh;
2694 unsigned int curr_off = 0;
2696 if (!page_has_buffers(page))
2698 head = bh = page_buffers(page);
2700 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2702 ext4_free_io_end(bh->b_private);
2703 bh->b_private = NULL;
2704 bh->b_end_io = NULL;
2706 curr_off = curr_off + bh->b_size;
2707 bh = bh->b_this_page;
2708 } while (bh != head);
2711 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2713 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2715 trace_ext4_invalidatepage(page, offset);
2718 * free any io_end structure allocated for buffers to be discarded
2720 if (ext4_should_dioread_nolock(page->mapping->host))
2721 ext4_invalidatepage_free_endio(page, offset);
2723 * If it's a full truncate we just forget about the pending dirtying
2726 ClearPageChecked(page);
2729 jbd2_journal_invalidatepage(journal, page, offset);
2731 block_invalidatepage(page, offset);
2734 static int ext4_releasepage(struct page *page, gfp_t wait)
2736 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2738 trace_ext4_releasepage(page);
2740 WARN_ON(PageChecked(page));
2741 if (!page_has_buffers(page))
2744 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2746 return try_to_free_buffers(page);
2750 * ext4_get_block used when preparing for a DIO write or buffer write.
2751 * We allocate an uinitialized extent if blocks haven't been allocated.
2752 * The extent will be converted to initialized after the IO is complete.
2754 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2755 struct buffer_head *bh_result, int create)
2757 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2758 inode->i_ino, create);
2759 return _ext4_get_block(inode, iblock, bh_result,
2760 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2763 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2764 ssize_t size, void *private, int ret,
2767 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2768 ext4_io_end_t *io_end = iocb->private;
2769 struct workqueue_struct *wq;
2770 unsigned long flags;
2771 struct ext4_inode_info *ei;
2773 /* if not async direct IO or dio with 0 bytes write, just return */
2774 if (!io_end || !size)
2777 ext_debug("ext4_end_io_dio(): io_end 0x%p"
2778 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2779 iocb->private, io_end->inode->i_ino, iocb, offset,
2782 /* if not aio dio with unwritten extents, just free io and return */
2783 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2784 ext4_free_io_end(io_end);
2785 iocb->private = NULL;
2788 aio_complete(iocb, ret, 0);
2789 inode_dio_done(inode);
2793 io_end->offset = offset;
2794 io_end->size = size;
2796 io_end->iocb = iocb;
2797 io_end->result = ret;
2799 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2801 /* Add the io_end to per-inode completed aio dio list*/
2802 ei = EXT4_I(io_end->inode);
2803 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2804 list_add_tail(&io_end->list, &ei->i_completed_io_list);
2805 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2807 /* queue the work to convert unwritten extents to written */
2808 queue_work(wq, &io_end->work);
2809 iocb->private = NULL;
2811 /* XXX: probably should move into the real I/O completion handler */
2812 inode_dio_done(inode);
2815 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2817 ext4_io_end_t *io_end = bh->b_private;
2818 struct workqueue_struct *wq;
2819 struct inode *inode;
2820 unsigned long flags;
2822 if (!test_clear_buffer_uninit(bh) || !io_end)
2825 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2826 printk("sb umounted, discard end_io request for inode %lu\n",
2827 io_end->inode->i_ino);
2828 ext4_free_io_end(io_end);
2833 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2834 * but being more careful is always safe for the future change.
2836 inode = io_end->inode;
2837 ext4_set_io_unwritten_flag(inode, io_end);
2839 /* Add the io_end to per-inode completed io list*/
2840 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2841 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2842 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2844 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2845 /* queue the work to convert unwritten extents to written */
2846 queue_work(wq, &io_end->work);
2848 bh->b_private = NULL;
2849 bh->b_end_io = NULL;
2850 clear_buffer_uninit(bh);
2851 end_buffer_async_write(bh, uptodate);
2854 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2856 ext4_io_end_t *io_end;
2857 struct page *page = bh->b_page;
2858 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2859 size_t size = bh->b_size;
2862 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2864 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2868 io_end->offset = offset;
2869 io_end->size = size;
2871 * We need to hold a reference to the page to make sure it
2872 * doesn't get evicted before ext4_end_io_work() has a chance
2873 * to convert the extent from written to unwritten.
2875 io_end->page = page;
2876 get_page(io_end->page);
2878 bh->b_private = io_end;
2879 bh->b_end_io = ext4_end_io_buffer_write;
2884 * For ext4 extent files, ext4 will do direct-io write to holes,
2885 * preallocated extents, and those write extend the file, no need to
2886 * fall back to buffered IO.
2888 * For holes, we fallocate those blocks, mark them as uninitialized
2889 * If those blocks were preallocated, we mark sure they are splited, but
2890 * still keep the range to write as uninitialized.
2892 * The unwrritten extents will be converted to written when DIO is completed.
2893 * For async direct IO, since the IO may still pending when return, we
2894 * set up an end_io call back function, which will do the conversion
2895 * when async direct IO completed.
2897 * If the O_DIRECT write will extend the file then add this inode to the
2898 * orphan list. So recovery will truncate it back to the original size
2899 * if the machine crashes during the write.
2902 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2903 const struct iovec *iov, loff_t offset,
2904 unsigned long nr_segs)
2906 struct file *file = iocb->ki_filp;
2907 struct inode *inode = file->f_mapping->host;
2909 size_t count = iov_length(iov, nr_segs);
2911 loff_t final_size = offset + count;
2912 if (rw == WRITE && final_size <= inode->i_size) {
2914 * We could direct write to holes and fallocate.
2916 * Allocated blocks to fill the hole are marked as uninitialized
2917 * to prevent parallel buffered read to expose the stale data
2918 * before DIO complete the data IO.
2920 * As to previously fallocated extents, ext4 get_block
2921 * will just simply mark the buffer mapped but still
2922 * keep the extents uninitialized.
2924 * for non AIO case, we will convert those unwritten extents
2925 * to written after return back from blockdev_direct_IO.
2927 * for async DIO, the conversion needs to be defered when
2928 * the IO is completed. The ext4 end_io callback function
2929 * will be called to take care of the conversion work.
2930 * Here for async case, we allocate an io_end structure to
2933 iocb->private = NULL;
2934 EXT4_I(inode)->cur_aio_dio = NULL;
2935 if (!is_sync_kiocb(iocb)) {
2936 iocb->private = ext4_init_io_end(inode, GFP_NOFS);
2940 * we save the io structure for current async
2941 * direct IO, so that later ext4_map_blocks()
2942 * could flag the io structure whether there
2943 * is a unwritten extents needs to be converted
2944 * when IO is completed.
2946 EXT4_I(inode)->cur_aio_dio = iocb->private;
2949 ret = __blockdev_direct_IO(rw, iocb, inode,
2950 inode->i_sb->s_bdev, iov,
2952 ext4_get_block_write,
2955 DIO_LOCKING | DIO_SKIP_HOLES);
2957 EXT4_I(inode)->cur_aio_dio = NULL;
2959 * The io_end structure takes a reference to the inode,
2960 * that structure needs to be destroyed and the
2961 * reference to the inode need to be dropped, when IO is
2962 * complete, even with 0 byte write, or failed.
2964 * In the successful AIO DIO case, the io_end structure will be
2965 * desctroyed and the reference to the inode will be dropped
2966 * after the end_io call back function is called.
2968 * In the case there is 0 byte write, or error case, since
2969 * VFS direct IO won't invoke the end_io call back function,
2970 * we need to free the end_io structure here.
2972 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
2973 ext4_free_io_end(iocb->private);
2974 iocb->private = NULL;
2975 } else if (ret > 0 && ext4_test_inode_state(inode,
2976 EXT4_STATE_DIO_UNWRITTEN)) {
2979 * for non AIO case, since the IO is already
2980 * completed, we could do the conversion right here
2982 err = ext4_convert_unwritten_extents(inode,
2986 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
2991 /* for write the the end of file case, we fall back to old way */
2992 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
2995 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
2996 const struct iovec *iov, loff_t offset,
2997 unsigned long nr_segs)
2999 struct file *file = iocb->ki_filp;
3000 struct inode *inode = file->f_mapping->host;
3004 * If we are doing data journalling we don't support O_DIRECT
3006 if (ext4_should_journal_data(inode))
3009 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3010 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3011 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3013 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3014 trace_ext4_direct_IO_exit(inode, offset,
3015 iov_length(iov, nr_segs), rw, ret);
3020 * Pages can be marked dirty completely asynchronously from ext4's journalling
3021 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3022 * much here because ->set_page_dirty is called under VFS locks. The page is
3023 * not necessarily locked.
3025 * We cannot just dirty the page and leave attached buffers clean, because the
3026 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3027 * or jbddirty because all the journalling code will explode.
3029 * So what we do is to mark the page "pending dirty" and next time writepage
3030 * is called, propagate that into the buffers appropriately.
3032 static int ext4_journalled_set_page_dirty(struct page *page)
3034 SetPageChecked(page);
3035 return __set_page_dirty_nobuffers(page);
3038 static const struct address_space_operations ext4_ordered_aops = {
3039 .readpage = ext4_readpage,
3040 .readpages = ext4_readpages,
3041 .writepage = ext4_writepage,
3042 .write_begin = ext4_write_begin,
3043 .write_end = ext4_ordered_write_end,
3045 .invalidatepage = ext4_invalidatepage,
3046 .releasepage = ext4_releasepage,
3047 .direct_IO = ext4_direct_IO,
3048 .migratepage = buffer_migrate_page,
3049 .is_partially_uptodate = block_is_partially_uptodate,
3050 .error_remove_page = generic_error_remove_page,
3053 static const struct address_space_operations ext4_writeback_aops = {
3054 .readpage = ext4_readpage,
3055 .readpages = ext4_readpages,
3056 .writepage = ext4_writepage,
3057 .write_begin = ext4_write_begin,
3058 .write_end = ext4_writeback_write_end,
3060 .invalidatepage = ext4_invalidatepage,
3061 .releasepage = ext4_releasepage,
3062 .direct_IO = ext4_direct_IO,
3063 .migratepage = buffer_migrate_page,
3064 .is_partially_uptodate = block_is_partially_uptodate,
3065 .error_remove_page = generic_error_remove_page,
3068 static const struct address_space_operations ext4_journalled_aops = {
3069 .readpage = ext4_readpage,
3070 .readpages = ext4_readpages,
3071 .writepage = ext4_writepage,
3072 .write_begin = ext4_write_begin,
3073 .write_end = ext4_journalled_write_end,
3074 .set_page_dirty = ext4_journalled_set_page_dirty,
3076 .invalidatepage = ext4_invalidatepage,
3077 .releasepage = ext4_releasepage,
3078 .direct_IO = ext4_direct_IO,
3079 .is_partially_uptodate = block_is_partially_uptodate,
3080 .error_remove_page = generic_error_remove_page,
3083 static const struct address_space_operations ext4_da_aops = {
3084 .readpage = ext4_readpage,
3085 .readpages = ext4_readpages,
3086 .writepage = ext4_writepage,
3087 .writepages = ext4_da_writepages,
3088 .write_begin = ext4_da_write_begin,
3089 .write_end = ext4_da_write_end,
3091 .invalidatepage = ext4_da_invalidatepage,
3092 .releasepage = ext4_releasepage,
3093 .direct_IO = ext4_direct_IO,
3094 .migratepage = buffer_migrate_page,
3095 .is_partially_uptodate = block_is_partially_uptodate,
3096 .error_remove_page = generic_error_remove_page,
3099 void ext4_set_aops(struct inode *inode)
3101 if (ext4_should_order_data(inode) &&
3102 test_opt(inode->i_sb, DELALLOC))
3103 inode->i_mapping->a_ops = &ext4_da_aops;
3104 else if (ext4_should_order_data(inode))
3105 inode->i_mapping->a_ops = &ext4_ordered_aops;
3106 else if (ext4_should_writeback_data(inode) &&
3107 test_opt(inode->i_sb, DELALLOC))
3108 inode->i_mapping->a_ops = &ext4_da_aops;
3109 else if (ext4_should_writeback_data(inode))
3110 inode->i_mapping->a_ops = &ext4_writeback_aops;
3112 inode->i_mapping->a_ops = &ext4_journalled_aops;
3117 * ext4_discard_partial_page_buffers()
3118 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3119 * This function finds and locks the page containing the offset
3120 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3121 * Calling functions that already have the page locked should call
3122 * ext4_discard_partial_page_buffers_no_lock directly.
3124 int ext4_discard_partial_page_buffers(handle_t *handle,
3125 struct address_space *mapping, loff_t from,
3126 loff_t length, int flags)
3128 struct inode *inode = mapping->host;
3132 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3133 mapping_gfp_mask(mapping) & ~__GFP_FS);
3137 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3138 from, length, flags);
3141 page_cache_release(page);
3146 * ext4_discard_partial_page_buffers_no_lock()
3147 * Zeros a page range of length 'length' starting from offset 'from'.
3148 * Buffer heads that correspond to the block aligned regions of the
3149 * zeroed range will be unmapped. Unblock aligned regions
3150 * will have the corresponding buffer head mapped if needed so that
3151 * that region of the page can be updated with the partial zero out.
3153 * This function assumes that the page has already been locked. The
3154 * The range to be discarded must be contained with in the given page.
3155 * If the specified range exceeds the end of the page it will be shortened
3156 * to the end of the page that corresponds to 'from'. This function is
3157 * appropriate for updating a page and it buffer heads to be unmapped and
3158 * zeroed for blocks that have been either released, or are going to be
3161 * handle: The journal handle
3162 * inode: The files inode
3163 * page: A locked page that contains the offset "from"
3164 * from: The starting byte offset (from the begining of the file)
3165 * to begin discarding
3166 * len: The length of bytes to discard
3167 * flags: Optional flags that may be used:
3169 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3170 * Only zero the regions of the page whose buffer heads
3171 * have already been unmapped. This flag is appropriate
3172 * for updateing the contents of a page whose blocks may
3173 * have already been released, and we only want to zero
3174 * out the regions that correspond to those released blocks.
3176 * Returns zero on sucess or negative on failure.
3178 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3179 struct inode *inode, struct page *page, loff_t from,
3180 loff_t length, int flags)
3182 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3183 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3184 unsigned int blocksize, max, pos;
3186 struct buffer_head *bh;
3189 blocksize = inode->i_sb->s_blocksize;
3190 max = PAGE_CACHE_SIZE - offset;
3192 if (index != page->index)
3196 * correct length if it does not fall between
3197 * 'from' and the end of the page
3199 if (length > max || length < 0)
3202 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3204 if (!page_has_buffers(page)) {
3206 * If the range to be discarded covers a partial block
3207 * we need to get the page buffers. This is because
3208 * partial blocks cannot be released and the page needs
3209 * to be updated with the contents of the block before
3210 * we write the zeros on top of it.
3212 if ((from & (blocksize - 1)) ||
3213 ((from + length) & (blocksize - 1))) {
3214 create_empty_buffers(page, blocksize, 0);
3217 * If there are no partial blocks,
3218 * there is nothing to update,
3219 * so we can return now
3225 /* Find the buffer that contains "offset" */
3226 bh = page_buffers(page);
3228 while (offset >= pos) {
3229 bh = bh->b_this_page;
3235 while (pos < offset + length) {
3236 unsigned int end_of_block, range_to_discard;
3240 /* The length of space left to zero and unmap */
3241 range_to_discard = offset + length - pos;
3243 /* The length of space until the end of the block */
3244 end_of_block = blocksize - (pos & (blocksize-1));
3247 * Do not unmap or zero past end of block
3248 * for this buffer head
3250 if (range_to_discard > end_of_block)
3251 range_to_discard = end_of_block;
3255 * Skip this buffer head if we are only zeroing unampped
3256 * regions of the page
3258 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3262 /* If the range is block aligned, unmap */
3263 if (range_to_discard == blocksize) {
3264 clear_buffer_dirty(bh);
3266 clear_buffer_mapped(bh);
3267 clear_buffer_req(bh);
3268 clear_buffer_new(bh);
3269 clear_buffer_delay(bh);
3270 clear_buffer_unwritten(bh);
3271 clear_buffer_uptodate(bh);
3272 zero_user(page, pos, range_to_discard);
3273 BUFFER_TRACE(bh, "Buffer discarded");
3278 * If this block is not completely contained in the range
3279 * to be discarded, then it is not going to be released. Because
3280 * we need to keep this block, we need to make sure this part
3281 * of the page is uptodate before we modify it by writeing
3282 * partial zeros on it.
3284 if (!buffer_mapped(bh)) {
3286 * Buffer head must be mapped before we can read
3289 BUFFER_TRACE(bh, "unmapped");
3290 ext4_get_block(inode, iblock, bh, 0);
3291 /* unmapped? It's a hole - nothing to do */
3292 if (!buffer_mapped(bh)) {
3293 BUFFER_TRACE(bh, "still unmapped");
3298 /* Ok, it's mapped. Make sure it's up-to-date */
3299 if (PageUptodate(page))
3300 set_buffer_uptodate(bh);
3302 if (!buffer_uptodate(bh)) {
3304 ll_rw_block(READ, 1, &bh);
3306 /* Uhhuh. Read error. Complain and punt.*/
3307 if (!buffer_uptodate(bh))
3311 if (ext4_should_journal_data(inode)) {
3312 BUFFER_TRACE(bh, "get write access");
3313 err = ext4_journal_get_write_access(handle, bh);
3318 zero_user(page, pos, range_to_discard);
3321 if (ext4_should_journal_data(inode)) {
3322 err = ext4_handle_dirty_metadata(handle, inode, bh);
3324 mark_buffer_dirty(bh);
3326 BUFFER_TRACE(bh, "Partial buffer zeroed");
3328 bh = bh->b_this_page;
3330 pos += range_to_discard;
3337 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3338 * up to the end of the block which corresponds to `from'.
3339 * This required during truncate. We need to physically zero the tail end
3340 * of that block so it doesn't yield old data if the file is later grown.
3342 int ext4_block_truncate_page(handle_t *handle,
3343 struct address_space *mapping, loff_t from)
3345 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3348 struct inode *inode = mapping->host;
3350 blocksize = inode->i_sb->s_blocksize;
3351 length = blocksize - (offset & (blocksize - 1));
3353 return ext4_block_zero_page_range(handle, mapping, from, length);
3357 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3358 * starting from file offset 'from'. The range to be zero'd must
3359 * be contained with in one block. If the specified range exceeds
3360 * the end of the block it will be shortened to end of the block
3361 * that cooresponds to 'from'
3363 int ext4_block_zero_page_range(handle_t *handle,
3364 struct address_space *mapping, loff_t from, loff_t length)
3366 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3367 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3368 unsigned blocksize, max, pos;
3370 struct inode *inode = mapping->host;
3371 struct buffer_head *bh;
3375 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3376 mapping_gfp_mask(mapping) & ~__GFP_FS);
3380 blocksize = inode->i_sb->s_blocksize;
3381 max = blocksize - (offset & (blocksize - 1));
3384 * correct length if it does not fall between
3385 * 'from' and the end of the block
3387 if (length > max || length < 0)
3390 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3392 if (!page_has_buffers(page))
3393 create_empty_buffers(page, blocksize, 0);
3395 /* Find the buffer that contains "offset" */
3396 bh = page_buffers(page);
3398 while (offset >= pos) {
3399 bh = bh->b_this_page;
3405 if (buffer_freed(bh)) {
3406 BUFFER_TRACE(bh, "freed: skip");
3410 if (!buffer_mapped(bh)) {
3411 BUFFER_TRACE(bh, "unmapped");
3412 ext4_get_block(inode, iblock, bh, 0);
3413 /* unmapped? It's a hole - nothing to do */
3414 if (!buffer_mapped(bh)) {
3415 BUFFER_TRACE(bh, "still unmapped");
3420 /* Ok, it's mapped. Make sure it's up-to-date */
3421 if (PageUptodate(page))
3422 set_buffer_uptodate(bh);
3424 if (!buffer_uptodate(bh)) {
3426 ll_rw_block(READ, 1, &bh);
3428 /* Uhhuh. Read error. Complain and punt. */
3429 if (!buffer_uptodate(bh))
3433 if (ext4_should_journal_data(inode)) {
3434 BUFFER_TRACE(bh, "get write access");
3435 err = ext4_journal_get_write_access(handle, bh);
3440 zero_user(page, offset, length);
3442 BUFFER_TRACE(bh, "zeroed end of block");
3445 if (ext4_should_journal_data(inode)) {
3446 err = ext4_handle_dirty_metadata(handle, inode, bh);
3448 mark_buffer_dirty(bh);
3452 page_cache_release(page);
3456 int ext4_can_truncate(struct inode *inode)
3458 if (S_ISREG(inode->i_mode))
3460 if (S_ISDIR(inode->i_mode))
3462 if (S_ISLNK(inode->i_mode))
3463 return !ext4_inode_is_fast_symlink(inode);
3468 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3469 * associated with the given offset and length
3471 * @inode: File inode
3472 * @offset: The offset where the hole will begin
3473 * @len: The length of the hole
3475 * Returns: 0 on sucess or negative on failure
3478 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3480 struct inode *inode = file->f_path.dentry->d_inode;
3481 if (!S_ISREG(inode->i_mode))
3484 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3485 /* TODO: Add support for non extent hole punching */
3489 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3490 /* TODO: Add support for bigalloc file systems */
3494 return ext4_ext_punch_hole(file, offset, length);
3500 * We block out ext4_get_block() block instantiations across the entire
3501 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3502 * simultaneously on behalf of the same inode.
3504 * As we work through the truncate and commmit bits of it to the journal there
3505 * is one core, guiding principle: the file's tree must always be consistent on
3506 * disk. We must be able to restart the truncate after a crash.
3508 * The file's tree may be transiently inconsistent in memory (although it
3509 * probably isn't), but whenever we close off and commit a journal transaction,
3510 * the contents of (the filesystem + the journal) must be consistent and
3511 * restartable. It's pretty simple, really: bottom up, right to left (although
3512 * left-to-right works OK too).
3514 * Note that at recovery time, journal replay occurs *before* the restart of
3515 * truncate against the orphan inode list.
3517 * The committed inode has the new, desired i_size (which is the same as
3518 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3519 * that this inode's truncate did not complete and it will again call
3520 * ext4_truncate() to have another go. So there will be instantiated blocks
3521 * to the right of the truncation point in a crashed ext4 filesystem. But
3522 * that's fine - as long as they are linked from the inode, the post-crash
3523 * ext4_truncate() run will find them and release them.
3525 void ext4_truncate(struct inode *inode)
3527 trace_ext4_truncate_enter(inode);
3529 if (!ext4_can_truncate(inode))
3532 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3534 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3535 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3537 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3538 ext4_ext_truncate(inode);
3540 ext4_ind_truncate(inode);
3542 trace_ext4_truncate_exit(inode);
3546 * ext4_get_inode_loc returns with an extra refcount against the inode's
3547 * underlying buffer_head on success. If 'in_mem' is true, we have all
3548 * data in memory that is needed to recreate the on-disk version of this
3551 static int __ext4_get_inode_loc(struct inode *inode,
3552 struct ext4_iloc *iloc, int in_mem)
3554 struct ext4_group_desc *gdp;
3555 struct buffer_head *bh;
3556 struct super_block *sb = inode->i_sb;
3558 int inodes_per_block, inode_offset;
3561 if (!ext4_valid_inum(sb, inode->i_ino))
3564 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3565 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3570 * Figure out the offset within the block group inode table
3572 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3573 inode_offset = ((inode->i_ino - 1) %
3574 EXT4_INODES_PER_GROUP(sb));
3575 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3576 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3578 bh = sb_getblk(sb, block);
3580 EXT4_ERROR_INODE_BLOCK(inode, block,
3581 "unable to read itable block");
3584 if (!buffer_uptodate(bh)) {
3588 * If the buffer has the write error flag, we have failed
3589 * to write out another inode in the same block. In this
3590 * case, we don't have to read the block because we may
3591 * read the old inode data successfully.
3593 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3594 set_buffer_uptodate(bh);
3596 if (buffer_uptodate(bh)) {
3597 /* someone brought it uptodate while we waited */
3603 * If we have all information of the inode in memory and this
3604 * is the only valid inode in the block, we need not read the
3608 struct buffer_head *bitmap_bh;
3611 start = inode_offset & ~(inodes_per_block - 1);
3613 /* Is the inode bitmap in cache? */
3614 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3619 * If the inode bitmap isn't in cache then the
3620 * optimisation may end up performing two reads instead
3621 * of one, so skip it.
3623 if (!buffer_uptodate(bitmap_bh)) {
3627 for (i = start; i < start + inodes_per_block; i++) {
3628 if (i == inode_offset)
3630 if (ext4_test_bit(i, bitmap_bh->b_data))
3634 if (i == start + inodes_per_block) {
3635 /* all other inodes are free, so skip I/O */
3636 memset(bh->b_data, 0, bh->b_size);
3637 set_buffer_uptodate(bh);
3645 * If we need to do any I/O, try to pre-readahead extra
3646 * blocks from the inode table.
3648 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3649 ext4_fsblk_t b, end, table;
3652 table = ext4_inode_table(sb, gdp);
3653 /* s_inode_readahead_blks is always a power of 2 */
3654 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3657 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3658 num = EXT4_INODES_PER_GROUP(sb);
3659 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3660 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3661 num -= ext4_itable_unused_count(sb, gdp);
3662 table += num / inodes_per_block;
3666 sb_breadahead(sb, b++);
3670 * There are other valid inodes in the buffer, this inode
3671 * has in-inode xattrs, or we don't have this inode in memory.
3672 * Read the block from disk.
3674 trace_ext4_load_inode(inode);
3676 bh->b_end_io = end_buffer_read_sync;
3677 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3679 if (!buffer_uptodate(bh)) {
3680 EXT4_ERROR_INODE_BLOCK(inode, block,
3681 "unable to read itable block");
3691 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3693 /* We have all inode data except xattrs in memory here. */
3694 return __ext4_get_inode_loc(inode, iloc,
3695 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3698 void ext4_set_inode_flags(struct inode *inode)
3700 unsigned int flags = EXT4_I(inode)->i_flags;
3702 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3703 if (flags & EXT4_SYNC_FL)
3704 inode->i_flags |= S_SYNC;
3705 if (flags & EXT4_APPEND_FL)
3706 inode->i_flags |= S_APPEND;
3707 if (flags & EXT4_IMMUTABLE_FL)
3708 inode->i_flags |= S_IMMUTABLE;
3709 if (flags & EXT4_NOATIME_FL)
3710 inode->i_flags |= S_NOATIME;
3711 if (flags & EXT4_DIRSYNC_FL)
3712 inode->i_flags |= S_DIRSYNC;
3715 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3716 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3718 unsigned int vfs_fl;
3719 unsigned long old_fl, new_fl;
3722 vfs_fl = ei->vfs_inode.i_flags;
3723 old_fl = ei->i_flags;
3724 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3725 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3727 if (vfs_fl & S_SYNC)
3728 new_fl |= EXT4_SYNC_FL;
3729 if (vfs_fl & S_APPEND)
3730 new_fl |= EXT4_APPEND_FL;
3731 if (vfs_fl & S_IMMUTABLE)
3732 new_fl |= EXT4_IMMUTABLE_FL;
3733 if (vfs_fl & S_NOATIME)
3734 new_fl |= EXT4_NOATIME_FL;
3735 if (vfs_fl & S_DIRSYNC)
3736 new_fl |= EXT4_DIRSYNC_FL;
3737 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3740 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3741 struct ext4_inode_info *ei)
3744 struct inode *inode = &(ei->vfs_inode);
3745 struct super_block *sb = inode->i_sb;
3747 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3748 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3749 /* we are using combined 48 bit field */
3750 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3751 le32_to_cpu(raw_inode->i_blocks_lo);
3752 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3753 /* i_blocks represent file system block size */
3754 return i_blocks << (inode->i_blkbits - 9);
3759 return le32_to_cpu(raw_inode->i_blocks_lo);
3763 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3765 struct ext4_iloc iloc;
3766 struct ext4_inode *raw_inode;
3767 struct ext4_inode_info *ei;
3768 struct inode *inode;
3769 journal_t *journal = EXT4_SB(sb)->s_journal;
3773 inode = iget_locked(sb, ino);
3775 return ERR_PTR(-ENOMEM);
3776 if (!(inode->i_state & I_NEW))
3782 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3785 raw_inode = ext4_raw_inode(&iloc);
3786 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3787 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3788 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3789 if (!(test_opt(inode->i_sb, NO_UID32))) {
3790 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3791 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3793 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3795 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3796 ei->i_dir_start_lookup = 0;
3797 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3798 /* We now have enough fields to check if the inode was active or not.
3799 * This is needed because nfsd might try to access dead inodes
3800 * the test is that same one that e2fsck uses
3801 * NeilBrown 1999oct15
3803 if (inode->i_nlink == 0) {
3804 if (inode->i_mode == 0 ||
3805 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3806 /* this inode is deleted */
3810 /* The only unlinked inodes we let through here have
3811 * valid i_mode and are being read by the orphan
3812 * recovery code: that's fine, we're about to complete
3813 * the process of deleting those. */
3815 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3816 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3817 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3818 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3820 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3821 inode->i_size = ext4_isize(raw_inode);
3822 ei->i_disksize = inode->i_size;
3824 ei->i_reserved_quota = 0;
3826 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3827 ei->i_block_group = iloc.block_group;
3828 ei->i_last_alloc_group = ~0;
3830 * NOTE! The in-memory inode i_data array is in little-endian order
3831 * even on big-endian machines: we do NOT byteswap the block numbers!
3833 for (block = 0; block < EXT4_N_BLOCKS; block++)
3834 ei->i_data[block] = raw_inode->i_block[block];
3835 INIT_LIST_HEAD(&ei->i_orphan);
3838 * Set transaction id's of transactions that have to be committed
3839 * to finish f[data]sync. We set them to currently running transaction
3840 * as we cannot be sure that the inode or some of its metadata isn't
3841 * part of the transaction - the inode could have been reclaimed and
3842 * now it is reread from disk.
3845 transaction_t *transaction;
3848 read_lock(&journal->j_state_lock);
3849 if (journal->j_running_transaction)
3850 transaction = journal->j_running_transaction;
3852 transaction = journal->j_committing_transaction;
3854 tid = transaction->t_tid;
3856 tid = journal->j_commit_sequence;
3857 read_unlock(&journal->j_state_lock);
3858 ei->i_sync_tid = tid;
3859 ei->i_datasync_tid = tid;
3862 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3863 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3864 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3865 EXT4_INODE_SIZE(inode->i_sb)) {
3869 if (ei->i_extra_isize == 0) {
3870 /* The extra space is currently unused. Use it. */
3871 ei->i_extra_isize = sizeof(struct ext4_inode) -
3872 EXT4_GOOD_OLD_INODE_SIZE;
3874 __le32 *magic = (void *)raw_inode +
3875 EXT4_GOOD_OLD_INODE_SIZE +
3877 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3878 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3881 ei->i_extra_isize = 0;
3883 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3884 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3885 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3886 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3888 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3889 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3890 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3892 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3896 if (ei->i_file_acl &&
3897 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3898 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3902 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3903 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3904 (S_ISLNK(inode->i_mode) &&
3905 !ext4_inode_is_fast_symlink(inode)))
3906 /* Validate extent which is part of inode */
3907 ret = ext4_ext_check_inode(inode);
3908 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3909 (S_ISLNK(inode->i_mode) &&
3910 !ext4_inode_is_fast_symlink(inode))) {
3911 /* Validate block references which are part of inode */
3912 ret = ext4_ind_check_inode(inode);
3917 if (S_ISREG(inode->i_mode)) {
3918 inode->i_op = &ext4_file_inode_operations;
3919 inode->i_fop = &ext4_file_operations;
3920 ext4_set_aops(inode);
3921 } else if (S_ISDIR(inode->i_mode)) {
3922 inode->i_op = &ext4_dir_inode_operations;
3923 inode->i_fop = &ext4_dir_operations;
3924 } else if (S_ISLNK(inode->i_mode)) {
3925 if (ext4_inode_is_fast_symlink(inode)) {
3926 inode->i_op = &ext4_fast_symlink_inode_operations;
3927 nd_terminate_link(ei->i_data, inode->i_size,
3928 sizeof(ei->i_data) - 1);
3930 inode->i_op = &ext4_symlink_inode_operations;
3931 ext4_set_aops(inode);
3933 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3934 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3935 inode->i_op = &ext4_special_inode_operations;
3936 if (raw_inode->i_block[0])
3937 init_special_inode(inode, inode->i_mode,
3938 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3940 init_special_inode(inode, inode->i_mode,
3941 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3944 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3948 ext4_set_inode_flags(inode);
3949 unlock_new_inode(inode);
3955 return ERR_PTR(ret);
3958 static int ext4_inode_blocks_set(handle_t *handle,
3959 struct ext4_inode *raw_inode,
3960 struct ext4_inode_info *ei)
3962 struct inode *inode = &(ei->vfs_inode);
3963 u64 i_blocks = inode->i_blocks;
3964 struct super_block *sb = inode->i_sb;
3966 if (i_blocks <= ~0U) {
3968 * i_blocks can be represnted in a 32 bit variable
3969 * as multiple of 512 bytes
3971 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3972 raw_inode->i_blocks_high = 0;
3973 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3976 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3979 if (i_blocks <= 0xffffffffffffULL) {
3981 * i_blocks can be represented in a 48 bit variable
3982 * as multiple of 512 bytes
3984 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3985 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3986 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3988 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3989 /* i_block is stored in file system block size */
3990 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3991 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3992 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3998 * Post the struct inode info into an on-disk inode location in the
3999 * buffer-cache. This gobbles the caller's reference to the
4000 * buffer_head in the inode location struct.
4002 * The caller must have write access to iloc->bh.
4004 static int ext4_do_update_inode(handle_t *handle,
4005 struct inode *inode,
4006 struct ext4_iloc *iloc)
4008 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4009 struct ext4_inode_info *ei = EXT4_I(inode);
4010 struct buffer_head *bh = iloc->bh;
4011 int err = 0, rc, block;
4013 /* For fields not not tracking in the in-memory inode,
4014 * initialise them to zero for new inodes. */
4015 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4016 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4018 ext4_get_inode_flags(ei);
4019 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4020 if (!(test_opt(inode->i_sb, NO_UID32))) {
4021 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4022 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4024 * Fix up interoperability with old kernels. Otherwise, old inodes get
4025 * re-used with the upper 16 bits of the uid/gid intact
4028 raw_inode->i_uid_high =
4029 cpu_to_le16(high_16_bits(inode->i_uid));
4030 raw_inode->i_gid_high =
4031 cpu_to_le16(high_16_bits(inode->i_gid));
4033 raw_inode->i_uid_high = 0;
4034 raw_inode->i_gid_high = 0;
4037 raw_inode->i_uid_low =
4038 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4039 raw_inode->i_gid_low =
4040 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4041 raw_inode->i_uid_high = 0;
4042 raw_inode->i_gid_high = 0;
4044 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4046 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4047 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4048 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4049 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4051 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4053 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4054 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4055 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4056 cpu_to_le32(EXT4_OS_HURD))
4057 raw_inode->i_file_acl_high =
4058 cpu_to_le16(ei->i_file_acl >> 32);
4059 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4060 ext4_isize_set(raw_inode, ei->i_disksize);
4061 if (ei->i_disksize > 0x7fffffffULL) {
4062 struct super_block *sb = inode->i_sb;
4063 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4064 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4065 EXT4_SB(sb)->s_es->s_rev_level ==
4066 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4067 /* If this is the first large file
4068 * created, add a flag to the superblock.
4070 err = ext4_journal_get_write_access(handle,
4071 EXT4_SB(sb)->s_sbh);
4074 ext4_update_dynamic_rev(sb);
4075 EXT4_SET_RO_COMPAT_FEATURE(sb,
4076 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4078 ext4_handle_sync(handle);
4079 err = ext4_handle_dirty_metadata(handle, NULL,
4080 EXT4_SB(sb)->s_sbh);
4083 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4084 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4085 if (old_valid_dev(inode->i_rdev)) {
4086 raw_inode->i_block[0] =
4087 cpu_to_le32(old_encode_dev(inode->i_rdev));
4088 raw_inode->i_block[1] = 0;
4090 raw_inode->i_block[0] = 0;
4091 raw_inode->i_block[1] =
4092 cpu_to_le32(new_encode_dev(inode->i_rdev));
4093 raw_inode->i_block[2] = 0;
4096 for (block = 0; block < EXT4_N_BLOCKS; block++)
4097 raw_inode->i_block[block] = ei->i_data[block];
4099 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4100 if (ei->i_extra_isize) {
4101 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4102 raw_inode->i_version_hi =
4103 cpu_to_le32(inode->i_version >> 32);
4104 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4107 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4108 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4111 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4113 ext4_update_inode_fsync_trans(handle, inode, 0);
4116 ext4_std_error(inode->i_sb, err);
4121 * ext4_write_inode()
4123 * We are called from a few places:
4125 * - Within generic_file_write() for O_SYNC files.
4126 * Here, there will be no transaction running. We wait for any running
4127 * trasnaction to commit.
4129 * - Within sys_sync(), kupdate and such.
4130 * We wait on commit, if tol to.
4132 * - Within prune_icache() (PF_MEMALLOC == true)
4133 * Here we simply return. We can't afford to block kswapd on the
4136 * In all cases it is actually safe for us to return without doing anything,
4137 * because the inode has been copied into a raw inode buffer in
4138 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4141 * Note that we are absolutely dependent upon all inode dirtiers doing the
4142 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4143 * which we are interested.
4145 * It would be a bug for them to not do this. The code:
4147 * mark_inode_dirty(inode)
4149 * inode->i_size = expr;
4151 * is in error because a kswapd-driven write_inode() could occur while
4152 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4153 * will no longer be on the superblock's dirty inode list.
4155 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4159 if (current->flags & PF_MEMALLOC)
4162 if (EXT4_SB(inode->i_sb)->s_journal) {
4163 if (ext4_journal_current_handle()) {
4164 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4169 if (wbc->sync_mode != WB_SYNC_ALL)
4172 err = ext4_force_commit(inode->i_sb);
4174 struct ext4_iloc iloc;
4176 err = __ext4_get_inode_loc(inode, &iloc, 0);
4179 if (wbc->sync_mode == WB_SYNC_ALL)
4180 sync_dirty_buffer(iloc.bh);
4181 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4182 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4183 "IO error syncing inode");
4194 * Called from notify_change.
4196 * We want to trap VFS attempts to truncate the file as soon as
4197 * possible. In particular, we want to make sure that when the VFS
4198 * shrinks i_size, we put the inode on the orphan list and modify
4199 * i_disksize immediately, so that during the subsequent flushing of
4200 * dirty pages and freeing of disk blocks, we can guarantee that any
4201 * commit will leave the blocks being flushed in an unused state on
4202 * disk. (On recovery, the inode will get truncated and the blocks will
4203 * be freed, so we have a strong guarantee that no future commit will
4204 * leave these blocks visible to the user.)
4206 * Another thing we have to assure is that if we are in ordered mode
4207 * and inode is still attached to the committing transaction, we must
4208 * we start writeout of all the dirty pages which are being truncated.
4209 * This way we are sure that all the data written in the previous
4210 * transaction are already on disk (truncate waits for pages under
4213 * Called with inode->i_mutex down.
4215 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4217 struct inode *inode = dentry->d_inode;
4220 const unsigned int ia_valid = attr->ia_valid;
4222 error = inode_change_ok(inode, attr);
4226 if (is_quota_modification(inode, attr))
4227 dquot_initialize(inode);
4228 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4229 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4232 /* (user+group)*(old+new) structure, inode write (sb,
4233 * inode block, ? - but truncate inode update has it) */
4234 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4235 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4236 if (IS_ERR(handle)) {
4237 error = PTR_ERR(handle);
4240 error = dquot_transfer(inode, attr);
4242 ext4_journal_stop(handle);
4245 /* Update corresponding info in inode so that everything is in
4246 * one transaction */
4247 if (attr->ia_valid & ATTR_UID)
4248 inode->i_uid = attr->ia_uid;
4249 if (attr->ia_valid & ATTR_GID)
4250 inode->i_gid = attr->ia_gid;
4251 error = ext4_mark_inode_dirty(handle, inode);
4252 ext4_journal_stop(handle);
4255 if (attr->ia_valid & ATTR_SIZE) {
4256 inode_dio_wait(inode);
4258 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4259 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4261 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4266 if (S_ISREG(inode->i_mode) &&
4267 attr->ia_valid & ATTR_SIZE &&
4268 (attr->ia_size < inode->i_size)) {
4271 handle = ext4_journal_start(inode, 3);
4272 if (IS_ERR(handle)) {
4273 error = PTR_ERR(handle);
4276 if (ext4_handle_valid(handle)) {
4277 error = ext4_orphan_add(handle, inode);
4280 EXT4_I(inode)->i_disksize = attr->ia_size;
4281 rc = ext4_mark_inode_dirty(handle, inode);
4284 ext4_journal_stop(handle);
4286 if (ext4_should_order_data(inode)) {
4287 error = ext4_begin_ordered_truncate(inode,
4290 /* Do as much error cleanup as possible */
4291 handle = ext4_journal_start(inode, 3);
4292 if (IS_ERR(handle)) {
4293 ext4_orphan_del(NULL, inode);
4296 ext4_orphan_del(handle, inode);
4298 ext4_journal_stop(handle);
4304 if (attr->ia_valid & ATTR_SIZE) {
4305 if (attr->ia_size != i_size_read(inode)) {
4306 truncate_setsize(inode, attr->ia_size);
4307 ext4_truncate(inode);
4308 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4309 ext4_truncate(inode);
4313 setattr_copy(inode, attr);
4314 mark_inode_dirty(inode);
4318 * If the call to ext4_truncate failed to get a transaction handle at
4319 * all, we need to clean up the in-core orphan list manually.
4321 if (orphan && inode->i_nlink)
4322 ext4_orphan_del(NULL, inode);
4324 if (!rc && (ia_valid & ATTR_MODE))
4325 rc = ext4_acl_chmod(inode);
4328 ext4_std_error(inode->i_sb, error);
4334 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4337 struct inode *inode;
4338 unsigned long delalloc_blocks;
4340 inode = dentry->d_inode;
4341 generic_fillattr(inode, stat);
4344 * We can't update i_blocks if the block allocation is delayed
4345 * otherwise in the case of system crash before the real block
4346 * allocation is done, we will have i_blocks inconsistent with
4347 * on-disk file blocks.
4348 * We always keep i_blocks updated together with real
4349 * allocation. But to not confuse with user, stat
4350 * will return the blocks that include the delayed allocation
4351 * blocks for this file.
4353 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4355 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4359 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4361 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4362 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4363 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4367 * Account for index blocks, block groups bitmaps and block group
4368 * descriptor blocks if modify datablocks and index blocks
4369 * worse case, the indexs blocks spread over different block groups
4371 * If datablocks are discontiguous, they are possible to spread over
4372 * different block groups too. If they are contiuguous, with flexbg,
4373 * they could still across block group boundary.
4375 * Also account for superblock, inode, quota and xattr blocks
4377 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4379 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4385 * How many index blocks need to touch to modify nrblocks?
4386 * The "Chunk" flag indicating whether the nrblocks is
4387 * physically contiguous on disk
4389 * For Direct IO and fallocate, they calls get_block to allocate
4390 * one single extent at a time, so they could set the "Chunk" flag
4392 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4397 * Now let's see how many group bitmaps and group descriptors need
4407 if (groups > ngroups)
4409 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4410 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4412 /* bitmaps and block group descriptor blocks */
4413 ret += groups + gdpblocks;
4415 /* Blocks for super block, inode, quota and xattr blocks */
4416 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4422 * Calculate the total number of credits to reserve to fit
4423 * the modification of a single pages into a single transaction,
4424 * which may include multiple chunks of block allocations.
4426 * This could be called via ext4_write_begin()
4428 * We need to consider the worse case, when
4429 * one new block per extent.
4431 int ext4_writepage_trans_blocks(struct inode *inode)
4433 int bpp = ext4_journal_blocks_per_page(inode);
4436 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4438 /* Account for data blocks for journalled mode */
4439 if (ext4_should_journal_data(inode))
4445 * Calculate the journal credits for a chunk of data modification.
4447 * This is called from DIO, fallocate or whoever calling
4448 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4450 * journal buffers for data blocks are not included here, as DIO
4451 * and fallocate do no need to journal data buffers.
4453 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4455 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4459 * The caller must have previously called ext4_reserve_inode_write().
4460 * Give this, we know that the caller already has write access to iloc->bh.
4462 int ext4_mark_iloc_dirty(handle_t *handle,
4463 struct inode *inode, struct ext4_iloc *iloc)
4467 if (test_opt(inode->i_sb, I_VERSION))
4468 inode_inc_iversion(inode);
4470 /* the do_update_inode consumes one bh->b_count */
4473 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4474 err = ext4_do_update_inode(handle, inode, iloc);
4480 * On success, We end up with an outstanding reference count against
4481 * iloc->bh. This _must_ be cleaned up later.
4485 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4486 struct ext4_iloc *iloc)
4490 err = ext4_get_inode_loc(inode, iloc);
4492 BUFFER_TRACE(iloc->bh, "get_write_access");
4493 err = ext4_journal_get_write_access(handle, iloc->bh);
4499 ext4_std_error(inode->i_sb, err);
4504 * Expand an inode by new_extra_isize bytes.
4505 * Returns 0 on success or negative error number on failure.
4507 static int ext4_expand_extra_isize(struct inode *inode,
4508 unsigned int new_extra_isize,
4509 struct ext4_iloc iloc,
4512 struct ext4_inode *raw_inode;
4513 struct ext4_xattr_ibody_header *header;
4515 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4518 raw_inode = ext4_raw_inode(&iloc);
4520 header = IHDR(inode, raw_inode);
4522 /* No extended attributes present */
4523 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4524 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4525 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4527 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4531 /* try to expand with EAs present */
4532 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4537 * What we do here is to mark the in-core inode as clean with respect to inode
4538 * dirtiness (it may still be data-dirty).
4539 * This means that the in-core inode may be reaped by prune_icache
4540 * without having to perform any I/O. This is a very good thing,
4541 * because *any* task may call prune_icache - even ones which
4542 * have a transaction open against a different journal.
4544 * Is this cheating? Not really. Sure, we haven't written the
4545 * inode out, but prune_icache isn't a user-visible syncing function.
4546 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4547 * we start and wait on commits.
4549 * Is this efficient/effective? Well, we're being nice to the system
4550 * by cleaning up our inodes proactively so they can be reaped
4551 * without I/O. But we are potentially leaving up to five seconds'
4552 * worth of inodes floating about which prune_icache wants us to
4553 * write out. One way to fix that would be to get prune_icache()
4554 * to do a write_super() to free up some memory. It has the desired
4557 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4559 struct ext4_iloc iloc;
4560 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4561 static unsigned int mnt_count;
4565 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4566 err = ext4_reserve_inode_write(handle, inode, &iloc);
4567 if (ext4_handle_valid(handle) &&
4568 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4569 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4571 * We need extra buffer credits since we may write into EA block
4572 * with this same handle. If journal_extend fails, then it will
4573 * only result in a minor loss of functionality for that inode.
4574 * If this is felt to be critical, then e2fsck should be run to
4575 * force a large enough s_min_extra_isize.
4577 if ((jbd2_journal_extend(handle,
4578 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4579 ret = ext4_expand_extra_isize(inode,
4580 sbi->s_want_extra_isize,
4583 ext4_set_inode_state(inode,
4584 EXT4_STATE_NO_EXPAND);
4586 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4587 ext4_warning(inode->i_sb,
4588 "Unable to expand inode %lu. Delete"
4589 " some EAs or run e2fsck.",
4592 le16_to_cpu(sbi->s_es->s_mnt_count);
4598 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4603 * ext4_dirty_inode() is called from __mark_inode_dirty()
4605 * We're really interested in the case where a file is being extended.
4606 * i_size has been changed by generic_commit_write() and we thus need
4607 * to include the updated inode in the current transaction.
4609 * Also, dquot_alloc_block() will always dirty the inode when blocks
4610 * are allocated to the file.
4612 * If the inode is marked synchronous, we don't honour that here - doing
4613 * so would cause a commit on atime updates, which we don't bother doing.
4614 * We handle synchronous inodes at the highest possible level.
4616 void ext4_dirty_inode(struct inode *inode, int flags)
4620 handle = ext4_journal_start(inode, 2);
4624 ext4_mark_inode_dirty(handle, inode);
4626 ext4_journal_stop(handle);
4633 * Bind an inode's backing buffer_head into this transaction, to prevent
4634 * it from being flushed to disk early. Unlike
4635 * ext4_reserve_inode_write, this leaves behind no bh reference and
4636 * returns no iloc structure, so the caller needs to repeat the iloc
4637 * lookup to mark the inode dirty later.
4639 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4641 struct ext4_iloc iloc;
4645 err = ext4_get_inode_loc(inode, &iloc);
4647 BUFFER_TRACE(iloc.bh, "get_write_access");
4648 err = jbd2_journal_get_write_access(handle, iloc.bh);
4650 err = ext4_handle_dirty_metadata(handle,
4656 ext4_std_error(inode->i_sb, err);
4661 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4668 * We have to be very careful here: changing a data block's
4669 * journaling status dynamically is dangerous. If we write a
4670 * data block to the journal, change the status and then delete
4671 * that block, we risk forgetting to revoke the old log record
4672 * from the journal and so a subsequent replay can corrupt data.
4673 * So, first we make sure that the journal is empty and that
4674 * nobody is changing anything.
4677 journal = EXT4_JOURNAL(inode);
4680 if (is_journal_aborted(journal))
4683 jbd2_journal_lock_updates(journal);
4684 jbd2_journal_flush(journal);
4687 * OK, there are no updates running now, and all cached data is
4688 * synced to disk. We are now in a completely consistent state
4689 * which doesn't have anything in the journal, and we know that
4690 * no filesystem updates are running, so it is safe to modify
4691 * the inode's in-core data-journaling state flag now.
4695 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4697 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4698 ext4_set_aops(inode);
4700 jbd2_journal_unlock_updates(journal);
4702 /* Finally we can mark the inode as dirty. */
4704 handle = ext4_journal_start(inode, 1);
4706 return PTR_ERR(handle);
4708 err = ext4_mark_inode_dirty(handle, inode);
4709 ext4_handle_sync(handle);
4710 ext4_journal_stop(handle);
4711 ext4_std_error(inode->i_sb, err);
4716 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4718 return !buffer_mapped(bh);
4721 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4723 struct page *page = vmf->page;
4727 struct file *file = vma->vm_file;
4728 struct inode *inode = file->f_path.dentry->d_inode;
4729 struct address_space *mapping = inode->i_mapping;
4731 get_block_t *get_block;
4735 * This check is racy but catches the common case. We rely on
4736 * __block_page_mkwrite() to do a reliable check.
4738 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4739 /* Delalloc case is easy... */
4740 if (test_opt(inode->i_sb, DELALLOC) &&
4741 !ext4_should_journal_data(inode) &&
4742 !ext4_nonda_switch(inode->i_sb)) {
4744 ret = __block_page_mkwrite(vma, vmf,
4745 ext4_da_get_block_prep);
4746 } while (ret == -ENOSPC &&
4747 ext4_should_retry_alloc(inode->i_sb, &retries));
4752 size = i_size_read(inode);
4753 /* Page got truncated from under us? */
4754 if (page->mapping != mapping || page_offset(page) > size) {
4756 ret = VM_FAULT_NOPAGE;
4760 if (page->index == size >> PAGE_CACHE_SHIFT)
4761 len = size & ~PAGE_CACHE_MASK;
4763 len = PAGE_CACHE_SIZE;
4765 * Return if we have all the buffers mapped. This avoids the need to do
4766 * journal_start/journal_stop which can block and take a long time
4768 if (page_has_buffers(page)) {
4769 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4770 ext4_bh_unmapped)) {
4771 /* Wait so that we don't change page under IO */
4772 wait_on_page_writeback(page);
4773 ret = VM_FAULT_LOCKED;
4778 /* OK, we need to fill the hole... */
4779 if (ext4_should_dioread_nolock(inode))
4780 get_block = ext4_get_block_write;
4782 get_block = ext4_get_block;
4784 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4785 if (IS_ERR(handle)) {
4786 ret = VM_FAULT_SIGBUS;
4789 ret = __block_page_mkwrite(vma, vmf, get_block);
4790 if (!ret && ext4_should_journal_data(inode)) {
4791 if (walk_page_buffers(handle, page_buffers(page), 0,
4792 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4794 ret = VM_FAULT_SIGBUS;
4795 ext4_journal_stop(handle);
4798 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4800 ext4_journal_stop(handle);
4801 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4804 ret = block_page_mkwrite_return(ret);