ext4: track all extent status in extent status tree
[linux-2.6.git] / fs / ext4 / inode.c
blob576b586b61aa76b28ca90aaa0292a1411f047356
1 /*
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)
9 * from
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
21 #include <linux/fs.h>
22 #include <linux/time.h>
23 #include <linux/jbd2.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
41 #include "ext4_jbd2.h"
42 #include "xattr.h"
43 #include "acl.h"
44 #include "truncate.h"
46 #include <trace/events/ext4.h>
48 #define MPAGE_DA_EXTENT_TAIL 0x01
50 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
51 struct ext4_inode_info *ei)
53 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
54 __u16 csum_lo;
55 __u16 csum_hi = 0;
56 __u32 csum;
58 csum_lo = raw->i_checksum_lo;
59 raw->i_checksum_lo = 0;
60 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
61 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
62 csum_hi = raw->i_checksum_hi;
63 raw->i_checksum_hi = 0;
66 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
67 EXT4_INODE_SIZE(inode->i_sb));
69 raw->i_checksum_lo = csum_lo;
70 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
71 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
72 raw->i_checksum_hi = csum_hi;
74 return csum;
77 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
78 struct ext4_inode_info *ei)
80 __u32 provided, calculated;
82 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
83 cpu_to_le32(EXT4_OS_LINUX) ||
84 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
85 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
86 return 1;
88 provided = le16_to_cpu(raw->i_checksum_lo);
89 calculated = ext4_inode_csum(inode, raw, ei);
90 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
91 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
92 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
93 else
94 calculated &= 0xFFFF;
96 return provided == calculated;
99 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
100 struct ext4_inode_info *ei)
102 __u32 csum;
104 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
105 cpu_to_le32(EXT4_OS_LINUX) ||
106 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
107 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
108 return;
110 csum = ext4_inode_csum(inode, raw, ei);
111 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
112 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
113 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
114 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
117 static inline int ext4_begin_ordered_truncate(struct inode *inode,
118 loff_t new_size)
120 trace_ext4_begin_ordered_truncate(inode, new_size);
122 * If jinode is zero, then we never opened the file for
123 * writing, so there's no need to call
124 * jbd2_journal_begin_ordered_truncate() since there's no
125 * outstanding writes we need to flush.
127 if (!EXT4_I(inode)->jinode)
128 return 0;
129 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
130 EXT4_I(inode)->jinode,
131 new_size);
134 static void ext4_invalidatepage(struct page *page, unsigned long offset);
135 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
136 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
137 static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
138 struct inode *inode, struct page *page, loff_t from,
139 loff_t length, int flags);
142 * Test whether an inode is a fast symlink.
144 static int ext4_inode_is_fast_symlink(struct inode *inode)
146 int ea_blocks = EXT4_I(inode)->i_file_acl ?
147 (inode->i_sb->s_blocksize >> 9) : 0;
149 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
153 * Restart the transaction associated with *handle. This does a commit,
154 * so before we call here everything must be consistently dirtied against
155 * this transaction.
157 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
158 int nblocks)
160 int ret;
163 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
164 * moment, get_block can be called only for blocks inside i_size since
165 * page cache has been already dropped and writes are blocked by
166 * i_mutex. So we can safely drop the i_data_sem here.
168 BUG_ON(EXT4_JOURNAL(inode) == NULL);
169 jbd_debug(2, "restarting handle %p\n", handle);
170 up_write(&EXT4_I(inode)->i_data_sem);
171 ret = ext4_journal_restart(handle, nblocks);
172 down_write(&EXT4_I(inode)->i_data_sem);
173 ext4_discard_preallocations(inode);
175 return ret;
179 * Called at the last iput() if i_nlink is zero.
181 void ext4_evict_inode(struct inode *inode)
183 handle_t *handle;
184 int err;
186 trace_ext4_evict_inode(inode);
188 ext4_ioend_wait(inode);
190 if (inode->i_nlink) {
192 * When journalling data dirty buffers are tracked only in the
193 * journal. So although mm thinks everything is clean and
194 * ready for reaping the inode might still have some pages to
195 * write in the running transaction or waiting to be
196 * checkpointed. Thus calling jbd2_journal_invalidatepage()
197 * (via truncate_inode_pages()) to discard these buffers can
198 * cause data loss. Also even if we did not discard these
199 * buffers, we would have no way to find them after the inode
200 * is reaped and thus user could see stale data if he tries to
201 * read them before the transaction is checkpointed. So be
202 * careful and force everything to disk here... We use
203 * ei->i_datasync_tid to store the newest transaction
204 * containing inode's data.
206 * Note that directories do not have this problem because they
207 * don't use page cache.
209 if (ext4_should_journal_data(inode) &&
210 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
211 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
212 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
214 jbd2_log_start_commit(journal, commit_tid);
215 jbd2_log_wait_commit(journal, commit_tid);
216 filemap_write_and_wait(&inode->i_data);
218 truncate_inode_pages(&inode->i_data, 0);
219 goto no_delete;
222 if (!is_bad_inode(inode))
223 dquot_initialize(inode);
225 if (ext4_should_order_data(inode))
226 ext4_begin_ordered_truncate(inode, 0);
227 truncate_inode_pages(&inode->i_data, 0);
229 if (is_bad_inode(inode))
230 goto no_delete;
233 * Protect us against freezing - iput() caller didn't have to have any
234 * protection against it
236 sb_start_intwrite(inode->i_sb);
237 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
238 ext4_blocks_for_truncate(inode)+3);
239 if (IS_ERR(handle)) {
240 ext4_std_error(inode->i_sb, PTR_ERR(handle));
242 * If we're going to skip the normal cleanup, we still need to
243 * make sure that the in-core orphan linked list is properly
244 * cleaned up.
246 ext4_orphan_del(NULL, inode);
247 sb_end_intwrite(inode->i_sb);
248 goto no_delete;
251 if (IS_SYNC(inode))
252 ext4_handle_sync(handle);
253 inode->i_size = 0;
254 err = ext4_mark_inode_dirty(handle, inode);
255 if (err) {
256 ext4_warning(inode->i_sb,
257 "couldn't mark inode dirty (err %d)", err);
258 goto stop_handle;
260 if (inode->i_blocks)
261 ext4_truncate(inode);
264 * ext4_ext_truncate() doesn't reserve any slop when it
265 * restarts journal transactions; therefore there may not be
266 * enough credits left in the handle to remove the inode from
267 * the orphan list and set the dtime field.
269 if (!ext4_handle_has_enough_credits(handle, 3)) {
270 err = ext4_journal_extend(handle, 3);
271 if (err > 0)
272 err = ext4_journal_restart(handle, 3);
273 if (err != 0) {
274 ext4_warning(inode->i_sb,
275 "couldn't extend journal (err %d)", err);
276 stop_handle:
277 ext4_journal_stop(handle);
278 ext4_orphan_del(NULL, inode);
279 sb_end_intwrite(inode->i_sb);
280 goto no_delete;
285 * Kill off the orphan record which ext4_truncate created.
286 * AKPM: I think this can be inside the above `if'.
287 * Note that ext4_orphan_del() has to be able to cope with the
288 * deletion of a non-existent orphan - this is because we don't
289 * know if ext4_truncate() actually created an orphan record.
290 * (Well, we could do this if we need to, but heck - it works)
292 ext4_orphan_del(handle, inode);
293 EXT4_I(inode)->i_dtime = get_seconds();
296 * One subtle ordering requirement: if anything has gone wrong
297 * (transaction abort, IO errors, whatever), then we can still
298 * do these next steps (the fs will already have been marked as
299 * having errors), but we can't free the inode if the mark_dirty
300 * fails.
302 if (ext4_mark_inode_dirty(handle, inode))
303 /* If that failed, just do the required in-core inode clear. */
304 ext4_clear_inode(inode);
305 else
306 ext4_free_inode(handle, inode);
307 ext4_journal_stop(handle);
308 sb_end_intwrite(inode->i_sb);
309 return;
310 no_delete:
311 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
314 #ifdef CONFIG_QUOTA
315 qsize_t *ext4_get_reserved_space(struct inode *inode)
317 return &EXT4_I(inode)->i_reserved_quota;
319 #endif
322 * Calculate the number of metadata blocks need to reserve
323 * to allocate a block located at @lblock
325 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
327 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
328 return ext4_ext_calc_metadata_amount(inode, lblock);
330 return ext4_ind_calc_metadata_amount(inode, lblock);
334 * Called with i_data_sem down, which is important since we can call
335 * ext4_discard_preallocations() from here.
337 void ext4_da_update_reserve_space(struct inode *inode,
338 int used, int quota_claim)
340 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
341 struct ext4_inode_info *ei = EXT4_I(inode);
343 spin_lock(&ei->i_block_reservation_lock);
344 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
345 if (unlikely(used > ei->i_reserved_data_blocks)) {
346 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
347 "with only %d reserved data blocks",
348 __func__, inode->i_ino, used,
349 ei->i_reserved_data_blocks);
350 WARN_ON(1);
351 used = ei->i_reserved_data_blocks;
354 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
355 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
356 "with only %d reserved metadata blocks "
357 "(releasing %d blocks with reserved %d data blocks)",
358 inode->i_ino, ei->i_allocated_meta_blocks,
359 ei->i_reserved_meta_blocks, used,
360 ei->i_reserved_data_blocks);
361 WARN_ON(1);
362 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
365 /* Update per-inode reservations */
366 ei->i_reserved_data_blocks -= used;
367 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
368 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
369 used + ei->i_allocated_meta_blocks);
370 ei->i_allocated_meta_blocks = 0;
372 if (ei->i_reserved_data_blocks == 0) {
374 * We can release all of the reserved metadata blocks
375 * only when we have written all of the delayed
376 * allocation blocks.
378 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
379 ei->i_reserved_meta_blocks);
380 ei->i_reserved_meta_blocks = 0;
381 ei->i_da_metadata_calc_len = 0;
383 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
385 /* Update quota subsystem for data blocks */
386 if (quota_claim)
387 dquot_claim_block(inode, EXT4_C2B(sbi, used));
388 else {
390 * We did fallocate with an offset that is already delayed
391 * allocated. So on delayed allocated writeback we should
392 * not re-claim the quota for fallocated blocks.
394 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
398 * If we have done all the pending block allocations and if
399 * there aren't any writers on the inode, we can discard the
400 * inode's preallocations.
402 if ((ei->i_reserved_data_blocks == 0) &&
403 (atomic_read(&inode->i_writecount) == 0))
404 ext4_discard_preallocations(inode);
407 static int __check_block_validity(struct inode *inode, const char *func,
408 unsigned int line,
409 struct ext4_map_blocks *map)
411 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
412 map->m_len)) {
413 ext4_error_inode(inode, func, line, map->m_pblk,
414 "lblock %lu mapped to illegal pblock "
415 "(length %d)", (unsigned long) map->m_lblk,
416 map->m_len);
417 return -EIO;
419 return 0;
422 #define check_block_validity(inode, map) \
423 __check_block_validity((inode), __func__, __LINE__, (map))
426 * Return the number of contiguous dirty pages in a given inode
427 * starting at page frame idx.
429 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
430 unsigned int max_pages)
432 struct address_space *mapping = inode->i_mapping;
433 pgoff_t index;
434 struct pagevec pvec;
435 pgoff_t num = 0;
436 int i, nr_pages, done = 0;
438 if (max_pages == 0)
439 return 0;
440 pagevec_init(&pvec, 0);
441 while (!done) {
442 index = idx;
443 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
444 PAGECACHE_TAG_DIRTY,
445 (pgoff_t)PAGEVEC_SIZE);
446 if (nr_pages == 0)
447 break;
448 for (i = 0; i < nr_pages; i++) {
449 struct page *page = pvec.pages[i];
450 struct buffer_head *bh, *head;
452 lock_page(page);
453 if (unlikely(page->mapping != mapping) ||
454 !PageDirty(page) ||
455 PageWriteback(page) ||
456 page->index != idx) {
457 done = 1;
458 unlock_page(page);
459 break;
461 if (page_has_buffers(page)) {
462 bh = head = page_buffers(page);
463 do {
464 if (!buffer_delay(bh) &&
465 !buffer_unwritten(bh))
466 done = 1;
467 bh = bh->b_this_page;
468 } while (!done && (bh != head));
470 unlock_page(page);
471 if (done)
472 break;
473 idx++;
474 num++;
475 if (num >= max_pages) {
476 done = 1;
477 break;
480 pagevec_release(&pvec);
482 return num;
486 * The ext4_map_blocks() function tries to look up the requested blocks,
487 * and returns if the blocks are already mapped.
489 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
490 * and store the allocated blocks in the result buffer head and mark it
491 * mapped.
493 * If file type is extents based, it will call ext4_ext_map_blocks(),
494 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
495 * based files
497 * On success, it returns the number of blocks being mapped or allocate.
498 * if create==0 and the blocks are pre-allocated and uninitialized block,
499 * the result buffer head is unmapped. If the create ==1, it will make sure
500 * the buffer head is mapped.
502 * It returns 0 if plain look up failed (blocks have not been allocated), in
503 * that case, buffer head is unmapped
505 * It returns the error in case of allocation failure.
507 int ext4_map_blocks(handle_t *handle, struct inode *inode,
508 struct ext4_map_blocks *map, int flags)
510 int retval;
512 map->m_flags = 0;
513 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
514 "logical block %lu\n", inode->i_ino, flags, map->m_len,
515 (unsigned long) map->m_lblk);
517 * Try to see if we can get the block without requesting a new
518 * file system block.
520 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
521 down_read((&EXT4_I(inode)->i_data_sem));
522 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
523 retval = ext4_ext_map_blocks(handle, inode, map, flags &
524 EXT4_GET_BLOCKS_KEEP_SIZE);
525 } else {
526 retval = ext4_ind_map_blocks(handle, inode, map, flags &
527 EXT4_GET_BLOCKS_KEEP_SIZE);
529 if (retval > 0) {
530 int ret;
531 unsigned long long status;
533 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
534 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
535 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
536 ext4_find_delalloc_range(inode, map->m_lblk,
537 map->m_lblk + map->m_len - 1))
538 status |= EXTENT_STATUS_DELAYED;
539 ret = ext4_es_insert_extent(inode, map->m_lblk,
540 map->m_len, map->m_pblk, status);
541 if (ret < 0)
542 retval = ret;
544 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
545 up_read((&EXT4_I(inode)->i_data_sem));
547 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
548 int ret = check_block_validity(inode, map);
549 if (ret != 0)
550 return ret;
553 /* If it is only a block(s) look up */
554 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
555 return retval;
558 * Returns if the blocks have already allocated
560 * Note that if blocks have been preallocated
561 * ext4_ext_get_block() returns the create = 0
562 * with buffer head unmapped.
564 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
565 return retval;
568 * Here we clear m_flags because after allocating an new extent,
569 * it will be set again.
571 map->m_flags &= ~EXT4_MAP_FLAGS;
574 * New blocks allocate and/or writing to uninitialized extent
575 * will possibly result in updating i_data, so we take
576 * the write lock of i_data_sem, and call get_blocks()
577 * with create == 1 flag.
579 down_write((&EXT4_I(inode)->i_data_sem));
582 * if the caller is from delayed allocation writeout path
583 * we have already reserved fs blocks for allocation
584 * let the underlying get_block() function know to
585 * avoid double accounting
587 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
588 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
590 * We need to check for EXT4 here because migrate
591 * could have changed the inode type in between
593 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
594 retval = ext4_ext_map_blocks(handle, inode, map, flags);
595 } else {
596 retval = ext4_ind_map_blocks(handle, inode, map, flags);
598 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
600 * We allocated new blocks which will result in
601 * i_data's format changing. Force the migrate
602 * to fail by clearing migrate flags
604 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
608 * Update reserved blocks/metadata blocks after successful
609 * block allocation which had been deferred till now. We don't
610 * support fallocate for non extent files. So we can update
611 * reserve space here.
613 if ((retval > 0) &&
614 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
615 ext4_da_update_reserve_space(inode, retval, 1);
617 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
618 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
620 if (retval > 0) {
621 int ret;
622 unsigned long long status;
624 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
625 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
626 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
627 ext4_find_delalloc_range(inode, map->m_lblk,
628 map->m_lblk + map->m_len - 1))
629 status |= EXTENT_STATUS_DELAYED;
630 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
631 map->m_pblk, status);
632 if (ret < 0)
633 retval = ret;
636 up_write((&EXT4_I(inode)->i_data_sem));
637 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
638 int ret = check_block_validity(inode, map);
639 if (ret != 0)
640 return ret;
642 return retval;
645 /* Maximum number of blocks we map for direct IO at once. */
646 #define DIO_MAX_BLOCKS 4096
648 static int _ext4_get_block(struct inode *inode, sector_t iblock,
649 struct buffer_head *bh, int flags)
651 handle_t *handle = ext4_journal_current_handle();
652 struct ext4_map_blocks map;
653 int ret = 0, started = 0;
654 int dio_credits;
656 if (ext4_has_inline_data(inode))
657 return -ERANGE;
659 map.m_lblk = iblock;
660 map.m_len = bh->b_size >> inode->i_blkbits;
662 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
663 /* Direct IO write... */
664 if (map.m_len > DIO_MAX_BLOCKS)
665 map.m_len = DIO_MAX_BLOCKS;
666 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
667 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
668 dio_credits);
669 if (IS_ERR(handle)) {
670 ret = PTR_ERR(handle);
671 return ret;
673 started = 1;
676 ret = ext4_map_blocks(handle, inode, &map, flags);
677 if (ret > 0) {
678 map_bh(bh, inode->i_sb, map.m_pblk);
679 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
680 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
681 ret = 0;
683 if (started)
684 ext4_journal_stop(handle);
685 return ret;
688 int ext4_get_block(struct inode *inode, sector_t iblock,
689 struct buffer_head *bh, int create)
691 return _ext4_get_block(inode, iblock, bh,
692 create ? EXT4_GET_BLOCKS_CREATE : 0);
696 * `handle' can be NULL if create is zero
698 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
699 ext4_lblk_t block, int create, int *errp)
701 struct ext4_map_blocks map;
702 struct buffer_head *bh;
703 int fatal = 0, err;
705 J_ASSERT(handle != NULL || create == 0);
707 map.m_lblk = block;
708 map.m_len = 1;
709 err = ext4_map_blocks(handle, inode, &map,
710 create ? EXT4_GET_BLOCKS_CREATE : 0);
712 /* ensure we send some value back into *errp */
713 *errp = 0;
715 if (create && err == 0)
716 err = -ENOSPC; /* should never happen */
717 if (err < 0)
718 *errp = err;
719 if (err <= 0)
720 return NULL;
722 bh = sb_getblk(inode->i_sb, map.m_pblk);
723 if (unlikely(!bh)) {
724 *errp = -ENOMEM;
725 return NULL;
727 if (map.m_flags & EXT4_MAP_NEW) {
728 J_ASSERT(create != 0);
729 J_ASSERT(handle != NULL);
732 * Now that we do not always journal data, we should
733 * keep in mind whether this should always journal the
734 * new buffer as metadata. For now, regular file
735 * writes use ext4_get_block instead, so it's not a
736 * problem.
738 lock_buffer(bh);
739 BUFFER_TRACE(bh, "call get_create_access");
740 fatal = ext4_journal_get_create_access(handle, bh);
741 if (!fatal && !buffer_uptodate(bh)) {
742 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
743 set_buffer_uptodate(bh);
745 unlock_buffer(bh);
746 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
747 err = ext4_handle_dirty_metadata(handle, inode, bh);
748 if (!fatal)
749 fatal = err;
750 } else {
751 BUFFER_TRACE(bh, "not a new buffer");
753 if (fatal) {
754 *errp = fatal;
755 brelse(bh);
756 bh = NULL;
758 return bh;
761 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
762 ext4_lblk_t block, int create, int *err)
764 struct buffer_head *bh;
766 bh = ext4_getblk(handle, inode, block, create, err);
767 if (!bh)
768 return bh;
769 if (buffer_uptodate(bh))
770 return bh;
771 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
772 wait_on_buffer(bh);
773 if (buffer_uptodate(bh))
774 return bh;
775 put_bh(bh);
776 *err = -EIO;
777 return NULL;
780 int ext4_walk_page_buffers(handle_t *handle,
781 struct buffer_head *head,
782 unsigned from,
783 unsigned to,
784 int *partial,
785 int (*fn)(handle_t *handle,
786 struct buffer_head *bh))
788 struct buffer_head *bh;
789 unsigned block_start, block_end;
790 unsigned blocksize = head->b_size;
791 int err, ret = 0;
792 struct buffer_head *next;
794 for (bh = head, block_start = 0;
795 ret == 0 && (bh != head || !block_start);
796 block_start = block_end, bh = next) {
797 next = bh->b_this_page;
798 block_end = block_start + blocksize;
799 if (block_end <= from || block_start >= to) {
800 if (partial && !buffer_uptodate(bh))
801 *partial = 1;
802 continue;
804 err = (*fn)(handle, bh);
805 if (!ret)
806 ret = err;
808 return ret;
812 * To preserve ordering, it is essential that the hole instantiation and
813 * the data write be encapsulated in a single transaction. We cannot
814 * close off a transaction and start a new one between the ext4_get_block()
815 * and the commit_write(). So doing the jbd2_journal_start at the start of
816 * prepare_write() is the right place.
818 * Also, this function can nest inside ext4_writepage(). In that case, we
819 * *know* that ext4_writepage() has generated enough buffer credits to do the
820 * whole page. So we won't block on the journal in that case, which is good,
821 * because the caller may be PF_MEMALLOC.
823 * By accident, ext4 can be reentered when a transaction is open via
824 * quota file writes. If we were to commit the transaction while thus
825 * reentered, there can be a deadlock - we would be holding a quota
826 * lock, and the commit would never complete if another thread had a
827 * transaction open and was blocking on the quota lock - a ranking
828 * violation.
830 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
831 * will _not_ run commit under these circumstances because handle->h_ref
832 * is elevated. We'll still have enough credits for the tiny quotafile
833 * write.
835 int do_journal_get_write_access(handle_t *handle,
836 struct buffer_head *bh)
838 int dirty = buffer_dirty(bh);
839 int ret;
841 if (!buffer_mapped(bh) || buffer_freed(bh))
842 return 0;
844 * __block_write_begin() could have dirtied some buffers. Clean
845 * the dirty bit as jbd2_journal_get_write_access() could complain
846 * otherwise about fs integrity issues. Setting of the dirty bit
847 * by __block_write_begin() isn't a real problem here as we clear
848 * the bit before releasing a page lock and thus writeback cannot
849 * ever write the buffer.
851 if (dirty)
852 clear_buffer_dirty(bh);
853 ret = ext4_journal_get_write_access(handle, bh);
854 if (!ret && dirty)
855 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
856 return ret;
859 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
860 struct buffer_head *bh_result, int create);
861 static int ext4_write_begin(struct file *file, struct address_space *mapping,
862 loff_t pos, unsigned len, unsigned flags,
863 struct page **pagep, void **fsdata)
865 struct inode *inode = mapping->host;
866 int ret, needed_blocks;
867 handle_t *handle;
868 int retries = 0;
869 struct page *page;
870 pgoff_t index;
871 unsigned from, to;
873 trace_ext4_write_begin(inode, pos, len, flags);
875 * Reserve one block more for addition to orphan list in case
876 * we allocate blocks but write fails for some reason
878 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
879 index = pos >> PAGE_CACHE_SHIFT;
880 from = pos & (PAGE_CACHE_SIZE - 1);
881 to = from + len;
883 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
884 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
885 flags, pagep);
886 if (ret < 0)
887 return ret;
888 if (ret == 1)
889 return 0;
893 * grab_cache_page_write_begin() can take a long time if the
894 * system is thrashing due to memory pressure, or if the page
895 * is being written back. So grab it first before we start
896 * the transaction handle. This also allows us to allocate
897 * the page (if needed) without using GFP_NOFS.
899 retry_grab:
900 page = grab_cache_page_write_begin(mapping, index, flags);
901 if (!page)
902 return -ENOMEM;
903 unlock_page(page);
905 retry_journal:
906 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
907 if (IS_ERR(handle)) {
908 page_cache_release(page);
909 return PTR_ERR(handle);
912 lock_page(page);
913 if (page->mapping != mapping) {
914 /* The page got truncated from under us */
915 unlock_page(page);
916 page_cache_release(page);
917 ext4_journal_stop(handle);
918 goto retry_grab;
920 wait_on_page_writeback(page);
922 if (ext4_should_dioread_nolock(inode))
923 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
924 else
925 ret = __block_write_begin(page, pos, len, ext4_get_block);
927 if (!ret && ext4_should_journal_data(inode)) {
928 ret = ext4_walk_page_buffers(handle, page_buffers(page),
929 from, to, NULL,
930 do_journal_get_write_access);
933 if (ret) {
934 unlock_page(page);
936 * __block_write_begin may have instantiated a few blocks
937 * outside i_size. Trim these off again. Don't need
938 * i_size_read because we hold i_mutex.
940 * Add inode to orphan list in case we crash before
941 * truncate finishes
943 if (pos + len > inode->i_size && ext4_can_truncate(inode))
944 ext4_orphan_add(handle, inode);
946 ext4_journal_stop(handle);
947 if (pos + len > inode->i_size) {
948 ext4_truncate_failed_write(inode);
950 * If truncate failed early the inode might
951 * still be on the orphan list; we need to
952 * make sure the inode is removed from the
953 * orphan list in that case.
955 if (inode->i_nlink)
956 ext4_orphan_del(NULL, inode);
959 if (ret == -ENOSPC &&
960 ext4_should_retry_alloc(inode->i_sb, &retries))
961 goto retry_journal;
962 page_cache_release(page);
963 return ret;
965 *pagep = page;
966 return ret;
969 /* For write_end() in data=journal mode */
970 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
972 if (!buffer_mapped(bh) || buffer_freed(bh))
973 return 0;
974 set_buffer_uptodate(bh);
975 return ext4_handle_dirty_metadata(handle, NULL, bh);
978 static int ext4_generic_write_end(struct file *file,
979 struct address_space *mapping,
980 loff_t pos, unsigned len, unsigned copied,
981 struct page *page, void *fsdata)
983 int i_size_changed = 0;
984 struct inode *inode = mapping->host;
985 handle_t *handle = ext4_journal_current_handle();
987 if (ext4_has_inline_data(inode))
988 copied = ext4_write_inline_data_end(inode, pos, len,
989 copied, page);
990 else
991 copied = block_write_end(file, mapping, pos,
992 len, copied, page, fsdata);
995 * No need to use i_size_read() here, the i_size
996 * cannot change under us because we hold i_mutex.
998 * But it's important to update i_size while still holding page lock:
999 * page writeout could otherwise come in and zero beyond i_size.
1001 if (pos + copied > inode->i_size) {
1002 i_size_write(inode, pos + copied);
1003 i_size_changed = 1;
1006 if (pos + copied > EXT4_I(inode)->i_disksize) {
1007 /* We need to mark inode dirty even if
1008 * new_i_size is less that inode->i_size
1009 * bu greater than i_disksize.(hint delalloc)
1011 ext4_update_i_disksize(inode, (pos + copied));
1012 i_size_changed = 1;
1014 unlock_page(page);
1015 page_cache_release(page);
1018 * Don't mark the inode dirty under page lock. First, it unnecessarily
1019 * makes the holding time of page lock longer. Second, it forces lock
1020 * ordering of page lock and transaction start for journaling
1021 * filesystems.
1023 if (i_size_changed)
1024 ext4_mark_inode_dirty(handle, inode);
1026 return copied;
1030 * We need to pick up the new inode size which generic_commit_write gave us
1031 * `file' can be NULL - eg, when called from page_symlink().
1033 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1034 * buffers are managed internally.
1036 static int ext4_ordered_write_end(struct file *file,
1037 struct address_space *mapping,
1038 loff_t pos, unsigned len, unsigned copied,
1039 struct page *page, void *fsdata)
1041 handle_t *handle = ext4_journal_current_handle();
1042 struct inode *inode = mapping->host;
1043 int ret = 0, ret2;
1045 trace_ext4_ordered_write_end(inode, pos, len, copied);
1046 ret = ext4_jbd2_file_inode(handle, inode);
1048 if (ret == 0) {
1049 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1050 page, fsdata);
1051 copied = ret2;
1052 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1053 /* if we have allocated more blocks and copied
1054 * less. We will have blocks allocated outside
1055 * inode->i_size. So truncate them
1057 ext4_orphan_add(handle, inode);
1058 if (ret2 < 0)
1059 ret = ret2;
1060 } else {
1061 unlock_page(page);
1062 page_cache_release(page);
1065 ret2 = ext4_journal_stop(handle);
1066 if (!ret)
1067 ret = ret2;
1069 if (pos + len > inode->i_size) {
1070 ext4_truncate_failed_write(inode);
1072 * If truncate failed early the inode might still be
1073 * on the orphan list; we need to make sure the inode
1074 * is removed from the orphan list in that case.
1076 if (inode->i_nlink)
1077 ext4_orphan_del(NULL, inode);
1081 return ret ? ret : copied;
1084 static int ext4_writeback_write_end(struct file *file,
1085 struct address_space *mapping,
1086 loff_t pos, unsigned len, unsigned copied,
1087 struct page *page, void *fsdata)
1089 handle_t *handle = ext4_journal_current_handle();
1090 struct inode *inode = mapping->host;
1091 int ret = 0, ret2;
1093 trace_ext4_writeback_write_end(inode, pos, len, copied);
1094 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1095 page, fsdata);
1096 copied = ret2;
1097 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1098 /* if we have allocated more blocks and copied
1099 * less. We will have blocks allocated outside
1100 * inode->i_size. So truncate them
1102 ext4_orphan_add(handle, inode);
1104 if (ret2 < 0)
1105 ret = ret2;
1107 ret2 = ext4_journal_stop(handle);
1108 if (!ret)
1109 ret = ret2;
1111 if (pos + len > inode->i_size) {
1112 ext4_truncate_failed_write(inode);
1114 * If truncate failed early the inode might still be
1115 * on the orphan list; we need to make sure the inode
1116 * is removed from the orphan list in that case.
1118 if (inode->i_nlink)
1119 ext4_orphan_del(NULL, inode);
1122 return ret ? ret : copied;
1125 static int ext4_journalled_write_end(struct file *file,
1126 struct address_space *mapping,
1127 loff_t pos, unsigned len, unsigned copied,
1128 struct page *page, void *fsdata)
1130 handle_t *handle = ext4_journal_current_handle();
1131 struct inode *inode = mapping->host;
1132 int ret = 0, ret2;
1133 int partial = 0;
1134 unsigned from, to;
1135 loff_t new_i_size;
1137 trace_ext4_journalled_write_end(inode, pos, len, copied);
1138 from = pos & (PAGE_CACHE_SIZE - 1);
1139 to = from + len;
1141 BUG_ON(!ext4_handle_valid(handle));
1143 if (ext4_has_inline_data(inode))
1144 copied = ext4_write_inline_data_end(inode, pos, len,
1145 copied, page);
1146 else {
1147 if (copied < len) {
1148 if (!PageUptodate(page))
1149 copied = 0;
1150 page_zero_new_buffers(page, from+copied, to);
1153 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1154 to, &partial, write_end_fn);
1155 if (!partial)
1156 SetPageUptodate(page);
1158 new_i_size = pos + copied;
1159 if (new_i_size > inode->i_size)
1160 i_size_write(inode, pos+copied);
1161 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1162 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1163 if (new_i_size > EXT4_I(inode)->i_disksize) {
1164 ext4_update_i_disksize(inode, new_i_size);
1165 ret2 = ext4_mark_inode_dirty(handle, inode);
1166 if (!ret)
1167 ret = ret2;
1170 unlock_page(page);
1171 page_cache_release(page);
1172 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1173 /* if we have allocated more blocks and copied
1174 * less. We will have blocks allocated outside
1175 * inode->i_size. So truncate them
1177 ext4_orphan_add(handle, inode);
1179 ret2 = ext4_journal_stop(handle);
1180 if (!ret)
1181 ret = ret2;
1182 if (pos + len > inode->i_size) {
1183 ext4_truncate_failed_write(inode);
1185 * If truncate failed early the inode might still be
1186 * on the orphan list; we need to make sure the inode
1187 * is removed from the orphan list in that case.
1189 if (inode->i_nlink)
1190 ext4_orphan_del(NULL, inode);
1193 return ret ? ret : copied;
1197 * Reserve a single cluster located at lblock
1199 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1201 int retries = 0;
1202 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1203 struct ext4_inode_info *ei = EXT4_I(inode);
1204 unsigned int md_needed;
1205 int ret;
1206 ext4_lblk_t save_last_lblock;
1207 int save_len;
1210 * We will charge metadata quota at writeout time; this saves
1211 * us from metadata over-estimation, though we may go over by
1212 * a small amount in the end. Here we just reserve for data.
1214 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1215 if (ret)
1216 return ret;
1219 * recalculate the amount of metadata blocks to reserve
1220 * in order to allocate nrblocks
1221 * worse case is one extent per block
1223 repeat:
1224 spin_lock(&ei->i_block_reservation_lock);
1226 * ext4_calc_metadata_amount() has side effects, which we have
1227 * to be prepared undo if we fail to claim space.
1229 save_len = ei->i_da_metadata_calc_len;
1230 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1231 md_needed = EXT4_NUM_B2C(sbi,
1232 ext4_calc_metadata_amount(inode, lblock));
1233 trace_ext4_da_reserve_space(inode, md_needed);
1236 * We do still charge estimated metadata to the sb though;
1237 * we cannot afford to run out of free blocks.
1239 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1240 ei->i_da_metadata_calc_len = save_len;
1241 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1242 spin_unlock(&ei->i_block_reservation_lock);
1243 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1244 yield();
1245 goto repeat;
1247 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1248 return -ENOSPC;
1250 ei->i_reserved_data_blocks++;
1251 ei->i_reserved_meta_blocks += md_needed;
1252 spin_unlock(&ei->i_block_reservation_lock);
1254 return 0; /* success */
1257 static void ext4_da_release_space(struct inode *inode, int to_free)
1259 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1260 struct ext4_inode_info *ei = EXT4_I(inode);
1262 if (!to_free)
1263 return; /* Nothing to release, exit */
1265 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1267 trace_ext4_da_release_space(inode, to_free);
1268 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1270 * if there aren't enough reserved blocks, then the
1271 * counter is messed up somewhere. Since this
1272 * function is called from invalidate page, it's
1273 * harmless to return without any action.
1275 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1276 "ino %lu, to_free %d with only %d reserved "
1277 "data blocks", inode->i_ino, to_free,
1278 ei->i_reserved_data_blocks);
1279 WARN_ON(1);
1280 to_free = ei->i_reserved_data_blocks;
1282 ei->i_reserved_data_blocks -= to_free;
1284 if (ei->i_reserved_data_blocks == 0) {
1286 * We can release all of the reserved metadata blocks
1287 * only when we have written all of the delayed
1288 * allocation blocks.
1289 * Note that in case of bigalloc, i_reserved_meta_blocks,
1290 * i_reserved_data_blocks, etc. refer to number of clusters.
1292 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1293 ei->i_reserved_meta_blocks);
1294 ei->i_reserved_meta_blocks = 0;
1295 ei->i_da_metadata_calc_len = 0;
1298 /* update fs dirty data blocks counter */
1299 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1301 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1303 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1306 static void ext4_da_page_release_reservation(struct page *page,
1307 unsigned long offset)
1309 int to_release = 0;
1310 struct buffer_head *head, *bh;
1311 unsigned int curr_off = 0;
1312 struct inode *inode = page->mapping->host;
1313 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1314 int num_clusters;
1315 ext4_fsblk_t lblk;
1317 head = page_buffers(page);
1318 bh = head;
1319 do {
1320 unsigned int next_off = curr_off + bh->b_size;
1322 if ((offset <= curr_off) && (buffer_delay(bh))) {
1323 to_release++;
1324 clear_buffer_delay(bh);
1326 curr_off = next_off;
1327 } while ((bh = bh->b_this_page) != head);
1329 if (to_release) {
1330 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1331 ext4_es_remove_extent(inode, lblk, to_release);
1334 /* If we have released all the blocks belonging to a cluster, then we
1335 * need to release the reserved space for that cluster. */
1336 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1337 while (num_clusters > 0) {
1338 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1339 ((num_clusters - 1) << sbi->s_cluster_bits);
1340 if (sbi->s_cluster_ratio == 1 ||
1341 !ext4_find_delalloc_cluster(inode, lblk))
1342 ext4_da_release_space(inode, 1);
1344 num_clusters--;
1349 * Delayed allocation stuff
1353 * mpage_da_submit_io - walks through extent of pages and try to write
1354 * them with writepage() call back
1356 * @mpd->inode: inode
1357 * @mpd->first_page: first page of the extent
1358 * @mpd->next_page: page after the last page of the extent
1360 * By the time mpage_da_submit_io() is called we expect all blocks
1361 * to be allocated. this may be wrong if allocation failed.
1363 * As pages are already locked by write_cache_pages(), we can't use it
1365 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1366 struct ext4_map_blocks *map)
1368 struct pagevec pvec;
1369 unsigned long index, end;
1370 int ret = 0, err, nr_pages, i;
1371 struct inode *inode = mpd->inode;
1372 struct address_space *mapping = inode->i_mapping;
1373 loff_t size = i_size_read(inode);
1374 unsigned int len, block_start;
1375 struct buffer_head *bh, *page_bufs = NULL;
1376 sector_t pblock = 0, cur_logical = 0;
1377 struct ext4_io_submit io_submit;
1379 BUG_ON(mpd->next_page <= mpd->first_page);
1380 memset(&io_submit, 0, sizeof(io_submit));
1382 * We need to start from the first_page to the next_page - 1
1383 * to make sure we also write the mapped dirty buffer_heads.
1384 * If we look at mpd->b_blocknr we would only be looking
1385 * at the currently mapped buffer_heads.
1387 index = mpd->first_page;
1388 end = mpd->next_page - 1;
1390 pagevec_init(&pvec, 0);
1391 while (index <= end) {
1392 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1393 if (nr_pages == 0)
1394 break;
1395 for (i = 0; i < nr_pages; i++) {
1396 int skip_page = 0;
1397 struct page *page = pvec.pages[i];
1399 index = page->index;
1400 if (index > end)
1401 break;
1403 if (index == size >> PAGE_CACHE_SHIFT)
1404 len = size & ~PAGE_CACHE_MASK;
1405 else
1406 len = PAGE_CACHE_SIZE;
1407 if (map) {
1408 cur_logical = index << (PAGE_CACHE_SHIFT -
1409 inode->i_blkbits);
1410 pblock = map->m_pblk + (cur_logical -
1411 map->m_lblk);
1413 index++;
1415 BUG_ON(!PageLocked(page));
1416 BUG_ON(PageWriteback(page));
1418 bh = page_bufs = page_buffers(page);
1419 block_start = 0;
1420 do {
1421 if (map && (cur_logical >= map->m_lblk) &&
1422 (cur_logical <= (map->m_lblk +
1423 (map->m_len - 1)))) {
1424 if (buffer_delay(bh)) {
1425 clear_buffer_delay(bh);
1426 bh->b_blocknr = pblock;
1428 if (buffer_unwritten(bh) ||
1429 buffer_mapped(bh))
1430 BUG_ON(bh->b_blocknr != pblock);
1431 if (map->m_flags & EXT4_MAP_UNINIT)
1432 set_buffer_uninit(bh);
1433 clear_buffer_unwritten(bh);
1437 * skip page if block allocation undone and
1438 * block is dirty
1440 if (ext4_bh_delay_or_unwritten(NULL, bh))
1441 skip_page = 1;
1442 bh = bh->b_this_page;
1443 block_start += bh->b_size;
1444 cur_logical++;
1445 pblock++;
1446 } while (bh != page_bufs);
1448 if (skip_page) {
1449 unlock_page(page);
1450 continue;
1453 clear_page_dirty_for_io(page);
1454 err = ext4_bio_write_page(&io_submit, page, len,
1455 mpd->wbc);
1456 if (!err)
1457 mpd->pages_written++;
1459 * In error case, we have to continue because
1460 * remaining pages are still locked
1462 if (ret == 0)
1463 ret = err;
1465 pagevec_release(&pvec);
1467 ext4_io_submit(&io_submit);
1468 return ret;
1471 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1473 int nr_pages, i;
1474 pgoff_t index, end;
1475 struct pagevec pvec;
1476 struct inode *inode = mpd->inode;
1477 struct address_space *mapping = inode->i_mapping;
1478 ext4_lblk_t start, last;
1480 index = mpd->first_page;
1481 end = mpd->next_page - 1;
1483 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1484 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1485 ext4_es_remove_extent(inode, start, last - start + 1);
1487 pagevec_init(&pvec, 0);
1488 while (index <= end) {
1489 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1490 if (nr_pages == 0)
1491 break;
1492 for (i = 0; i < nr_pages; i++) {
1493 struct page *page = pvec.pages[i];
1494 if (page->index > end)
1495 break;
1496 BUG_ON(!PageLocked(page));
1497 BUG_ON(PageWriteback(page));
1498 block_invalidatepage(page, 0);
1499 ClearPageUptodate(page);
1500 unlock_page(page);
1502 index = pvec.pages[nr_pages - 1]->index + 1;
1503 pagevec_release(&pvec);
1505 return;
1508 static void ext4_print_free_blocks(struct inode *inode)
1510 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1511 struct super_block *sb = inode->i_sb;
1513 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1514 EXT4_C2B(EXT4_SB(inode->i_sb),
1515 ext4_count_free_clusters(inode->i_sb)));
1516 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1517 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1518 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1519 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1520 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1521 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1522 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1523 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1524 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1525 EXT4_I(inode)->i_reserved_data_blocks);
1526 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1527 EXT4_I(inode)->i_reserved_meta_blocks);
1528 return;
1532 * mpage_da_map_and_submit - go through given space, map them
1533 * if necessary, and then submit them for I/O
1535 * @mpd - bh describing space
1537 * The function skips space we know is already mapped to disk blocks.
1540 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1542 int err, blks, get_blocks_flags;
1543 struct ext4_map_blocks map, *mapp = NULL;
1544 sector_t next = mpd->b_blocknr;
1545 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1546 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1547 handle_t *handle = NULL;
1550 * If the blocks are mapped already, or we couldn't accumulate
1551 * any blocks, then proceed immediately to the submission stage.
1553 if ((mpd->b_size == 0) ||
1554 ((mpd->b_state & (1 << BH_Mapped)) &&
1555 !(mpd->b_state & (1 << BH_Delay)) &&
1556 !(mpd->b_state & (1 << BH_Unwritten))))
1557 goto submit_io;
1559 handle = ext4_journal_current_handle();
1560 BUG_ON(!handle);
1563 * Call ext4_map_blocks() to allocate any delayed allocation
1564 * blocks, or to convert an uninitialized extent to be
1565 * initialized (in the case where we have written into
1566 * one or more preallocated blocks).
1568 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1569 * indicate that we are on the delayed allocation path. This
1570 * affects functions in many different parts of the allocation
1571 * call path. This flag exists primarily because we don't
1572 * want to change *many* call functions, so ext4_map_blocks()
1573 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1574 * inode's allocation semaphore is taken.
1576 * If the blocks in questions were delalloc blocks, set
1577 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1578 * variables are updated after the blocks have been allocated.
1580 map.m_lblk = next;
1581 map.m_len = max_blocks;
1582 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1583 if (ext4_should_dioread_nolock(mpd->inode))
1584 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1585 if (mpd->b_state & (1 << BH_Delay))
1586 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1588 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1589 if (blks < 0) {
1590 struct super_block *sb = mpd->inode->i_sb;
1592 err = blks;
1594 * If get block returns EAGAIN or ENOSPC and there
1595 * appears to be free blocks we will just let
1596 * mpage_da_submit_io() unlock all of the pages.
1598 if (err == -EAGAIN)
1599 goto submit_io;
1601 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1602 mpd->retval = err;
1603 goto submit_io;
1607 * get block failure will cause us to loop in
1608 * writepages, because a_ops->writepage won't be able
1609 * to make progress. The page will be redirtied by
1610 * writepage and writepages will again try to write
1611 * the same.
1613 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1614 ext4_msg(sb, KERN_CRIT,
1615 "delayed block allocation failed for inode %lu "
1616 "at logical offset %llu with max blocks %zd "
1617 "with error %d", mpd->inode->i_ino,
1618 (unsigned long long) next,
1619 mpd->b_size >> mpd->inode->i_blkbits, err);
1620 ext4_msg(sb, KERN_CRIT,
1621 "This should not happen!! Data will be lost");
1622 if (err == -ENOSPC)
1623 ext4_print_free_blocks(mpd->inode);
1625 /* invalidate all the pages */
1626 ext4_da_block_invalidatepages(mpd);
1628 /* Mark this page range as having been completed */
1629 mpd->io_done = 1;
1630 return;
1632 BUG_ON(blks == 0);
1634 mapp = &map;
1635 if (map.m_flags & EXT4_MAP_NEW) {
1636 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1637 int i;
1639 for (i = 0; i < map.m_len; i++)
1640 unmap_underlying_metadata(bdev, map.m_pblk + i);
1644 * Update on-disk size along with block allocation.
1646 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1647 if (disksize > i_size_read(mpd->inode))
1648 disksize = i_size_read(mpd->inode);
1649 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1650 ext4_update_i_disksize(mpd->inode, disksize);
1651 err = ext4_mark_inode_dirty(handle, mpd->inode);
1652 if (err)
1653 ext4_error(mpd->inode->i_sb,
1654 "Failed to mark inode %lu dirty",
1655 mpd->inode->i_ino);
1658 submit_io:
1659 mpage_da_submit_io(mpd, mapp);
1660 mpd->io_done = 1;
1663 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1664 (1 << BH_Delay) | (1 << BH_Unwritten))
1667 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1669 * @mpd->lbh - extent of blocks
1670 * @logical - logical number of the block in the file
1671 * @b_state - b_state of the buffer head added
1673 * the function is used to collect contig. blocks in same state
1675 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd, sector_t logical,
1676 unsigned long b_state)
1678 sector_t next;
1679 int blkbits = mpd->inode->i_blkbits;
1680 int nrblocks = mpd->b_size >> blkbits;
1683 * XXX Don't go larger than mballoc is willing to allocate
1684 * This is a stopgap solution. We eventually need to fold
1685 * mpage_da_submit_io() into this function and then call
1686 * ext4_map_blocks() multiple times in a loop
1688 if (nrblocks >= (8*1024*1024 >> blkbits))
1689 goto flush_it;
1691 /* check if the reserved journal credits might overflow */
1692 if (!ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS)) {
1693 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1695 * With non-extent format we are limited by the journal
1696 * credit available. Total credit needed to insert
1697 * nrblocks contiguous blocks is dependent on the
1698 * nrblocks. So limit nrblocks.
1700 goto flush_it;
1704 * First block in the extent
1706 if (mpd->b_size == 0) {
1707 mpd->b_blocknr = logical;
1708 mpd->b_size = 1 << blkbits;
1709 mpd->b_state = b_state & BH_FLAGS;
1710 return;
1713 next = mpd->b_blocknr + nrblocks;
1715 * Can we merge the block to our big extent?
1717 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1718 mpd->b_size += 1 << blkbits;
1719 return;
1722 flush_it:
1724 * We couldn't merge the block to our extent, so we
1725 * need to flush current extent and start new one
1727 mpage_da_map_and_submit(mpd);
1728 return;
1731 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1733 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1737 * This function is grabs code from the very beginning of
1738 * ext4_map_blocks, but assumes that the caller is from delayed write
1739 * time. This function looks up the requested blocks and sets the
1740 * buffer delay bit under the protection of i_data_sem.
1742 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1743 struct ext4_map_blocks *map,
1744 struct buffer_head *bh)
1746 int retval;
1747 sector_t invalid_block = ~((sector_t) 0xffff);
1749 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1750 invalid_block = ~0;
1752 map->m_flags = 0;
1753 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1754 "logical block %lu\n", inode->i_ino, map->m_len,
1755 (unsigned long) map->m_lblk);
1757 * Try to see if we can get the block without requesting a new
1758 * file system block.
1760 down_read((&EXT4_I(inode)->i_data_sem));
1761 if (ext4_has_inline_data(inode)) {
1763 * We will soon create blocks for this page, and let
1764 * us pretend as if the blocks aren't allocated yet.
1765 * In case of clusters, we have to handle the work
1766 * of mapping from cluster so that the reserved space
1767 * is calculated properly.
1769 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1770 ext4_find_delalloc_cluster(inode, map->m_lblk))
1771 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1772 retval = 0;
1773 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1774 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1775 else
1776 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1778 if (retval == 0) {
1779 int ret;
1781 * XXX: __block_prepare_write() unmaps passed block,
1782 * is it OK?
1784 /* If the block was allocated from previously allocated cluster,
1785 * then we dont need to reserve it again. */
1786 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1787 ret = ext4_da_reserve_space(inode, iblock);
1788 if (ret) {
1789 /* not enough space to reserve */
1790 retval = ret;
1791 goto out_unlock;
1795 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1796 ~0, EXTENT_STATUS_DELAYED);
1797 if (ret) {
1798 retval = ret;
1799 goto out_unlock;
1802 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1803 * and it should not appear on the bh->b_state.
1805 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1807 map_bh(bh, inode->i_sb, invalid_block);
1808 set_buffer_new(bh);
1809 set_buffer_delay(bh);
1810 } else if (retval > 0) {
1811 int ret;
1812 unsigned long long status;
1814 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1815 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1816 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1817 map->m_pblk, status);
1818 if (ret != 0)
1819 retval = ret;
1822 out_unlock:
1823 up_read((&EXT4_I(inode)->i_data_sem));
1825 return retval;
1829 * This is a special get_blocks_t callback which is used by
1830 * ext4_da_write_begin(). It will either return mapped block or
1831 * reserve space for a single block.
1833 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1834 * We also have b_blocknr = -1 and b_bdev initialized properly
1836 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1837 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1838 * initialized properly.
1840 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1841 struct buffer_head *bh, int create)
1843 struct ext4_map_blocks map;
1844 int ret = 0;
1846 BUG_ON(create == 0);
1847 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1849 map.m_lblk = iblock;
1850 map.m_len = 1;
1853 * first, we need to know whether the block is allocated already
1854 * preallocated blocks are unmapped but should treated
1855 * the same as allocated blocks.
1857 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1858 if (ret <= 0)
1859 return ret;
1861 map_bh(bh, inode->i_sb, map.m_pblk);
1862 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1864 if (buffer_unwritten(bh)) {
1865 /* A delayed write to unwritten bh should be marked
1866 * new and mapped. Mapped ensures that we don't do
1867 * get_block multiple times when we write to the same
1868 * offset and new ensures that we do proper zero out
1869 * for partial write.
1871 set_buffer_new(bh);
1872 set_buffer_mapped(bh);
1874 return 0;
1877 static int bget_one(handle_t *handle, struct buffer_head *bh)
1879 get_bh(bh);
1880 return 0;
1883 static int bput_one(handle_t *handle, struct buffer_head *bh)
1885 put_bh(bh);
1886 return 0;
1889 static int __ext4_journalled_writepage(struct page *page,
1890 unsigned int len)
1892 struct address_space *mapping = page->mapping;
1893 struct inode *inode = mapping->host;
1894 struct buffer_head *page_bufs = NULL;
1895 handle_t *handle = NULL;
1896 int ret = 0, err = 0;
1897 int inline_data = ext4_has_inline_data(inode);
1898 struct buffer_head *inode_bh = NULL;
1900 ClearPageChecked(page);
1902 if (inline_data) {
1903 BUG_ON(page->index != 0);
1904 BUG_ON(len > ext4_get_max_inline_size(inode));
1905 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1906 if (inode_bh == NULL)
1907 goto out;
1908 } else {
1909 page_bufs = page_buffers(page);
1910 if (!page_bufs) {
1911 BUG();
1912 goto out;
1914 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1915 NULL, bget_one);
1917 /* As soon as we unlock the page, it can go away, but we have
1918 * references to buffers so we are safe */
1919 unlock_page(page);
1921 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1922 ext4_writepage_trans_blocks(inode));
1923 if (IS_ERR(handle)) {
1924 ret = PTR_ERR(handle);
1925 goto out;
1928 BUG_ON(!ext4_handle_valid(handle));
1930 if (inline_data) {
1931 ret = ext4_journal_get_write_access(handle, inode_bh);
1933 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1935 } else {
1936 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1937 do_journal_get_write_access);
1939 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1940 write_end_fn);
1942 if (ret == 0)
1943 ret = err;
1944 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1945 err = ext4_journal_stop(handle);
1946 if (!ret)
1947 ret = err;
1949 if (!ext4_has_inline_data(inode))
1950 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1951 NULL, bput_one);
1952 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1953 out:
1954 brelse(inode_bh);
1955 return ret;
1959 * Note that we don't need to start a transaction unless we're journaling data
1960 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1961 * need to file the inode to the transaction's list in ordered mode because if
1962 * we are writing back data added by write(), the inode is already there and if
1963 * we are writing back data modified via mmap(), no one guarantees in which
1964 * transaction the data will hit the disk. In case we are journaling data, we
1965 * cannot start transaction directly because transaction start ranks above page
1966 * lock so we have to do some magic.
1968 * This function can get called via...
1969 * - ext4_da_writepages after taking page lock (have journal handle)
1970 * - journal_submit_inode_data_buffers (no journal handle)
1971 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1972 * - grab_page_cache when doing write_begin (have journal handle)
1974 * We don't do any block allocation in this function. If we have page with
1975 * multiple blocks we need to write those buffer_heads that are mapped. This
1976 * is important for mmaped based write. So if we do with blocksize 1K
1977 * truncate(f, 1024);
1978 * a = mmap(f, 0, 4096);
1979 * a[0] = 'a';
1980 * truncate(f, 4096);
1981 * we have in the page first buffer_head mapped via page_mkwrite call back
1982 * but other buffer_heads would be unmapped but dirty (dirty done via the
1983 * do_wp_page). So writepage should write the first block. If we modify
1984 * the mmap area beyond 1024 we will again get a page_fault and the
1985 * page_mkwrite callback will do the block allocation and mark the
1986 * buffer_heads mapped.
1988 * We redirty the page if we have any buffer_heads that is either delay or
1989 * unwritten in the page.
1991 * We can get recursively called as show below.
1993 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1994 * ext4_writepage()
1996 * But since we don't do any block allocation we should not deadlock.
1997 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1999 static int ext4_writepage(struct page *page,
2000 struct writeback_control *wbc)
2002 int ret = 0;
2003 loff_t size;
2004 unsigned int len;
2005 struct buffer_head *page_bufs = NULL;
2006 struct inode *inode = page->mapping->host;
2007 struct ext4_io_submit io_submit;
2009 trace_ext4_writepage(page);
2010 size = i_size_read(inode);
2011 if (page->index == size >> PAGE_CACHE_SHIFT)
2012 len = size & ~PAGE_CACHE_MASK;
2013 else
2014 len = PAGE_CACHE_SIZE;
2016 page_bufs = page_buffers(page);
2018 * We cannot do block allocation or other extent handling in this
2019 * function. If there are buffers needing that, we have to redirty
2020 * the page. But we may reach here when we do a journal commit via
2021 * journal_submit_inode_data_buffers() and in that case we must write
2022 * allocated buffers to achieve data=ordered mode guarantees.
2024 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2025 ext4_bh_delay_or_unwritten)) {
2026 redirty_page_for_writepage(wbc, page);
2027 if (current->flags & PF_MEMALLOC) {
2029 * For memory cleaning there's no point in writing only
2030 * some buffers. So just bail out. Warn if we came here
2031 * from direct reclaim.
2033 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2034 == PF_MEMALLOC);
2035 unlock_page(page);
2036 return 0;
2040 if (PageChecked(page) && ext4_should_journal_data(inode))
2042 * It's mmapped pagecache. Add buffers and journal it. There
2043 * doesn't seem much point in redirtying the page here.
2045 return __ext4_journalled_writepage(page, len);
2047 memset(&io_submit, 0, sizeof(io_submit));
2048 ret = ext4_bio_write_page(&io_submit, page, len, wbc);
2049 ext4_io_submit(&io_submit);
2050 return ret;
2054 * This is called via ext4_da_writepages() to
2055 * calculate the total number of credits to reserve to fit
2056 * a single extent allocation into a single transaction,
2057 * ext4_da_writpeages() will loop calling this before
2058 * the block allocation.
2061 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2063 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2066 * With non-extent format the journal credit needed to
2067 * insert nrblocks contiguous block is dependent on
2068 * number of contiguous block. So we will limit
2069 * number of contiguous block to a sane value
2071 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2072 (max_blocks > EXT4_MAX_TRANS_DATA))
2073 max_blocks = EXT4_MAX_TRANS_DATA;
2075 return ext4_chunk_trans_blocks(inode, max_blocks);
2079 * write_cache_pages_da - walk the list of dirty pages of the given
2080 * address space and accumulate pages that need writing, and call
2081 * mpage_da_map_and_submit to map a single contiguous memory region
2082 * and then write them.
2084 static int write_cache_pages_da(handle_t *handle,
2085 struct address_space *mapping,
2086 struct writeback_control *wbc,
2087 struct mpage_da_data *mpd,
2088 pgoff_t *done_index)
2090 struct buffer_head *bh, *head;
2091 struct inode *inode = mapping->host;
2092 struct pagevec pvec;
2093 unsigned int nr_pages;
2094 sector_t logical;
2095 pgoff_t index, end;
2096 long nr_to_write = wbc->nr_to_write;
2097 int i, tag, ret = 0;
2099 memset(mpd, 0, sizeof(struct mpage_da_data));
2100 mpd->wbc = wbc;
2101 mpd->inode = inode;
2102 pagevec_init(&pvec, 0);
2103 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2104 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2106 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2107 tag = PAGECACHE_TAG_TOWRITE;
2108 else
2109 tag = PAGECACHE_TAG_DIRTY;
2111 *done_index = index;
2112 while (index <= end) {
2113 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2114 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2115 if (nr_pages == 0)
2116 return 0;
2118 for (i = 0; i < nr_pages; i++) {
2119 struct page *page = pvec.pages[i];
2122 * At this point, the page may be truncated or
2123 * invalidated (changing page->mapping to NULL), or
2124 * even swizzled back from swapper_space to tmpfs file
2125 * mapping. However, page->index will not change
2126 * because we have a reference on the page.
2128 if (page->index > end)
2129 goto out;
2131 *done_index = page->index + 1;
2134 * If we can't merge this page, and we have
2135 * accumulated an contiguous region, write it
2137 if ((mpd->next_page != page->index) &&
2138 (mpd->next_page != mpd->first_page)) {
2139 mpage_da_map_and_submit(mpd);
2140 goto ret_extent_tail;
2143 lock_page(page);
2146 * If the page is no longer dirty, or its
2147 * mapping no longer corresponds to inode we
2148 * are writing (which means it has been
2149 * truncated or invalidated), or the page is
2150 * already under writeback and we are not
2151 * doing a data integrity writeback, skip the page
2153 if (!PageDirty(page) ||
2154 (PageWriteback(page) &&
2155 (wbc->sync_mode == WB_SYNC_NONE)) ||
2156 unlikely(page->mapping != mapping)) {
2157 unlock_page(page);
2158 continue;
2161 wait_on_page_writeback(page);
2162 BUG_ON(PageWriteback(page));
2165 * If we have inline data and arrive here, it means that
2166 * we will soon create the block for the 1st page, so
2167 * we'd better clear the inline data here.
2169 if (ext4_has_inline_data(inode)) {
2170 BUG_ON(ext4_test_inode_state(inode,
2171 EXT4_STATE_MAY_INLINE_DATA));
2172 ext4_destroy_inline_data(handle, inode);
2175 if (mpd->next_page != page->index)
2176 mpd->first_page = page->index;
2177 mpd->next_page = page->index + 1;
2178 logical = (sector_t) page->index <<
2179 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2181 /* Add all dirty buffers to mpd */
2182 head = page_buffers(page);
2183 bh = head;
2184 do {
2185 BUG_ON(buffer_locked(bh));
2187 * We need to try to allocate unmapped blocks
2188 * in the same page. Otherwise we won't make
2189 * progress with the page in ext4_writepage
2191 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2192 mpage_add_bh_to_extent(mpd, logical,
2193 bh->b_state);
2194 if (mpd->io_done)
2195 goto ret_extent_tail;
2196 } else if (buffer_dirty(bh) &&
2197 buffer_mapped(bh)) {
2199 * mapped dirty buffer. We need to
2200 * update the b_state because we look
2201 * at b_state in mpage_da_map_blocks.
2202 * We don't update b_size because if we
2203 * find an unmapped buffer_head later
2204 * we need to use the b_state flag of
2205 * that buffer_head.
2207 if (mpd->b_size == 0)
2208 mpd->b_state =
2209 bh->b_state & BH_FLAGS;
2211 logical++;
2212 } while ((bh = bh->b_this_page) != head);
2214 if (nr_to_write > 0) {
2215 nr_to_write--;
2216 if (nr_to_write == 0 &&
2217 wbc->sync_mode == WB_SYNC_NONE)
2219 * We stop writing back only if we are
2220 * not doing integrity sync. In case of
2221 * integrity sync we have to keep going
2222 * because someone may be concurrently
2223 * dirtying pages, and we might have
2224 * synced a lot of newly appeared dirty
2225 * pages, but have not synced all of the
2226 * old dirty pages.
2228 goto out;
2231 pagevec_release(&pvec);
2232 cond_resched();
2234 return 0;
2235 ret_extent_tail:
2236 ret = MPAGE_DA_EXTENT_TAIL;
2237 out:
2238 pagevec_release(&pvec);
2239 cond_resched();
2240 return ret;
2244 static int ext4_da_writepages(struct address_space *mapping,
2245 struct writeback_control *wbc)
2247 pgoff_t index;
2248 int range_whole = 0;
2249 handle_t *handle = NULL;
2250 struct mpage_da_data mpd;
2251 struct inode *inode = mapping->host;
2252 int pages_written = 0;
2253 unsigned int max_pages;
2254 int range_cyclic, cycled = 1, io_done = 0;
2255 int needed_blocks, ret = 0;
2256 long desired_nr_to_write, nr_to_writebump = 0;
2257 loff_t range_start = wbc->range_start;
2258 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2259 pgoff_t done_index = 0;
2260 pgoff_t end;
2261 struct blk_plug plug;
2263 trace_ext4_da_writepages(inode, wbc);
2266 * No pages to write? This is mainly a kludge to avoid starting
2267 * a transaction for special inodes like journal inode on last iput()
2268 * because that could violate lock ordering on umount
2270 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2271 return 0;
2274 * If the filesystem has aborted, it is read-only, so return
2275 * right away instead of dumping stack traces later on that
2276 * will obscure the real source of the problem. We test
2277 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2278 * the latter could be true if the filesystem is mounted
2279 * read-only, and in that case, ext4_da_writepages should
2280 * *never* be called, so if that ever happens, we would want
2281 * the stack trace.
2283 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2284 return -EROFS;
2286 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2287 range_whole = 1;
2289 range_cyclic = wbc->range_cyclic;
2290 if (wbc->range_cyclic) {
2291 index = mapping->writeback_index;
2292 if (index)
2293 cycled = 0;
2294 wbc->range_start = index << PAGE_CACHE_SHIFT;
2295 wbc->range_end = LLONG_MAX;
2296 wbc->range_cyclic = 0;
2297 end = -1;
2298 } else {
2299 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2300 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2304 * This works around two forms of stupidity. The first is in
2305 * the writeback code, which caps the maximum number of pages
2306 * written to be 1024 pages. This is wrong on multiple
2307 * levels; different architectues have a different page size,
2308 * which changes the maximum amount of data which gets
2309 * written. Secondly, 4 megabytes is way too small. XFS
2310 * forces this value to be 16 megabytes by multiplying
2311 * nr_to_write parameter by four, and then relies on its
2312 * allocator to allocate larger extents to make them
2313 * contiguous. Unfortunately this brings us to the second
2314 * stupidity, which is that ext4's mballoc code only allocates
2315 * at most 2048 blocks. So we force contiguous writes up to
2316 * the number of dirty blocks in the inode, or
2317 * sbi->max_writeback_mb_bump whichever is smaller.
2319 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2320 if (!range_cyclic && range_whole) {
2321 if (wbc->nr_to_write == LONG_MAX)
2322 desired_nr_to_write = wbc->nr_to_write;
2323 else
2324 desired_nr_to_write = wbc->nr_to_write * 8;
2325 } else
2326 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2327 max_pages);
2328 if (desired_nr_to_write > max_pages)
2329 desired_nr_to_write = max_pages;
2331 if (wbc->nr_to_write < desired_nr_to_write) {
2332 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2333 wbc->nr_to_write = desired_nr_to_write;
2336 retry:
2337 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2338 tag_pages_for_writeback(mapping, index, end);
2340 blk_start_plug(&plug);
2341 while (!ret && wbc->nr_to_write > 0) {
2344 * we insert one extent at a time. So we need
2345 * credit needed for single extent allocation.
2346 * journalled mode is currently not supported
2347 * by delalloc
2349 BUG_ON(ext4_should_journal_data(inode));
2350 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2352 /* start a new transaction*/
2353 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2354 needed_blocks);
2355 if (IS_ERR(handle)) {
2356 ret = PTR_ERR(handle);
2357 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2358 "%ld pages, ino %lu; err %d", __func__,
2359 wbc->nr_to_write, inode->i_ino, ret);
2360 blk_finish_plug(&plug);
2361 goto out_writepages;
2365 * Now call write_cache_pages_da() to find the next
2366 * contiguous region of logical blocks that need
2367 * blocks to be allocated by ext4 and submit them.
2369 ret = write_cache_pages_da(handle, mapping,
2370 wbc, &mpd, &done_index);
2372 * If we have a contiguous extent of pages and we
2373 * haven't done the I/O yet, map the blocks and submit
2374 * them for I/O.
2376 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2377 mpage_da_map_and_submit(&mpd);
2378 ret = MPAGE_DA_EXTENT_TAIL;
2380 trace_ext4_da_write_pages(inode, &mpd);
2381 wbc->nr_to_write -= mpd.pages_written;
2383 ext4_journal_stop(handle);
2385 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2386 /* commit the transaction which would
2387 * free blocks released in the transaction
2388 * and try again
2390 jbd2_journal_force_commit_nested(sbi->s_journal);
2391 ret = 0;
2392 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2394 * Got one extent now try with rest of the pages.
2395 * If mpd.retval is set -EIO, journal is aborted.
2396 * So we don't need to write any more.
2398 pages_written += mpd.pages_written;
2399 ret = mpd.retval;
2400 io_done = 1;
2401 } else if (wbc->nr_to_write)
2403 * There is no more writeout needed
2404 * or we requested for a noblocking writeout
2405 * and we found the device congested
2407 break;
2409 blk_finish_plug(&plug);
2410 if (!io_done && !cycled) {
2411 cycled = 1;
2412 index = 0;
2413 wbc->range_start = index << PAGE_CACHE_SHIFT;
2414 wbc->range_end = mapping->writeback_index - 1;
2415 goto retry;
2418 /* Update index */
2419 wbc->range_cyclic = range_cyclic;
2420 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2422 * set the writeback_index so that range_cyclic
2423 * mode will write it back later
2425 mapping->writeback_index = done_index;
2427 out_writepages:
2428 wbc->nr_to_write -= nr_to_writebump;
2429 wbc->range_start = range_start;
2430 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2431 return ret;
2434 static int ext4_nonda_switch(struct super_block *sb)
2436 s64 free_blocks, dirty_blocks;
2437 struct ext4_sb_info *sbi = EXT4_SB(sb);
2440 * switch to non delalloc mode if we are running low
2441 * on free block. The free block accounting via percpu
2442 * counters can get slightly wrong with percpu_counter_batch getting
2443 * accumulated on each CPU without updating global counters
2444 * Delalloc need an accurate free block accounting. So switch
2445 * to non delalloc when we are near to error range.
2447 free_blocks = EXT4_C2B(sbi,
2448 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2449 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2451 * Start pushing delalloc when 1/2 of free blocks are dirty.
2453 if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
2454 !writeback_in_progress(sb->s_bdi) &&
2455 down_read_trylock(&sb->s_umount)) {
2456 writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2457 up_read(&sb->s_umount);
2460 if (2 * free_blocks < 3 * dirty_blocks ||
2461 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2463 * free block count is less than 150% of dirty blocks
2464 * or free blocks is less than watermark
2466 return 1;
2468 return 0;
2471 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2472 loff_t pos, unsigned len, unsigned flags,
2473 struct page **pagep, void **fsdata)
2475 int ret, retries = 0;
2476 struct page *page;
2477 pgoff_t index;
2478 struct inode *inode = mapping->host;
2479 handle_t *handle;
2481 index = pos >> PAGE_CACHE_SHIFT;
2483 if (ext4_nonda_switch(inode->i_sb)) {
2484 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2485 return ext4_write_begin(file, mapping, pos,
2486 len, flags, pagep, fsdata);
2488 *fsdata = (void *)0;
2489 trace_ext4_da_write_begin(inode, pos, len, flags);
2491 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2492 ret = ext4_da_write_inline_data_begin(mapping, inode,
2493 pos, len, flags,
2494 pagep, fsdata);
2495 if (ret < 0)
2496 return ret;
2497 if (ret == 1)
2498 return 0;
2502 * grab_cache_page_write_begin() can take a long time if the
2503 * system is thrashing due to memory pressure, or if the page
2504 * is being written back. So grab it first before we start
2505 * the transaction handle. This also allows us to allocate
2506 * the page (if needed) without using GFP_NOFS.
2508 retry_grab:
2509 page = grab_cache_page_write_begin(mapping, index, flags);
2510 if (!page)
2511 return -ENOMEM;
2512 unlock_page(page);
2515 * With delayed allocation, we don't log the i_disksize update
2516 * if there is delayed block allocation. But we still need
2517 * to journalling the i_disksize update if writes to the end
2518 * of file which has an already mapped buffer.
2520 retry_journal:
2521 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2522 if (IS_ERR(handle)) {
2523 page_cache_release(page);
2524 return PTR_ERR(handle);
2527 lock_page(page);
2528 if (page->mapping != mapping) {
2529 /* The page got truncated from under us */
2530 unlock_page(page);
2531 page_cache_release(page);
2532 ext4_journal_stop(handle);
2533 goto retry_grab;
2535 /* In case writeback began while the page was unlocked */
2536 wait_on_page_writeback(page);
2538 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2539 if (ret < 0) {
2540 unlock_page(page);
2541 ext4_journal_stop(handle);
2543 * block_write_begin may have instantiated a few blocks
2544 * outside i_size. Trim these off again. Don't need
2545 * i_size_read because we hold i_mutex.
2547 if (pos + len > inode->i_size)
2548 ext4_truncate_failed_write(inode);
2550 if (ret == -ENOSPC &&
2551 ext4_should_retry_alloc(inode->i_sb, &retries))
2552 goto retry_journal;
2554 page_cache_release(page);
2555 return ret;
2558 *pagep = page;
2559 return ret;
2563 * Check if we should update i_disksize
2564 * when write to the end of file but not require block allocation
2566 static int ext4_da_should_update_i_disksize(struct page *page,
2567 unsigned long offset)
2569 struct buffer_head *bh;
2570 struct inode *inode = page->mapping->host;
2571 unsigned int idx;
2572 int i;
2574 bh = page_buffers(page);
2575 idx = offset >> inode->i_blkbits;
2577 for (i = 0; i < idx; i++)
2578 bh = bh->b_this_page;
2580 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2581 return 0;
2582 return 1;
2585 static int ext4_da_write_end(struct file *file,
2586 struct address_space *mapping,
2587 loff_t pos, unsigned len, unsigned copied,
2588 struct page *page, void *fsdata)
2590 struct inode *inode = mapping->host;
2591 int ret = 0, ret2;
2592 handle_t *handle = ext4_journal_current_handle();
2593 loff_t new_i_size;
2594 unsigned long start, end;
2595 int write_mode = (int)(unsigned long)fsdata;
2597 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2598 switch (ext4_inode_journal_mode(inode)) {
2599 case EXT4_INODE_ORDERED_DATA_MODE:
2600 return ext4_ordered_write_end(file, mapping, pos,
2601 len, copied, page, fsdata);
2602 case EXT4_INODE_WRITEBACK_DATA_MODE:
2603 return ext4_writeback_write_end(file, mapping, pos,
2604 len, copied, page, fsdata);
2605 default:
2606 BUG();
2610 trace_ext4_da_write_end(inode, pos, len, copied);
2611 start = pos & (PAGE_CACHE_SIZE - 1);
2612 end = start + copied - 1;
2615 * generic_write_end() will run mark_inode_dirty() if i_size
2616 * changes. So let's piggyback the i_disksize mark_inode_dirty
2617 * into that.
2619 new_i_size = pos + copied;
2620 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2621 if (ext4_has_inline_data(inode) ||
2622 ext4_da_should_update_i_disksize(page, end)) {
2623 down_write(&EXT4_I(inode)->i_data_sem);
2624 if (new_i_size > EXT4_I(inode)->i_disksize)
2625 EXT4_I(inode)->i_disksize = new_i_size;
2626 up_write(&EXT4_I(inode)->i_data_sem);
2627 /* We need to mark inode dirty even if
2628 * new_i_size is less that inode->i_size
2629 * bu greater than i_disksize.(hint delalloc)
2631 ext4_mark_inode_dirty(handle, inode);
2635 if (write_mode != CONVERT_INLINE_DATA &&
2636 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2637 ext4_has_inline_data(inode))
2638 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2639 page);
2640 else
2641 ret2 = generic_write_end(file, mapping, pos, len, copied,
2642 page, fsdata);
2644 copied = ret2;
2645 if (ret2 < 0)
2646 ret = ret2;
2647 ret2 = ext4_journal_stop(handle);
2648 if (!ret)
2649 ret = ret2;
2651 return ret ? ret : copied;
2654 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2657 * Drop reserved blocks
2659 BUG_ON(!PageLocked(page));
2660 if (!page_has_buffers(page))
2661 goto out;
2663 ext4_da_page_release_reservation(page, offset);
2665 out:
2666 ext4_invalidatepage(page, offset);
2668 return;
2672 * Force all delayed allocation blocks to be allocated for a given inode.
2674 int ext4_alloc_da_blocks(struct inode *inode)
2676 trace_ext4_alloc_da_blocks(inode);
2678 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2679 !EXT4_I(inode)->i_reserved_meta_blocks)
2680 return 0;
2683 * We do something simple for now. The filemap_flush() will
2684 * also start triggering a write of the data blocks, which is
2685 * not strictly speaking necessary (and for users of
2686 * laptop_mode, not even desirable). However, to do otherwise
2687 * would require replicating code paths in:
2689 * ext4_da_writepages() ->
2690 * write_cache_pages() ---> (via passed in callback function)
2691 * __mpage_da_writepage() -->
2692 * mpage_add_bh_to_extent()
2693 * mpage_da_map_blocks()
2695 * The problem is that write_cache_pages(), located in
2696 * mm/page-writeback.c, marks pages clean in preparation for
2697 * doing I/O, which is not desirable if we're not planning on
2698 * doing I/O at all.
2700 * We could call write_cache_pages(), and then redirty all of
2701 * the pages by calling redirty_page_for_writepage() but that
2702 * would be ugly in the extreme. So instead we would need to
2703 * replicate parts of the code in the above functions,
2704 * simplifying them because we wouldn't actually intend to
2705 * write out the pages, but rather only collect contiguous
2706 * logical block extents, call the multi-block allocator, and
2707 * then update the buffer heads with the block allocations.
2709 * For now, though, we'll cheat by calling filemap_flush(),
2710 * which will map the blocks, and start the I/O, but not
2711 * actually wait for the I/O to complete.
2713 return filemap_flush(inode->i_mapping);
2717 * bmap() is special. It gets used by applications such as lilo and by
2718 * the swapper to find the on-disk block of a specific piece of data.
2720 * Naturally, this is dangerous if the block concerned is still in the
2721 * journal. If somebody makes a swapfile on an ext4 data-journaling
2722 * filesystem and enables swap, then they may get a nasty shock when the
2723 * data getting swapped to that swapfile suddenly gets overwritten by
2724 * the original zero's written out previously to the journal and
2725 * awaiting writeback in the kernel's buffer cache.
2727 * So, if we see any bmap calls here on a modified, data-journaled file,
2728 * take extra steps to flush any blocks which might be in the cache.
2730 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2732 struct inode *inode = mapping->host;
2733 journal_t *journal;
2734 int err;
2737 * We can get here for an inline file via the FIBMAP ioctl
2739 if (ext4_has_inline_data(inode))
2740 return 0;
2742 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2743 test_opt(inode->i_sb, DELALLOC)) {
2745 * With delalloc we want to sync the file
2746 * so that we can make sure we allocate
2747 * blocks for file
2749 filemap_write_and_wait(mapping);
2752 if (EXT4_JOURNAL(inode) &&
2753 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2755 * This is a REALLY heavyweight approach, but the use of
2756 * bmap on dirty files is expected to be extremely rare:
2757 * only if we run lilo or swapon on a freshly made file
2758 * do we expect this to happen.
2760 * (bmap requires CAP_SYS_RAWIO so this does not
2761 * represent an unprivileged user DOS attack --- we'd be
2762 * in trouble if mortal users could trigger this path at
2763 * will.)
2765 * NB. EXT4_STATE_JDATA is not set on files other than
2766 * regular files. If somebody wants to bmap a directory
2767 * or symlink and gets confused because the buffer
2768 * hasn't yet been flushed to disk, they deserve
2769 * everything they get.
2772 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2773 journal = EXT4_JOURNAL(inode);
2774 jbd2_journal_lock_updates(journal);
2775 err = jbd2_journal_flush(journal);
2776 jbd2_journal_unlock_updates(journal);
2778 if (err)
2779 return 0;
2782 return generic_block_bmap(mapping, block, ext4_get_block);
2785 static int ext4_readpage(struct file *file, struct page *page)
2787 int ret = -EAGAIN;
2788 struct inode *inode = page->mapping->host;
2790 trace_ext4_readpage(page);
2792 if (ext4_has_inline_data(inode))
2793 ret = ext4_readpage_inline(inode, page);
2795 if (ret == -EAGAIN)
2796 return mpage_readpage(page, ext4_get_block);
2798 return ret;
2801 static int
2802 ext4_readpages(struct file *file, struct address_space *mapping,
2803 struct list_head *pages, unsigned nr_pages)
2805 struct inode *inode = mapping->host;
2807 /* If the file has inline data, no need to do readpages. */
2808 if (ext4_has_inline_data(inode))
2809 return 0;
2811 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2814 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2816 trace_ext4_invalidatepage(page, offset);
2818 /* No journalling happens on data buffers when this function is used */
2819 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
2821 block_invalidatepage(page, offset);
2824 static int __ext4_journalled_invalidatepage(struct page *page,
2825 unsigned long offset)
2827 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2829 trace_ext4_journalled_invalidatepage(page, offset);
2832 * If it's a full truncate we just forget about the pending dirtying
2834 if (offset == 0)
2835 ClearPageChecked(page);
2837 return jbd2_journal_invalidatepage(journal, page, offset);
2840 /* Wrapper for aops... */
2841 static void ext4_journalled_invalidatepage(struct page *page,
2842 unsigned long offset)
2844 WARN_ON(__ext4_journalled_invalidatepage(page, offset) < 0);
2847 static int ext4_releasepage(struct page *page, gfp_t wait)
2849 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2851 trace_ext4_releasepage(page);
2853 WARN_ON(PageChecked(page));
2854 if (!page_has_buffers(page))
2855 return 0;
2856 if (journal)
2857 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2858 else
2859 return try_to_free_buffers(page);
2863 * ext4_get_block used when preparing for a DIO write or buffer write.
2864 * We allocate an uinitialized extent if blocks haven't been allocated.
2865 * The extent will be converted to initialized after the IO is complete.
2867 int ext4_get_block_write(struct inode *inode, sector_t iblock,
2868 struct buffer_head *bh_result, int create)
2870 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2871 inode->i_ino, create);
2872 return _ext4_get_block(inode, iblock, bh_result,
2873 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2876 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
2877 struct buffer_head *bh_result, int create)
2879 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
2880 inode->i_ino, create);
2881 return _ext4_get_block(inode, iblock, bh_result,
2882 EXT4_GET_BLOCKS_NO_LOCK);
2885 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2886 ssize_t size, void *private, int ret,
2887 bool is_async)
2889 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2890 ext4_io_end_t *io_end = iocb->private;
2892 /* if not async direct IO or dio with 0 bytes write, just return */
2893 if (!io_end || !size)
2894 goto out;
2896 ext_debug("ext4_end_io_dio(): io_end 0x%p "
2897 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
2898 iocb->private, io_end->inode->i_ino, iocb, offset,
2899 size);
2901 iocb->private = NULL;
2903 /* if not aio dio with unwritten extents, just free io and return */
2904 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2905 ext4_free_io_end(io_end);
2906 out:
2907 inode_dio_done(inode);
2908 if (is_async)
2909 aio_complete(iocb, ret, 0);
2910 return;
2913 io_end->offset = offset;
2914 io_end->size = size;
2915 if (is_async) {
2916 io_end->iocb = iocb;
2917 io_end->result = ret;
2920 ext4_add_complete_io(io_end);
2924 * For ext4 extent files, ext4 will do direct-io write to holes,
2925 * preallocated extents, and those write extend the file, no need to
2926 * fall back to buffered IO.
2928 * For holes, we fallocate those blocks, mark them as uninitialized
2929 * If those blocks were preallocated, we mark sure they are split, but
2930 * still keep the range to write as uninitialized.
2932 * The unwritten extents will be converted to written when DIO is completed.
2933 * For async direct IO, since the IO may still pending when return, we
2934 * set up an end_io call back function, which will do the conversion
2935 * when async direct IO completed.
2937 * If the O_DIRECT write will extend the file then add this inode to the
2938 * orphan list. So recovery will truncate it back to the original size
2939 * if the machine crashes during the write.
2942 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2943 const struct iovec *iov, loff_t offset,
2944 unsigned long nr_segs)
2946 struct file *file = iocb->ki_filp;
2947 struct inode *inode = file->f_mapping->host;
2948 ssize_t ret;
2949 size_t count = iov_length(iov, nr_segs);
2950 int overwrite = 0;
2951 get_block_t *get_block_func = NULL;
2952 int dio_flags = 0;
2953 loff_t final_size = offset + count;
2955 /* Use the old path for reads and writes beyond i_size. */
2956 if (rw != WRITE || final_size > inode->i_size)
2957 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
2959 BUG_ON(iocb->private == NULL);
2961 /* If we do a overwrite dio, i_mutex locking can be released */
2962 overwrite = *((int *)iocb->private);
2964 if (overwrite) {
2965 atomic_inc(&inode->i_dio_count);
2966 down_read(&EXT4_I(inode)->i_data_sem);
2967 mutex_unlock(&inode->i_mutex);
2971 * We could direct write to holes and fallocate.
2973 * Allocated blocks to fill the hole are marked as
2974 * uninitialized to prevent parallel buffered read to expose
2975 * the stale data before DIO complete the data IO.
2977 * As to previously fallocated extents, ext4 get_block will
2978 * just simply mark the buffer mapped but still keep the
2979 * extents uninitialized.
2981 * For non AIO case, we will convert those unwritten extents
2982 * to written after return back from blockdev_direct_IO.
2984 * For async DIO, the conversion needs to be deferred when the
2985 * IO is completed. The ext4 end_io callback function will be
2986 * called to take care of the conversion work. Here for async
2987 * case, we allocate an io_end structure to hook to the iocb.
2989 iocb->private = NULL;
2990 ext4_inode_aio_set(inode, NULL);
2991 if (!is_sync_kiocb(iocb)) {
2992 ext4_io_end_t *io_end = ext4_init_io_end(inode, GFP_NOFS);
2993 if (!io_end) {
2994 ret = -ENOMEM;
2995 goto retake_lock;
2997 io_end->flag |= EXT4_IO_END_DIRECT;
2998 iocb->private = io_end;
3000 * we save the io structure for current async direct
3001 * IO, so that later ext4_map_blocks() could flag the
3002 * io structure whether there is a unwritten extents
3003 * needs to be converted when IO is completed.
3005 ext4_inode_aio_set(inode, io_end);
3008 if (overwrite) {
3009 get_block_func = ext4_get_block_write_nolock;
3010 } else {
3011 get_block_func = ext4_get_block_write;
3012 dio_flags = DIO_LOCKING;
3014 ret = __blockdev_direct_IO(rw, iocb, inode,
3015 inode->i_sb->s_bdev, iov,
3016 offset, nr_segs,
3017 get_block_func,
3018 ext4_end_io_dio,
3019 NULL,
3020 dio_flags);
3022 if (iocb->private)
3023 ext4_inode_aio_set(inode, NULL);
3025 * The io_end structure takes a reference to the inode, that
3026 * structure needs to be destroyed and the reference to the
3027 * inode need to be dropped, when IO is complete, even with 0
3028 * byte write, or failed.
3030 * In the successful AIO DIO case, the io_end structure will
3031 * be destroyed and the reference to the inode will be dropped
3032 * after the end_io call back function is called.
3034 * In the case there is 0 byte write, or error case, since VFS
3035 * direct IO won't invoke the end_io call back function, we
3036 * need to free the end_io structure here.
3038 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3039 ext4_free_io_end(iocb->private);
3040 iocb->private = NULL;
3041 } else if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3042 EXT4_STATE_DIO_UNWRITTEN)) {
3043 int err;
3045 * for non AIO case, since the IO is already
3046 * completed, we could do the conversion right here
3048 err = ext4_convert_unwritten_extents(inode,
3049 offset, ret);
3050 if (err < 0)
3051 ret = err;
3052 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3055 retake_lock:
3056 /* take i_mutex locking again if we do a ovewrite dio */
3057 if (overwrite) {
3058 inode_dio_done(inode);
3059 up_read(&EXT4_I(inode)->i_data_sem);
3060 mutex_lock(&inode->i_mutex);
3063 return ret;
3066 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3067 const struct iovec *iov, loff_t offset,
3068 unsigned long nr_segs)
3070 struct file *file = iocb->ki_filp;
3071 struct inode *inode = file->f_mapping->host;
3072 ssize_t ret;
3075 * If we are doing data journalling we don't support O_DIRECT
3077 if (ext4_should_journal_data(inode))
3078 return 0;
3080 /* Let buffer I/O handle the inline data case. */
3081 if (ext4_has_inline_data(inode))
3082 return 0;
3084 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3085 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3086 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3087 else
3088 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3089 trace_ext4_direct_IO_exit(inode, offset,
3090 iov_length(iov, nr_segs), rw, ret);
3091 return ret;
3095 * Pages can be marked dirty completely asynchronously from ext4's journalling
3096 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3097 * much here because ->set_page_dirty is called under VFS locks. The page is
3098 * not necessarily locked.
3100 * We cannot just dirty the page and leave attached buffers clean, because the
3101 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3102 * or jbddirty because all the journalling code will explode.
3104 * So what we do is to mark the page "pending dirty" and next time writepage
3105 * is called, propagate that into the buffers appropriately.
3107 static int ext4_journalled_set_page_dirty(struct page *page)
3109 SetPageChecked(page);
3110 return __set_page_dirty_nobuffers(page);
3113 static const struct address_space_operations ext4_ordered_aops = {
3114 .readpage = ext4_readpage,
3115 .readpages = ext4_readpages,
3116 .writepage = ext4_writepage,
3117 .write_begin = ext4_write_begin,
3118 .write_end = ext4_ordered_write_end,
3119 .bmap = ext4_bmap,
3120 .invalidatepage = ext4_invalidatepage,
3121 .releasepage = ext4_releasepage,
3122 .direct_IO = ext4_direct_IO,
3123 .migratepage = buffer_migrate_page,
3124 .is_partially_uptodate = block_is_partially_uptodate,
3125 .error_remove_page = generic_error_remove_page,
3128 static const struct address_space_operations ext4_writeback_aops = {
3129 .readpage = ext4_readpage,
3130 .readpages = ext4_readpages,
3131 .writepage = ext4_writepage,
3132 .write_begin = ext4_write_begin,
3133 .write_end = ext4_writeback_write_end,
3134 .bmap = ext4_bmap,
3135 .invalidatepage = ext4_invalidatepage,
3136 .releasepage = ext4_releasepage,
3137 .direct_IO = ext4_direct_IO,
3138 .migratepage = buffer_migrate_page,
3139 .is_partially_uptodate = block_is_partially_uptodate,
3140 .error_remove_page = generic_error_remove_page,
3143 static const struct address_space_operations ext4_journalled_aops = {
3144 .readpage = ext4_readpage,
3145 .readpages = ext4_readpages,
3146 .writepage = ext4_writepage,
3147 .write_begin = ext4_write_begin,
3148 .write_end = ext4_journalled_write_end,
3149 .set_page_dirty = ext4_journalled_set_page_dirty,
3150 .bmap = ext4_bmap,
3151 .invalidatepage = ext4_journalled_invalidatepage,
3152 .releasepage = ext4_releasepage,
3153 .direct_IO = ext4_direct_IO,
3154 .is_partially_uptodate = block_is_partially_uptodate,
3155 .error_remove_page = generic_error_remove_page,
3158 static const struct address_space_operations ext4_da_aops = {
3159 .readpage = ext4_readpage,
3160 .readpages = ext4_readpages,
3161 .writepage = ext4_writepage,
3162 .writepages = ext4_da_writepages,
3163 .write_begin = ext4_da_write_begin,
3164 .write_end = ext4_da_write_end,
3165 .bmap = ext4_bmap,
3166 .invalidatepage = ext4_da_invalidatepage,
3167 .releasepage = ext4_releasepage,
3168 .direct_IO = ext4_direct_IO,
3169 .migratepage = buffer_migrate_page,
3170 .is_partially_uptodate = block_is_partially_uptodate,
3171 .error_remove_page = generic_error_remove_page,
3174 void ext4_set_aops(struct inode *inode)
3176 switch (ext4_inode_journal_mode(inode)) {
3177 case EXT4_INODE_ORDERED_DATA_MODE:
3178 if (test_opt(inode->i_sb, DELALLOC))
3179 inode->i_mapping->a_ops = &ext4_da_aops;
3180 else
3181 inode->i_mapping->a_ops = &ext4_ordered_aops;
3182 break;
3183 case EXT4_INODE_WRITEBACK_DATA_MODE:
3184 if (test_opt(inode->i_sb, DELALLOC))
3185 inode->i_mapping->a_ops = &ext4_da_aops;
3186 else
3187 inode->i_mapping->a_ops = &ext4_writeback_aops;
3188 break;
3189 case EXT4_INODE_JOURNAL_DATA_MODE:
3190 inode->i_mapping->a_ops = &ext4_journalled_aops;
3191 break;
3192 default:
3193 BUG();
3199 * ext4_discard_partial_page_buffers()
3200 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3201 * This function finds and locks the page containing the offset
3202 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3203 * Calling functions that already have the page locked should call
3204 * ext4_discard_partial_page_buffers_no_lock directly.
3206 int ext4_discard_partial_page_buffers(handle_t *handle,
3207 struct address_space *mapping, loff_t from,
3208 loff_t length, int flags)
3210 struct inode *inode = mapping->host;
3211 struct page *page;
3212 int err = 0;
3214 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3215 mapping_gfp_mask(mapping) & ~__GFP_FS);
3216 if (!page)
3217 return -ENOMEM;
3219 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3220 from, length, flags);
3222 unlock_page(page);
3223 page_cache_release(page);
3224 return err;
3228 * ext4_discard_partial_page_buffers_no_lock()
3229 * Zeros a page range of length 'length' starting from offset 'from'.
3230 * Buffer heads that correspond to the block aligned regions of the
3231 * zeroed range will be unmapped. Unblock aligned regions
3232 * will have the corresponding buffer head mapped if needed so that
3233 * that region of the page can be updated with the partial zero out.
3235 * This function assumes that the page has already been locked. The
3236 * The range to be discarded must be contained with in the given page.
3237 * If the specified range exceeds the end of the page it will be shortened
3238 * to the end of the page that corresponds to 'from'. This function is
3239 * appropriate for updating a page and it buffer heads to be unmapped and
3240 * zeroed for blocks that have been either released, or are going to be
3241 * released.
3243 * handle: The journal handle
3244 * inode: The files inode
3245 * page: A locked page that contains the offset "from"
3246 * from: The starting byte offset (from the beginning of the file)
3247 * to begin discarding
3248 * len: The length of bytes to discard
3249 * flags: Optional flags that may be used:
3251 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3252 * Only zero the regions of the page whose buffer heads
3253 * have already been unmapped. This flag is appropriate
3254 * for updating the contents of a page whose blocks may
3255 * have already been released, and we only want to zero
3256 * out the regions that correspond to those released blocks.
3258 * Returns zero on success or negative on failure.
3260 static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3261 struct inode *inode, struct page *page, loff_t from,
3262 loff_t length, int flags)
3264 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3265 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3266 unsigned int blocksize, max, pos;
3267 ext4_lblk_t iblock;
3268 struct buffer_head *bh;
3269 int err = 0;
3271 blocksize = inode->i_sb->s_blocksize;
3272 max = PAGE_CACHE_SIZE - offset;
3274 if (index != page->index)
3275 return -EINVAL;
3278 * correct length if it does not fall between
3279 * 'from' and the end of the page
3281 if (length > max || length < 0)
3282 length = max;
3284 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3286 if (!page_has_buffers(page))
3287 create_empty_buffers(page, blocksize, 0);
3289 /* Find the buffer that contains "offset" */
3290 bh = page_buffers(page);
3291 pos = blocksize;
3292 while (offset >= pos) {
3293 bh = bh->b_this_page;
3294 iblock++;
3295 pos += blocksize;
3298 pos = offset;
3299 while (pos < offset + length) {
3300 unsigned int end_of_block, range_to_discard;
3302 err = 0;
3304 /* The length of space left to zero and unmap */
3305 range_to_discard = offset + length - pos;
3307 /* The length of space until the end of the block */
3308 end_of_block = blocksize - (pos & (blocksize-1));
3311 * Do not unmap or zero past end of block
3312 * for this buffer head
3314 if (range_to_discard > end_of_block)
3315 range_to_discard = end_of_block;
3319 * Skip this buffer head if we are only zeroing unampped
3320 * regions of the page
3322 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3323 buffer_mapped(bh))
3324 goto next;
3326 /* If the range is block aligned, unmap */
3327 if (range_to_discard == blocksize) {
3328 clear_buffer_dirty(bh);
3329 bh->b_bdev = NULL;
3330 clear_buffer_mapped(bh);
3331 clear_buffer_req(bh);
3332 clear_buffer_new(bh);
3333 clear_buffer_delay(bh);
3334 clear_buffer_unwritten(bh);
3335 clear_buffer_uptodate(bh);
3336 zero_user(page, pos, range_to_discard);
3337 BUFFER_TRACE(bh, "Buffer discarded");
3338 goto next;
3342 * If this block is not completely contained in the range
3343 * to be discarded, then it is not going to be released. Because
3344 * we need to keep this block, we need to make sure this part
3345 * of the page is uptodate before we modify it by writeing
3346 * partial zeros on it.
3348 if (!buffer_mapped(bh)) {
3350 * Buffer head must be mapped before we can read
3351 * from the block
3353 BUFFER_TRACE(bh, "unmapped");
3354 ext4_get_block(inode, iblock, bh, 0);
3355 /* unmapped? It's a hole - nothing to do */
3356 if (!buffer_mapped(bh)) {
3357 BUFFER_TRACE(bh, "still unmapped");
3358 goto next;
3362 /* Ok, it's mapped. Make sure it's up-to-date */
3363 if (PageUptodate(page))
3364 set_buffer_uptodate(bh);
3366 if (!buffer_uptodate(bh)) {
3367 err = -EIO;
3368 ll_rw_block(READ, 1, &bh);
3369 wait_on_buffer(bh);
3370 /* Uhhuh. Read error. Complain and punt.*/
3371 if (!buffer_uptodate(bh))
3372 goto next;
3375 if (ext4_should_journal_data(inode)) {
3376 BUFFER_TRACE(bh, "get write access");
3377 err = ext4_journal_get_write_access(handle, bh);
3378 if (err)
3379 goto next;
3382 zero_user(page, pos, range_to_discard);
3384 err = 0;
3385 if (ext4_should_journal_data(inode)) {
3386 err = ext4_handle_dirty_metadata(handle, inode, bh);
3387 } else
3388 mark_buffer_dirty(bh);
3390 BUFFER_TRACE(bh, "Partial buffer zeroed");
3391 next:
3392 bh = bh->b_this_page;
3393 iblock++;
3394 pos += range_to_discard;
3397 return err;
3400 int ext4_can_truncate(struct inode *inode)
3402 if (S_ISREG(inode->i_mode))
3403 return 1;
3404 if (S_ISDIR(inode->i_mode))
3405 return 1;
3406 if (S_ISLNK(inode->i_mode))
3407 return !ext4_inode_is_fast_symlink(inode);
3408 return 0;
3412 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3413 * associated with the given offset and length
3415 * @inode: File inode
3416 * @offset: The offset where the hole will begin
3417 * @len: The length of the hole
3419 * Returns: 0 on success or negative on failure
3422 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3424 struct inode *inode = file->f_path.dentry->d_inode;
3425 if (!S_ISREG(inode->i_mode))
3426 return -EOPNOTSUPP;
3428 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3429 return ext4_ind_punch_hole(file, offset, length);
3431 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3432 /* TODO: Add support for bigalloc file systems */
3433 return -EOPNOTSUPP;
3436 trace_ext4_punch_hole(inode, offset, length);
3438 return ext4_ext_punch_hole(file, offset, length);
3442 * ext4_truncate()
3444 * We block out ext4_get_block() block instantiations across the entire
3445 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3446 * simultaneously on behalf of the same inode.
3448 * As we work through the truncate and commit bits of it to the journal there
3449 * is one core, guiding principle: the file's tree must always be consistent on
3450 * disk. We must be able to restart the truncate after a crash.
3452 * The file's tree may be transiently inconsistent in memory (although it
3453 * probably isn't), but whenever we close off and commit a journal transaction,
3454 * the contents of (the filesystem + the journal) must be consistent and
3455 * restartable. It's pretty simple, really: bottom up, right to left (although
3456 * left-to-right works OK too).
3458 * Note that at recovery time, journal replay occurs *before* the restart of
3459 * truncate against the orphan inode list.
3461 * The committed inode has the new, desired i_size (which is the same as
3462 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3463 * that this inode's truncate did not complete and it will again call
3464 * ext4_truncate() to have another go. So there will be instantiated blocks
3465 * to the right of the truncation point in a crashed ext4 filesystem. But
3466 * that's fine - as long as they are linked from the inode, the post-crash
3467 * ext4_truncate() run will find them and release them.
3469 void ext4_truncate(struct inode *inode)
3471 trace_ext4_truncate_enter(inode);
3473 if (!ext4_can_truncate(inode))
3474 return;
3476 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3478 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3479 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3481 if (ext4_has_inline_data(inode)) {
3482 int has_inline = 1;
3484 ext4_inline_data_truncate(inode, &has_inline);
3485 if (has_inline)
3486 return;
3489 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3490 ext4_ext_truncate(inode);
3491 else
3492 ext4_ind_truncate(inode);
3494 trace_ext4_truncate_exit(inode);
3498 * ext4_get_inode_loc returns with an extra refcount against the inode's
3499 * underlying buffer_head on success. If 'in_mem' is true, we have all
3500 * data in memory that is needed to recreate the on-disk version of this
3501 * inode.
3503 static int __ext4_get_inode_loc(struct inode *inode,
3504 struct ext4_iloc *iloc, int in_mem)
3506 struct ext4_group_desc *gdp;
3507 struct buffer_head *bh;
3508 struct super_block *sb = inode->i_sb;
3509 ext4_fsblk_t block;
3510 int inodes_per_block, inode_offset;
3512 iloc->bh = NULL;
3513 if (!ext4_valid_inum(sb, inode->i_ino))
3514 return -EIO;
3516 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3517 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3518 if (!gdp)
3519 return -EIO;
3522 * Figure out the offset within the block group inode table
3524 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3525 inode_offset = ((inode->i_ino - 1) %
3526 EXT4_INODES_PER_GROUP(sb));
3527 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3528 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3530 bh = sb_getblk(sb, block);
3531 if (unlikely(!bh))
3532 return -ENOMEM;
3533 if (!buffer_uptodate(bh)) {
3534 lock_buffer(bh);
3537 * If the buffer has the write error flag, we have failed
3538 * to write out another inode in the same block. In this
3539 * case, we don't have to read the block because we may
3540 * read the old inode data successfully.
3542 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3543 set_buffer_uptodate(bh);
3545 if (buffer_uptodate(bh)) {
3546 /* someone brought it uptodate while we waited */
3547 unlock_buffer(bh);
3548 goto has_buffer;
3552 * If we have all information of the inode in memory and this
3553 * is the only valid inode in the block, we need not read the
3554 * block.
3556 if (in_mem) {
3557 struct buffer_head *bitmap_bh;
3558 int i, start;
3560 start = inode_offset & ~(inodes_per_block - 1);
3562 /* Is the inode bitmap in cache? */
3563 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3564 if (unlikely(!bitmap_bh))
3565 goto make_io;
3568 * If the inode bitmap isn't in cache then the
3569 * optimisation may end up performing two reads instead
3570 * of one, so skip it.
3572 if (!buffer_uptodate(bitmap_bh)) {
3573 brelse(bitmap_bh);
3574 goto make_io;
3576 for (i = start; i < start + inodes_per_block; i++) {
3577 if (i == inode_offset)
3578 continue;
3579 if (ext4_test_bit(i, bitmap_bh->b_data))
3580 break;
3582 brelse(bitmap_bh);
3583 if (i == start + inodes_per_block) {
3584 /* all other inodes are free, so skip I/O */
3585 memset(bh->b_data, 0, bh->b_size);
3586 set_buffer_uptodate(bh);
3587 unlock_buffer(bh);
3588 goto has_buffer;
3592 make_io:
3594 * If we need to do any I/O, try to pre-readahead extra
3595 * blocks from the inode table.
3597 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3598 ext4_fsblk_t b, end, table;
3599 unsigned num;
3601 table = ext4_inode_table(sb, gdp);
3602 /* s_inode_readahead_blks is always a power of 2 */
3603 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3604 if (table > b)
3605 b = table;
3606 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3607 num = EXT4_INODES_PER_GROUP(sb);
3608 if (ext4_has_group_desc_csum(sb))
3609 num -= ext4_itable_unused_count(sb, gdp);
3610 table += num / inodes_per_block;
3611 if (end > table)
3612 end = table;
3613 while (b <= end)
3614 sb_breadahead(sb, b++);
3618 * There are other valid inodes in the buffer, this inode
3619 * has in-inode xattrs, or we don't have this inode in memory.
3620 * Read the block from disk.
3622 trace_ext4_load_inode(inode);
3623 get_bh(bh);
3624 bh->b_end_io = end_buffer_read_sync;
3625 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3626 wait_on_buffer(bh);
3627 if (!buffer_uptodate(bh)) {
3628 EXT4_ERROR_INODE_BLOCK(inode, block,
3629 "unable to read itable block");
3630 brelse(bh);
3631 return -EIO;
3634 has_buffer:
3635 iloc->bh = bh;
3636 return 0;
3639 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3641 /* We have all inode data except xattrs in memory here. */
3642 return __ext4_get_inode_loc(inode, iloc,
3643 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3646 void ext4_set_inode_flags(struct inode *inode)
3648 unsigned int flags = EXT4_I(inode)->i_flags;
3650 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3651 if (flags & EXT4_SYNC_FL)
3652 inode->i_flags |= S_SYNC;
3653 if (flags & EXT4_APPEND_FL)
3654 inode->i_flags |= S_APPEND;
3655 if (flags & EXT4_IMMUTABLE_FL)
3656 inode->i_flags |= S_IMMUTABLE;
3657 if (flags & EXT4_NOATIME_FL)
3658 inode->i_flags |= S_NOATIME;
3659 if (flags & EXT4_DIRSYNC_FL)
3660 inode->i_flags |= S_DIRSYNC;
3663 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3664 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3666 unsigned int vfs_fl;
3667 unsigned long old_fl, new_fl;
3669 do {
3670 vfs_fl = ei->vfs_inode.i_flags;
3671 old_fl = ei->i_flags;
3672 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3673 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3674 EXT4_DIRSYNC_FL);
3675 if (vfs_fl & S_SYNC)
3676 new_fl |= EXT4_SYNC_FL;
3677 if (vfs_fl & S_APPEND)
3678 new_fl |= EXT4_APPEND_FL;
3679 if (vfs_fl & S_IMMUTABLE)
3680 new_fl |= EXT4_IMMUTABLE_FL;
3681 if (vfs_fl & S_NOATIME)
3682 new_fl |= EXT4_NOATIME_FL;
3683 if (vfs_fl & S_DIRSYNC)
3684 new_fl |= EXT4_DIRSYNC_FL;
3685 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3688 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3689 struct ext4_inode_info *ei)
3691 blkcnt_t i_blocks ;
3692 struct inode *inode = &(ei->vfs_inode);
3693 struct super_block *sb = inode->i_sb;
3695 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3696 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3697 /* we are using combined 48 bit field */
3698 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3699 le32_to_cpu(raw_inode->i_blocks_lo);
3700 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3701 /* i_blocks represent file system block size */
3702 return i_blocks << (inode->i_blkbits - 9);
3703 } else {
3704 return i_blocks;
3706 } else {
3707 return le32_to_cpu(raw_inode->i_blocks_lo);
3711 static inline void ext4_iget_extra_inode(struct inode *inode,
3712 struct ext4_inode *raw_inode,
3713 struct ext4_inode_info *ei)
3715 __le32 *magic = (void *)raw_inode +
3716 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
3717 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
3718 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3719 ext4_find_inline_data_nolock(inode);
3720 } else
3721 EXT4_I(inode)->i_inline_off = 0;
3724 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3726 struct ext4_iloc iloc;
3727 struct ext4_inode *raw_inode;
3728 struct ext4_inode_info *ei;
3729 struct inode *inode;
3730 journal_t *journal = EXT4_SB(sb)->s_journal;
3731 long ret;
3732 int block;
3733 uid_t i_uid;
3734 gid_t i_gid;
3736 inode = iget_locked(sb, ino);
3737 if (!inode)
3738 return ERR_PTR(-ENOMEM);
3739 if (!(inode->i_state & I_NEW))
3740 return inode;
3742 ei = EXT4_I(inode);
3743 iloc.bh = NULL;
3745 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3746 if (ret < 0)
3747 goto bad_inode;
3748 raw_inode = ext4_raw_inode(&iloc);
3750 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3751 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3752 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3753 EXT4_INODE_SIZE(inode->i_sb)) {
3754 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
3755 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
3756 EXT4_INODE_SIZE(inode->i_sb));
3757 ret = -EIO;
3758 goto bad_inode;
3760 } else
3761 ei->i_extra_isize = 0;
3763 /* Precompute checksum seed for inode metadata */
3764 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3765 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
3766 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3767 __u32 csum;
3768 __le32 inum = cpu_to_le32(inode->i_ino);
3769 __le32 gen = raw_inode->i_generation;
3770 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
3771 sizeof(inum));
3772 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
3773 sizeof(gen));
3776 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
3777 EXT4_ERROR_INODE(inode, "checksum invalid");
3778 ret = -EIO;
3779 goto bad_inode;
3782 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3783 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3784 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3785 if (!(test_opt(inode->i_sb, NO_UID32))) {
3786 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3787 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3789 i_uid_write(inode, i_uid);
3790 i_gid_write(inode, i_gid);
3791 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3793 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3794 ei->i_inline_off = 0;
3795 ei->i_dir_start_lookup = 0;
3796 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3797 /* We now have enough fields to check if the inode was active or not.
3798 * This is needed because nfsd might try to access dead inodes
3799 * the test is that same one that e2fsck uses
3800 * NeilBrown 1999oct15
3802 if (inode->i_nlink == 0) {
3803 if (inode->i_mode == 0 ||
3804 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3805 /* this inode is deleted */
3806 ret = -ESTALE;
3807 goto bad_inode;
3809 /* The only unlinked inodes we let through here have
3810 * valid i_mode and are being read by the orphan
3811 * recovery code: that's fine, we're about to complete
3812 * the process of deleting those. */
3814 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3815 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3816 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3817 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3818 ei->i_file_acl |=
3819 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3820 inode->i_size = ext4_isize(raw_inode);
3821 ei->i_disksize = inode->i_size;
3822 #ifdef CONFIG_QUOTA
3823 ei->i_reserved_quota = 0;
3824 #endif
3825 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3826 ei->i_block_group = iloc.block_group;
3827 ei->i_last_alloc_group = ~0;
3829 * NOTE! The in-memory inode i_data array is in little-endian order
3830 * even on big-endian machines: we do NOT byteswap the block numbers!
3832 for (block = 0; block < EXT4_N_BLOCKS; block++)
3833 ei->i_data[block] = raw_inode->i_block[block];
3834 INIT_LIST_HEAD(&ei->i_orphan);
3837 * Set transaction id's of transactions that have to be committed
3838 * to finish f[data]sync. We set them to currently running transaction
3839 * as we cannot be sure that the inode or some of its metadata isn't
3840 * part of the transaction - the inode could have been reclaimed and
3841 * now it is reread from disk.
3843 if (journal) {
3844 transaction_t *transaction;
3845 tid_t tid;
3847 read_lock(&journal->j_state_lock);
3848 if (journal->j_running_transaction)
3849 transaction = journal->j_running_transaction;
3850 else
3851 transaction = journal->j_committing_transaction;
3852 if (transaction)
3853 tid = transaction->t_tid;
3854 else
3855 tid = journal->j_commit_sequence;
3856 read_unlock(&journal->j_state_lock);
3857 ei->i_sync_tid = tid;
3858 ei->i_datasync_tid = tid;
3861 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3862 if (ei->i_extra_isize == 0) {
3863 /* The extra space is currently unused. Use it. */
3864 ei->i_extra_isize = sizeof(struct ext4_inode) -
3865 EXT4_GOOD_OLD_INODE_SIZE;
3866 } else {
3867 ext4_iget_extra_inode(inode, raw_inode, ei);
3871 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3872 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3873 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3874 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3876 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3877 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3878 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3879 inode->i_version |=
3880 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3883 ret = 0;
3884 if (ei->i_file_acl &&
3885 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3886 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3887 ei->i_file_acl);
3888 ret = -EIO;
3889 goto bad_inode;
3890 } else if (!ext4_has_inline_data(inode)) {
3891 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3892 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3893 (S_ISLNK(inode->i_mode) &&
3894 !ext4_inode_is_fast_symlink(inode))))
3895 /* Validate extent which is part of inode */
3896 ret = ext4_ext_check_inode(inode);
3897 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3898 (S_ISLNK(inode->i_mode) &&
3899 !ext4_inode_is_fast_symlink(inode))) {
3900 /* Validate block references which are part of inode */
3901 ret = ext4_ind_check_inode(inode);
3904 if (ret)
3905 goto bad_inode;
3907 if (S_ISREG(inode->i_mode)) {
3908 inode->i_op = &ext4_file_inode_operations;
3909 inode->i_fop = &ext4_file_operations;
3910 ext4_set_aops(inode);
3911 } else if (S_ISDIR(inode->i_mode)) {
3912 inode->i_op = &ext4_dir_inode_operations;
3913 inode->i_fop = &ext4_dir_operations;
3914 } else if (S_ISLNK(inode->i_mode)) {
3915 if (ext4_inode_is_fast_symlink(inode)) {
3916 inode->i_op = &ext4_fast_symlink_inode_operations;
3917 nd_terminate_link(ei->i_data, inode->i_size,
3918 sizeof(ei->i_data) - 1);
3919 } else {
3920 inode->i_op = &ext4_symlink_inode_operations;
3921 ext4_set_aops(inode);
3923 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3924 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3925 inode->i_op = &ext4_special_inode_operations;
3926 if (raw_inode->i_block[0])
3927 init_special_inode(inode, inode->i_mode,
3928 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3929 else
3930 init_special_inode(inode, inode->i_mode,
3931 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3932 } else {
3933 ret = -EIO;
3934 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3935 goto bad_inode;
3937 brelse(iloc.bh);
3938 ext4_set_inode_flags(inode);
3939 unlock_new_inode(inode);
3940 return inode;
3942 bad_inode:
3943 brelse(iloc.bh);
3944 iget_failed(inode);
3945 return ERR_PTR(ret);
3948 static int ext4_inode_blocks_set(handle_t *handle,
3949 struct ext4_inode *raw_inode,
3950 struct ext4_inode_info *ei)
3952 struct inode *inode = &(ei->vfs_inode);
3953 u64 i_blocks = inode->i_blocks;
3954 struct super_block *sb = inode->i_sb;
3956 if (i_blocks <= ~0U) {
3958 * i_blocks can be represented in a 32 bit variable
3959 * as multiple of 512 bytes
3961 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3962 raw_inode->i_blocks_high = 0;
3963 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3964 return 0;
3966 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3967 return -EFBIG;
3969 if (i_blocks <= 0xffffffffffffULL) {
3971 * i_blocks can be represented in a 48 bit variable
3972 * as multiple of 512 bytes
3974 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3975 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3976 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3977 } else {
3978 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3979 /* i_block is stored in file system block size */
3980 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3981 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3982 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3984 return 0;
3988 * Post the struct inode info into an on-disk inode location in the
3989 * buffer-cache. This gobbles the caller's reference to the
3990 * buffer_head in the inode location struct.
3992 * The caller must have write access to iloc->bh.
3994 static int ext4_do_update_inode(handle_t *handle,
3995 struct inode *inode,
3996 struct ext4_iloc *iloc)
3998 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
3999 struct ext4_inode_info *ei = EXT4_I(inode);
4000 struct buffer_head *bh = iloc->bh;
4001 int err = 0, rc, block;
4002 int need_datasync = 0;
4003 uid_t i_uid;
4004 gid_t i_gid;
4006 /* For fields not not tracking in the in-memory inode,
4007 * initialise them to zero for new inodes. */
4008 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4009 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4011 ext4_get_inode_flags(ei);
4012 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4013 i_uid = i_uid_read(inode);
4014 i_gid = i_gid_read(inode);
4015 if (!(test_opt(inode->i_sb, NO_UID32))) {
4016 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4017 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4019 * Fix up interoperability with old kernels. Otherwise, old inodes get
4020 * re-used with the upper 16 bits of the uid/gid intact
4022 if (!ei->i_dtime) {
4023 raw_inode->i_uid_high =
4024 cpu_to_le16(high_16_bits(i_uid));
4025 raw_inode->i_gid_high =
4026 cpu_to_le16(high_16_bits(i_gid));
4027 } else {
4028 raw_inode->i_uid_high = 0;
4029 raw_inode->i_gid_high = 0;
4031 } else {
4032 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4033 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4034 raw_inode->i_uid_high = 0;
4035 raw_inode->i_gid_high = 0;
4037 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4039 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4040 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4041 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4042 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4044 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4045 goto out_brelse;
4046 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4047 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4048 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4049 cpu_to_le32(EXT4_OS_HURD))
4050 raw_inode->i_file_acl_high =
4051 cpu_to_le16(ei->i_file_acl >> 32);
4052 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4053 if (ei->i_disksize != ext4_isize(raw_inode)) {
4054 ext4_isize_set(raw_inode, ei->i_disksize);
4055 need_datasync = 1;
4057 if (ei->i_disksize > 0x7fffffffULL) {
4058 struct super_block *sb = inode->i_sb;
4059 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4060 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4061 EXT4_SB(sb)->s_es->s_rev_level ==
4062 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4063 /* If this is the first large file
4064 * created, add a flag to the superblock.
4066 err = ext4_journal_get_write_access(handle,
4067 EXT4_SB(sb)->s_sbh);
4068 if (err)
4069 goto out_brelse;
4070 ext4_update_dynamic_rev(sb);
4071 EXT4_SET_RO_COMPAT_FEATURE(sb,
4072 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4073 ext4_handle_sync(handle);
4074 err = ext4_handle_dirty_super(handle, sb);
4077 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4078 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4079 if (old_valid_dev(inode->i_rdev)) {
4080 raw_inode->i_block[0] =
4081 cpu_to_le32(old_encode_dev(inode->i_rdev));
4082 raw_inode->i_block[1] = 0;
4083 } else {
4084 raw_inode->i_block[0] = 0;
4085 raw_inode->i_block[1] =
4086 cpu_to_le32(new_encode_dev(inode->i_rdev));
4087 raw_inode->i_block[2] = 0;
4089 } else if (!ext4_has_inline_data(inode)) {
4090 for (block = 0; block < EXT4_N_BLOCKS; block++)
4091 raw_inode->i_block[block] = ei->i_data[block];
4094 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4095 if (ei->i_extra_isize) {
4096 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4097 raw_inode->i_version_hi =
4098 cpu_to_le32(inode->i_version >> 32);
4099 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4102 ext4_inode_csum_set(inode, raw_inode, ei);
4104 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4105 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4106 if (!err)
4107 err = rc;
4108 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4110 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4111 out_brelse:
4112 brelse(bh);
4113 ext4_std_error(inode->i_sb, err);
4114 return err;
4118 * ext4_write_inode()
4120 * We are called from a few places:
4122 * - Within generic_file_write() for O_SYNC files.
4123 * Here, there will be no transaction running. We wait for any running
4124 * transaction to commit.
4126 * - Within sys_sync(), kupdate and such.
4127 * We wait on commit, if tol to.
4129 * - Within prune_icache() (PF_MEMALLOC == true)
4130 * Here we simply return. We can't afford to block kswapd on the
4131 * journal commit.
4133 * In all cases it is actually safe for us to return without doing anything,
4134 * because the inode has been copied into a raw inode buffer in
4135 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4136 * knfsd.
4138 * Note that we are absolutely dependent upon all inode dirtiers doing the
4139 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4140 * which we are interested.
4142 * It would be a bug for them to not do this. The code:
4144 * mark_inode_dirty(inode)
4145 * stuff();
4146 * inode->i_size = expr;
4148 * is in error because a kswapd-driven write_inode() could occur while
4149 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4150 * will no longer be on the superblock's dirty inode list.
4152 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4154 int err;
4156 if (current->flags & PF_MEMALLOC)
4157 return 0;
4159 if (EXT4_SB(inode->i_sb)->s_journal) {
4160 if (ext4_journal_current_handle()) {
4161 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4162 dump_stack();
4163 return -EIO;
4166 if (wbc->sync_mode != WB_SYNC_ALL)
4167 return 0;
4169 err = ext4_force_commit(inode->i_sb);
4170 } else {
4171 struct ext4_iloc iloc;
4173 err = __ext4_get_inode_loc(inode, &iloc, 0);
4174 if (err)
4175 return err;
4176 if (wbc->sync_mode == WB_SYNC_ALL)
4177 sync_dirty_buffer(iloc.bh);
4178 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4179 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4180 "IO error syncing inode");
4181 err = -EIO;
4183 brelse(iloc.bh);
4185 return err;
4189 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4190 * buffers that are attached to a page stradding i_size and are undergoing
4191 * commit. In that case we have to wait for commit to finish and try again.
4193 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4195 struct page *page;
4196 unsigned offset;
4197 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4198 tid_t commit_tid = 0;
4199 int ret;
4201 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4203 * All buffers in the last page remain valid? Then there's nothing to
4204 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4205 * blocksize case
4207 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4208 return;
4209 while (1) {
4210 page = find_lock_page(inode->i_mapping,
4211 inode->i_size >> PAGE_CACHE_SHIFT);
4212 if (!page)
4213 return;
4214 ret = __ext4_journalled_invalidatepage(page, offset);
4215 unlock_page(page);
4216 page_cache_release(page);
4217 if (ret != -EBUSY)
4218 return;
4219 commit_tid = 0;
4220 read_lock(&journal->j_state_lock);
4221 if (journal->j_committing_transaction)
4222 commit_tid = journal->j_committing_transaction->t_tid;
4223 read_unlock(&journal->j_state_lock);
4224 if (commit_tid)
4225 jbd2_log_wait_commit(journal, commit_tid);
4230 * ext4_setattr()
4232 * Called from notify_change.
4234 * We want to trap VFS attempts to truncate the file as soon as
4235 * possible. In particular, we want to make sure that when the VFS
4236 * shrinks i_size, we put the inode on the orphan list and modify
4237 * i_disksize immediately, so that during the subsequent flushing of
4238 * dirty pages and freeing of disk blocks, we can guarantee that any
4239 * commit will leave the blocks being flushed in an unused state on
4240 * disk. (On recovery, the inode will get truncated and the blocks will
4241 * be freed, so we have a strong guarantee that no future commit will
4242 * leave these blocks visible to the user.)
4244 * Another thing we have to assure is that if we are in ordered mode
4245 * and inode is still attached to the committing transaction, we must
4246 * we start writeout of all the dirty pages which are being truncated.
4247 * This way we are sure that all the data written in the previous
4248 * transaction are already on disk (truncate waits for pages under
4249 * writeback).
4251 * Called with inode->i_mutex down.
4253 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4255 struct inode *inode = dentry->d_inode;
4256 int error, rc = 0;
4257 int orphan = 0;
4258 const unsigned int ia_valid = attr->ia_valid;
4260 error = inode_change_ok(inode, attr);
4261 if (error)
4262 return error;
4264 if (is_quota_modification(inode, attr))
4265 dquot_initialize(inode);
4266 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4267 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4268 handle_t *handle;
4270 /* (user+group)*(old+new) structure, inode write (sb,
4271 * inode block, ? - but truncate inode update has it) */
4272 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4273 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4274 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4275 if (IS_ERR(handle)) {
4276 error = PTR_ERR(handle);
4277 goto err_out;
4279 error = dquot_transfer(inode, attr);
4280 if (error) {
4281 ext4_journal_stop(handle);
4282 return error;
4284 /* Update corresponding info in inode so that everything is in
4285 * one transaction */
4286 if (attr->ia_valid & ATTR_UID)
4287 inode->i_uid = attr->ia_uid;
4288 if (attr->ia_valid & ATTR_GID)
4289 inode->i_gid = attr->ia_gid;
4290 error = ext4_mark_inode_dirty(handle, inode);
4291 ext4_journal_stop(handle);
4294 if (attr->ia_valid & ATTR_SIZE) {
4296 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4297 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4299 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4300 return -EFBIG;
4304 if (S_ISREG(inode->i_mode) &&
4305 attr->ia_valid & ATTR_SIZE &&
4306 (attr->ia_size < inode->i_size)) {
4307 handle_t *handle;
4309 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4310 if (IS_ERR(handle)) {
4311 error = PTR_ERR(handle);
4312 goto err_out;
4314 if (ext4_handle_valid(handle)) {
4315 error = ext4_orphan_add(handle, inode);
4316 orphan = 1;
4318 EXT4_I(inode)->i_disksize = attr->ia_size;
4319 rc = ext4_mark_inode_dirty(handle, inode);
4320 if (!error)
4321 error = rc;
4322 ext4_journal_stop(handle);
4324 if (ext4_should_order_data(inode)) {
4325 error = ext4_begin_ordered_truncate(inode,
4326 attr->ia_size);
4327 if (error) {
4328 /* Do as much error cleanup as possible */
4329 handle = ext4_journal_start(inode,
4330 EXT4_HT_INODE, 3);
4331 if (IS_ERR(handle)) {
4332 ext4_orphan_del(NULL, inode);
4333 goto err_out;
4335 ext4_orphan_del(handle, inode);
4336 orphan = 0;
4337 ext4_journal_stop(handle);
4338 goto err_out;
4343 if (attr->ia_valid & ATTR_SIZE) {
4344 if (attr->ia_size != inode->i_size) {
4345 loff_t oldsize = inode->i_size;
4347 i_size_write(inode, attr->ia_size);
4349 * Blocks are going to be removed from the inode. Wait
4350 * for dio in flight. Temporarily disable
4351 * dioread_nolock to prevent livelock.
4353 if (orphan) {
4354 if (!ext4_should_journal_data(inode)) {
4355 ext4_inode_block_unlocked_dio(inode);
4356 inode_dio_wait(inode);
4357 ext4_inode_resume_unlocked_dio(inode);
4358 } else
4359 ext4_wait_for_tail_page_commit(inode);
4362 * Truncate pagecache after we've waited for commit
4363 * in data=journal mode to make pages freeable.
4365 truncate_pagecache(inode, oldsize, inode->i_size);
4367 ext4_truncate(inode);
4370 if (!rc) {
4371 setattr_copy(inode, attr);
4372 mark_inode_dirty(inode);
4376 * If the call to ext4_truncate failed to get a transaction handle at
4377 * all, we need to clean up the in-core orphan list manually.
4379 if (orphan && inode->i_nlink)
4380 ext4_orphan_del(NULL, inode);
4382 if (!rc && (ia_valid & ATTR_MODE))
4383 rc = ext4_acl_chmod(inode);
4385 err_out:
4386 ext4_std_error(inode->i_sb, error);
4387 if (!error)
4388 error = rc;
4389 return error;
4392 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4393 struct kstat *stat)
4395 struct inode *inode;
4396 unsigned long delalloc_blocks;
4398 inode = dentry->d_inode;
4399 generic_fillattr(inode, stat);
4402 * We can't update i_blocks if the block allocation is delayed
4403 * otherwise in the case of system crash before the real block
4404 * allocation is done, we will have i_blocks inconsistent with
4405 * on-disk file blocks.
4406 * We always keep i_blocks updated together with real
4407 * allocation. But to not confuse with user, stat
4408 * will return the blocks that include the delayed allocation
4409 * blocks for this file.
4411 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4412 EXT4_I(inode)->i_reserved_data_blocks);
4414 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4415 return 0;
4418 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4420 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4421 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4422 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4426 * Account for index blocks, block groups bitmaps and block group
4427 * descriptor blocks if modify datablocks and index blocks
4428 * worse case, the indexs blocks spread over different block groups
4430 * If datablocks are discontiguous, they are possible to spread over
4431 * different block groups too. If they are contiguous, with flexbg,
4432 * they could still across block group boundary.
4434 * Also account for superblock, inode, quota and xattr blocks
4436 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4438 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4439 int gdpblocks;
4440 int idxblocks;
4441 int ret = 0;
4444 * How many index blocks need to touch to modify nrblocks?
4445 * The "Chunk" flag indicating whether the nrblocks is
4446 * physically contiguous on disk
4448 * For Direct IO and fallocate, they calls get_block to allocate
4449 * one single extent at a time, so they could set the "Chunk" flag
4451 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4453 ret = idxblocks;
4456 * Now let's see how many group bitmaps and group descriptors need
4457 * to account
4459 groups = idxblocks;
4460 if (chunk)
4461 groups += 1;
4462 else
4463 groups += nrblocks;
4465 gdpblocks = groups;
4466 if (groups > ngroups)
4467 groups = ngroups;
4468 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4469 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4471 /* bitmaps and block group descriptor blocks */
4472 ret += groups + gdpblocks;
4474 /* Blocks for super block, inode, quota and xattr blocks */
4475 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4477 return ret;
4481 * Calculate the total number of credits to reserve to fit
4482 * the modification of a single pages into a single transaction,
4483 * which may include multiple chunks of block allocations.
4485 * This could be called via ext4_write_begin()
4487 * We need to consider the worse case, when
4488 * one new block per extent.
4490 int ext4_writepage_trans_blocks(struct inode *inode)
4492 int bpp = ext4_journal_blocks_per_page(inode);
4493 int ret;
4495 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4497 /* Account for data blocks for journalled mode */
4498 if (ext4_should_journal_data(inode))
4499 ret += bpp;
4500 return ret;
4504 * Calculate the journal credits for a chunk of data modification.
4506 * This is called from DIO, fallocate or whoever calling
4507 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4509 * journal buffers for data blocks are not included here, as DIO
4510 * and fallocate do no need to journal data buffers.
4512 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4514 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4518 * The caller must have previously called ext4_reserve_inode_write().
4519 * Give this, we know that the caller already has write access to iloc->bh.
4521 int ext4_mark_iloc_dirty(handle_t *handle,
4522 struct inode *inode, struct ext4_iloc *iloc)
4524 int err = 0;
4526 if (IS_I_VERSION(inode))
4527 inode_inc_iversion(inode);
4529 /* the do_update_inode consumes one bh->b_count */
4530 get_bh(iloc->bh);
4532 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4533 err = ext4_do_update_inode(handle, inode, iloc);
4534 put_bh(iloc->bh);
4535 return err;
4539 * On success, We end up with an outstanding reference count against
4540 * iloc->bh. This _must_ be cleaned up later.
4544 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4545 struct ext4_iloc *iloc)
4547 int err;
4549 err = ext4_get_inode_loc(inode, iloc);
4550 if (!err) {
4551 BUFFER_TRACE(iloc->bh, "get_write_access");
4552 err = ext4_journal_get_write_access(handle, iloc->bh);
4553 if (err) {
4554 brelse(iloc->bh);
4555 iloc->bh = NULL;
4558 ext4_std_error(inode->i_sb, err);
4559 return err;
4563 * Expand an inode by new_extra_isize bytes.
4564 * Returns 0 on success or negative error number on failure.
4566 static int ext4_expand_extra_isize(struct inode *inode,
4567 unsigned int new_extra_isize,
4568 struct ext4_iloc iloc,
4569 handle_t *handle)
4571 struct ext4_inode *raw_inode;
4572 struct ext4_xattr_ibody_header *header;
4574 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4575 return 0;
4577 raw_inode = ext4_raw_inode(&iloc);
4579 header = IHDR(inode, raw_inode);
4581 /* No extended attributes present */
4582 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4583 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4584 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4585 new_extra_isize);
4586 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4587 return 0;
4590 /* try to expand with EAs present */
4591 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4592 raw_inode, handle);
4596 * What we do here is to mark the in-core inode as clean with respect to inode
4597 * dirtiness (it may still be data-dirty).
4598 * This means that the in-core inode may be reaped by prune_icache
4599 * without having to perform any I/O. This is a very good thing,
4600 * because *any* task may call prune_icache - even ones which
4601 * have a transaction open against a different journal.
4603 * Is this cheating? Not really. Sure, we haven't written the
4604 * inode out, but prune_icache isn't a user-visible syncing function.
4605 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4606 * we start and wait on commits.
4608 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4610 struct ext4_iloc iloc;
4611 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4612 static unsigned int mnt_count;
4613 int err, ret;
4615 might_sleep();
4616 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4617 err = ext4_reserve_inode_write(handle, inode, &iloc);
4618 if (ext4_handle_valid(handle) &&
4619 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4620 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4622 * We need extra buffer credits since we may write into EA block
4623 * with this same handle. If journal_extend fails, then it will
4624 * only result in a minor loss of functionality for that inode.
4625 * If this is felt to be critical, then e2fsck should be run to
4626 * force a large enough s_min_extra_isize.
4628 if ((jbd2_journal_extend(handle,
4629 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4630 ret = ext4_expand_extra_isize(inode,
4631 sbi->s_want_extra_isize,
4632 iloc, handle);
4633 if (ret) {
4634 ext4_set_inode_state(inode,
4635 EXT4_STATE_NO_EXPAND);
4636 if (mnt_count !=
4637 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4638 ext4_warning(inode->i_sb,
4639 "Unable to expand inode %lu. Delete"
4640 " some EAs or run e2fsck.",
4641 inode->i_ino);
4642 mnt_count =
4643 le16_to_cpu(sbi->s_es->s_mnt_count);
4648 if (!err)
4649 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4650 return err;
4654 * ext4_dirty_inode() is called from __mark_inode_dirty()
4656 * We're really interested in the case where a file is being extended.
4657 * i_size has been changed by generic_commit_write() and we thus need
4658 * to include the updated inode in the current transaction.
4660 * Also, dquot_alloc_block() will always dirty the inode when blocks
4661 * are allocated to the file.
4663 * If the inode is marked synchronous, we don't honour that here - doing
4664 * so would cause a commit on atime updates, which we don't bother doing.
4665 * We handle synchronous inodes at the highest possible level.
4667 void ext4_dirty_inode(struct inode *inode, int flags)
4669 handle_t *handle;
4671 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4672 if (IS_ERR(handle))
4673 goto out;
4675 ext4_mark_inode_dirty(handle, inode);
4677 ext4_journal_stop(handle);
4678 out:
4679 return;
4682 #if 0
4684 * Bind an inode's backing buffer_head into this transaction, to prevent
4685 * it from being flushed to disk early. Unlike
4686 * ext4_reserve_inode_write, this leaves behind no bh reference and
4687 * returns no iloc structure, so the caller needs to repeat the iloc
4688 * lookup to mark the inode dirty later.
4690 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4692 struct ext4_iloc iloc;
4694 int err = 0;
4695 if (handle) {
4696 err = ext4_get_inode_loc(inode, &iloc);
4697 if (!err) {
4698 BUFFER_TRACE(iloc.bh, "get_write_access");
4699 err = jbd2_journal_get_write_access(handle, iloc.bh);
4700 if (!err)
4701 err = ext4_handle_dirty_metadata(handle,
4702 NULL,
4703 iloc.bh);
4704 brelse(iloc.bh);
4707 ext4_std_error(inode->i_sb, err);
4708 return err;
4710 #endif
4712 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4714 journal_t *journal;
4715 handle_t *handle;
4716 int err;
4719 * We have to be very careful here: changing a data block's
4720 * journaling status dynamically is dangerous. If we write a
4721 * data block to the journal, change the status and then delete
4722 * that block, we risk forgetting to revoke the old log record
4723 * from the journal and so a subsequent replay can corrupt data.
4724 * So, first we make sure that the journal is empty and that
4725 * nobody is changing anything.
4728 journal = EXT4_JOURNAL(inode);
4729 if (!journal)
4730 return 0;
4731 if (is_journal_aborted(journal))
4732 return -EROFS;
4733 /* We have to allocate physical blocks for delalloc blocks
4734 * before flushing journal. otherwise delalloc blocks can not
4735 * be allocated any more. even more truncate on delalloc blocks
4736 * could trigger BUG by flushing delalloc blocks in journal.
4737 * There is no delalloc block in non-journal data mode.
4739 if (val && test_opt(inode->i_sb, DELALLOC)) {
4740 err = ext4_alloc_da_blocks(inode);
4741 if (err < 0)
4742 return err;
4745 /* Wait for all existing dio workers */
4746 ext4_inode_block_unlocked_dio(inode);
4747 inode_dio_wait(inode);
4749 jbd2_journal_lock_updates(journal);
4752 * OK, there are no updates running now, and all cached data is
4753 * synced to disk. We are now in a completely consistent state
4754 * which doesn't have anything in the journal, and we know that
4755 * no filesystem updates are running, so it is safe to modify
4756 * the inode's in-core data-journaling state flag now.
4759 if (val)
4760 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4761 else {
4762 jbd2_journal_flush(journal);
4763 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4765 ext4_set_aops(inode);
4767 jbd2_journal_unlock_updates(journal);
4768 ext4_inode_resume_unlocked_dio(inode);
4770 /* Finally we can mark the inode as dirty. */
4772 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
4773 if (IS_ERR(handle))
4774 return PTR_ERR(handle);
4776 err = ext4_mark_inode_dirty(handle, inode);
4777 ext4_handle_sync(handle);
4778 ext4_journal_stop(handle);
4779 ext4_std_error(inode->i_sb, err);
4781 return err;
4784 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4786 return !buffer_mapped(bh);
4789 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4791 struct page *page = vmf->page;
4792 loff_t size;
4793 unsigned long len;
4794 int ret;
4795 struct file *file = vma->vm_file;
4796 struct inode *inode = file->f_path.dentry->d_inode;
4797 struct address_space *mapping = inode->i_mapping;
4798 handle_t *handle;
4799 get_block_t *get_block;
4800 int retries = 0;
4802 sb_start_pagefault(inode->i_sb);
4803 file_update_time(vma->vm_file);
4804 /* Delalloc case is easy... */
4805 if (test_opt(inode->i_sb, DELALLOC) &&
4806 !ext4_should_journal_data(inode) &&
4807 !ext4_nonda_switch(inode->i_sb)) {
4808 do {
4809 ret = __block_page_mkwrite(vma, vmf,
4810 ext4_da_get_block_prep);
4811 } while (ret == -ENOSPC &&
4812 ext4_should_retry_alloc(inode->i_sb, &retries));
4813 goto out_ret;
4816 lock_page(page);
4817 size = i_size_read(inode);
4818 /* Page got truncated from under us? */
4819 if (page->mapping != mapping || page_offset(page) > size) {
4820 unlock_page(page);
4821 ret = VM_FAULT_NOPAGE;
4822 goto out;
4825 if (page->index == size >> PAGE_CACHE_SHIFT)
4826 len = size & ~PAGE_CACHE_MASK;
4827 else
4828 len = PAGE_CACHE_SIZE;
4830 * Return if we have all the buffers mapped. This avoids the need to do
4831 * journal_start/journal_stop which can block and take a long time
4833 if (page_has_buffers(page)) {
4834 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
4835 0, len, NULL,
4836 ext4_bh_unmapped)) {
4837 /* Wait so that we don't change page under IO */
4838 wait_on_page_writeback(page);
4839 ret = VM_FAULT_LOCKED;
4840 goto out;
4843 unlock_page(page);
4844 /* OK, we need to fill the hole... */
4845 if (ext4_should_dioread_nolock(inode))
4846 get_block = ext4_get_block_write;
4847 else
4848 get_block = ext4_get_block;
4849 retry_alloc:
4850 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
4851 ext4_writepage_trans_blocks(inode));
4852 if (IS_ERR(handle)) {
4853 ret = VM_FAULT_SIGBUS;
4854 goto out;
4856 ret = __block_page_mkwrite(vma, vmf, get_block);
4857 if (!ret && ext4_should_journal_data(inode)) {
4858 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
4859 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4860 unlock_page(page);
4861 ret = VM_FAULT_SIGBUS;
4862 ext4_journal_stop(handle);
4863 goto out;
4865 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4867 ext4_journal_stop(handle);
4868 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4869 goto retry_alloc;
4870 out_ret:
4871 ret = block_page_mkwrite_return(ret);
4872 out:
4873 sb_end_pagefault(inode->i_sb);
4874 return ret;