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>
40 #include <linux/aio.h>
42 #include "ext4_jbd2.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
59 csum_lo = le16_to_cpu(raw->i_checksum_lo);
60 raw->i_checksum_lo = 0;
61 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
62 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
63 csum_hi = le16_to_cpu(raw->i_checksum_hi);
64 raw->i_checksum_hi = 0;
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
68 EXT4_INODE_SIZE(inode->i_sb));
70 raw->i_checksum_lo = cpu_to_le16(csum_lo);
71 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
72 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
73 raw->i_checksum_hi = cpu_to_le16(csum_hi);
78 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
79 struct ext4_inode_info *ei)
81 __u32 provided, calculated;
83 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
84 cpu_to_le32(EXT4_OS_LINUX) ||
85 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
86 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
89 provided = le16_to_cpu(raw->i_checksum_lo);
90 calculated = ext4_inode_csum(inode, raw, ei);
91 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
92 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
93 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
97 return provided == calculated;
100 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
101 struct ext4_inode_info *ei)
105 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
106 cpu_to_le32(EXT4_OS_LINUX) ||
107 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
108 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
111 csum = ext4_inode_csum(inode, raw, ei);
112 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
113 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
114 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
115 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
118 static inline int ext4_begin_ordered_truncate(struct inode *inode,
121 trace_ext4_begin_ordered_truncate(inode, new_size);
123 * If jinode is zero, then we never opened the file for
124 * writing, so there's no need to call
125 * jbd2_journal_begin_ordered_truncate() since there's no
126 * outstanding writes we need to flush.
128 if (!EXT4_I(inode)->jinode)
130 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
131 EXT4_I(inode)->jinode,
135 static void ext4_invalidatepage(struct page *page, unsigned int offset,
136 unsigned int length);
137 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
138 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
141 * Test whether an inode is a fast symlink.
143 static int ext4_inode_is_fast_symlink(struct inode *inode)
145 int ea_blocks = EXT4_I(inode)->i_file_acl ?
146 (inode->i_sb->s_blocksize >> 9) : 0;
148 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
152 * Restart the transaction associated with *handle. This does a commit,
153 * so before we call here everything must be consistently dirtied against
156 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
162 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
163 * moment, get_block can be called only for blocks inside i_size since
164 * page cache has been already dropped and writes are blocked by
165 * i_mutex. So we can safely drop the i_data_sem here.
167 BUG_ON(EXT4_JOURNAL(inode) == NULL);
168 jbd_debug(2, "restarting handle %p\n", handle);
169 up_write(&EXT4_I(inode)->i_data_sem);
170 ret = ext4_journal_restart(handle, nblocks);
171 down_write(&EXT4_I(inode)->i_data_sem);
172 ext4_discard_preallocations(inode);
178 * Called at the last iput() if i_nlink is zero.
180 void ext4_evict_inode(struct inode *inode)
185 trace_ext4_evict_inode(inode);
187 if (inode->i_nlink) {
189 * When journalling data dirty buffers are tracked only in the
190 * journal. So although mm thinks everything is clean and
191 * ready for reaping the inode might still have some pages to
192 * write in the running transaction or waiting to be
193 * checkpointed. Thus calling jbd2_journal_invalidatepage()
194 * (via truncate_inode_pages()) to discard these buffers can
195 * cause data loss. Also even if we did not discard these
196 * buffers, we would have no way to find them after the inode
197 * is reaped and thus user could see stale data if he tries to
198 * read them before the transaction is checkpointed. So be
199 * careful and force everything to disk here... We use
200 * ei->i_datasync_tid to store the newest transaction
201 * containing inode's data.
203 * Note that directories do not have this problem because they
204 * don't use page cache.
206 if (ext4_should_journal_data(inode) &&
207 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
208 inode->i_ino != EXT4_JOURNAL_INO) {
209 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
210 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
212 jbd2_complete_transaction(journal, commit_tid);
213 filemap_write_and_wait(&inode->i_data);
215 truncate_inode_pages(&inode->i_data, 0);
216 ext4_ioend_shutdown(inode);
220 if (!is_bad_inode(inode))
221 dquot_initialize(inode);
223 if (ext4_should_order_data(inode))
224 ext4_begin_ordered_truncate(inode, 0);
225 truncate_inode_pages(&inode->i_data, 0);
226 ext4_ioend_shutdown(inode);
228 if (is_bad_inode(inode))
232 * Protect us against freezing - iput() caller didn't have to have any
233 * protection against it
235 sb_start_intwrite(inode->i_sb);
236 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
237 ext4_blocks_for_truncate(inode)+3);
238 if (IS_ERR(handle)) {
239 ext4_std_error(inode->i_sb, PTR_ERR(handle));
241 * If we're going to skip the normal cleanup, we still need to
242 * make sure that the in-core orphan linked list is properly
245 ext4_orphan_del(NULL, inode);
246 sb_end_intwrite(inode->i_sb);
251 ext4_handle_sync(handle);
253 err = ext4_mark_inode_dirty(handle, inode);
255 ext4_warning(inode->i_sb,
256 "couldn't mark inode dirty (err %d)", err);
260 ext4_truncate(inode);
263 * ext4_ext_truncate() doesn't reserve any slop when it
264 * restarts journal transactions; therefore there may not be
265 * enough credits left in the handle to remove the inode from
266 * the orphan list and set the dtime field.
268 if (!ext4_handle_has_enough_credits(handle, 3)) {
269 err = ext4_journal_extend(handle, 3);
271 err = ext4_journal_restart(handle, 3);
273 ext4_warning(inode->i_sb,
274 "couldn't extend journal (err %d)", err);
276 ext4_journal_stop(handle);
277 ext4_orphan_del(NULL, inode);
278 sb_end_intwrite(inode->i_sb);
284 * Kill off the orphan record which ext4_truncate created.
285 * AKPM: I think this can be inside the above `if'.
286 * Note that ext4_orphan_del() has to be able to cope with the
287 * deletion of a non-existent orphan - this is because we don't
288 * know if ext4_truncate() actually created an orphan record.
289 * (Well, we could do this if we need to, but heck - it works)
291 ext4_orphan_del(handle, inode);
292 EXT4_I(inode)->i_dtime = get_seconds();
295 * One subtle ordering requirement: if anything has gone wrong
296 * (transaction abort, IO errors, whatever), then we can still
297 * do these next steps (the fs will already have been marked as
298 * having errors), but we can't free the inode if the mark_dirty
301 if (ext4_mark_inode_dirty(handle, inode))
302 /* If that failed, just do the required in-core inode clear. */
303 ext4_clear_inode(inode);
305 ext4_free_inode(handle, inode);
306 ext4_journal_stop(handle);
307 sb_end_intwrite(inode->i_sb);
310 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
314 qsize_t *ext4_get_reserved_space(struct inode *inode)
316 return &EXT4_I(inode)->i_reserved_quota;
321 * Calculate the number of metadata blocks need to reserve
322 * to allocate a block located at @lblock
324 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
326 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
327 return ext4_ext_calc_metadata_amount(inode, lblock);
329 return ext4_ind_calc_metadata_amount(inode, lblock);
333 * Called with i_data_sem down, which is important since we can call
334 * ext4_discard_preallocations() from here.
336 void ext4_da_update_reserve_space(struct inode *inode,
337 int used, int quota_claim)
339 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
340 struct ext4_inode_info *ei = EXT4_I(inode);
342 spin_lock(&ei->i_block_reservation_lock);
343 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
344 if (unlikely(used > ei->i_reserved_data_blocks)) {
345 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
346 "with only %d reserved data blocks",
347 __func__, inode->i_ino, used,
348 ei->i_reserved_data_blocks);
350 used = ei->i_reserved_data_blocks;
353 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
354 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
355 "with only %d reserved metadata blocks "
356 "(releasing %d blocks with reserved %d data blocks)",
357 inode->i_ino, ei->i_allocated_meta_blocks,
358 ei->i_reserved_meta_blocks, used,
359 ei->i_reserved_data_blocks);
361 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
364 /* Update per-inode reservations */
365 ei->i_reserved_data_blocks -= used;
366 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
367 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
368 used + ei->i_allocated_meta_blocks);
369 ei->i_allocated_meta_blocks = 0;
371 if (ei->i_reserved_data_blocks == 0) {
373 * We can release all of the reserved metadata blocks
374 * only when we have written all of the delayed
377 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
378 ei->i_reserved_meta_blocks);
379 ei->i_reserved_meta_blocks = 0;
380 ei->i_da_metadata_calc_len = 0;
382 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
384 /* Update quota subsystem for data blocks */
386 dquot_claim_block(inode, EXT4_C2B(sbi, used));
389 * We did fallocate with an offset that is already delayed
390 * allocated. So on delayed allocated writeback we should
391 * not re-claim the quota for fallocated blocks.
393 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
397 * If we have done all the pending block allocations and if
398 * there aren't any writers on the inode, we can discard the
399 * inode's preallocations.
401 if ((ei->i_reserved_data_blocks == 0) &&
402 (atomic_read(&inode->i_writecount) == 0))
403 ext4_discard_preallocations(inode);
406 static int __check_block_validity(struct inode *inode, const char *func,
408 struct ext4_map_blocks *map)
410 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
412 ext4_error_inode(inode, func, line, map->m_pblk,
413 "lblock %lu mapped to illegal pblock "
414 "(length %d)", (unsigned long) map->m_lblk,
421 #define check_block_validity(inode, map) \
422 __check_block_validity((inode), __func__, __LINE__, (map))
425 * Return the number of contiguous dirty pages in a given inode
426 * starting at page frame idx.
428 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
429 unsigned int max_pages)
431 struct address_space *mapping = inode->i_mapping;
435 int i, nr_pages, done = 0;
439 pagevec_init(&pvec, 0);
442 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
444 (pgoff_t)PAGEVEC_SIZE);
447 for (i = 0; i < nr_pages; i++) {
448 struct page *page = pvec.pages[i];
449 struct buffer_head *bh, *head;
452 if (unlikely(page->mapping != mapping) ||
454 PageWriteback(page) ||
455 page->index != idx) {
460 if (page_has_buffers(page)) {
461 bh = head = page_buffers(page);
463 if (!buffer_delay(bh) &&
464 !buffer_unwritten(bh))
466 bh = bh->b_this_page;
467 } while (!done && (bh != head));
474 if (num >= max_pages) {
479 pagevec_release(&pvec);
484 #ifdef ES_AGGRESSIVE_TEST
485 static void ext4_map_blocks_es_recheck(handle_t *handle,
487 struct ext4_map_blocks *es_map,
488 struct ext4_map_blocks *map,
495 * There is a race window that the result is not the same.
496 * e.g. xfstests #223 when dioread_nolock enables. The reason
497 * is that we lookup a block mapping in extent status tree with
498 * out taking i_data_sem. So at the time the unwritten extent
499 * could be converted.
501 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
502 down_read((&EXT4_I(inode)->i_data_sem));
503 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
504 retval = ext4_ext_map_blocks(handle, inode, map, flags &
505 EXT4_GET_BLOCKS_KEEP_SIZE);
507 retval = ext4_ind_map_blocks(handle, inode, map, flags &
508 EXT4_GET_BLOCKS_KEEP_SIZE);
510 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
511 up_read((&EXT4_I(inode)->i_data_sem));
513 * Clear EXT4_MAP_FROM_CLUSTER and EXT4_MAP_BOUNDARY flag
514 * because it shouldn't be marked in es_map->m_flags.
516 map->m_flags &= ~(EXT4_MAP_FROM_CLUSTER | EXT4_MAP_BOUNDARY);
519 * We don't check m_len because extent will be collpased in status
520 * tree. So the m_len might not equal.
522 if (es_map->m_lblk != map->m_lblk ||
523 es_map->m_flags != map->m_flags ||
524 es_map->m_pblk != map->m_pblk) {
525 printk("ES cache assertation failed for inode: %lu "
526 "es_cached ex [%d/%d/%llu/%x] != "
527 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
528 inode->i_ino, es_map->m_lblk, es_map->m_len,
529 es_map->m_pblk, es_map->m_flags, map->m_lblk,
530 map->m_len, map->m_pblk, map->m_flags,
534 #endif /* ES_AGGRESSIVE_TEST */
537 * The ext4_map_blocks() function tries to look up the requested blocks,
538 * and returns if the blocks are already mapped.
540 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
541 * and store the allocated blocks in the result buffer head and mark it
544 * If file type is extents based, it will call ext4_ext_map_blocks(),
545 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
548 * On success, it returns the number of blocks being mapped or allocate.
549 * if create==0 and the blocks are pre-allocated and uninitialized block,
550 * the result buffer head is unmapped. If the create ==1, it will make sure
551 * the buffer head is mapped.
553 * It returns 0 if plain look up failed (blocks have not been allocated), in
554 * that case, buffer head is unmapped
556 * It returns the error in case of allocation failure.
558 int ext4_map_blocks(handle_t *handle, struct inode *inode,
559 struct ext4_map_blocks *map, int flags)
561 struct extent_status es;
563 #ifdef ES_AGGRESSIVE_TEST
564 struct ext4_map_blocks orig_map;
566 memcpy(&orig_map, map, sizeof(*map));
570 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
571 "logical block %lu\n", inode->i_ino, flags, map->m_len,
572 (unsigned long) map->m_lblk);
574 /* Lookup extent status tree firstly */
575 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
576 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
577 map->m_pblk = ext4_es_pblock(&es) +
578 map->m_lblk - es.es_lblk;
579 map->m_flags |= ext4_es_is_written(&es) ?
580 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
581 retval = es.es_len - (map->m_lblk - es.es_lblk);
582 if (retval > map->m_len)
585 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
590 #ifdef ES_AGGRESSIVE_TEST
591 ext4_map_blocks_es_recheck(handle, inode, map,
598 * Try to see if we can get the block without requesting a new
601 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
602 down_read((&EXT4_I(inode)->i_data_sem));
603 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
604 retval = ext4_ext_map_blocks(handle, inode, map, flags &
605 EXT4_GET_BLOCKS_KEEP_SIZE);
607 retval = ext4_ind_map_blocks(handle, inode, map, flags &
608 EXT4_GET_BLOCKS_KEEP_SIZE);
612 unsigned long long status;
614 #ifdef ES_AGGRESSIVE_TEST
615 if (retval != map->m_len) {
616 printk("ES len assertation failed for inode: %lu "
617 "retval %d != map->m_len %d "
618 "in %s (lookup)\n", inode->i_ino, retval,
619 map->m_len, __func__);
623 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
624 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
625 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
626 ext4_find_delalloc_range(inode, map->m_lblk,
627 map->m_lblk + map->m_len - 1))
628 status |= EXTENT_STATUS_DELAYED;
629 ret = ext4_es_insert_extent(inode, map->m_lblk,
630 map->m_len, map->m_pblk, status);
634 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
635 up_read((&EXT4_I(inode)->i_data_sem));
638 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
639 int ret = check_block_validity(inode, map);
644 /* If it is only a block(s) look up */
645 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
649 * Returns if the blocks have already allocated
651 * Note that if blocks have been preallocated
652 * ext4_ext_get_block() returns the create = 0
653 * with buffer head unmapped.
655 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
659 * Here we clear m_flags because after allocating an new extent,
660 * it will be set again.
662 map->m_flags &= ~EXT4_MAP_FLAGS;
665 * New blocks allocate and/or writing to uninitialized extent
666 * will possibly result in updating i_data, so we take
667 * the write lock of i_data_sem, and call get_blocks()
668 * with create == 1 flag.
670 down_write((&EXT4_I(inode)->i_data_sem));
673 * if the caller is from delayed allocation writeout path
674 * we have already reserved fs blocks for allocation
675 * let the underlying get_block() function know to
676 * avoid double accounting
678 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
679 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
681 * We need to check for EXT4 here because migrate
682 * could have changed the inode type in between
684 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
685 retval = ext4_ext_map_blocks(handle, inode, map, flags);
687 retval = ext4_ind_map_blocks(handle, inode, map, flags);
689 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
691 * We allocated new blocks which will result in
692 * i_data's format changing. Force the migrate
693 * to fail by clearing migrate flags
695 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
699 * Update reserved blocks/metadata blocks after successful
700 * block allocation which had been deferred till now. We don't
701 * support fallocate for non extent files. So we can update
702 * reserve space here.
705 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
706 ext4_da_update_reserve_space(inode, retval, 1);
708 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
709 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
713 unsigned long long status;
715 #ifdef ES_AGGRESSIVE_TEST
716 if (retval != map->m_len) {
717 printk("ES len assertation failed for inode: %lu "
718 "retval %d != map->m_len %d "
719 "in %s (allocation)\n", inode->i_ino, retval,
720 map->m_len, __func__);
725 * If the extent has been zeroed out, we don't need to update
726 * extent status tree.
728 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
729 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
730 if (ext4_es_is_written(&es))
733 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
734 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
735 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
736 ext4_find_delalloc_range(inode, map->m_lblk,
737 map->m_lblk + map->m_len - 1))
738 status |= EXTENT_STATUS_DELAYED;
739 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
740 map->m_pblk, status);
746 up_write((&EXT4_I(inode)->i_data_sem));
747 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
748 int ret = check_block_validity(inode, map);
755 /* Maximum number of blocks we map for direct IO at once. */
756 #define DIO_MAX_BLOCKS 4096
758 static int _ext4_get_block(struct inode *inode, sector_t iblock,
759 struct buffer_head *bh, int flags)
761 handle_t *handle = ext4_journal_current_handle();
762 struct ext4_map_blocks map;
763 int ret = 0, started = 0;
766 if (ext4_has_inline_data(inode))
770 map.m_len = bh->b_size >> inode->i_blkbits;
772 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
773 /* Direct IO write... */
774 if (map.m_len > DIO_MAX_BLOCKS)
775 map.m_len = DIO_MAX_BLOCKS;
776 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
777 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
779 if (IS_ERR(handle)) {
780 ret = PTR_ERR(handle);
786 ret = ext4_map_blocks(handle, inode, &map, flags);
788 map_bh(bh, inode->i_sb, map.m_pblk);
789 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
790 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
794 ext4_journal_stop(handle);
798 int ext4_get_block(struct inode *inode, sector_t iblock,
799 struct buffer_head *bh, int create)
801 return _ext4_get_block(inode, iblock, bh,
802 create ? EXT4_GET_BLOCKS_CREATE : 0);
806 * `handle' can be NULL if create is zero
808 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
809 ext4_lblk_t block, int create, int *errp)
811 struct ext4_map_blocks map;
812 struct buffer_head *bh;
815 J_ASSERT(handle != NULL || create == 0);
819 err = ext4_map_blocks(handle, inode, &map,
820 create ? EXT4_GET_BLOCKS_CREATE : 0);
822 /* ensure we send some value back into *errp */
825 if (create && err == 0)
826 err = -ENOSPC; /* should never happen */
832 bh = sb_getblk(inode->i_sb, map.m_pblk);
837 if (map.m_flags & EXT4_MAP_NEW) {
838 J_ASSERT(create != 0);
839 J_ASSERT(handle != NULL);
842 * Now that we do not always journal data, we should
843 * keep in mind whether this should always journal the
844 * new buffer as metadata. For now, regular file
845 * writes use ext4_get_block instead, so it's not a
849 BUFFER_TRACE(bh, "call get_create_access");
850 fatal = ext4_journal_get_create_access(handle, bh);
851 if (!fatal && !buffer_uptodate(bh)) {
852 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
853 set_buffer_uptodate(bh);
856 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
857 err = ext4_handle_dirty_metadata(handle, inode, bh);
861 BUFFER_TRACE(bh, "not a new buffer");
871 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
872 ext4_lblk_t block, int create, int *err)
874 struct buffer_head *bh;
876 bh = ext4_getblk(handle, inode, block, create, err);
879 if (buffer_uptodate(bh))
881 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
883 if (buffer_uptodate(bh))
890 int ext4_walk_page_buffers(handle_t *handle,
891 struct buffer_head *head,
895 int (*fn)(handle_t *handle,
896 struct buffer_head *bh))
898 struct buffer_head *bh;
899 unsigned block_start, block_end;
900 unsigned blocksize = head->b_size;
902 struct buffer_head *next;
904 for (bh = head, block_start = 0;
905 ret == 0 && (bh != head || !block_start);
906 block_start = block_end, bh = next) {
907 next = bh->b_this_page;
908 block_end = block_start + blocksize;
909 if (block_end <= from || block_start >= to) {
910 if (partial && !buffer_uptodate(bh))
914 err = (*fn)(handle, bh);
922 * To preserve ordering, it is essential that the hole instantiation and
923 * the data write be encapsulated in a single transaction. We cannot
924 * close off a transaction and start a new one between the ext4_get_block()
925 * and the commit_write(). So doing the jbd2_journal_start at the start of
926 * prepare_write() is the right place.
928 * Also, this function can nest inside ext4_writepage(). In that case, we
929 * *know* that ext4_writepage() has generated enough buffer credits to do the
930 * whole page. So we won't block on the journal in that case, which is good,
931 * because the caller may be PF_MEMALLOC.
933 * By accident, ext4 can be reentered when a transaction is open via
934 * quota file writes. If we were to commit the transaction while thus
935 * reentered, there can be a deadlock - we would be holding a quota
936 * lock, and the commit would never complete if another thread had a
937 * transaction open and was blocking on the quota lock - a ranking
940 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
941 * will _not_ run commit under these circumstances because handle->h_ref
942 * is elevated. We'll still have enough credits for the tiny quotafile
945 int do_journal_get_write_access(handle_t *handle,
946 struct buffer_head *bh)
948 int dirty = buffer_dirty(bh);
951 if (!buffer_mapped(bh) || buffer_freed(bh))
954 * __block_write_begin() could have dirtied some buffers. Clean
955 * the dirty bit as jbd2_journal_get_write_access() could complain
956 * otherwise about fs integrity issues. Setting of the dirty bit
957 * by __block_write_begin() isn't a real problem here as we clear
958 * the bit before releasing a page lock and thus writeback cannot
959 * ever write the buffer.
962 clear_buffer_dirty(bh);
963 ret = ext4_journal_get_write_access(handle, bh);
965 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
969 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
970 struct buffer_head *bh_result, int create);
971 static int ext4_write_begin(struct file *file, struct address_space *mapping,
972 loff_t pos, unsigned len, unsigned flags,
973 struct page **pagep, void **fsdata)
975 struct inode *inode = mapping->host;
976 int ret, needed_blocks;
983 trace_ext4_write_begin(inode, pos, len, flags);
985 * Reserve one block more for addition to orphan list in case
986 * we allocate blocks but write fails for some reason
988 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
989 index = pos >> PAGE_CACHE_SHIFT;
990 from = pos & (PAGE_CACHE_SIZE - 1);
993 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
994 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1003 * grab_cache_page_write_begin() can take a long time if the
1004 * system is thrashing due to memory pressure, or if the page
1005 * is being written back. So grab it first before we start
1006 * the transaction handle. This also allows us to allocate
1007 * the page (if needed) without using GFP_NOFS.
1010 page = grab_cache_page_write_begin(mapping, index, flags);
1016 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1017 if (IS_ERR(handle)) {
1018 page_cache_release(page);
1019 return PTR_ERR(handle);
1023 if (page->mapping != mapping) {
1024 /* The page got truncated from under us */
1026 page_cache_release(page);
1027 ext4_journal_stop(handle);
1030 wait_on_page_writeback(page);
1032 if (ext4_should_dioread_nolock(inode))
1033 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1035 ret = __block_write_begin(page, pos, len, ext4_get_block);
1037 if (!ret && ext4_should_journal_data(inode)) {
1038 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1040 do_journal_get_write_access);
1046 * __block_write_begin may have instantiated a few blocks
1047 * outside i_size. Trim these off again. Don't need
1048 * i_size_read because we hold i_mutex.
1050 * Add inode to orphan list in case we crash before
1053 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1054 ext4_orphan_add(handle, inode);
1056 ext4_journal_stop(handle);
1057 if (pos + len > inode->i_size) {
1058 ext4_truncate_failed_write(inode);
1060 * If truncate failed early the inode might
1061 * still be on the orphan list; we need to
1062 * make sure the inode is removed from the
1063 * orphan list in that case.
1066 ext4_orphan_del(NULL, inode);
1069 if (ret == -ENOSPC &&
1070 ext4_should_retry_alloc(inode->i_sb, &retries))
1072 page_cache_release(page);
1079 /* For write_end() in data=journal mode */
1080 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1083 if (!buffer_mapped(bh) || buffer_freed(bh))
1085 set_buffer_uptodate(bh);
1086 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1087 clear_buffer_meta(bh);
1088 clear_buffer_prio(bh);
1093 * We need to pick up the new inode size which generic_commit_write gave us
1094 * `file' can be NULL - eg, when called from page_symlink().
1096 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1097 * buffers are managed internally.
1099 static int ext4_write_end(struct file *file,
1100 struct address_space *mapping,
1101 loff_t pos, unsigned len, unsigned copied,
1102 struct page *page, void *fsdata)
1104 handle_t *handle = ext4_journal_current_handle();
1105 struct inode *inode = mapping->host;
1107 int i_size_changed = 0;
1109 trace_ext4_write_end(inode, pos, len, copied);
1110 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1111 ret = ext4_jbd2_file_inode(handle, inode);
1114 page_cache_release(page);
1119 if (ext4_has_inline_data(inode))
1120 copied = ext4_write_inline_data_end(inode, pos, len,
1123 copied = block_write_end(file, mapping, pos,
1124 len, copied, page, fsdata);
1127 * No need to use i_size_read() here, the i_size
1128 * cannot change under us because we hole i_mutex.
1130 * But it's important to update i_size while still holding page lock:
1131 * page writeout could otherwise come in and zero beyond i_size.
1133 if (pos + copied > inode->i_size) {
1134 i_size_write(inode, pos + copied);
1138 if (pos + copied > EXT4_I(inode)->i_disksize) {
1139 /* We need to mark inode dirty even if
1140 * new_i_size is less that inode->i_size
1141 * but greater than i_disksize. (hint delalloc)
1143 ext4_update_i_disksize(inode, (pos + copied));
1147 page_cache_release(page);
1150 * Don't mark the inode dirty under page lock. First, it unnecessarily
1151 * makes the holding time of page lock longer. Second, it forces lock
1152 * ordering of page lock and transaction start for journaling
1156 ext4_mark_inode_dirty(handle, inode);
1160 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1161 /* if we have allocated more blocks and copied
1162 * less. We will have blocks allocated outside
1163 * inode->i_size. So truncate them
1165 ext4_orphan_add(handle, inode);
1167 ret2 = ext4_journal_stop(handle);
1171 if (pos + len > inode->i_size) {
1172 ext4_truncate_failed_write(inode);
1174 * If truncate failed early the inode might still be
1175 * on the orphan list; we need to make sure the inode
1176 * is removed from the orphan list in that case.
1179 ext4_orphan_del(NULL, inode);
1182 return ret ? ret : copied;
1185 static int ext4_journalled_write_end(struct file *file,
1186 struct address_space *mapping,
1187 loff_t pos, unsigned len, unsigned copied,
1188 struct page *page, void *fsdata)
1190 handle_t *handle = ext4_journal_current_handle();
1191 struct inode *inode = mapping->host;
1197 trace_ext4_journalled_write_end(inode, pos, len, copied);
1198 from = pos & (PAGE_CACHE_SIZE - 1);
1201 BUG_ON(!ext4_handle_valid(handle));
1203 if (ext4_has_inline_data(inode))
1204 copied = ext4_write_inline_data_end(inode, pos, len,
1208 if (!PageUptodate(page))
1210 page_zero_new_buffers(page, from+copied, to);
1213 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1214 to, &partial, write_end_fn);
1216 SetPageUptodate(page);
1218 new_i_size = pos + copied;
1219 if (new_i_size > inode->i_size)
1220 i_size_write(inode, pos+copied);
1221 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1222 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1223 if (new_i_size > EXT4_I(inode)->i_disksize) {
1224 ext4_update_i_disksize(inode, new_i_size);
1225 ret2 = ext4_mark_inode_dirty(handle, inode);
1231 page_cache_release(page);
1232 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1233 /* if we have allocated more blocks and copied
1234 * less. We will have blocks allocated outside
1235 * inode->i_size. So truncate them
1237 ext4_orphan_add(handle, inode);
1239 ret2 = ext4_journal_stop(handle);
1242 if (pos + len > inode->i_size) {
1243 ext4_truncate_failed_write(inode);
1245 * If truncate failed early the inode might still be
1246 * on the orphan list; we need to make sure the inode
1247 * is removed from the orphan list in that case.
1250 ext4_orphan_del(NULL, inode);
1253 return ret ? ret : copied;
1257 * Reserve a metadata for a single block located at lblock
1259 static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1262 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1263 struct ext4_inode_info *ei = EXT4_I(inode);
1264 unsigned int md_needed;
1265 ext4_lblk_t save_last_lblock;
1269 * recalculate the amount of metadata blocks to reserve
1270 * in order to allocate nrblocks
1271 * worse case is one extent per block
1274 spin_lock(&ei->i_block_reservation_lock);
1276 * ext4_calc_metadata_amount() has side effects, which we have
1277 * to be prepared undo if we fail to claim space.
1279 save_len = ei->i_da_metadata_calc_len;
1280 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1281 md_needed = EXT4_NUM_B2C(sbi,
1282 ext4_calc_metadata_amount(inode, lblock));
1283 trace_ext4_da_reserve_space(inode, md_needed);
1286 * We do still charge estimated metadata to the sb though;
1287 * we cannot afford to run out of free blocks.
1289 if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1290 ei->i_da_metadata_calc_len = save_len;
1291 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1292 spin_unlock(&ei->i_block_reservation_lock);
1293 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1299 ei->i_reserved_meta_blocks += md_needed;
1300 spin_unlock(&ei->i_block_reservation_lock);
1302 return 0; /* success */
1306 * Reserve a single cluster located at lblock
1308 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1311 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1312 struct ext4_inode_info *ei = EXT4_I(inode);
1313 unsigned int md_needed;
1315 ext4_lblk_t save_last_lblock;
1319 * We will charge metadata quota at writeout time; this saves
1320 * us from metadata over-estimation, though we may go over by
1321 * a small amount in the end. Here we just reserve for data.
1323 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1328 * recalculate the amount of metadata blocks to reserve
1329 * in order to allocate nrblocks
1330 * worse case is one extent per block
1333 spin_lock(&ei->i_block_reservation_lock);
1335 * ext4_calc_metadata_amount() has side effects, which we have
1336 * to be prepared undo if we fail to claim space.
1338 save_len = ei->i_da_metadata_calc_len;
1339 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1340 md_needed = EXT4_NUM_B2C(sbi,
1341 ext4_calc_metadata_amount(inode, lblock));
1342 trace_ext4_da_reserve_space(inode, md_needed);
1345 * We do still charge estimated metadata to the sb though;
1346 * we cannot afford to run out of free blocks.
1348 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1349 ei->i_da_metadata_calc_len = save_len;
1350 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1351 spin_unlock(&ei->i_block_reservation_lock);
1352 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1356 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1359 ei->i_reserved_data_blocks++;
1360 ei->i_reserved_meta_blocks += md_needed;
1361 spin_unlock(&ei->i_block_reservation_lock);
1363 return 0; /* success */
1366 static void ext4_da_release_space(struct inode *inode, int to_free)
1368 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1369 struct ext4_inode_info *ei = EXT4_I(inode);
1372 return; /* Nothing to release, exit */
1374 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1376 trace_ext4_da_release_space(inode, to_free);
1377 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1379 * if there aren't enough reserved blocks, then the
1380 * counter is messed up somewhere. Since this
1381 * function is called from invalidate page, it's
1382 * harmless to return without any action.
1384 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1385 "ino %lu, to_free %d with only %d reserved "
1386 "data blocks", inode->i_ino, to_free,
1387 ei->i_reserved_data_blocks);
1389 to_free = ei->i_reserved_data_blocks;
1391 ei->i_reserved_data_blocks -= to_free;
1393 if (ei->i_reserved_data_blocks == 0) {
1395 * We can release all of the reserved metadata blocks
1396 * only when we have written all of the delayed
1397 * allocation blocks.
1398 * Note that in case of bigalloc, i_reserved_meta_blocks,
1399 * i_reserved_data_blocks, etc. refer to number of clusters.
1401 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1402 ei->i_reserved_meta_blocks);
1403 ei->i_reserved_meta_blocks = 0;
1404 ei->i_da_metadata_calc_len = 0;
1407 /* update fs dirty data blocks counter */
1408 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1410 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1412 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1415 static void ext4_da_page_release_reservation(struct page *page,
1416 unsigned int offset,
1417 unsigned int length)
1420 struct buffer_head *head, *bh;
1421 unsigned int curr_off = 0;
1422 struct inode *inode = page->mapping->host;
1423 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1424 unsigned int stop = offset + length;
1428 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1430 head = page_buffers(page);
1433 unsigned int next_off = curr_off + bh->b_size;
1435 if (next_off > stop)
1438 if ((offset <= curr_off) && (buffer_delay(bh))) {
1440 clear_buffer_delay(bh);
1442 curr_off = next_off;
1443 } while ((bh = bh->b_this_page) != head);
1446 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1447 ext4_es_remove_extent(inode, lblk, to_release);
1450 /* If we have released all the blocks belonging to a cluster, then we
1451 * need to release the reserved space for that cluster. */
1452 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1453 while (num_clusters > 0) {
1454 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1455 ((num_clusters - 1) << sbi->s_cluster_bits);
1456 if (sbi->s_cluster_ratio == 1 ||
1457 !ext4_find_delalloc_cluster(inode, lblk))
1458 ext4_da_release_space(inode, 1);
1465 * Delayed allocation stuff
1469 * mpage_da_submit_io - walks through extent of pages and try to write
1470 * them with writepage() call back
1472 * @mpd->inode: inode
1473 * @mpd->first_page: first page of the extent
1474 * @mpd->next_page: page after the last page of the extent
1476 * By the time mpage_da_submit_io() is called we expect all blocks
1477 * to be allocated. this may be wrong if allocation failed.
1479 * As pages are already locked by write_cache_pages(), we can't use it
1481 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1482 struct ext4_map_blocks *map)
1484 struct pagevec pvec;
1485 unsigned long index, end;
1486 int ret = 0, err, nr_pages, i;
1487 struct inode *inode = mpd->inode;
1488 struct address_space *mapping = inode->i_mapping;
1489 loff_t size = i_size_read(inode);
1490 unsigned int len, block_start;
1491 struct buffer_head *bh, *page_bufs = NULL;
1492 sector_t pblock = 0, cur_logical = 0;
1493 struct ext4_io_submit io_submit;
1495 BUG_ON(mpd->next_page <= mpd->first_page);
1496 memset(&io_submit, 0, sizeof(io_submit));
1498 * We need to start from the first_page to the next_page - 1
1499 * to make sure we also write the mapped dirty buffer_heads.
1500 * If we look at mpd->b_blocknr we would only be looking
1501 * at the currently mapped buffer_heads.
1503 index = mpd->first_page;
1504 end = mpd->next_page - 1;
1506 pagevec_init(&pvec, 0);
1507 while (index <= end) {
1508 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1511 for (i = 0; i < nr_pages; i++) {
1513 struct page *page = pvec.pages[i];
1515 index = page->index;
1519 if (index == size >> PAGE_CACHE_SHIFT)
1520 len = size & ~PAGE_CACHE_MASK;
1522 len = PAGE_CACHE_SIZE;
1524 cur_logical = index << (PAGE_CACHE_SHIFT -
1526 pblock = map->m_pblk + (cur_logical -
1531 BUG_ON(!PageLocked(page));
1532 BUG_ON(PageWriteback(page));
1534 bh = page_bufs = page_buffers(page);
1537 if (map && (cur_logical >= map->m_lblk) &&
1538 (cur_logical <= (map->m_lblk +
1539 (map->m_len - 1)))) {
1540 if (buffer_delay(bh)) {
1541 clear_buffer_delay(bh);
1542 bh->b_blocknr = pblock;
1544 if (buffer_unwritten(bh) ||
1546 BUG_ON(bh->b_blocknr != pblock);
1547 if (map->m_flags & EXT4_MAP_UNINIT)
1548 set_buffer_uninit(bh);
1549 clear_buffer_unwritten(bh);
1553 * skip page if block allocation undone and
1556 if (ext4_bh_delay_or_unwritten(NULL, bh))
1558 bh = bh->b_this_page;
1559 block_start += bh->b_size;
1562 } while (bh != page_bufs);
1569 clear_page_dirty_for_io(page);
1570 err = ext4_bio_write_page(&io_submit, page, len,
1573 mpd->pages_written++;
1575 * In error case, we have to continue because
1576 * remaining pages are still locked
1581 pagevec_release(&pvec);
1583 ext4_io_submit(&io_submit);
1587 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1591 struct pagevec pvec;
1592 struct inode *inode = mpd->inode;
1593 struct address_space *mapping = inode->i_mapping;
1594 ext4_lblk_t start, last;
1596 index = mpd->first_page;
1597 end = mpd->next_page - 1;
1599 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1600 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1601 ext4_es_remove_extent(inode, start, last - start + 1);
1603 pagevec_init(&pvec, 0);
1604 while (index <= end) {
1605 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1608 for (i = 0; i < nr_pages; i++) {
1609 struct page *page = pvec.pages[i];
1610 if (page->index > end)
1612 BUG_ON(!PageLocked(page));
1613 BUG_ON(PageWriteback(page));
1614 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1615 ClearPageUptodate(page);
1618 index = pvec.pages[nr_pages - 1]->index + 1;
1619 pagevec_release(&pvec);
1624 static void ext4_print_free_blocks(struct inode *inode)
1626 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1627 struct super_block *sb = inode->i_sb;
1628 struct ext4_inode_info *ei = EXT4_I(inode);
1630 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1631 EXT4_C2B(EXT4_SB(inode->i_sb),
1632 ext4_count_free_clusters(sb)));
1633 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1634 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1635 (long long) EXT4_C2B(EXT4_SB(sb),
1636 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1637 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1638 (long long) EXT4_C2B(EXT4_SB(sb),
1639 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1640 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1641 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1642 ei->i_reserved_data_blocks);
1643 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1644 ei->i_reserved_meta_blocks);
1645 ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1646 ei->i_allocated_meta_blocks);
1651 * mpage_da_map_and_submit - go through given space, map them
1652 * if necessary, and then submit them for I/O
1654 * @mpd - bh describing space
1656 * The function skips space we know is already mapped to disk blocks.
1659 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1661 int err, blks, get_blocks_flags;
1662 struct ext4_map_blocks map, *mapp = NULL;
1663 sector_t next = mpd->b_blocknr;
1664 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1665 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1666 handle_t *handle = NULL;
1669 * If the blocks are mapped already, or we couldn't accumulate
1670 * any blocks, then proceed immediately to the submission stage.
1672 if ((mpd->b_size == 0) ||
1673 ((mpd->b_state & (1 << BH_Mapped)) &&
1674 !(mpd->b_state & (1 << BH_Delay)) &&
1675 !(mpd->b_state & (1 << BH_Unwritten))))
1678 handle = ext4_journal_current_handle();
1682 * Call ext4_map_blocks() to allocate any delayed allocation
1683 * blocks, or to convert an uninitialized extent to be
1684 * initialized (in the case where we have written into
1685 * one or more preallocated blocks).
1687 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1688 * indicate that we are on the delayed allocation path. This
1689 * affects functions in many different parts of the allocation
1690 * call path. This flag exists primarily because we don't
1691 * want to change *many* call functions, so ext4_map_blocks()
1692 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1693 * inode's allocation semaphore is taken.
1695 * If the blocks in questions were delalloc blocks, set
1696 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1697 * variables are updated after the blocks have been allocated.
1700 map.m_len = max_blocks;
1702 * We're in delalloc path and it is possible that we're going to
1703 * need more metadata blocks than previously reserved. However
1704 * we must not fail because we're in writeback and there is
1705 * nothing we can do about it so it might result in data loss.
1706 * So use reserved blocks to allocate metadata if possible.
1708 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
1709 EXT4_GET_BLOCKS_METADATA_NOFAIL;
1710 if (ext4_should_dioread_nolock(mpd->inode))
1711 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1712 if (mpd->b_state & (1 << BH_Delay))
1713 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1716 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1718 struct super_block *sb = mpd->inode->i_sb;
1722 * If get block returns EAGAIN or ENOSPC and there
1723 * appears to be free blocks we will just let
1724 * mpage_da_submit_io() unlock all of the pages.
1729 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1735 * get block failure will cause us to loop in
1736 * writepages, because a_ops->writepage won't be able
1737 * to make progress. The page will be redirtied by
1738 * writepage and writepages will again try to write
1741 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1742 ext4_msg(sb, KERN_CRIT,
1743 "delayed block allocation failed for inode %lu "
1744 "at logical offset %llu with max blocks %zd "
1745 "with error %d", mpd->inode->i_ino,
1746 (unsigned long long) next,
1747 mpd->b_size >> mpd->inode->i_blkbits, err);
1748 ext4_msg(sb, KERN_CRIT,
1749 "This should not happen!! Data will be lost");
1751 ext4_print_free_blocks(mpd->inode);
1753 /* invalidate all the pages */
1754 ext4_da_block_invalidatepages(mpd);
1756 /* Mark this page range as having been completed */
1763 if (map.m_flags & EXT4_MAP_NEW) {
1764 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1767 for (i = 0; i < map.m_len; i++)
1768 unmap_underlying_metadata(bdev, map.m_pblk + i);
1772 * Update on-disk size along with block allocation.
1774 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1775 if (disksize > i_size_read(mpd->inode))
1776 disksize = i_size_read(mpd->inode);
1777 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1778 ext4_update_i_disksize(mpd->inode, disksize);
1779 err = ext4_mark_inode_dirty(handle, mpd->inode);
1781 ext4_error(mpd->inode->i_sb,
1782 "Failed to mark inode %lu dirty",
1787 mpage_da_submit_io(mpd, mapp);
1791 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1792 (1 << BH_Delay) | (1 << BH_Unwritten))
1795 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1797 * @mpd->lbh - extent of blocks
1798 * @logical - logical number of the block in the file
1799 * @b_state - b_state of the buffer head added
1801 * the function is used to collect contig. blocks in same state
1803 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd, sector_t logical,
1804 unsigned long b_state)
1807 int blkbits = mpd->inode->i_blkbits;
1808 int nrblocks = mpd->b_size >> blkbits;
1811 * XXX Don't go larger than mballoc is willing to allocate
1812 * This is a stopgap solution. We eventually need to fold
1813 * mpage_da_submit_io() into this function and then call
1814 * ext4_map_blocks() multiple times in a loop
1816 if (nrblocks >= (8*1024*1024 >> blkbits))
1819 /* check if the reserved journal credits might overflow */
1820 if (!ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS)) {
1821 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1823 * With non-extent format we are limited by the journal
1824 * credit available. Total credit needed to insert
1825 * nrblocks contiguous blocks is dependent on the
1826 * nrblocks. So limit nrblocks.
1832 * First block in the extent
1834 if (mpd->b_size == 0) {
1835 mpd->b_blocknr = logical;
1836 mpd->b_size = 1 << blkbits;
1837 mpd->b_state = b_state & BH_FLAGS;
1841 next = mpd->b_blocknr + nrblocks;
1843 * Can we merge the block to our big extent?
1845 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1846 mpd->b_size += 1 << blkbits;
1852 * We couldn't merge the block to our extent, so we
1853 * need to flush current extent and start new one
1855 mpage_da_map_and_submit(mpd);
1859 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1861 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1865 * This function is grabs code from the very beginning of
1866 * ext4_map_blocks, but assumes that the caller is from delayed write
1867 * time. This function looks up the requested blocks and sets the
1868 * buffer delay bit under the protection of i_data_sem.
1870 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1871 struct ext4_map_blocks *map,
1872 struct buffer_head *bh)
1874 struct extent_status es;
1876 sector_t invalid_block = ~((sector_t) 0xffff);
1877 #ifdef ES_AGGRESSIVE_TEST
1878 struct ext4_map_blocks orig_map;
1880 memcpy(&orig_map, map, sizeof(*map));
1883 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1887 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1888 "logical block %lu\n", inode->i_ino, map->m_len,
1889 (unsigned long) map->m_lblk);
1891 /* Lookup extent status tree firstly */
1892 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1894 if (ext4_es_is_hole(&es)) {
1896 down_read((&EXT4_I(inode)->i_data_sem));
1901 * Delayed extent could be allocated by fallocate.
1902 * So we need to check it.
1904 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1905 map_bh(bh, inode->i_sb, invalid_block);
1907 set_buffer_delay(bh);
1911 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1912 retval = es.es_len - (iblock - es.es_lblk);
1913 if (retval > map->m_len)
1914 retval = map->m_len;
1915 map->m_len = retval;
1916 if (ext4_es_is_written(&es))
1917 map->m_flags |= EXT4_MAP_MAPPED;
1918 else if (ext4_es_is_unwritten(&es))
1919 map->m_flags |= EXT4_MAP_UNWRITTEN;
1923 #ifdef ES_AGGRESSIVE_TEST
1924 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1930 * Try to see if we can get the block without requesting a new
1931 * file system block.
1933 down_read((&EXT4_I(inode)->i_data_sem));
1934 if (ext4_has_inline_data(inode)) {
1936 * We will soon create blocks for this page, and let
1937 * us pretend as if the blocks aren't allocated yet.
1938 * In case of clusters, we have to handle the work
1939 * of mapping from cluster so that the reserved space
1940 * is calculated properly.
1942 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1943 ext4_find_delalloc_cluster(inode, map->m_lblk))
1944 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1946 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1947 retval = ext4_ext_map_blocks(NULL, inode, map,
1948 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1950 retval = ext4_ind_map_blocks(NULL, inode, map,
1951 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1957 * XXX: __block_prepare_write() unmaps passed block,
1961 * If the block was allocated from previously allocated cluster,
1962 * then we don't need to reserve it again. However we still need
1963 * to reserve metadata for every block we're going to write.
1965 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1966 ret = ext4_da_reserve_space(inode, iblock);
1968 /* not enough space to reserve */
1973 ret = ext4_da_reserve_metadata(inode, iblock);
1975 /* not enough space to reserve */
1981 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1982 ~0, EXTENT_STATUS_DELAYED);
1988 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1989 * and it should not appear on the bh->b_state.
1991 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1993 map_bh(bh, inode->i_sb, invalid_block);
1995 set_buffer_delay(bh);
1996 } else if (retval > 0) {
1998 unsigned long long status;
2000 #ifdef ES_AGGRESSIVE_TEST
2001 if (retval != map->m_len) {
2002 printk("ES len assertation failed for inode: %lu "
2003 "retval %d != map->m_len %d "
2004 "in %s (lookup)\n", inode->i_ino, retval,
2005 map->m_len, __func__);
2009 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
2010 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
2011 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
2012 map->m_pblk, status);
2018 up_read((&EXT4_I(inode)->i_data_sem));
2024 * This is a special get_blocks_t callback which is used by
2025 * ext4_da_write_begin(). It will either return mapped block or
2026 * reserve space for a single block.
2028 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2029 * We also have b_blocknr = -1 and b_bdev initialized properly
2031 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2032 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2033 * initialized properly.
2035 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2036 struct buffer_head *bh, int create)
2038 struct ext4_map_blocks map;
2041 BUG_ON(create == 0);
2042 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2044 map.m_lblk = iblock;
2048 * first, we need to know whether the block is allocated already
2049 * preallocated blocks are unmapped but should treated
2050 * the same as allocated blocks.
2052 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
2056 map_bh(bh, inode->i_sb, map.m_pblk);
2057 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
2059 if (buffer_unwritten(bh)) {
2060 /* A delayed write to unwritten bh should be marked
2061 * new and mapped. Mapped ensures that we don't do
2062 * get_block multiple times when we write to the same
2063 * offset and new ensures that we do proper zero out
2064 * for partial write.
2067 set_buffer_mapped(bh);
2072 static int bget_one(handle_t *handle, struct buffer_head *bh)
2078 static int bput_one(handle_t *handle, struct buffer_head *bh)
2084 static int __ext4_journalled_writepage(struct page *page,
2087 struct address_space *mapping = page->mapping;
2088 struct inode *inode = mapping->host;
2089 struct buffer_head *page_bufs = NULL;
2090 handle_t *handle = NULL;
2091 int ret = 0, err = 0;
2092 int inline_data = ext4_has_inline_data(inode);
2093 struct buffer_head *inode_bh = NULL;
2095 ClearPageChecked(page);
2098 BUG_ON(page->index != 0);
2099 BUG_ON(len > ext4_get_max_inline_size(inode));
2100 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2101 if (inode_bh == NULL)
2104 page_bufs = page_buffers(page);
2109 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2112 /* As soon as we unlock the page, it can go away, but we have
2113 * references to buffers so we are safe */
2116 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2117 ext4_writepage_trans_blocks(inode));
2118 if (IS_ERR(handle)) {
2119 ret = PTR_ERR(handle);
2123 BUG_ON(!ext4_handle_valid(handle));
2126 ret = ext4_journal_get_write_access(handle, inode_bh);
2128 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
2131 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2132 do_journal_get_write_access);
2134 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2139 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2140 err = ext4_journal_stop(handle);
2144 if (!ext4_has_inline_data(inode))
2145 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2147 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2154 * Note that we don't need to start a transaction unless we're journaling data
2155 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2156 * need to file the inode to the transaction's list in ordered mode because if
2157 * we are writing back data added by write(), the inode is already there and if
2158 * we are writing back data modified via mmap(), no one guarantees in which
2159 * transaction the data will hit the disk. In case we are journaling data, we
2160 * cannot start transaction directly because transaction start ranks above page
2161 * lock so we have to do some magic.
2163 * This function can get called via...
2164 * - ext4_da_writepages after taking page lock (have journal handle)
2165 * - journal_submit_inode_data_buffers (no journal handle)
2166 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2167 * - grab_page_cache when doing write_begin (have journal handle)
2169 * We don't do any block allocation in this function. If we have page with
2170 * multiple blocks we need to write those buffer_heads that are mapped. This
2171 * is important for mmaped based write. So if we do with blocksize 1K
2172 * truncate(f, 1024);
2173 * a = mmap(f, 0, 4096);
2175 * truncate(f, 4096);
2176 * we have in the page first buffer_head mapped via page_mkwrite call back
2177 * but other buffer_heads would be unmapped but dirty (dirty done via the
2178 * do_wp_page). So writepage should write the first block. If we modify
2179 * the mmap area beyond 1024 we will again get a page_fault and the
2180 * page_mkwrite callback will do the block allocation and mark the
2181 * buffer_heads mapped.
2183 * We redirty the page if we have any buffer_heads that is either delay or
2184 * unwritten in the page.
2186 * We can get recursively called as show below.
2188 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2191 * But since we don't do any block allocation we should not deadlock.
2192 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2194 static int ext4_writepage(struct page *page,
2195 struct writeback_control *wbc)
2200 struct buffer_head *page_bufs = NULL;
2201 struct inode *inode = page->mapping->host;
2202 struct ext4_io_submit io_submit;
2204 trace_ext4_writepage(page);
2205 size = i_size_read(inode);
2206 if (page->index == size >> PAGE_CACHE_SHIFT)
2207 len = size & ~PAGE_CACHE_MASK;
2209 len = PAGE_CACHE_SIZE;
2211 page_bufs = page_buffers(page);
2213 * We cannot do block allocation or other extent handling in this
2214 * function. If there are buffers needing that, we have to redirty
2215 * the page. But we may reach here when we do a journal commit via
2216 * journal_submit_inode_data_buffers() and in that case we must write
2217 * allocated buffers to achieve data=ordered mode guarantees.
2219 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2220 ext4_bh_delay_or_unwritten)) {
2221 redirty_page_for_writepage(wbc, page);
2222 if (current->flags & PF_MEMALLOC) {
2224 * For memory cleaning there's no point in writing only
2225 * some buffers. So just bail out. Warn if we came here
2226 * from direct reclaim.
2228 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2235 if (PageChecked(page) && ext4_should_journal_data(inode))
2237 * It's mmapped pagecache. Add buffers and journal it. There
2238 * doesn't seem much point in redirtying the page here.
2240 return __ext4_journalled_writepage(page, len);
2242 memset(&io_submit, 0, sizeof(io_submit));
2243 ret = ext4_bio_write_page(&io_submit, page, len, wbc);
2244 ext4_io_submit(&io_submit);
2249 * This is called via ext4_da_writepages() to
2250 * calculate the total number of credits to reserve to fit
2251 * a single extent allocation into a single transaction,
2252 * ext4_da_writpeages() will loop calling this before
2253 * the block allocation.
2256 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2258 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2261 * With non-extent format the journal credit needed to
2262 * insert nrblocks contiguous block is dependent on
2263 * number of contiguous block. So we will limit
2264 * number of contiguous block to a sane value
2266 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2267 (max_blocks > EXT4_MAX_TRANS_DATA))
2268 max_blocks = EXT4_MAX_TRANS_DATA;
2270 return ext4_chunk_trans_blocks(inode, max_blocks);
2274 * write_cache_pages_da - walk the list of dirty pages of the given
2275 * address space and accumulate pages that need writing, and call
2276 * mpage_da_map_and_submit to map a single contiguous memory region
2277 * and then write them.
2279 static int write_cache_pages_da(handle_t *handle,
2280 struct address_space *mapping,
2281 struct writeback_control *wbc,
2282 struct mpage_da_data *mpd,
2283 pgoff_t *done_index)
2285 struct buffer_head *bh, *head;
2286 struct inode *inode = mapping->host;
2287 struct pagevec pvec;
2288 unsigned int nr_pages;
2291 long nr_to_write = wbc->nr_to_write;
2292 int i, tag, ret = 0;
2294 memset(mpd, 0, sizeof(struct mpage_da_data));
2297 pagevec_init(&pvec, 0);
2298 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2299 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2301 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2302 tag = PAGECACHE_TAG_TOWRITE;
2304 tag = PAGECACHE_TAG_DIRTY;
2306 *done_index = index;
2307 while (index <= end) {
2308 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2309 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2313 for (i = 0; i < nr_pages; i++) {
2314 struct page *page = pvec.pages[i];
2317 * At this point, the page may be truncated or
2318 * invalidated (changing page->mapping to NULL), or
2319 * even swizzled back from swapper_space to tmpfs file
2320 * mapping. However, page->index will not change
2321 * because we have a reference on the page.
2323 if (page->index > end)
2326 *done_index = page->index + 1;
2329 * If we can't merge this page, and we have
2330 * accumulated an contiguous region, write it
2332 if ((mpd->next_page != page->index) &&
2333 (mpd->next_page != mpd->first_page)) {
2334 mpage_da_map_and_submit(mpd);
2335 goto ret_extent_tail;
2341 * If the page is no longer dirty, or its
2342 * mapping no longer corresponds to inode we
2343 * are writing (which means it has been
2344 * truncated or invalidated), or the page is
2345 * already under writeback and we are not
2346 * doing a data integrity writeback, skip the page
2348 if (!PageDirty(page) ||
2349 (PageWriteback(page) &&
2350 (wbc->sync_mode == WB_SYNC_NONE)) ||
2351 unlikely(page->mapping != mapping)) {
2356 wait_on_page_writeback(page);
2357 BUG_ON(PageWriteback(page));
2360 * If we have inline data and arrive here, it means that
2361 * we will soon create the block for the 1st page, so
2362 * we'd better clear the inline data here.
2364 if (ext4_has_inline_data(inode)) {
2365 BUG_ON(ext4_test_inode_state(inode,
2366 EXT4_STATE_MAY_INLINE_DATA));
2367 ext4_destroy_inline_data(handle, inode);
2370 if (mpd->next_page != page->index)
2371 mpd->first_page = page->index;
2372 mpd->next_page = page->index + 1;
2373 logical = (sector_t) page->index <<
2374 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2376 /* Add all dirty buffers to mpd */
2377 head = page_buffers(page);
2380 BUG_ON(buffer_locked(bh));
2382 * We need to try to allocate unmapped blocks
2383 * in the same page. Otherwise we won't make
2384 * progress with the page in ext4_writepage
2386 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2387 mpage_add_bh_to_extent(mpd, logical,
2390 goto ret_extent_tail;
2391 } else if (buffer_dirty(bh) &&
2392 buffer_mapped(bh)) {
2394 * mapped dirty buffer. We need to
2395 * update the b_state because we look
2396 * at b_state in mpage_da_map_blocks.
2397 * We don't update b_size because if we
2398 * find an unmapped buffer_head later
2399 * we need to use the b_state flag of
2402 if (mpd->b_size == 0)
2404 bh->b_state & BH_FLAGS;
2407 } while ((bh = bh->b_this_page) != head);
2409 if (nr_to_write > 0) {
2411 if (nr_to_write == 0 &&
2412 wbc->sync_mode == WB_SYNC_NONE)
2414 * We stop writing back only if we are
2415 * not doing integrity sync. In case of
2416 * integrity sync we have to keep going
2417 * because someone may be concurrently
2418 * dirtying pages, and we might have
2419 * synced a lot of newly appeared dirty
2420 * pages, but have not synced all of the
2426 pagevec_release(&pvec);
2431 ret = MPAGE_DA_EXTENT_TAIL;
2433 pagevec_release(&pvec);
2439 static int ext4_da_writepages(struct address_space *mapping,
2440 struct writeback_control *wbc)
2443 int range_whole = 0;
2444 handle_t *handle = NULL;
2445 struct mpage_da_data mpd;
2446 struct inode *inode = mapping->host;
2447 int pages_written = 0;
2448 unsigned int max_pages;
2449 int range_cyclic, cycled = 1, io_done = 0;
2450 int needed_blocks, ret = 0;
2451 long desired_nr_to_write, nr_to_writebump = 0;
2452 loff_t range_start = wbc->range_start;
2453 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2454 pgoff_t done_index = 0;
2456 struct blk_plug plug;
2458 trace_ext4_da_writepages(inode, wbc);
2461 * No pages to write? This is mainly a kludge to avoid starting
2462 * a transaction for special inodes like journal inode on last iput()
2463 * because that could violate lock ordering on umount
2465 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2469 * If the filesystem has aborted, it is read-only, so return
2470 * right away instead of dumping stack traces later on that
2471 * will obscure the real source of the problem. We test
2472 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2473 * the latter could be true if the filesystem is mounted
2474 * read-only, and in that case, ext4_da_writepages should
2475 * *never* be called, so if that ever happens, we would want
2478 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2481 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2484 range_cyclic = wbc->range_cyclic;
2485 if (wbc->range_cyclic) {
2486 index = mapping->writeback_index;
2489 wbc->range_start = index << PAGE_CACHE_SHIFT;
2490 wbc->range_end = LLONG_MAX;
2491 wbc->range_cyclic = 0;
2494 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2495 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2499 * This works around two forms of stupidity. The first is in
2500 * the writeback code, which caps the maximum number of pages
2501 * written to be 1024 pages. This is wrong on multiple
2502 * levels; different architectues have a different page size,
2503 * which changes the maximum amount of data which gets
2504 * written. Secondly, 4 megabytes is way too small. XFS
2505 * forces this value to be 16 megabytes by multiplying
2506 * nr_to_write parameter by four, and then relies on its
2507 * allocator to allocate larger extents to make them
2508 * contiguous. Unfortunately this brings us to the second
2509 * stupidity, which is that ext4's mballoc code only allocates
2510 * at most 2048 blocks. So we force contiguous writes up to
2511 * the number of dirty blocks in the inode, or
2512 * sbi->max_writeback_mb_bump whichever is smaller.
2514 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2515 if (!range_cyclic && range_whole) {
2516 if (wbc->nr_to_write == LONG_MAX)
2517 desired_nr_to_write = wbc->nr_to_write;
2519 desired_nr_to_write = wbc->nr_to_write * 8;
2521 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2523 if (desired_nr_to_write > max_pages)
2524 desired_nr_to_write = max_pages;
2526 if (wbc->nr_to_write < desired_nr_to_write) {
2527 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2528 wbc->nr_to_write = desired_nr_to_write;
2532 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2533 tag_pages_for_writeback(mapping, index, end);
2535 blk_start_plug(&plug);
2536 while (!ret && wbc->nr_to_write > 0) {
2539 * we insert one extent at a time. So we need
2540 * credit needed for single extent allocation.
2541 * journalled mode is currently not supported
2544 BUG_ON(ext4_should_journal_data(inode));
2545 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2547 /* start a new transaction*/
2548 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2550 if (IS_ERR(handle)) {
2551 ret = PTR_ERR(handle);
2552 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2553 "%ld pages, ino %lu; err %d", __func__,
2554 wbc->nr_to_write, inode->i_ino, ret);
2555 blk_finish_plug(&plug);
2556 goto out_writepages;
2560 * Now call write_cache_pages_da() to find the next
2561 * contiguous region of logical blocks that need
2562 * blocks to be allocated by ext4 and submit them.
2564 ret = write_cache_pages_da(handle, mapping,
2565 wbc, &mpd, &done_index);
2567 * If we have a contiguous extent of pages and we
2568 * haven't done the I/O yet, map the blocks and submit
2571 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2572 mpage_da_map_and_submit(&mpd);
2573 ret = MPAGE_DA_EXTENT_TAIL;
2575 trace_ext4_da_write_pages(inode, &mpd);
2576 wbc->nr_to_write -= mpd.pages_written;
2578 ext4_journal_stop(handle);
2580 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2581 /* commit the transaction which would
2582 * free blocks released in the transaction
2585 jbd2_journal_force_commit_nested(sbi->s_journal);
2587 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2589 * Got one extent now try with rest of the pages.
2590 * If mpd.retval is set -EIO, journal is aborted.
2591 * So we don't need to write any more.
2593 pages_written += mpd.pages_written;
2596 } else if (wbc->nr_to_write)
2598 * There is no more writeout needed
2599 * or we requested for a noblocking writeout
2600 * and we found the device congested
2604 blk_finish_plug(&plug);
2605 if (!io_done && !cycled) {
2608 wbc->range_start = index << PAGE_CACHE_SHIFT;
2609 wbc->range_end = mapping->writeback_index - 1;
2614 wbc->range_cyclic = range_cyclic;
2615 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2617 * set the writeback_index so that range_cyclic
2618 * mode will write it back later
2620 mapping->writeback_index = done_index;
2623 wbc->nr_to_write -= nr_to_writebump;
2624 wbc->range_start = range_start;
2625 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2629 static int ext4_nonda_switch(struct super_block *sb)
2631 s64 free_clusters, dirty_clusters;
2632 struct ext4_sb_info *sbi = EXT4_SB(sb);
2635 * switch to non delalloc mode if we are running low
2636 * on free block. The free block accounting via percpu
2637 * counters can get slightly wrong with percpu_counter_batch getting
2638 * accumulated on each CPU without updating global counters
2639 * Delalloc need an accurate free block accounting. So switch
2640 * to non delalloc when we are near to error range.
2643 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2645 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2647 * Start pushing delalloc when 1/2 of free blocks are dirty.
2649 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2650 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2652 if (2 * free_clusters < 3 * dirty_clusters ||
2653 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2655 * free block count is less than 150% of dirty blocks
2656 * or free blocks is less than watermark
2663 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2664 loff_t pos, unsigned len, unsigned flags,
2665 struct page **pagep, void **fsdata)
2667 int ret, retries = 0;
2670 struct inode *inode = mapping->host;
2673 index = pos >> PAGE_CACHE_SHIFT;
2675 if (ext4_nonda_switch(inode->i_sb)) {
2676 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2677 return ext4_write_begin(file, mapping, pos,
2678 len, flags, pagep, fsdata);
2680 *fsdata = (void *)0;
2681 trace_ext4_da_write_begin(inode, pos, len, flags);
2683 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2684 ret = ext4_da_write_inline_data_begin(mapping, inode,
2694 * grab_cache_page_write_begin() can take a long time if the
2695 * system is thrashing due to memory pressure, or if the page
2696 * is being written back. So grab it first before we start
2697 * the transaction handle. This also allows us to allocate
2698 * the page (if needed) without using GFP_NOFS.
2701 page = grab_cache_page_write_begin(mapping, index, flags);
2707 * With delayed allocation, we don't log the i_disksize update
2708 * if there is delayed block allocation. But we still need
2709 * to journalling the i_disksize update if writes to the end
2710 * of file which has an already mapped buffer.
2713 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2714 if (IS_ERR(handle)) {
2715 page_cache_release(page);
2716 return PTR_ERR(handle);
2720 if (page->mapping != mapping) {
2721 /* The page got truncated from under us */
2723 page_cache_release(page);
2724 ext4_journal_stop(handle);
2727 /* In case writeback began while the page was unlocked */
2728 wait_on_page_writeback(page);
2730 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2733 ext4_journal_stop(handle);
2735 * block_write_begin may have instantiated a few blocks
2736 * outside i_size. Trim these off again. Don't need
2737 * i_size_read because we hold i_mutex.
2739 if (pos + len > inode->i_size)
2740 ext4_truncate_failed_write(inode);
2742 if (ret == -ENOSPC &&
2743 ext4_should_retry_alloc(inode->i_sb, &retries))
2746 page_cache_release(page);
2755 * Check if we should update i_disksize
2756 * when write to the end of file but not require block allocation
2758 static int ext4_da_should_update_i_disksize(struct page *page,
2759 unsigned long offset)
2761 struct buffer_head *bh;
2762 struct inode *inode = page->mapping->host;
2766 bh = page_buffers(page);
2767 idx = offset >> inode->i_blkbits;
2769 for (i = 0; i < idx; i++)
2770 bh = bh->b_this_page;
2772 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2777 static int ext4_da_write_end(struct file *file,
2778 struct address_space *mapping,
2779 loff_t pos, unsigned len, unsigned copied,
2780 struct page *page, void *fsdata)
2782 struct inode *inode = mapping->host;
2784 handle_t *handle = ext4_journal_current_handle();
2786 unsigned long start, end;
2787 int write_mode = (int)(unsigned long)fsdata;
2789 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2790 return ext4_write_end(file, mapping, pos,
2791 len, copied, page, fsdata);
2793 trace_ext4_da_write_end(inode, pos, len, copied);
2794 start = pos & (PAGE_CACHE_SIZE - 1);
2795 end = start + copied - 1;
2798 * generic_write_end() will run mark_inode_dirty() if i_size
2799 * changes. So let's piggyback the i_disksize mark_inode_dirty
2802 new_i_size = pos + copied;
2803 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2804 if (ext4_has_inline_data(inode) ||
2805 ext4_da_should_update_i_disksize(page, end)) {
2806 down_write(&EXT4_I(inode)->i_data_sem);
2807 if (new_i_size > EXT4_I(inode)->i_disksize)
2808 EXT4_I(inode)->i_disksize = new_i_size;
2809 up_write(&EXT4_I(inode)->i_data_sem);
2810 /* We need to mark inode dirty even if
2811 * new_i_size is less that inode->i_size
2812 * bu greater than i_disksize.(hint delalloc)
2814 ext4_mark_inode_dirty(handle, inode);
2818 if (write_mode != CONVERT_INLINE_DATA &&
2819 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2820 ext4_has_inline_data(inode))
2821 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2824 ret2 = generic_write_end(file, mapping, pos, len, copied,
2830 ret2 = ext4_journal_stop(handle);
2834 return ret ? ret : copied;
2837 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2838 unsigned int length)
2841 * Drop reserved blocks
2843 BUG_ON(!PageLocked(page));
2844 if (!page_has_buffers(page))
2847 ext4_da_page_release_reservation(page, offset, length);
2850 ext4_invalidatepage(page, offset, length);
2856 * Force all delayed allocation blocks to be allocated for a given inode.
2858 int ext4_alloc_da_blocks(struct inode *inode)
2860 trace_ext4_alloc_da_blocks(inode);
2862 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2863 !EXT4_I(inode)->i_reserved_meta_blocks)
2867 * We do something simple for now. The filemap_flush() will
2868 * also start triggering a write of the data blocks, which is
2869 * not strictly speaking necessary (and for users of
2870 * laptop_mode, not even desirable). However, to do otherwise
2871 * would require replicating code paths in:
2873 * ext4_da_writepages() ->
2874 * write_cache_pages() ---> (via passed in callback function)
2875 * __mpage_da_writepage() -->
2876 * mpage_add_bh_to_extent()
2877 * mpage_da_map_blocks()
2879 * The problem is that write_cache_pages(), located in
2880 * mm/page-writeback.c, marks pages clean in preparation for
2881 * doing I/O, which is not desirable if we're not planning on
2884 * We could call write_cache_pages(), and then redirty all of
2885 * the pages by calling redirty_page_for_writepage() but that
2886 * would be ugly in the extreme. So instead we would need to
2887 * replicate parts of the code in the above functions,
2888 * simplifying them because we wouldn't actually intend to
2889 * write out the pages, but rather only collect contiguous
2890 * logical block extents, call the multi-block allocator, and
2891 * then update the buffer heads with the block allocations.
2893 * For now, though, we'll cheat by calling filemap_flush(),
2894 * which will map the blocks, and start the I/O, but not
2895 * actually wait for the I/O to complete.
2897 return filemap_flush(inode->i_mapping);
2901 * bmap() is special. It gets used by applications such as lilo and by
2902 * the swapper to find the on-disk block of a specific piece of data.
2904 * Naturally, this is dangerous if the block concerned is still in the
2905 * journal. If somebody makes a swapfile on an ext4 data-journaling
2906 * filesystem and enables swap, then they may get a nasty shock when the
2907 * data getting swapped to that swapfile suddenly gets overwritten by
2908 * the original zero's written out previously to the journal and
2909 * awaiting writeback in the kernel's buffer cache.
2911 * So, if we see any bmap calls here on a modified, data-journaled file,
2912 * take extra steps to flush any blocks which might be in the cache.
2914 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2916 struct inode *inode = mapping->host;
2921 * We can get here for an inline file via the FIBMAP ioctl
2923 if (ext4_has_inline_data(inode))
2926 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2927 test_opt(inode->i_sb, DELALLOC)) {
2929 * With delalloc we want to sync the file
2930 * so that we can make sure we allocate
2933 filemap_write_and_wait(mapping);
2936 if (EXT4_JOURNAL(inode) &&
2937 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2939 * This is a REALLY heavyweight approach, but the use of
2940 * bmap on dirty files is expected to be extremely rare:
2941 * only if we run lilo or swapon on a freshly made file
2942 * do we expect this to happen.
2944 * (bmap requires CAP_SYS_RAWIO so this does not
2945 * represent an unprivileged user DOS attack --- we'd be
2946 * in trouble if mortal users could trigger this path at
2949 * NB. EXT4_STATE_JDATA is not set on files other than
2950 * regular files. If somebody wants to bmap a directory
2951 * or symlink and gets confused because the buffer
2952 * hasn't yet been flushed to disk, they deserve
2953 * everything they get.
2956 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2957 journal = EXT4_JOURNAL(inode);
2958 jbd2_journal_lock_updates(journal);
2959 err = jbd2_journal_flush(journal);
2960 jbd2_journal_unlock_updates(journal);
2966 return generic_block_bmap(mapping, block, ext4_get_block);
2969 static int ext4_readpage(struct file *file, struct page *page)
2972 struct inode *inode = page->mapping->host;
2974 trace_ext4_readpage(page);
2976 if (ext4_has_inline_data(inode))
2977 ret = ext4_readpage_inline(inode, page);
2980 return mpage_readpage(page, ext4_get_block);
2986 ext4_readpages(struct file *file, struct address_space *mapping,
2987 struct list_head *pages, unsigned nr_pages)
2989 struct inode *inode = mapping->host;
2991 /* If the file has inline data, no need to do readpages. */
2992 if (ext4_has_inline_data(inode))
2995 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2998 static void ext4_invalidatepage(struct page *page, unsigned int offset,
2999 unsigned int length)
3001 trace_ext4_invalidatepage(page, offset, length);
3003 /* No journalling happens on data buffers when this function is used */
3004 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3006 block_invalidatepage(page, offset, length);
3009 static int __ext4_journalled_invalidatepage(struct page *page,
3010 unsigned int offset,
3011 unsigned int length)
3013 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3015 trace_ext4_journalled_invalidatepage(page, offset, length);
3018 * If it's a full truncate we just forget about the pending dirtying
3020 if (offset == 0 && length == PAGE_CACHE_SIZE)
3021 ClearPageChecked(page);
3023 return jbd2_journal_invalidatepage(journal, page, offset, length);
3026 /* Wrapper for aops... */
3027 static void ext4_journalled_invalidatepage(struct page *page,
3028 unsigned int offset,
3029 unsigned int length)
3031 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3034 static int ext4_releasepage(struct page *page, gfp_t wait)
3036 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3038 trace_ext4_releasepage(page);
3040 /* Page has dirty journalled data -> cannot release */
3041 if (PageChecked(page))
3044 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3046 return try_to_free_buffers(page);
3050 * ext4_get_block used when preparing for a DIO write or buffer write.
3051 * We allocate an uinitialized extent if blocks haven't been allocated.
3052 * The extent will be converted to initialized after the IO is complete.
3054 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3055 struct buffer_head *bh_result, int create)
3057 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3058 inode->i_ino, create);
3059 return _ext4_get_block(inode, iblock, bh_result,
3060 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3063 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3064 struct buffer_head *bh_result, int create)
3066 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3067 inode->i_ino, create);
3068 return _ext4_get_block(inode, iblock, bh_result,
3069 EXT4_GET_BLOCKS_NO_LOCK);
3072 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3073 ssize_t size, void *private, int ret,
3076 struct inode *inode = file_inode(iocb->ki_filp);
3077 ext4_io_end_t *io_end = iocb->private;
3079 /* if not async direct IO or dio with 0 bytes write, just return */
3080 if (!io_end || !size)
3083 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3084 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3085 iocb->private, io_end->inode->i_ino, iocb, offset,
3088 iocb->private = NULL;
3090 /* if not aio dio with unwritten extents, just free io and return */
3091 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
3092 ext4_free_io_end(io_end);
3094 inode_dio_done(inode);
3096 aio_complete(iocb, ret, 0);
3100 io_end->offset = offset;
3101 io_end->size = size;
3103 io_end->iocb = iocb;
3104 io_end->result = ret;
3107 ext4_add_complete_io(io_end);
3111 * For ext4 extent files, ext4 will do direct-io write to holes,
3112 * preallocated extents, and those write extend the file, no need to
3113 * fall back to buffered IO.
3115 * For holes, we fallocate those blocks, mark them as uninitialized
3116 * If those blocks were preallocated, we mark sure they are split, but
3117 * still keep the range to write as uninitialized.
3119 * The unwritten extents will be converted to written when DIO is completed.
3120 * For async direct IO, since the IO may still pending when return, we
3121 * set up an end_io call back function, which will do the conversion
3122 * when async direct IO completed.
3124 * If the O_DIRECT write will extend the file then add this inode to the
3125 * orphan list. So recovery will truncate it back to the original size
3126 * if the machine crashes during the write.
3129 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3130 const struct iovec *iov, loff_t offset,
3131 unsigned long nr_segs)
3133 struct file *file = iocb->ki_filp;
3134 struct inode *inode = file->f_mapping->host;
3136 size_t count = iov_length(iov, nr_segs);
3138 get_block_t *get_block_func = NULL;
3140 loff_t final_size = offset + count;
3142 /* Use the old path for reads and writes beyond i_size. */
3143 if (rw != WRITE || final_size > inode->i_size)
3144 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3146 BUG_ON(iocb->private == NULL);
3148 /* If we do a overwrite dio, i_mutex locking can be released */
3149 overwrite = *((int *)iocb->private);
3152 atomic_inc(&inode->i_dio_count);
3153 down_read(&EXT4_I(inode)->i_data_sem);
3154 mutex_unlock(&inode->i_mutex);
3158 * We could direct write to holes and fallocate.
3160 * Allocated blocks to fill the hole are marked as
3161 * uninitialized to prevent parallel buffered read to expose
3162 * the stale data before DIO complete the data IO.
3164 * As to previously fallocated extents, ext4 get_block will
3165 * just simply mark the buffer mapped but still keep the
3166 * extents uninitialized.
3168 * For non AIO case, we will convert those unwritten extents
3169 * to written after return back from blockdev_direct_IO.
3171 * For async DIO, the conversion needs to be deferred when the
3172 * IO is completed. The ext4 end_io callback function will be
3173 * called to take care of the conversion work. Here for async
3174 * case, we allocate an io_end structure to hook to the iocb.
3176 iocb->private = NULL;
3177 ext4_inode_aio_set(inode, NULL);
3178 if (!is_sync_kiocb(iocb)) {
3179 ext4_io_end_t *io_end = ext4_init_io_end(inode, GFP_NOFS);
3184 io_end->flag |= EXT4_IO_END_DIRECT;
3185 iocb->private = io_end;
3187 * we save the io structure for current async direct
3188 * IO, so that later ext4_map_blocks() could flag the
3189 * io structure whether there is a unwritten extents
3190 * needs to be converted when IO is completed.
3192 ext4_inode_aio_set(inode, io_end);
3196 get_block_func = ext4_get_block_write_nolock;
3198 get_block_func = ext4_get_block_write;
3199 dio_flags = DIO_LOCKING;
3201 ret = __blockdev_direct_IO(rw, iocb, inode,
3202 inode->i_sb->s_bdev, iov,
3210 ext4_inode_aio_set(inode, NULL);
3212 * The io_end structure takes a reference to the inode, that
3213 * structure needs to be destroyed and the reference to the
3214 * inode need to be dropped, when IO is complete, even with 0
3215 * byte write, or failed.
3217 * In the successful AIO DIO case, the io_end structure will
3218 * be destroyed and the reference to the inode will be dropped
3219 * after the end_io call back function is called.
3221 * In the case there is 0 byte write, or error case, since VFS
3222 * direct IO won't invoke the end_io call back function, we
3223 * need to free the end_io structure here.
3225 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3226 ext4_free_io_end(iocb->private);
3227 iocb->private = NULL;
3228 } else if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3229 EXT4_STATE_DIO_UNWRITTEN)) {
3232 * for non AIO case, since the IO is already
3233 * completed, we could do the conversion right here
3235 err = ext4_convert_unwritten_extents(inode,
3239 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3243 /* take i_mutex locking again if we do a ovewrite dio */
3245 inode_dio_done(inode);
3246 up_read(&EXT4_I(inode)->i_data_sem);
3247 mutex_lock(&inode->i_mutex);
3253 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3254 const struct iovec *iov, loff_t offset,
3255 unsigned long nr_segs)
3257 struct file *file = iocb->ki_filp;
3258 struct inode *inode = file->f_mapping->host;
3262 * If we are doing data journalling we don't support O_DIRECT
3264 if (ext4_should_journal_data(inode))
3267 /* Let buffer I/O handle the inline data case. */
3268 if (ext4_has_inline_data(inode))
3271 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3272 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3273 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3275 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3276 trace_ext4_direct_IO_exit(inode, offset,
3277 iov_length(iov, nr_segs), rw, ret);
3282 * Pages can be marked dirty completely asynchronously from ext4's journalling
3283 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3284 * much here because ->set_page_dirty is called under VFS locks. The page is
3285 * not necessarily locked.
3287 * We cannot just dirty the page and leave attached buffers clean, because the
3288 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3289 * or jbddirty because all the journalling code will explode.
3291 * So what we do is to mark the page "pending dirty" and next time writepage
3292 * is called, propagate that into the buffers appropriately.
3294 static int ext4_journalled_set_page_dirty(struct page *page)
3296 SetPageChecked(page);
3297 return __set_page_dirty_nobuffers(page);
3300 static const struct address_space_operations ext4_aops = {
3301 .readpage = ext4_readpage,
3302 .readpages = ext4_readpages,
3303 .writepage = ext4_writepage,
3304 .write_begin = ext4_write_begin,
3305 .write_end = ext4_write_end,
3307 .invalidatepage = ext4_invalidatepage,
3308 .releasepage = ext4_releasepage,
3309 .direct_IO = ext4_direct_IO,
3310 .migratepage = buffer_migrate_page,
3311 .is_partially_uptodate = block_is_partially_uptodate,
3312 .error_remove_page = generic_error_remove_page,
3315 static const struct address_space_operations ext4_journalled_aops = {
3316 .readpage = ext4_readpage,
3317 .readpages = ext4_readpages,
3318 .writepage = ext4_writepage,
3319 .write_begin = ext4_write_begin,
3320 .write_end = ext4_journalled_write_end,
3321 .set_page_dirty = ext4_journalled_set_page_dirty,
3323 .invalidatepage = ext4_journalled_invalidatepage,
3324 .releasepage = ext4_releasepage,
3325 .direct_IO = ext4_direct_IO,
3326 .is_partially_uptodate = block_is_partially_uptodate,
3327 .error_remove_page = generic_error_remove_page,
3330 static const struct address_space_operations ext4_da_aops = {
3331 .readpage = ext4_readpage,
3332 .readpages = ext4_readpages,
3333 .writepage = ext4_writepage,
3334 .writepages = ext4_da_writepages,
3335 .write_begin = ext4_da_write_begin,
3336 .write_end = ext4_da_write_end,
3338 .invalidatepage = ext4_da_invalidatepage,
3339 .releasepage = ext4_releasepage,
3340 .direct_IO = ext4_direct_IO,
3341 .migratepage = buffer_migrate_page,
3342 .is_partially_uptodate = block_is_partially_uptodate,
3343 .error_remove_page = generic_error_remove_page,
3346 void ext4_set_aops(struct inode *inode)
3348 switch (ext4_inode_journal_mode(inode)) {
3349 case EXT4_INODE_ORDERED_DATA_MODE:
3350 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3352 case EXT4_INODE_WRITEBACK_DATA_MODE:
3353 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3355 case EXT4_INODE_JOURNAL_DATA_MODE:
3356 inode->i_mapping->a_ops = &ext4_journalled_aops;
3361 if (test_opt(inode->i_sb, DELALLOC))
3362 inode->i_mapping->a_ops = &ext4_da_aops;
3364 inode->i_mapping->a_ops = &ext4_aops;
3368 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3369 * up to the end of the block which corresponds to `from'.
3370 * This required during truncate. We need to physically zero the tail end
3371 * of that block so it doesn't yield old data if the file is later grown.
3373 int ext4_block_truncate_page(handle_t *handle,
3374 struct address_space *mapping, loff_t from)
3376 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3379 struct inode *inode = mapping->host;
3381 blocksize = inode->i_sb->s_blocksize;
3382 length = blocksize - (offset & (blocksize - 1));
3384 return ext4_block_zero_page_range(handle, mapping, from, length);
3388 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3389 * starting from file offset 'from'. The range to be zero'd must
3390 * be contained with in one block. If the specified range exceeds
3391 * the end of the block it will be shortened to end of the block
3392 * that cooresponds to 'from'
3394 int ext4_block_zero_page_range(handle_t *handle,
3395 struct address_space *mapping, loff_t from, loff_t length)
3397 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3398 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3399 unsigned blocksize, max, pos;
3401 struct inode *inode = mapping->host;
3402 struct buffer_head *bh;
3406 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3407 mapping_gfp_mask(mapping) & ~__GFP_FS);
3411 blocksize = inode->i_sb->s_blocksize;
3412 max = blocksize - (offset & (blocksize - 1));
3415 * correct length if it does not fall between
3416 * 'from' and the end of the block
3418 if (length > max || length < 0)
3421 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3423 if (!page_has_buffers(page))
3424 create_empty_buffers(page, blocksize, 0);
3426 /* Find the buffer that contains "offset" */
3427 bh = page_buffers(page);
3429 while (offset >= pos) {
3430 bh = bh->b_this_page;
3436 if (buffer_freed(bh)) {
3437 BUFFER_TRACE(bh, "freed: skip");
3441 if (!buffer_mapped(bh)) {
3442 BUFFER_TRACE(bh, "unmapped");
3443 ext4_get_block(inode, iblock, bh, 0);
3444 /* unmapped? It's a hole - nothing to do */
3445 if (!buffer_mapped(bh)) {
3446 BUFFER_TRACE(bh, "still unmapped");
3451 /* Ok, it's mapped. Make sure it's up-to-date */
3452 if (PageUptodate(page))
3453 set_buffer_uptodate(bh);
3455 if (!buffer_uptodate(bh)) {
3457 ll_rw_block(READ, 1, &bh);
3459 /* Uhhuh. Read error. Complain and punt. */
3460 if (!buffer_uptodate(bh))
3464 if (ext4_should_journal_data(inode)) {
3465 BUFFER_TRACE(bh, "get write access");
3466 err = ext4_journal_get_write_access(handle, bh);
3471 zero_user(page, offset, length);
3473 BUFFER_TRACE(bh, "zeroed end of block");
3476 if (ext4_should_journal_data(inode)) {
3477 err = ext4_handle_dirty_metadata(handle, inode, bh);
3479 mark_buffer_dirty(bh);
3480 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3481 err = ext4_jbd2_file_inode(handle, inode);
3486 page_cache_release(page);
3490 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3491 loff_t lstart, loff_t length)
3493 struct super_block *sb = inode->i_sb;
3494 struct address_space *mapping = inode->i_mapping;
3495 unsigned partial = lstart & (sb->s_blocksize - 1);
3496 ext4_fsblk_t start, end;
3497 loff_t byte_end = (lstart + length - 1);
3500 start = lstart >> sb->s_blocksize_bits;
3501 end = byte_end >> sb->s_blocksize_bits;
3503 /* Handle partial zero within the single block */
3505 err = ext4_block_zero_page_range(handle, mapping,
3509 /* Handle partial zero out on the start of the range */
3511 err = ext4_block_zero_page_range(handle, mapping,
3512 lstart, sb->s_blocksize);
3516 /* Handle partial zero out on the end of the range */
3517 partial = byte_end & (sb->s_blocksize - 1);
3518 if (partial != sb->s_blocksize - 1)
3519 err = ext4_block_zero_page_range(handle, mapping,
3525 int ext4_can_truncate(struct inode *inode)
3527 if (S_ISREG(inode->i_mode))
3529 if (S_ISDIR(inode->i_mode))
3531 if (S_ISLNK(inode->i_mode))
3532 return !ext4_inode_is_fast_symlink(inode);
3537 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3538 * associated with the given offset and length
3540 * @inode: File inode
3541 * @offset: The offset where the hole will begin
3542 * @len: The length of the hole
3544 * Returns: 0 on success or negative on failure
3547 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3549 struct inode *inode = file_inode(file);
3550 struct super_block *sb = inode->i_sb;
3551 ext4_lblk_t first_block, stop_block;
3552 struct address_space *mapping = inode->i_mapping;
3553 loff_t first_block_offset, last_block_offset;
3555 unsigned int credits;
3558 if (!S_ISREG(inode->i_mode))
3561 if (EXT4_SB(sb)->s_cluster_ratio > 1) {
3562 /* TODO: Add support for bigalloc file systems */
3566 trace_ext4_punch_hole(inode, offset, length);
3569 * Write out all dirty pages to avoid race conditions
3570 * Then release them.
3572 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3573 ret = filemap_write_and_wait_range(mapping, offset,
3574 offset + length - 1);
3579 mutex_lock(&inode->i_mutex);
3580 /* It's not possible punch hole on append only file */
3581 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
3585 if (IS_SWAPFILE(inode)) {
3590 /* No need to punch hole beyond i_size */
3591 if (offset >= inode->i_size)
3595 * If the hole extends beyond i_size, set the hole
3596 * to end after the page that contains i_size
3598 if (offset + length > inode->i_size) {
3599 length = inode->i_size +
3600 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3604 first_block_offset = round_up(offset, sb->s_blocksize);
3605 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3607 /* Now release the pages and zero block aligned part of pages*/
3608 if (last_block_offset > first_block_offset)
3609 truncate_pagecache_range(inode, first_block_offset,
3612 /* Wait all existing dio workers, newcomers will block on i_mutex */
3613 ext4_inode_block_unlocked_dio(inode);
3614 ret = ext4_flush_unwritten_io(inode);
3617 inode_dio_wait(inode);
3619 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3620 credits = ext4_writepage_trans_blocks(inode);
3622 credits = ext4_blocks_for_truncate(inode);
3623 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3624 if (IS_ERR(handle)) {
3625 ret = PTR_ERR(handle);
3626 ext4_std_error(sb, ret);
3630 ret = ext4_zero_partial_blocks(handle, inode, offset,
3635 first_block = (offset + sb->s_blocksize - 1) >>
3636 EXT4_BLOCK_SIZE_BITS(sb);
3637 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3639 /* If there are no blocks to remove, return now */
3640 if (first_block >= stop_block)
3643 down_write(&EXT4_I(inode)->i_data_sem);
3644 ext4_discard_preallocations(inode);
3646 ret = ext4_es_remove_extent(inode, first_block,
3647 stop_block - first_block);
3649 up_write(&EXT4_I(inode)->i_data_sem);
3653 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3654 ret = ext4_ext_remove_space(inode, first_block,
3657 ret = ext4_free_hole_blocks(handle, inode, first_block,
3660 ext4_discard_preallocations(inode);
3661 up_write(&EXT4_I(inode)->i_data_sem);
3663 ext4_handle_sync(handle);
3664 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3665 ext4_mark_inode_dirty(handle, inode);
3667 ext4_journal_stop(handle);
3669 ext4_inode_resume_unlocked_dio(inode);
3671 mutex_unlock(&inode->i_mutex);
3678 * We block out ext4_get_block() block instantiations across the entire
3679 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3680 * simultaneously on behalf of the same inode.
3682 * As we work through the truncate and commit bits of it to the journal there
3683 * is one core, guiding principle: the file's tree must always be consistent on
3684 * disk. We must be able to restart the truncate after a crash.
3686 * The file's tree may be transiently inconsistent in memory (although it
3687 * probably isn't), but whenever we close off and commit a journal transaction,
3688 * the contents of (the filesystem + the journal) must be consistent and
3689 * restartable. It's pretty simple, really: bottom up, right to left (although
3690 * left-to-right works OK too).
3692 * Note that at recovery time, journal replay occurs *before* the restart of
3693 * truncate against the orphan inode list.
3695 * The committed inode has the new, desired i_size (which is the same as
3696 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3697 * that this inode's truncate did not complete and it will again call
3698 * ext4_truncate() to have another go. So there will be instantiated blocks
3699 * to the right of the truncation point in a crashed ext4 filesystem. But
3700 * that's fine - as long as they are linked from the inode, the post-crash
3701 * ext4_truncate() run will find them and release them.
3703 void ext4_truncate(struct inode *inode)
3705 struct ext4_inode_info *ei = EXT4_I(inode);
3706 unsigned int credits;
3708 struct address_space *mapping = inode->i_mapping;
3711 * There is a possibility that we're either freeing the inode
3712 * or it completely new indode. In those cases we might not
3713 * have i_mutex locked because it's not necessary.
3715 if (!(inode->i_state & (I_NEW|I_FREEING)))
3716 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3717 trace_ext4_truncate_enter(inode);
3719 if (!ext4_can_truncate(inode))
3722 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3724 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3725 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3727 if (ext4_has_inline_data(inode)) {
3730 ext4_inline_data_truncate(inode, &has_inline);
3736 * finish any pending end_io work so we won't run the risk of
3737 * converting any truncated blocks to initialized later
3739 ext4_flush_unwritten_io(inode);
3741 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3742 credits = ext4_writepage_trans_blocks(inode);
3744 credits = ext4_blocks_for_truncate(inode);
3746 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3747 if (IS_ERR(handle)) {
3748 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3752 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3753 ext4_block_truncate_page(handle, mapping, inode->i_size);
3756 * We add the inode to the orphan list, so that if this
3757 * truncate spans multiple transactions, and we crash, we will
3758 * resume the truncate when the filesystem recovers. It also
3759 * marks the inode dirty, to catch the new size.
3761 * Implication: the file must always be in a sane, consistent
3762 * truncatable state while each transaction commits.
3764 if (ext4_orphan_add(handle, inode))
3767 down_write(&EXT4_I(inode)->i_data_sem);
3769 ext4_discard_preallocations(inode);
3771 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3772 ext4_ext_truncate(handle, inode);
3774 ext4_ind_truncate(handle, inode);
3776 up_write(&ei->i_data_sem);
3779 ext4_handle_sync(handle);
3783 * If this was a simple ftruncate() and the file will remain alive,
3784 * then we need to clear up the orphan record which we created above.
3785 * However, if this was a real unlink then we were called by
3786 * ext4_delete_inode(), and we allow that function to clean up the
3787 * orphan info for us.
3790 ext4_orphan_del(handle, inode);
3792 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3793 ext4_mark_inode_dirty(handle, inode);
3794 ext4_journal_stop(handle);
3796 trace_ext4_truncate_exit(inode);
3800 * ext4_get_inode_loc returns with an extra refcount against the inode's
3801 * underlying buffer_head on success. If 'in_mem' is true, we have all
3802 * data in memory that is needed to recreate the on-disk version of this
3805 static int __ext4_get_inode_loc(struct inode *inode,
3806 struct ext4_iloc *iloc, int in_mem)
3808 struct ext4_group_desc *gdp;
3809 struct buffer_head *bh;
3810 struct super_block *sb = inode->i_sb;
3812 int inodes_per_block, inode_offset;
3815 if (!ext4_valid_inum(sb, inode->i_ino))
3818 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3819 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3824 * Figure out the offset within the block group inode table
3826 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3827 inode_offset = ((inode->i_ino - 1) %
3828 EXT4_INODES_PER_GROUP(sb));
3829 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3830 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3832 bh = sb_getblk(sb, block);
3835 if (!buffer_uptodate(bh)) {
3839 * If the buffer has the write error flag, we have failed
3840 * to write out another inode in the same block. In this
3841 * case, we don't have to read the block because we may
3842 * read the old inode data successfully.
3844 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3845 set_buffer_uptodate(bh);
3847 if (buffer_uptodate(bh)) {
3848 /* someone brought it uptodate while we waited */
3854 * If we have all information of the inode in memory and this
3855 * is the only valid inode in the block, we need not read the
3859 struct buffer_head *bitmap_bh;
3862 start = inode_offset & ~(inodes_per_block - 1);
3864 /* Is the inode bitmap in cache? */
3865 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3866 if (unlikely(!bitmap_bh))
3870 * If the inode bitmap isn't in cache then the
3871 * optimisation may end up performing two reads instead
3872 * of one, so skip it.
3874 if (!buffer_uptodate(bitmap_bh)) {
3878 for (i = start; i < start + inodes_per_block; i++) {
3879 if (i == inode_offset)
3881 if (ext4_test_bit(i, bitmap_bh->b_data))
3885 if (i == start + inodes_per_block) {
3886 /* all other inodes are free, so skip I/O */
3887 memset(bh->b_data, 0, bh->b_size);
3888 set_buffer_uptodate(bh);
3896 * If we need to do any I/O, try to pre-readahead extra
3897 * blocks from the inode table.
3899 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3900 ext4_fsblk_t b, end, table;
3902 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3904 table = ext4_inode_table(sb, gdp);
3905 /* s_inode_readahead_blks is always a power of 2 */
3906 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3910 num = EXT4_INODES_PER_GROUP(sb);
3911 if (ext4_has_group_desc_csum(sb))
3912 num -= ext4_itable_unused_count(sb, gdp);
3913 table += num / inodes_per_block;
3917 sb_breadahead(sb, b++);
3921 * There are other valid inodes in the buffer, this inode
3922 * has in-inode xattrs, or we don't have this inode in memory.
3923 * Read the block from disk.
3925 trace_ext4_load_inode(inode);
3927 bh->b_end_io = end_buffer_read_sync;
3928 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3930 if (!buffer_uptodate(bh)) {
3931 EXT4_ERROR_INODE_BLOCK(inode, block,
3932 "unable to read itable block");
3942 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3944 /* We have all inode data except xattrs in memory here. */
3945 return __ext4_get_inode_loc(inode, iloc,
3946 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3949 void ext4_set_inode_flags(struct inode *inode)
3951 unsigned int flags = EXT4_I(inode)->i_flags;
3953 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3954 if (flags & EXT4_SYNC_FL)
3955 inode->i_flags |= S_SYNC;
3956 if (flags & EXT4_APPEND_FL)
3957 inode->i_flags |= S_APPEND;
3958 if (flags & EXT4_IMMUTABLE_FL)
3959 inode->i_flags |= S_IMMUTABLE;
3960 if (flags & EXT4_NOATIME_FL)
3961 inode->i_flags |= S_NOATIME;
3962 if (flags & EXT4_DIRSYNC_FL)
3963 inode->i_flags |= S_DIRSYNC;
3966 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3967 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3969 unsigned int vfs_fl;
3970 unsigned long old_fl, new_fl;
3973 vfs_fl = ei->vfs_inode.i_flags;
3974 old_fl = ei->i_flags;
3975 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3976 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3978 if (vfs_fl & S_SYNC)
3979 new_fl |= EXT4_SYNC_FL;
3980 if (vfs_fl & S_APPEND)
3981 new_fl |= EXT4_APPEND_FL;
3982 if (vfs_fl & S_IMMUTABLE)
3983 new_fl |= EXT4_IMMUTABLE_FL;
3984 if (vfs_fl & S_NOATIME)
3985 new_fl |= EXT4_NOATIME_FL;
3986 if (vfs_fl & S_DIRSYNC)
3987 new_fl |= EXT4_DIRSYNC_FL;
3988 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3991 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3992 struct ext4_inode_info *ei)
3995 struct inode *inode = &(ei->vfs_inode);
3996 struct super_block *sb = inode->i_sb;
3998 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3999 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4000 /* we are using combined 48 bit field */
4001 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4002 le32_to_cpu(raw_inode->i_blocks_lo);
4003 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4004 /* i_blocks represent file system block size */
4005 return i_blocks << (inode->i_blkbits - 9);
4010 return le32_to_cpu(raw_inode->i_blocks_lo);
4014 static inline void ext4_iget_extra_inode(struct inode *inode,
4015 struct ext4_inode *raw_inode,
4016 struct ext4_inode_info *ei)
4018 __le32 *magic = (void *)raw_inode +
4019 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4020 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4021 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4022 ext4_find_inline_data_nolock(inode);
4024 EXT4_I(inode)->i_inline_off = 0;
4027 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4029 struct ext4_iloc iloc;
4030 struct ext4_inode *raw_inode;
4031 struct ext4_inode_info *ei;
4032 struct inode *inode;
4033 journal_t *journal = EXT4_SB(sb)->s_journal;
4039 inode = iget_locked(sb, ino);
4041 return ERR_PTR(-ENOMEM);
4042 if (!(inode->i_state & I_NEW))
4048 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4051 raw_inode = ext4_raw_inode(&iloc);
4053 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4054 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4055 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4056 EXT4_INODE_SIZE(inode->i_sb)) {
4057 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4058 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4059 EXT4_INODE_SIZE(inode->i_sb));
4064 ei->i_extra_isize = 0;
4066 /* Precompute checksum seed for inode metadata */
4067 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4068 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
4069 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4071 __le32 inum = cpu_to_le32(inode->i_ino);
4072 __le32 gen = raw_inode->i_generation;
4073 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4075 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4079 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4080 EXT4_ERROR_INODE(inode, "checksum invalid");
4085 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4086 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4087 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4088 if (!(test_opt(inode->i_sb, NO_UID32))) {
4089 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4090 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4092 i_uid_write(inode, i_uid);
4093 i_gid_write(inode, i_gid);
4094 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4096 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4097 ei->i_inline_off = 0;
4098 ei->i_dir_start_lookup = 0;
4099 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4100 /* We now have enough fields to check if the inode was active or not.
4101 * This is needed because nfsd might try to access dead inodes
4102 * the test is that same one that e2fsck uses
4103 * NeilBrown 1999oct15
4105 if (inode->i_nlink == 0) {
4106 if ((inode->i_mode == 0 ||
4107 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4108 ino != EXT4_BOOT_LOADER_INO) {
4109 /* this inode is deleted */
4113 /* The only unlinked inodes we let through here have
4114 * valid i_mode and are being read by the orphan
4115 * recovery code: that's fine, we're about to complete
4116 * the process of deleting those.
4117 * OR it is the EXT4_BOOT_LOADER_INO which is
4118 * not initialized on a new filesystem. */
4120 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4121 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4122 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4123 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4125 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4126 inode->i_size = ext4_isize(raw_inode);
4127 ei->i_disksize = inode->i_size;
4129 ei->i_reserved_quota = 0;
4131 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4132 ei->i_block_group = iloc.block_group;
4133 ei->i_last_alloc_group = ~0;
4135 * NOTE! The in-memory inode i_data array is in little-endian order
4136 * even on big-endian machines: we do NOT byteswap the block numbers!
4138 for (block = 0; block < EXT4_N_BLOCKS; block++)
4139 ei->i_data[block] = raw_inode->i_block[block];
4140 INIT_LIST_HEAD(&ei->i_orphan);
4143 * Set transaction id's of transactions that have to be committed
4144 * to finish f[data]sync. We set them to currently running transaction
4145 * as we cannot be sure that the inode or some of its metadata isn't
4146 * part of the transaction - the inode could have been reclaimed and
4147 * now it is reread from disk.
4150 transaction_t *transaction;
4153 read_lock(&journal->j_state_lock);
4154 if (journal->j_running_transaction)
4155 transaction = journal->j_running_transaction;
4157 transaction = journal->j_committing_transaction;
4159 tid = transaction->t_tid;
4161 tid = journal->j_commit_sequence;
4162 read_unlock(&journal->j_state_lock);
4163 ei->i_sync_tid = tid;
4164 ei->i_datasync_tid = tid;
4167 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4168 if (ei->i_extra_isize == 0) {
4169 /* The extra space is currently unused. Use it. */
4170 ei->i_extra_isize = sizeof(struct ext4_inode) -
4171 EXT4_GOOD_OLD_INODE_SIZE;
4173 ext4_iget_extra_inode(inode, raw_inode, ei);
4177 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4178 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4179 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4180 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4182 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4183 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4184 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4186 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4190 if (ei->i_file_acl &&
4191 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4192 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4196 } else if (!ext4_has_inline_data(inode)) {
4197 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4198 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4199 (S_ISLNK(inode->i_mode) &&
4200 !ext4_inode_is_fast_symlink(inode))))
4201 /* Validate extent which is part of inode */
4202 ret = ext4_ext_check_inode(inode);
4203 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4204 (S_ISLNK(inode->i_mode) &&
4205 !ext4_inode_is_fast_symlink(inode))) {
4206 /* Validate block references which are part of inode */
4207 ret = ext4_ind_check_inode(inode);
4213 if (S_ISREG(inode->i_mode)) {
4214 inode->i_op = &ext4_file_inode_operations;
4215 inode->i_fop = &ext4_file_operations;
4216 ext4_set_aops(inode);
4217 } else if (S_ISDIR(inode->i_mode)) {
4218 inode->i_op = &ext4_dir_inode_operations;
4219 inode->i_fop = &ext4_dir_operations;
4220 } else if (S_ISLNK(inode->i_mode)) {
4221 if (ext4_inode_is_fast_symlink(inode)) {
4222 inode->i_op = &ext4_fast_symlink_inode_operations;
4223 nd_terminate_link(ei->i_data, inode->i_size,
4224 sizeof(ei->i_data) - 1);
4226 inode->i_op = &ext4_symlink_inode_operations;
4227 ext4_set_aops(inode);
4229 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4230 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4231 inode->i_op = &ext4_special_inode_operations;
4232 if (raw_inode->i_block[0])
4233 init_special_inode(inode, inode->i_mode,
4234 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4236 init_special_inode(inode, inode->i_mode,
4237 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4238 } else if (ino == EXT4_BOOT_LOADER_INO) {
4239 make_bad_inode(inode);
4242 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4246 ext4_set_inode_flags(inode);
4247 unlock_new_inode(inode);
4253 return ERR_PTR(ret);
4256 static int ext4_inode_blocks_set(handle_t *handle,
4257 struct ext4_inode *raw_inode,
4258 struct ext4_inode_info *ei)
4260 struct inode *inode = &(ei->vfs_inode);
4261 u64 i_blocks = inode->i_blocks;
4262 struct super_block *sb = inode->i_sb;
4264 if (i_blocks <= ~0U) {
4266 * i_blocks can be represented in a 32 bit variable
4267 * as multiple of 512 bytes
4269 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4270 raw_inode->i_blocks_high = 0;
4271 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4274 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4277 if (i_blocks <= 0xffffffffffffULL) {
4279 * i_blocks can be represented in a 48 bit variable
4280 * as multiple of 512 bytes
4282 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4283 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4284 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4286 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4287 /* i_block is stored in file system block size */
4288 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4289 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4290 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4296 * Post the struct inode info into an on-disk inode location in the
4297 * buffer-cache. This gobbles the caller's reference to the
4298 * buffer_head in the inode location struct.
4300 * The caller must have write access to iloc->bh.
4302 static int ext4_do_update_inode(handle_t *handle,
4303 struct inode *inode,
4304 struct ext4_iloc *iloc)
4306 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4307 struct ext4_inode_info *ei = EXT4_I(inode);
4308 struct buffer_head *bh = iloc->bh;
4309 int err = 0, rc, block;
4310 int need_datasync = 0;
4314 /* For fields not not tracking in the in-memory inode,
4315 * initialise them to zero for new inodes. */
4316 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4317 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4319 ext4_get_inode_flags(ei);
4320 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4321 i_uid = i_uid_read(inode);
4322 i_gid = i_gid_read(inode);
4323 if (!(test_opt(inode->i_sb, NO_UID32))) {
4324 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4325 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4327 * Fix up interoperability with old kernels. Otherwise, old inodes get
4328 * re-used with the upper 16 bits of the uid/gid intact
4331 raw_inode->i_uid_high =
4332 cpu_to_le16(high_16_bits(i_uid));
4333 raw_inode->i_gid_high =
4334 cpu_to_le16(high_16_bits(i_gid));
4336 raw_inode->i_uid_high = 0;
4337 raw_inode->i_gid_high = 0;
4340 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4341 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4342 raw_inode->i_uid_high = 0;
4343 raw_inode->i_gid_high = 0;
4345 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4347 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4348 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4349 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4350 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4352 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4354 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4355 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4356 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4357 cpu_to_le32(EXT4_OS_HURD))
4358 raw_inode->i_file_acl_high =
4359 cpu_to_le16(ei->i_file_acl >> 32);
4360 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4361 if (ei->i_disksize != ext4_isize(raw_inode)) {
4362 ext4_isize_set(raw_inode, ei->i_disksize);
4365 if (ei->i_disksize > 0x7fffffffULL) {
4366 struct super_block *sb = inode->i_sb;
4367 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4368 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4369 EXT4_SB(sb)->s_es->s_rev_level ==
4370 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4371 /* If this is the first large file
4372 * created, add a flag to the superblock.
4374 err = ext4_journal_get_write_access(handle,
4375 EXT4_SB(sb)->s_sbh);
4378 ext4_update_dynamic_rev(sb);
4379 EXT4_SET_RO_COMPAT_FEATURE(sb,
4380 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4381 ext4_handle_sync(handle);
4382 err = ext4_handle_dirty_super(handle, sb);
4385 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4386 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4387 if (old_valid_dev(inode->i_rdev)) {
4388 raw_inode->i_block[0] =
4389 cpu_to_le32(old_encode_dev(inode->i_rdev));
4390 raw_inode->i_block[1] = 0;
4392 raw_inode->i_block[0] = 0;
4393 raw_inode->i_block[1] =
4394 cpu_to_le32(new_encode_dev(inode->i_rdev));
4395 raw_inode->i_block[2] = 0;
4397 } else if (!ext4_has_inline_data(inode)) {
4398 for (block = 0; block < EXT4_N_BLOCKS; block++)
4399 raw_inode->i_block[block] = ei->i_data[block];
4402 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4403 if (ei->i_extra_isize) {
4404 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4405 raw_inode->i_version_hi =
4406 cpu_to_le32(inode->i_version >> 32);
4407 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4410 ext4_inode_csum_set(inode, raw_inode, ei);
4412 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4413 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4416 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4418 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4421 ext4_std_error(inode->i_sb, err);
4426 * ext4_write_inode()
4428 * We are called from a few places:
4430 * - Within generic_file_write() for O_SYNC files.
4431 * Here, there will be no transaction running. We wait for any running
4432 * transaction to commit.
4434 * - Within sys_sync(), kupdate and such.
4435 * We wait on commit, if tol to.
4437 * - Within prune_icache() (PF_MEMALLOC == true)
4438 * Here we simply return. We can't afford to block kswapd on the
4441 * In all cases it is actually safe for us to return without doing anything,
4442 * because the inode has been copied into a raw inode buffer in
4443 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4446 * Note that we are absolutely dependent upon all inode dirtiers doing the
4447 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4448 * which we are interested.
4450 * It would be a bug for them to not do this. The code:
4452 * mark_inode_dirty(inode)
4454 * inode->i_size = expr;
4456 * is in error because a kswapd-driven write_inode() could occur while
4457 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4458 * will no longer be on the superblock's dirty inode list.
4460 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4464 if (current->flags & PF_MEMALLOC)
4467 if (EXT4_SB(inode->i_sb)->s_journal) {
4468 if (ext4_journal_current_handle()) {
4469 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4474 if (wbc->sync_mode != WB_SYNC_ALL)
4477 err = ext4_force_commit(inode->i_sb);
4479 struct ext4_iloc iloc;
4481 err = __ext4_get_inode_loc(inode, &iloc, 0);
4484 if (wbc->sync_mode == WB_SYNC_ALL)
4485 sync_dirty_buffer(iloc.bh);
4486 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4487 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4488 "IO error syncing inode");
4497 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4498 * buffers that are attached to a page stradding i_size and are undergoing
4499 * commit. In that case we have to wait for commit to finish and try again.
4501 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4505 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4506 tid_t commit_tid = 0;
4509 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4511 * All buffers in the last page remain valid? Then there's nothing to
4512 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4515 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4518 page = find_lock_page(inode->i_mapping,
4519 inode->i_size >> PAGE_CACHE_SHIFT);
4522 ret = __ext4_journalled_invalidatepage(page, offset,
4523 PAGE_CACHE_SIZE - offset);
4525 page_cache_release(page);
4529 read_lock(&journal->j_state_lock);
4530 if (journal->j_committing_transaction)
4531 commit_tid = journal->j_committing_transaction->t_tid;
4532 read_unlock(&journal->j_state_lock);
4534 jbd2_log_wait_commit(journal, commit_tid);
4541 * Called from notify_change.
4543 * We want to trap VFS attempts to truncate the file as soon as
4544 * possible. In particular, we want to make sure that when the VFS
4545 * shrinks i_size, we put the inode on the orphan list and modify
4546 * i_disksize immediately, so that during the subsequent flushing of
4547 * dirty pages and freeing of disk blocks, we can guarantee that any
4548 * commit will leave the blocks being flushed in an unused state on
4549 * disk. (On recovery, the inode will get truncated and the blocks will
4550 * be freed, so we have a strong guarantee that no future commit will
4551 * leave these blocks visible to the user.)
4553 * Another thing we have to assure is that if we are in ordered mode
4554 * and inode is still attached to the committing transaction, we must
4555 * we start writeout of all the dirty pages which are being truncated.
4556 * This way we are sure that all the data written in the previous
4557 * transaction are already on disk (truncate waits for pages under
4560 * Called with inode->i_mutex down.
4562 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4564 struct inode *inode = dentry->d_inode;
4567 const unsigned int ia_valid = attr->ia_valid;
4569 error = inode_change_ok(inode, attr);
4573 if (is_quota_modification(inode, attr))
4574 dquot_initialize(inode);
4575 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4576 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4579 /* (user+group)*(old+new) structure, inode write (sb,
4580 * inode block, ? - but truncate inode update has it) */
4581 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4582 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4583 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4584 if (IS_ERR(handle)) {
4585 error = PTR_ERR(handle);
4588 error = dquot_transfer(inode, attr);
4590 ext4_journal_stop(handle);
4593 /* Update corresponding info in inode so that everything is in
4594 * one transaction */
4595 if (attr->ia_valid & ATTR_UID)
4596 inode->i_uid = attr->ia_uid;
4597 if (attr->ia_valid & ATTR_GID)
4598 inode->i_gid = attr->ia_gid;
4599 error = ext4_mark_inode_dirty(handle, inode);
4600 ext4_journal_stop(handle);
4603 if (attr->ia_valid & ATTR_SIZE) {
4605 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4606 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4608 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4613 if (S_ISREG(inode->i_mode) &&
4614 attr->ia_valid & ATTR_SIZE &&
4615 (attr->ia_size < inode->i_size)) {
4618 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4619 if (IS_ERR(handle)) {
4620 error = PTR_ERR(handle);
4623 if (ext4_handle_valid(handle)) {
4624 error = ext4_orphan_add(handle, inode);
4627 EXT4_I(inode)->i_disksize = attr->ia_size;
4628 rc = ext4_mark_inode_dirty(handle, inode);
4631 ext4_journal_stop(handle);
4633 if (ext4_should_order_data(inode)) {
4634 error = ext4_begin_ordered_truncate(inode,
4637 /* Do as much error cleanup as possible */
4638 handle = ext4_journal_start(inode,
4640 if (IS_ERR(handle)) {
4641 ext4_orphan_del(NULL, inode);
4644 ext4_orphan_del(handle, inode);
4646 ext4_journal_stop(handle);
4652 if (attr->ia_valid & ATTR_SIZE) {
4653 if (attr->ia_size != inode->i_size) {
4654 loff_t oldsize = inode->i_size;
4656 i_size_write(inode, attr->ia_size);
4658 * Blocks are going to be removed from the inode. Wait
4659 * for dio in flight. Temporarily disable
4660 * dioread_nolock to prevent livelock.
4663 if (!ext4_should_journal_data(inode)) {
4664 ext4_inode_block_unlocked_dio(inode);
4665 inode_dio_wait(inode);
4666 ext4_inode_resume_unlocked_dio(inode);
4668 ext4_wait_for_tail_page_commit(inode);
4671 * Truncate pagecache after we've waited for commit
4672 * in data=journal mode to make pages freeable.
4674 truncate_pagecache(inode, oldsize, inode->i_size);
4676 ext4_truncate(inode);
4680 setattr_copy(inode, attr);
4681 mark_inode_dirty(inode);
4685 * If the call to ext4_truncate failed to get a transaction handle at
4686 * all, we need to clean up the in-core orphan list manually.
4688 if (orphan && inode->i_nlink)
4689 ext4_orphan_del(NULL, inode);
4691 if (!rc && (ia_valid & ATTR_MODE))
4692 rc = ext4_acl_chmod(inode);
4695 ext4_std_error(inode->i_sb, error);
4701 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4704 struct inode *inode;
4705 unsigned long long delalloc_blocks;
4707 inode = dentry->d_inode;
4708 generic_fillattr(inode, stat);
4711 * We can't update i_blocks if the block allocation is delayed
4712 * otherwise in the case of system crash before the real block
4713 * allocation is done, we will have i_blocks inconsistent with
4714 * on-disk file blocks.
4715 * We always keep i_blocks updated together with real
4716 * allocation. But to not confuse with user, stat
4717 * will return the blocks that include the delayed allocation
4718 * blocks for this file.
4720 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4721 EXT4_I(inode)->i_reserved_data_blocks);
4723 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
4727 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4729 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4730 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4731 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4735 * Account for index blocks, block groups bitmaps and block group
4736 * descriptor blocks if modify datablocks and index blocks
4737 * worse case, the indexs blocks spread over different block groups
4739 * If datablocks are discontiguous, they are possible to spread over
4740 * different block groups too. If they are contiguous, with flexbg,
4741 * they could still across block group boundary.
4743 * Also account for superblock, inode, quota and xattr blocks
4745 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4747 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4753 * How many index blocks need to touch to modify nrblocks?
4754 * The "Chunk" flag indicating whether the nrblocks is
4755 * physically contiguous on disk
4757 * For Direct IO and fallocate, they calls get_block to allocate
4758 * one single extent at a time, so they could set the "Chunk" flag
4760 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4765 * Now let's see how many group bitmaps and group descriptors need
4775 if (groups > ngroups)
4777 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4778 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4780 /* bitmaps and block group descriptor blocks */
4781 ret += groups + gdpblocks;
4783 /* Blocks for super block, inode, quota and xattr blocks */
4784 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4790 * Calculate the total number of credits to reserve to fit
4791 * the modification of a single pages into a single transaction,
4792 * which may include multiple chunks of block allocations.
4794 * This could be called via ext4_write_begin()
4796 * We need to consider the worse case, when
4797 * one new block per extent.
4799 int ext4_writepage_trans_blocks(struct inode *inode)
4801 int bpp = ext4_journal_blocks_per_page(inode);
4804 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4806 /* Account for data blocks for journalled mode */
4807 if (ext4_should_journal_data(inode))
4813 * Calculate the journal credits for a chunk of data modification.
4815 * This is called from DIO, fallocate or whoever calling
4816 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4818 * journal buffers for data blocks are not included here, as DIO
4819 * and fallocate do no need to journal data buffers.
4821 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4823 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4827 * The caller must have previously called ext4_reserve_inode_write().
4828 * Give this, we know that the caller already has write access to iloc->bh.
4830 int ext4_mark_iloc_dirty(handle_t *handle,
4831 struct inode *inode, struct ext4_iloc *iloc)
4835 if (IS_I_VERSION(inode))
4836 inode_inc_iversion(inode);
4838 /* the do_update_inode consumes one bh->b_count */
4841 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4842 err = ext4_do_update_inode(handle, inode, iloc);
4848 * On success, We end up with an outstanding reference count against
4849 * iloc->bh. This _must_ be cleaned up later.
4853 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4854 struct ext4_iloc *iloc)
4858 err = ext4_get_inode_loc(inode, iloc);
4860 BUFFER_TRACE(iloc->bh, "get_write_access");
4861 err = ext4_journal_get_write_access(handle, iloc->bh);
4867 ext4_std_error(inode->i_sb, err);
4872 * Expand an inode by new_extra_isize bytes.
4873 * Returns 0 on success or negative error number on failure.
4875 static int ext4_expand_extra_isize(struct inode *inode,
4876 unsigned int new_extra_isize,
4877 struct ext4_iloc iloc,
4880 struct ext4_inode *raw_inode;
4881 struct ext4_xattr_ibody_header *header;
4883 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4886 raw_inode = ext4_raw_inode(&iloc);
4888 header = IHDR(inode, raw_inode);
4890 /* No extended attributes present */
4891 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4892 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4893 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4895 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4899 /* try to expand with EAs present */
4900 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4905 * What we do here is to mark the in-core inode as clean with respect to inode
4906 * dirtiness (it may still be data-dirty).
4907 * This means that the in-core inode may be reaped by prune_icache
4908 * without having to perform any I/O. This is a very good thing,
4909 * because *any* task may call prune_icache - even ones which
4910 * have a transaction open against a different journal.
4912 * Is this cheating? Not really. Sure, we haven't written the
4913 * inode out, but prune_icache isn't a user-visible syncing function.
4914 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4915 * we start and wait on commits.
4917 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4919 struct ext4_iloc iloc;
4920 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4921 static unsigned int mnt_count;
4925 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4926 err = ext4_reserve_inode_write(handle, inode, &iloc);
4927 if (ext4_handle_valid(handle) &&
4928 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4929 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4931 * We need extra buffer credits since we may write into EA block
4932 * with this same handle. If journal_extend fails, then it will
4933 * only result in a minor loss of functionality for that inode.
4934 * If this is felt to be critical, then e2fsck should be run to
4935 * force a large enough s_min_extra_isize.
4937 if ((jbd2_journal_extend(handle,
4938 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4939 ret = ext4_expand_extra_isize(inode,
4940 sbi->s_want_extra_isize,
4943 ext4_set_inode_state(inode,
4944 EXT4_STATE_NO_EXPAND);
4946 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4947 ext4_warning(inode->i_sb,
4948 "Unable to expand inode %lu. Delete"
4949 " some EAs or run e2fsck.",
4952 le16_to_cpu(sbi->s_es->s_mnt_count);
4958 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4963 * ext4_dirty_inode() is called from __mark_inode_dirty()
4965 * We're really interested in the case where a file is being extended.
4966 * i_size has been changed by generic_commit_write() and we thus need
4967 * to include the updated inode in the current transaction.
4969 * Also, dquot_alloc_block() will always dirty the inode when blocks
4970 * are allocated to the file.
4972 * If the inode is marked synchronous, we don't honour that here - doing
4973 * so would cause a commit on atime updates, which we don't bother doing.
4974 * We handle synchronous inodes at the highest possible level.
4976 void ext4_dirty_inode(struct inode *inode, int flags)
4980 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4984 ext4_mark_inode_dirty(handle, inode);
4986 ext4_journal_stop(handle);
4993 * Bind an inode's backing buffer_head into this transaction, to prevent
4994 * it from being flushed to disk early. Unlike
4995 * ext4_reserve_inode_write, this leaves behind no bh reference and
4996 * returns no iloc structure, so the caller needs to repeat the iloc
4997 * lookup to mark the inode dirty later.
4999 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5001 struct ext4_iloc iloc;
5005 err = ext4_get_inode_loc(inode, &iloc);
5007 BUFFER_TRACE(iloc.bh, "get_write_access");
5008 err = jbd2_journal_get_write_access(handle, iloc.bh);
5010 err = ext4_handle_dirty_metadata(handle,
5016 ext4_std_error(inode->i_sb, err);
5021 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5028 * We have to be very careful here: changing a data block's
5029 * journaling status dynamically is dangerous. If we write a
5030 * data block to the journal, change the status and then delete
5031 * that block, we risk forgetting to revoke the old log record
5032 * from the journal and so a subsequent replay can corrupt data.
5033 * So, first we make sure that the journal is empty and that
5034 * nobody is changing anything.
5037 journal = EXT4_JOURNAL(inode);
5040 if (is_journal_aborted(journal))
5042 /* We have to allocate physical blocks for delalloc blocks
5043 * before flushing journal. otherwise delalloc blocks can not
5044 * be allocated any more. even more truncate on delalloc blocks
5045 * could trigger BUG by flushing delalloc blocks in journal.
5046 * There is no delalloc block in non-journal data mode.
5048 if (val && test_opt(inode->i_sb, DELALLOC)) {
5049 err = ext4_alloc_da_blocks(inode);
5054 /* Wait for all existing dio workers */
5055 ext4_inode_block_unlocked_dio(inode);
5056 inode_dio_wait(inode);
5058 jbd2_journal_lock_updates(journal);
5061 * OK, there are no updates running now, and all cached data is
5062 * synced to disk. We are now in a completely consistent state
5063 * which doesn't have anything in the journal, and we know that
5064 * no filesystem updates are running, so it is safe to modify
5065 * the inode's in-core data-journaling state flag now.
5069 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5071 jbd2_journal_flush(journal);
5072 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5074 ext4_set_aops(inode);
5076 jbd2_journal_unlock_updates(journal);
5077 ext4_inode_resume_unlocked_dio(inode);
5079 /* Finally we can mark the inode as dirty. */
5081 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5083 return PTR_ERR(handle);
5085 err = ext4_mark_inode_dirty(handle, inode);
5086 ext4_handle_sync(handle);
5087 ext4_journal_stop(handle);
5088 ext4_std_error(inode->i_sb, err);
5093 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5095 return !buffer_mapped(bh);
5098 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5100 struct page *page = vmf->page;
5104 struct file *file = vma->vm_file;
5105 struct inode *inode = file_inode(file);
5106 struct address_space *mapping = inode->i_mapping;
5108 get_block_t *get_block;
5111 sb_start_pagefault(inode->i_sb);
5112 file_update_time(vma->vm_file);
5113 /* Delalloc case is easy... */
5114 if (test_opt(inode->i_sb, DELALLOC) &&
5115 !ext4_should_journal_data(inode) &&
5116 !ext4_nonda_switch(inode->i_sb)) {
5118 ret = __block_page_mkwrite(vma, vmf,
5119 ext4_da_get_block_prep);
5120 } while (ret == -ENOSPC &&
5121 ext4_should_retry_alloc(inode->i_sb, &retries));
5126 size = i_size_read(inode);
5127 /* Page got truncated from under us? */
5128 if (page->mapping != mapping || page_offset(page) > size) {
5130 ret = VM_FAULT_NOPAGE;
5134 if (page->index == size >> PAGE_CACHE_SHIFT)
5135 len = size & ~PAGE_CACHE_MASK;
5137 len = PAGE_CACHE_SIZE;
5139 * Return if we have all the buffers mapped. This avoids the need to do
5140 * journal_start/journal_stop which can block and take a long time
5142 if (page_has_buffers(page)) {
5143 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5145 ext4_bh_unmapped)) {
5146 /* Wait so that we don't change page under IO */
5147 wait_for_stable_page(page);
5148 ret = VM_FAULT_LOCKED;
5153 /* OK, we need to fill the hole... */
5154 if (ext4_should_dioread_nolock(inode))
5155 get_block = ext4_get_block_write;
5157 get_block = ext4_get_block;
5159 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5160 ext4_writepage_trans_blocks(inode));
5161 if (IS_ERR(handle)) {
5162 ret = VM_FAULT_SIGBUS;
5165 ret = __block_page_mkwrite(vma, vmf, get_block);
5166 if (!ret && ext4_should_journal_data(inode)) {
5167 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5168 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5170 ret = VM_FAULT_SIGBUS;
5171 ext4_journal_stop(handle);
5174 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5176 ext4_journal_stop(handle);
5177 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5180 ret = block_page_mkwrite_return(ret);
5182 sb_end_pagefault(inode->i_sb);