gro: Allow tunnel stacking in the case of FOU/GUE
[linux/fpc-iii.git] / fs / ext4 / inode.c
blob5beca5c5413e6ee146a4d48508785ec8bd28bc47
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/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/quotaops.h>
26 #include <linux/string.h>
27 #include <linux/buffer_head.h>
28 #include <linux/writeback.h>
29 #include <linux/pagevec.h>
30 #include <linux/mpage.h>
31 #include <linux/namei.h>
32 #include <linux/uio.h>
33 #include <linux/bio.h>
34 #include <linux/workqueue.h>
35 #include <linux/kernel.h>
36 #include <linux/printk.h>
37 #include <linux/slab.h>
38 #include <linux/bitops.h>
40 #include "ext4_jbd2.h"
41 #include "xattr.h"
42 #include "acl.h"
43 #include "truncate.h"
45 #include <trace/events/ext4.h>
47 #define MPAGE_DA_EXTENT_TAIL 0x01
49 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
50 struct ext4_inode_info *ei)
52 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
53 __u16 csum_lo;
54 __u16 csum_hi = 0;
55 __u32 csum;
57 csum_lo = le16_to_cpu(raw->i_checksum_lo);
58 raw->i_checksum_lo = 0;
59 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
60 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
61 csum_hi = le16_to_cpu(raw->i_checksum_hi);
62 raw->i_checksum_hi = 0;
65 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
66 EXT4_INODE_SIZE(inode->i_sb));
68 raw->i_checksum_lo = cpu_to_le16(csum_lo);
69 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
70 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
71 raw->i_checksum_hi = cpu_to_le16(csum_hi);
73 return csum;
76 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
77 struct ext4_inode_info *ei)
79 __u32 provided, calculated;
81 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
82 cpu_to_le32(EXT4_OS_LINUX) ||
83 !ext4_has_metadata_csum(inode->i_sb))
84 return 1;
86 provided = le16_to_cpu(raw->i_checksum_lo);
87 calculated = ext4_inode_csum(inode, raw, ei);
88 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
89 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
90 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
91 else
92 calculated &= 0xFFFF;
94 return provided == calculated;
97 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
98 struct ext4_inode_info *ei)
100 __u32 csum;
102 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
103 cpu_to_le32(EXT4_OS_LINUX) ||
104 !ext4_has_metadata_csum(inode->i_sb))
105 return;
107 csum = ext4_inode_csum(inode, raw, ei);
108 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
109 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
110 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
111 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
114 static inline int ext4_begin_ordered_truncate(struct inode *inode,
115 loff_t new_size)
117 trace_ext4_begin_ordered_truncate(inode, new_size);
119 * If jinode is zero, then we never opened the file for
120 * writing, so there's no need to call
121 * jbd2_journal_begin_ordered_truncate() since there's no
122 * outstanding writes we need to flush.
124 if (!EXT4_I(inode)->jinode)
125 return 0;
126 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
127 EXT4_I(inode)->jinode,
128 new_size);
131 static void ext4_invalidatepage(struct page *page, unsigned int offset,
132 unsigned int length);
133 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
134 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
135 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
136 int pextents);
139 * Test whether an inode is a fast symlink.
141 int ext4_inode_is_fast_symlink(struct inode *inode)
143 int ea_blocks = EXT4_I(inode)->i_file_acl ?
144 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
146 if (ext4_has_inline_data(inode))
147 return 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 if (inode->i_nlink) {
190 * When journalling data dirty buffers are tracked only in the
191 * journal. So although mm thinks everything is clean and
192 * ready for reaping the inode might still have some pages to
193 * write in the running transaction or waiting to be
194 * checkpointed. Thus calling jbd2_journal_invalidatepage()
195 * (via truncate_inode_pages()) to discard these buffers can
196 * cause data loss. Also even if we did not discard these
197 * buffers, we would have no way to find them after the inode
198 * is reaped and thus user could see stale data if he tries to
199 * read them before the transaction is checkpointed. So be
200 * careful and force everything to disk here... We use
201 * ei->i_datasync_tid to store the newest transaction
202 * containing inode's data.
204 * Note that directories do not have this problem because they
205 * don't use page cache.
207 if (inode->i_ino != EXT4_JOURNAL_INO &&
208 ext4_should_journal_data(inode) &&
209 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
210 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
211 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
213 jbd2_complete_transaction(journal, commit_tid);
214 filemap_write_and_wait(&inode->i_data);
216 truncate_inode_pages_final(&inode->i_data);
218 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
219 goto no_delete;
222 if (is_bad_inode(inode))
223 goto no_delete;
224 dquot_initialize(inode);
226 if (ext4_should_order_data(inode))
227 ext4_begin_ordered_truncate(inode, 0);
228 truncate_inode_pages_final(&inode->i_data);
230 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
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 * Called with i_data_sem down, which is important since we can call
323 * ext4_discard_preallocations() from here.
325 void ext4_da_update_reserve_space(struct inode *inode,
326 int used, int quota_claim)
328 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
329 struct ext4_inode_info *ei = EXT4_I(inode);
331 spin_lock(&ei->i_block_reservation_lock);
332 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
333 if (unlikely(used > ei->i_reserved_data_blocks)) {
334 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
335 "with only %d reserved data blocks",
336 __func__, inode->i_ino, used,
337 ei->i_reserved_data_blocks);
338 WARN_ON(1);
339 used = ei->i_reserved_data_blocks;
342 /* Update per-inode reservations */
343 ei->i_reserved_data_blocks -= used;
344 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
346 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
348 /* Update quota subsystem for data blocks */
349 if (quota_claim)
350 dquot_claim_block(inode, EXT4_C2B(sbi, used));
351 else {
353 * We did fallocate with an offset that is already delayed
354 * allocated. So on delayed allocated writeback we should
355 * not re-claim the quota for fallocated blocks.
357 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
361 * If we have done all the pending block allocations and if
362 * there aren't any writers on the inode, we can discard the
363 * inode's preallocations.
365 if ((ei->i_reserved_data_blocks == 0) &&
366 (atomic_read(&inode->i_writecount) == 0))
367 ext4_discard_preallocations(inode);
370 static int __check_block_validity(struct inode *inode, const char *func,
371 unsigned int line,
372 struct ext4_map_blocks *map)
374 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
375 map->m_len)) {
376 ext4_error_inode(inode, func, line, map->m_pblk,
377 "lblock %lu mapped to illegal pblock "
378 "(length %d)", (unsigned long) map->m_lblk,
379 map->m_len);
380 return -EIO;
382 return 0;
385 #define check_block_validity(inode, map) \
386 __check_block_validity((inode), __func__, __LINE__, (map))
388 #ifdef ES_AGGRESSIVE_TEST
389 static void ext4_map_blocks_es_recheck(handle_t *handle,
390 struct inode *inode,
391 struct ext4_map_blocks *es_map,
392 struct ext4_map_blocks *map,
393 int flags)
395 int retval;
397 map->m_flags = 0;
399 * There is a race window that the result is not the same.
400 * e.g. xfstests #223 when dioread_nolock enables. The reason
401 * is that we lookup a block mapping in extent status tree with
402 * out taking i_data_sem. So at the time the unwritten extent
403 * could be converted.
405 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
406 down_read(&EXT4_I(inode)->i_data_sem);
407 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
408 retval = ext4_ext_map_blocks(handle, inode, map, flags &
409 EXT4_GET_BLOCKS_KEEP_SIZE);
410 } else {
411 retval = ext4_ind_map_blocks(handle, inode, map, flags &
412 EXT4_GET_BLOCKS_KEEP_SIZE);
414 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
415 up_read((&EXT4_I(inode)->i_data_sem));
418 * We don't check m_len because extent will be collpased in status
419 * tree. So the m_len might not equal.
421 if (es_map->m_lblk != map->m_lblk ||
422 es_map->m_flags != map->m_flags ||
423 es_map->m_pblk != map->m_pblk) {
424 printk("ES cache assertion failed for inode: %lu "
425 "es_cached ex [%d/%d/%llu/%x] != "
426 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
427 inode->i_ino, es_map->m_lblk, es_map->m_len,
428 es_map->m_pblk, es_map->m_flags, map->m_lblk,
429 map->m_len, map->m_pblk, map->m_flags,
430 retval, flags);
433 #endif /* ES_AGGRESSIVE_TEST */
436 * The ext4_map_blocks() function tries to look up the requested blocks,
437 * and returns if the blocks are already mapped.
439 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
440 * and store the allocated blocks in the result buffer head and mark it
441 * mapped.
443 * If file type is extents based, it will call ext4_ext_map_blocks(),
444 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
445 * based files
447 * On success, it returns the number of blocks being mapped or allocated.
448 * if create==0 and the blocks are pre-allocated and unwritten block,
449 * the result buffer head is unmapped. If the create ==1, it will make sure
450 * the buffer head is mapped.
452 * It returns 0 if plain look up failed (blocks have not been allocated), in
453 * that case, buffer head is unmapped
455 * It returns the error in case of allocation failure.
457 int ext4_map_blocks(handle_t *handle, struct inode *inode,
458 struct ext4_map_blocks *map, int flags)
460 struct extent_status es;
461 int retval;
462 int ret = 0;
463 #ifdef ES_AGGRESSIVE_TEST
464 struct ext4_map_blocks orig_map;
466 memcpy(&orig_map, map, sizeof(*map));
467 #endif
469 map->m_flags = 0;
470 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
471 "logical block %lu\n", inode->i_ino, flags, map->m_len,
472 (unsigned long) map->m_lblk);
475 * ext4_map_blocks returns an int, and m_len is an unsigned int
477 if (unlikely(map->m_len > INT_MAX))
478 map->m_len = INT_MAX;
480 /* We can handle the block number less than EXT_MAX_BLOCKS */
481 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
482 return -EIO;
484 /* Lookup extent status tree firstly */
485 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
486 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
487 map->m_pblk = ext4_es_pblock(&es) +
488 map->m_lblk - es.es_lblk;
489 map->m_flags |= ext4_es_is_written(&es) ?
490 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
491 retval = es.es_len - (map->m_lblk - es.es_lblk);
492 if (retval > map->m_len)
493 retval = map->m_len;
494 map->m_len = retval;
495 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
496 retval = 0;
497 } else {
498 BUG_ON(1);
500 #ifdef ES_AGGRESSIVE_TEST
501 ext4_map_blocks_es_recheck(handle, inode, map,
502 &orig_map, flags);
503 #endif
504 goto found;
508 * Try to see if we can get the block without requesting a new
509 * file system block.
511 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
512 down_read(&EXT4_I(inode)->i_data_sem);
513 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
514 retval = ext4_ext_map_blocks(handle, inode, map, flags &
515 EXT4_GET_BLOCKS_KEEP_SIZE);
516 } else {
517 retval = ext4_ind_map_blocks(handle, inode, map, flags &
518 EXT4_GET_BLOCKS_KEEP_SIZE);
520 if (retval > 0) {
521 unsigned int status;
523 if (unlikely(retval != map->m_len)) {
524 ext4_warning(inode->i_sb,
525 "ES len assertion failed for inode "
526 "%lu: retval %d != map->m_len %d",
527 inode->i_ino, retval, map->m_len);
528 WARN_ON(1);
531 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
532 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
533 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
534 !(status & EXTENT_STATUS_WRITTEN) &&
535 ext4_find_delalloc_range(inode, map->m_lblk,
536 map->m_lblk + map->m_len - 1))
537 status |= EXTENT_STATUS_DELAYED;
538 ret = ext4_es_insert_extent(inode, map->m_lblk,
539 map->m_len, map->m_pblk, status);
540 if (ret < 0)
541 retval = ret;
543 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
544 up_read((&EXT4_I(inode)->i_data_sem));
546 found:
547 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
548 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)
566 * If we need to convert extent to unwritten
567 * we continue and do the actual work in
568 * ext4_ext_map_blocks()
570 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
571 return retval;
574 * Here we clear m_flags because after allocating an new extent,
575 * it will be set again.
577 map->m_flags &= ~EXT4_MAP_FLAGS;
580 * New blocks allocate and/or writing to unwritten extent
581 * will possibly result in updating i_data, so we take
582 * the write lock of i_data_sem, and call get_block()
583 * with create == 1 flag.
585 down_write(&EXT4_I(inode)->i_data_sem);
588 * We need to check for EXT4 here because migrate
589 * could have changed the inode type in between
591 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
592 retval = ext4_ext_map_blocks(handle, inode, map, flags);
593 } else {
594 retval = ext4_ind_map_blocks(handle, inode, map, flags);
596 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
598 * We allocated new blocks which will result in
599 * i_data's format changing. Force the migrate
600 * to fail by clearing migrate flags
602 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
606 * Update reserved blocks/metadata blocks after successful
607 * block allocation which had been deferred till now. We don't
608 * support fallocate for non extent files. So we can update
609 * reserve space here.
611 if ((retval > 0) &&
612 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
613 ext4_da_update_reserve_space(inode, retval, 1);
616 if (retval > 0) {
617 unsigned int status;
619 if (unlikely(retval != map->m_len)) {
620 ext4_warning(inode->i_sb,
621 "ES len assertion failed for inode "
622 "%lu: retval %d != map->m_len %d",
623 inode->i_ino, retval, map->m_len);
624 WARN_ON(1);
628 * If the extent has been zeroed out, we don't need to update
629 * extent status tree.
631 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
632 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
633 if (ext4_es_is_written(&es))
634 goto has_zeroout;
636 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
637 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
638 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
639 !(status & EXTENT_STATUS_WRITTEN) &&
640 ext4_find_delalloc_range(inode, map->m_lblk,
641 map->m_lblk + map->m_len - 1))
642 status |= EXTENT_STATUS_DELAYED;
643 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
644 map->m_pblk, status);
645 if (ret < 0)
646 retval = ret;
649 has_zeroout:
650 up_write((&EXT4_I(inode)->i_data_sem));
651 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
652 ret = check_block_validity(inode, map);
653 if (ret != 0)
654 return ret;
656 return retval;
660 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
661 * we have to be careful as someone else may be manipulating b_state as well.
663 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
665 unsigned long old_state;
666 unsigned long new_state;
668 flags &= EXT4_MAP_FLAGS;
670 /* Dummy buffer_head? Set non-atomically. */
671 if (!bh->b_page) {
672 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
673 return;
676 * Someone else may be modifying b_state. Be careful! This is ugly but
677 * once we get rid of using bh as a container for mapping information
678 * to pass to / from get_block functions, this can go away.
680 do {
681 old_state = READ_ONCE(bh->b_state);
682 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
683 } while (unlikely(
684 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
687 /* Maximum number of blocks we map for direct IO at once. */
688 #define DIO_MAX_BLOCKS 4096
690 static int _ext4_get_block(struct inode *inode, sector_t iblock,
691 struct buffer_head *bh, int flags)
693 handle_t *handle = ext4_journal_current_handle();
694 struct ext4_map_blocks map;
695 int ret = 0, started = 0;
696 int dio_credits;
698 if (ext4_has_inline_data(inode))
699 return -ERANGE;
701 map.m_lblk = iblock;
702 map.m_len = bh->b_size >> inode->i_blkbits;
704 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
705 /* Direct IO write... */
706 if (map.m_len > DIO_MAX_BLOCKS)
707 map.m_len = DIO_MAX_BLOCKS;
708 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
709 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
710 dio_credits);
711 if (IS_ERR(handle)) {
712 ret = PTR_ERR(handle);
713 return ret;
715 started = 1;
718 ret = ext4_map_blocks(handle, inode, &map, flags);
719 if (ret > 0) {
720 ext4_io_end_t *io_end = ext4_inode_aio(inode);
722 map_bh(bh, inode->i_sb, map.m_pblk);
723 ext4_update_bh_state(bh, map.m_flags);
724 if (IS_DAX(inode) && buffer_unwritten(bh)) {
726 * dgc: I suspect unwritten conversion on ext4+DAX is
727 * fundamentally broken here when there are concurrent
728 * read/write in progress on this inode.
730 WARN_ON_ONCE(io_end);
731 bh->b_assoc_map = inode->i_mapping;
732 bh->b_private = (void *)(unsigned long)iblock;
734 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
735 set_buffer_defer_completion(bh);
736 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
737 ret = 0;
739 if (started)
740 ext4_journal_stop(handle);
741 return ret;
744 int ext4_get_block(struct inode *inode, sector_t iblock,
745 struct buffer_head *bh, int create)
747 return _ext4_get_block(inode, iblock, bh,
748 create ? EXT4_GET_BLOCKS_CREATE : 0);
752 * `handle' can be NULL if create is zero
754 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
755 ext4_lblk_t block, int create)
757 struct ext4_map_blocks map;
758 struct buffer_head *bh;
759 int err;
761 J_ASSERT(handle != NULL || create == 0);
763 map.m_lblk = block;
764 map.m_len = 1;
765 err = ext4_map_blocks(handle, inode, &map,
766 create ? EXT4_GET_BLOCKS_CREATE : 0);
768 if (err == 0)
769 return create ? ERR_PTR(-ENOSPC) : NULL;
770 if (err < 0)
771 return ERR_PTR(err);
773 bh = sb_getblk(inode->i_sb, map.m_pblk);
774 if (unlikely(!bh))
775 return ERR_PTR(-ENOMEM);
776 if (map.m_flags & EXT4_MAP_NEW) {
777 J_ASSERT(create != 0);
778 J_ASSERT(handle != NULL);
781 * Now that we do not always journal data, we should
782 * keep in mind whether this should always journal the
783 * new buffer as metadata. For now, regular file
784 * writes use ext4_get_block instead, so it's not a
785 * problem.
787 lock_buffer(bh);
788 BUFFER_TRACE(bh, "call get_create_access");
789 err = ext4_journal_get_create_access(handle, bh);
790 if (unlikely(err)) {
791 unlock_buffer(bh);
792 goto errout;
794 if (!buffer_uptodate(bh)) {
795 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
796 set_buffer_uptodate(bh);
798 unlock_buffer(bh);
799 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
800 err = ext4_handle_dirty_metadata(handle, inode, bh);
801 if (unlikely(err))
802 goto errout;
803 } else
804 BUFFER_TRACE(bh, "not a new buffer");
805 return bh;
806 errout:
807 brelse(bh);
808 return ERR_PTR(err);
811 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
812 ext4_lblk_t block, int create)
814 struct buffer_head *bh;
816 bh = ext4_getblk(handle, inode, block, create);
817 if (IS_ERR(bh))
818 return bh;
819 if (!bh || buffer_uptodate(bh))
820 return bh;
821 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
822 wait_on_buffer(bh);
823 if (buffer_uptodate(bh))
824 return bh;
825 put_bh(bh);
826 return ERR_PTR(-EIO);
829 int ext4_walk_page_buffers(handle_t *handle,
830 struct buffer_head *head,
831 unsigned from,
832 unsigned to,
833 int *partial,
834 int (*fn)(handle_t *handle,
835 struct buffer_head *bh))
837 struct buffer_head *bh;
838 unsigned block_start, block_end;
839 unsigned blocksize = head->b_size;
840 int err, ret = 0;
841 struct buffer_head *next;
843 for (bh = head, block_start = 0;
844 ret == 0 && (bh != head || !block_start);
845 block_start = block_end, bh = next) {
846 next = bh->b_this_page;
847 block_end = block_start + blocksize;
848 if (block_end <= from || block_start >= to) {
849 if (partial && !buffer_uptodate(bh))
850 *partial = 1;
851 continue;
853 err = (*fn)(handle, bh);
854 if (!ret)
855 ret = err;
857 return ret;
861 * To preserve ordering, it is essential that the hole instantiation and
862 * the data write be encapsulated in a single transaction. We cannot
863 * close off a transaction and start a new one between the ext4_get_block()
864 * and the commit_write(). So doing the jbd2_journal_start at the start of
865 * prepare_write() is the right place.
867 * Also, this function can nest inside ext4_writepage(). In that case, we
868 * *know* that ext4_writepage() has generated enough buffer credits to do the
869 * whole page. So we won't block on the journal in that case, which is good,
870 * because the caller may be PF_MEMALLOC.
872 * By accident, ext4 can be reentered when a transaction is open via
873 * quota file writes. If we were to commit the transaction while thus
874 * reentered, there can be a deadlock - we would be holding a quota
875 * lock, and the commit would never complete if another thread had a
876 * transaction open and was blocking on the quota lock - a ranking
877 * violation.
879 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
880 * will _not_ run commit under these circumstances because handle->h_ref
881 * is elevated. We'll still have enough credits for the tiny quotafile
882 * write.
884 int do_journal_get_write_access(handle_t *handle,
885 struct buffer_head *bh)
887 int dirty = buffer_dirty(bh);
888 int ret;
890 if (!buffer_mapped(bh) || buffer_freed(bh))
891 return 0;
893 * __block_write_begin() could have dirtied some buffers. Clean
894 * the dirty bit as jbd2_journal_get_write_access() could complain
895 * otherwise about fs integrity issues. Setting of the dirty bit
896 * by __block_write_begin() isn't a real problem here as we clear
897 * the bit before releasing a page lock and thus writeback cannot
898 * ever write the buffer.
900 if (dirty)
901 clear_buffer_dirty(bh);
902 BUFFER_TRACE(bh, "get write access");
903 ret = ext4_journal_get_write_access(handle, bh);
904 if (!ret && dirty)
905 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
906 return ret;
909 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
910 struct buffer_head *bh_result, int create);
912 #ifdef CONFIG_EXT4_FS_ENCRYPTION
913 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
914 get_block_t *get_block)
916 unsigned from = pos & (PAGE_CACHE_SIZE - 1);
917 unsigned to = from + len;
918 struct inode *inode = page->mapping->host;
919 unsigned block_start, block_end;
920 sector_t block;
921 int err = 0;
922 unsigned blocksize = inode->i_sb->s_blocksize;
923 unsigned bbits;
924 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
925 bool decrypt = false;
927 BUG_ON(!PageLocked(page));
928 BUG_ON(from > PAGE_CACHE_SIZE);
929 BUG_ON(to > PAGE_CACHE_SIZE);
930 BUG_ON(from > to);
932 if (!page_has_buffers(page))
933 create_empty_buffers(page, blocksize, 0);
934 head = page_buffers(page);
935 bbits = ilog2(blocksize);
936 block = (sector_t)page->index << (PAGE_CACHE_SHIFT - bbits);
938 for (bh = head, block_start = 0; bh != head || !block_start;
939 block++, block_start = block_end, bh = bh->b_this_page) {
940 block_end = block_start + blocksize;
941 if (block_end <= from || block_start >= to) {
942 if (PageUptodate(page)) {
943 if (!buffer_uptodate(bh))
944 set_buffer_uptodate(bh);
946 continue;
948 if (buffer_new(bh))
949 clear_buffer_new(bh);
950 if (!buffer_mapped(bh)) {
951 WARN_ON(bh->b_size != blocksize);
952 err = get_block(inode, block, bh, 1);
953 if (err)
954 break;
955 if (buffer_new(bh)) {
956 unmap_underlying_metadata(bh->b_bdev,
957 bh->b_blocknr);
958 if (PageUptodate(page)) {
959 clear_buffer_new(bh);
960 set_buffer_uptodate(bh);
961 mark_buffer_dirty(bh);
962 continue;
964 if (block_end > to || block_start < from)
965 zero_user_segments(page, to, block_end,
966 block_start, from);
967 continue;
970 if (PageUptodate(page)) {
971 if (!buffer_uptodate(bh))
972 set_buffer_uptodate(bh);
973 continue;
975 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
976 !buffer_unwritten(bh) &&
977 (block_start < from || block_end > to)) {
978 ll_rw_block(READ, 1, &bh);
979 *wait_bh++ = bh;
980 decrypt = ext4_encrypted_inode(inode) &&
981 S_ISREG(inode->i_mode);
985 * If we issued read requests, let them complete.
987 while (wait_bh > wait) {
988 wait_on_buffer(*--wait_bh);
989 if (!buffer_uptodate(*wait_bh))
990 err = -EIO;
992 if (unlikely(err))
993 page_zero_new_buffers(page, from, to);
994 else if (decrypt)
995 err = ext4_decrypt_one(inode, page);
996 return err;
998 #endif
1000 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1001 loff_t pos, unsigned len, unsigned flags,
1002 struct page **pagep, void **fsdata)
1004 struct inode *inode = mapping->host;
1005 int ret, needed_blocks;
1006 handle_t *handle;
1007 int retries = 0;
1008 struct page *page;
1009 pgoff_t index;
1010 unsigned from, to;
1012 trace_ext4_write_begin(inode, pos, len, flags);
1014 * Reserve one block more for addition to orphan list in case
1015 * we allocate blocks but write fails for some reason
1017 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1018 index = pos >> PAGE_CACHE_SHIFT;
1019 from = pos & (PAGE_CACHE_SIZE - 1);
1020 to = from + len;
1022 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1023 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1024 flags, pagep);
1025 if (ret < 0)
1026 return ret;
1027 if (ret == 1)
1028 return 0;
1032 * grab_cache_page_write_begin() can take a long time if the
1033 * system is thrashing due to memory pressure, or if the page
1034 * is being written back. So grab it first before we start
1035 * the transaction handle. This also allows us to allocate
1036 * the page (if needed) without using GFP_NOFS.
1038 retry_grab:
1039 page = grab_cache_page_write_begin(mapping, index, flags);
1040 if (!page)
1041 return -ENOMEM;
1042 unlock_page(page);
1044 retry_journal:
1045 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1046 if (IS_ERR(handle)) {
1047 page_cache_release(page);
1048 return PTR_ERR(handle);
1051 lock_page(page);
1052 if (page->mapping != mapping) {
1053 /* The page got truncated from under us */
1054 unlock_page(page);
1055 page_cache_release(page);
1056 ext4_journal_stop(handle);
1057 goto retry_grab;
1059 /* In case writeback began while the page was unlocked */
1060 wait_for_stable_page(page);
1062 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1063 if (ext4_should_dioread_nolock(inode))
1064 ret = ext4_block_write_begin(page, pos, len,
1065 ext4_get_block_write);
1066 else
1067 ret = ext4_block_write_begin(page, pos, len,
1068 ext4_get_block);
1069 #else
1070 if (ext4_should_dioread_nolock(inode))
1071 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1072 else
1073 ret = __block_write_begin(page, pos, len, ext4_get_block);
1074 #endif
1075 if (!ret && ext4_should_journal_data(inode)) {
1076 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1077 from, to, NULL,
1078 do_journal_get_write_access);
1081 if (ret) {
1082 unlock_page(page);
1084 * __block_write_begin may have instantiated a few blocks
1085 * outside i_size. Trim these off again. Don't need
1086 * i_size_read because we hold i_mutex.
1088 * Add inode to orphan list in case we crash before
1089 * truncate finishes
1091 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1092 ext4_orphan_add(handle, inode);
1094 ext4_journal_stop(handle);
1095 if (pos + len > inode->i_size) {
1096 ext4_truncate_failed_write(inode);
1098 * If truncate failed early the inode might
1099 * still be on the orphan list; we need to
1100 * make sure the inode is removed from the
1101 * orphan list in that case.
1103 if (inode->i_nlink)
1104 ext4_orphan_del(NULL, inode);
1107 if (ret == -ENOSPC &&
1108 ext4_should_retry_alloc(inode->i_sb, &retries))
1109 goto retry_journal;
1110 page_cache_release(page);
1111 return ret;
1113 *pagep = page;
1114 return ret;
1117 /* For write_end() in data=journal mode */
1118 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1120 int ret;
1121 if (!buffer_mapped(bh) || buffer_freed(bh))
1122 return 0;
1123 set_buffer_uptodate(bh);
1124 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1125 clear_buffer_meta(bh);
1126 clear_buffer_prio(bh);
1127 return ret;
1131 * We need to pick up the new inode size which generic_commit_write gave us
1132 * `file' can be NULL - eg, when called from page_symlink().
1134 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1135 * buffers are managed internally.
1137 static int ext4_write_end(struct file *file,
1138 struct address_space *mapping,
1139 loff_t pos, unsigned len, unsigned copied,
1140 struct page *page, void *fsdata)
1142 handle_t *handle = ext4_journal_current_handle();
1143 struct inode *inode = mapping->host;
1144 loff_t old_size = inode->i_size;
1145 int ret = 0, ret2;
1146 int i_size_changed = 0;
1148 trace_ext4_write_end(inode, pos, len, copied);
1149 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1150 ret = ext4_jbd2_file_inode(handle, inode);
1151 if (ret) {
1152 unlock_page(page);
1153 page_cache_release(page);
1154 goto errout;
1158 if (ext4_has_inline_data(inode)) {
1159 ret = ext4_write_inline_data_end(inode, pos, len,
1160 copied, page);
1161 if (ret < 0)
1162 goto errout;
1163 copied = ret;
1164 } else
1165 copied = block_write_end(file, mapping, pos,
1166 len, copied, page, fsdata);
1168 * it's important to update i_size while still holding page lock:
1169 * page writeout could otherwise come in and zero beyond i_size.
1171 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1172 unlock_page(page);
1173 page_cache_release(page);
1175 if (old_size < pos)
1176 pagecache_isize_extended(inode, old_size, pos);
1178 * Don't mark the inode dirty under page lock. First, it unnecessarily
1179 * makes the holding time of page lock longer. Second, it forces lock
1180 * ordering of page lock and transaction start for journaling
1181 * filesystems.
1183 if (i_size_changed)
1184 ext4_mark_inode_dirty(handle, inode);
1186 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1187 /* if we have allocated more blocks and copied
1188 * less. We will have blocks allocated outside
1189 * inode->i_size. So truncate them
1191 ext4_orphan_add(handle, inode);
1192 errout:
1193 ret2 = ext4_journal_stop(handle);
1194 if (!ret)
1195 ret = ret2;
1197 if (pos + len > inode->i_size) {
1198 ext4_truncate_failed_write(inode);
1200 * If truncate failed early the inode might still be
1201 * on the orphan list; we need to make sure the inode
1202 * is removed from the orphan list in that case.
1204 if (inode->i_nlink)
1205 ext4_orphan_del(NULL, inode);
1208 return ret ? ret : copied;
1211 static int ext4_journalled_write_end(struct file *file,
1212 struct address_space *mapping,
1213 loff_t pos, unsigned len, unsigned copied,
1214 struct page *page, void *fsdata)
1216 handle_t *handle = ext4_journal_current_handle();
1217 struct inode *inode = mapping->host;
1218 loff_t old_size = inode->i_size;
1219 int ret = 0, ret2;
1220 int partial = 0;
1221 unsigned from, to;
1222 int size_changed = 0;
1224 trace_ext4_journalled_write_end(inode, pos, len, copied);
1225 from = pos & (PAGE_CACHE_SIZE - 1);
1226 to = from + len;
1228 BUG_ON(!ext4_handle_valid(handle));
1230 if (ext4_has_inline_data(inode))
1231 copied = ext4_write_inline_data_end(inode, pos, len,
1232 copied, page);
1233 else {
1234 if (copied < len) {
1235 if (!PageUptodate(page))
1236 copied = 0;
1237 page_zero_new_buffers(page, from+copied, to);
1240 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1241 to, &partial, write_end_fn);
1242 if (!partial)
1243 SetPageUptodate(page);
1245 size_changed = ext4_update_inode_size(inode, pos + copied);
1246 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1247 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1248 unlock_page(page);
1249 page_cache_release(page);
1251 if (old_size < pos)
1252 pagecache_isize_extended(inode, old_size, pos);
1254 if (size_changed) {
1255 ret2 = ext4_mark_inode_dirty(handle, inode);
1256 if (!ret)
1257 ret = ret2;
1260 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1261 /* if we have allocated more blocks and copied
1262 * less. We will have blocks allocated outside
1263 * inode->i_size. So truncate them
1265 ext4_orphan_add(handle, inode);
1267 ret2 = ext4_journal_stop(handle);
1268 if (!ret)
1269 ret = ret2;
1270 if (pos + len > inode->i_size) {
1271 ext4_truncate_failed_write(inode);
1273 * If truncate failed early the inode might still be
1274 * on the orphan list; we need to make sure the inode
1275 * is removed from the orphan list in that case.
1277 if (inode->i_nlink)
1278 ext4_orphan_del(NULL, inode);
1281 return ret ? ret : copied;
1285 * Reserve a single cluster located at lblock
1287 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1289 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1290 struct ext4_inode_info *ei = EXT4_I(inode);
1291 unsigned int md_needed;
1292 int ret;
1295 * We will charge metadata quota at writeout time; this saves
1296 * us from metadata over-estimation, though we may go over by
1297 * a small amount in the end. Here we just reserve for data.
1299 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1300 if (ret)
1301 return ret;
1304 * recalculate the amount of metadata blocks to reserve
1305 * in order to allocate nrblocks
1306 * worse case is one extent per block
1308 spin_lock(&ei->i_block_reservation_lock);
1310 * ext4_calc_metadata_amount() has side effects, which we have
1311 * to be prepared undo if we fail to claim space.
1313 md_needed = 0;
1314 trace_ext4_da_reserve_space(inode, 0);
1316 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1317 spin_unlock(&ei->i_block_reservation_lock);
1318 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1319 return -ENOSPC;
1321 ei->i_reserved_data_blocks++;
1322 spin_unlock(&ei->i_block_reservation_lock);
1324 return 0; /* success */
1327 static void ext4_da_release_space(struct inode *inode, int to_free)
1329 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1330 struct ext4_inode_info *ei = EXT4_I(inode);
1332 if (!to_free)
1333 return; /* Nothing to release, exit */
1335 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1337 trace_ext4_da_release_space(inode, to_free);
1338 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1340 * if there aren't enough reserved blocks, then the
1341 * counter is messed up somewhere. Since this
1342 * function is called from invalidate page, it's
1343 * harmless to return without any action.
1345 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1346 "ino %lu, to_free %d with only %d reserved "
1347 "data blocks", inode->i_ino, to_free,
1348 ei->i_reserved_data_blocks);
1349 WARN_ON(1);
1350 to_free = ei->i_reserved_data_blocks;
1352 ei->i_reserved_data_blocks -= to_free;
1354 /* update fs dirty data blocks counter */
1355 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1357 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1359 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1362 static void ext4_da_page_release_reservation(struct page *page,
1363 unsigned int offset,
1364 unsigned int length)
1366 int to_release = 0, contiguous_blks = 0;
1367 struct buffer_head *head, *bh;
1368 unsigned int curr_off = 0;
1369 struct inode *inode = page->mapping->host;
1370 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1371 unsigned int stop = offset + length;
1372 int num_clusters;
1373 ext4_fsblk_t lblk;
1375 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1377 head = page_buffers(page);
1378 bh = head;
1379 do {
1380 unsigned int next_off = curr_off + bh->b_size;
1382 if (next_off > stop)
1383 break;
1385 if ((offset <= curr_off) && (buffer_delay(bh))) {
1386 to_release++;
1387 contiguous_blks++;
1388 clear_buffer_delay(bh);
1389 } else if (contiguous_blks) {
1390 lblk = page->index <<
1391 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1392 lblk += (curr_off >> inode->i_blkbits) -
1393 contiguous_blks;
1394 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1395 contiguous_blks = 0;
1397 curr_off = next_off;
1398 } while ((bh = bh->b_this_page) != head);
1400 if (contiguous_blks) {
1401 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1402 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1403 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1406 /* If we have released all the blocks belonging to a cluster, then we
1407 * need to release the reserved space for that cluster. */
1408 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1409 while (num_clusters > 0) {
1410 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1411 ((num_clusters - 1) << sbi->s_cluster_bits);
1412 if (sbi->s_cluster_ratio == 1 ||
1413 !ext4_find_delalloc_cluster(inode, lblk))
1414 ext4_da_release_space(inode, 1);
1416 num_clusters--;
1421 * Delayed allocation stuff
1424 struct mpage_da_data {
1425 struct inode *inode;
1426 struct writeback_control *wbc;
1428 pgoff_t first_page; /* The first page to write */
1429 pgoff_t next_page; /* Current page to examine */
1430 pgoff_t last_page; /* Last page to examine */
1432 * Extent to map - this can be after first_page because that can be
1433 * fully mapped. We somewhat abuse m_flags to store whether the extent
1434 * is delalloc or unwritten.
1436 struct ext4_map_blocks map;
1437 struct ext4_io_submit io_submit; /* IO submission data */
1440 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1441 bool invalidate)
1443 int nr_pages, i;
1444 pgoff_t index, end;
1445 struct pagevec pvec;
1446 struct inode *inode = mpd->inode;
1447 struct address_space *mapping = inode->i_mapping;
1449 /* This is necessary when next_page == 0. */
1450 if (mpd->first_page >= mpd->next_page)
1451 return;
1453 index = mpd->first_page;
1454 end = mpd->next_page - 1;
1455 if (invalidate) {
1456 ext4_lblk_t start, last;
1457 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1458 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1459 ext4_es_remove_extent(inode, start, last - start + 1);
1462 pagevec_init(&pvec, 0);
1463 while (index <= end) {
1464 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1465 if (nr_pages == 0)
1466 break;
1467 for (i = 0; i < nr_pages; i++) {
1468 struct page *page = pvec.pages[i];
1469 if (page->index > end)
1470 break;
1471 BUG_ON(!PageLocked(page));
1472 BUG_ON(PageWriteback(page));
1473 if (invalidate) {
1474 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1475 ClearPageUptodate(page);
1477 unlock_page(page);
1479 index = pvec.pages[nr_pages - 1]->index + 1;
1480 pagevec_release(&pvec);
1484 static void ext4_print_free_blocks(struct inode *inode)
1486 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1487 struct super_block *sb = inode->i_sb;
1488 struct ext4_inode_info *ei = EXT4_I(inode);
1490 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1491 EXT4_C2B(EXT4_SB(inode->i_sb),
1492 ext4_count_free_clusters(sb)));
1493 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1494 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1495 (long long) EXT4_C2B(EXT4_SB(sb),
1496 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1497 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1498 (long long) EXT4_C2B(EXT4_SB(sb),
1499 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1500 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1501 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1502 ei->i_reserved_data_blocks);
1503 return;
1506 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1508 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1512 * This function is grabs code from the very beginning of
1513 * ext4_map_blocks, but assumes that the caller is from delayed write
1514 * time. This function looks up the requested blocks and sets the
1515 * buffer delay bit under the protection of i_data_sem.
1517 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1518 struct ext4_map_blocks *map,
1519 struct buffer_head *bh)
1521 struct extent_status es;
1522 int retval;
1523 sector_t invalid_block = ~((sector_t) 0xffff);
1524 #ifdef ES_AGGRESSIVE_TEST
1525 struct ext4_map_blocks orig_map;
1527 memcpy(&orig_map, map, sizeof(*map));
1528 #endif
1530 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1531 invalid_block = ~0;
1533 map->m_flags = 0;
1534 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1535 "logical block %lu\n", inode->i_ino, map->m_len,
1536 (unsigned long) map->m_lblk);
1538 /* Lookup extent status tree firstly */
1539 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1540 if (ext4_es_is_hole(&es)) {
1541 retval = 0;
1542 down_read(&EXT4_I(inode)->i_data_sem);
1543 goto add_delayed;
1547 * Delayed extent could be allocated by fallocate.
1548 * So we need to check it.
1550 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1551 map_bh(bh, inode->i_sb, invalid_block);
1552 set_buffer_new(bh);
1553 set_buffer_delay(bh);
1554 return 0;
1557 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1558 retval = es.es_len - (iblock - es.es_lblk);
1559 if (retval > map->m_len)
1560 retval = map->m_len;
1561 map->m_len = retval;
1562 if (ext4_es_is_written(&es))
1563 map->m_flags |= EXT4_MAP_MAPPED;
1564 else if (ext4_es_is_unwritten(&es))
1565 map->m_flags |= EXT4_MAP_UNWRITTEN;
1566 else
1567 BUG_ON(1);
1569 #ifdef ES_AGGRESSIVE_TEST
1570 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1571 #endif
1572 return retval;
1576 * Try to see if we can get the block without requesting a new
1577 * file system block.
1579 down_read(&EXT4_I(inode)->i_data_sem);
1580 if (ext4_has_inline_data(inode))
1581 retval = 0;
1582 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1583 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1584 else
1585 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1587 add_delayed:
1588 if (retval == 0) {
1589 int ret;
1591 * XXX: __block_prepare_write() unmaps passed block,
1592 * is it OK?
1595 * If the block was allocated from previously allocated cluster,
1596 * then we don't need to reserve it again. However we still need
1597 * to reserve metadata for every block we're going to write.
1599 if (EXT4_SB(inode->i_sb)->s_cluster_ratio <= 1 ||
1600 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1601 ret = ext4_da_reserve_space(inode, iblock);
1602 if (ret) {
1603 /* not enough space to reserve */
1604 retval = ret;
1605 goto out_unlock;
1609 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1610 ~0, EXTENT_STATUS_DELAYED);
1611 if (ret) {
1612 retval = ret;
1613 goto out_unlock;
1616 map_bh(bh, inode->i_sb, invalid_block);
1617 set_buffer_new(bh);
1618 set_buffer_delay(bh);
1619 } else if (retval > 0) {
1620 int ret;
1621 unsigned int status;
1623 if (unlikely(retval != map->m_len)) {
1624 ext4_warning(inode->i_sb,
1625 "ES len assertion failed for inode "
1626 "%lu: retval %d != map->m_len %d",
1627 inode->i_ino, retval, map->m_len);
1628 WARN_ON(1);
1631 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1632 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1633 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1634 map->m_pblk, status);
1635 if (ret != 0)
1636 retval = ret;
1639 out_unlock:
1640 up_read((&EXT4_I(inode)->i_data_sem));
1642 return retval;
1646 * This is a special get_block_t callback which is used by
1647 * ext4_da_write_begin(). It will either return mapped block or
1648 * reserve space for a single block.
1650 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1651 * We also have b_blocknr = -1 and b_bdev initialized properly
1653 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1654 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1655 * initialized properly.
1657 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1658 struct buffer_head *bh, int create)
1660 struct ext4_map_blocks map;
1661 int ret = 0;
1663 BUG_ON(create == 0);
1664 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1666 map.m_lblk = iblock;
1667 map.m_len = 1;
1670 * first, we need to know whether the block is allocated already
1671 * preallocated blocks are unmapped but should treated
1672 * the same as allocated blocks.
1674 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1675 if (ret <= 0)
1676 return ret;
1678 map_bh(bh, inode->i_sb, map.m_pblk);
1679 ext4_update_bh_state(bh, map.m_flags);
1681 if (buffer_unwritten(bh)) {
1682 /* A delayed write to unwritten bh should be marked
1683 * new and mapped. Mapped ensures that we don't do
1684 * get_block multiple times when we write to the same
1685 * offset and new ensures that we do proper zero out
1686 * for partial write.
1688 set_buffer_new(bh);
1689 set_buffer_mapped(bh);
1691 return 0;
1694 static int bget_one(handle_t *handle, struct buffer_head *bh)
1696 get_bh(bh);
1697 return 0;
1700 static int bput_one(handle_t *handle, struct buffer_head *bh)
1702 put_bh(bh);
1703 return 0;
1706 static int __ext4_journalled_writepage(struct page *page,
1707 unsigned int len)
1709 struct address_space *mapping = page->mapping;
1710 struct inode *inode = mapping->host;
1711 struct buffer_head *page_bufs = NULL;
1712 handle_t *handle = NULL;
1713 int ret = 0, err = 0;
1714 int inline_data = ext4_has_inline_data(inode);
1715 struct buffer_head *inode_bh = NULL;
1717 ClearPageChecked(page);
1719 if (inline_data) {
1720 BUG_ON(page->index != 0);
1721 BUG_ON(len > ext4_get_max_inline_size(inode));
1722 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1723 if (inode_bh == NULL)
1724 goto out;
1725 } else {
1726 page_bufs = page_buffers(page);
1727 if (!page_bufs) {
1728 BUG();
1729 goto out;
1731 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1732 NULL, bget_one);
1735 * We need to release the page lock before we start the
1736 * journal, so grab a reference so the page won't disappear
1737 * out from under us.
1739 get_page(page);
1740 unlock_page(page);
1742 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1743 ext4_writepage_trans_blocks(inode));
1744 if (IS_ERR(handle)) {
1745 ret = PTR_ERR(handle);
1746 put_page(page);
1747 goto out_no_pagelock;
1749 BUG_ON(!ext4_handle_valid(handle));
1751 lock_page(page);
1752 put_page(page);
1753 if (page->mapping != mapping) {
1754 /* The page got truncated from under us */
1755 ext4_journal_stop(handle);
1756 ret = 0;
1757 goto out;
1760 if (inline_data) {
1761 BUFFER_TRACE(inode_bh, "get write access");
1762 ret = ext4_journal_get_write_access(handle, inode_bh);
1764 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1766 } else {
1767 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1768 do_journal_get_write_access);
1770 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1771 write_end_fn);
1773 if (ret == 0)
1774 ret = err;
1775 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1776 err = ext4_journal_stop(handle);
1777 if (!ret)
1778 ret = err;
1780 if (!ext4_has_inline_data(inode))
1781 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1782 NULL, bput_one);
1783 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1784 out:
1785 unlock_page(page);
1786 out_no_pagelock:
1787 brelse(inode_bh);
1788 return ret;
1792 * Note that we don't need to start a transaction unless we're journaling data
1793 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1794 * need to file the inode to the transaction's list in ordered mode because if
1795 * we are writing back data added by write(), the inode is already there and if
1796 * we are writing back data modified via mmap(), no one guarantees in which
1797 * transaction the data will hit the disk. In case we are journaling data, we
1798 * cannot start transaction directly because transaction start ranks above page
1799 * lock so we have to do some magic.
1801 * This function can get called via...
1802 * - ext4_writepages after taking page lock (have journal handle)
1803 * - journal_submit_inode_data_buffers (no journal handle)
1804 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1805 * - grab_page_cache when doing write_begin (have journal handle)
1807 * We don't do any block allocation in this function. If we have page with
1808 * multiple blocks we need to write those buffer_heads that are mapped. This
1809 * is important for mmaped based write. So if we do with blocksize 1K
1810 * truncate(f, 1024);
1811 * a = mmap(f, 0, 4096);
1812 * a[0] = 'a';
1813 * truncate(f, 4096);
1814 * we have in the page first buffer_head mapped via page_mkwrite call back
1815 * but other buffer_heads would be unmapped but dirty (dirty done via the
1816 * do_wp_page). So writepage should write the first block. If we modify
1817 * the mmap area beyond 1024 we will again get a page_fault and the
1818 * page_mkwrite callback will do the block allocation and mark the
1819 * buffer_heads mapped.
1821 * We redirty the page if we have any buffer_heads that is either delay or
1822 * unwritten in the page.
1824 * We can get recursively called as show below.
1826 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1827 * ext4_writepage()
1829 * But since we don't do any block allocation we should not deadlock.
1830 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1832 static int ext4_writepage(struct page *page,
1833 struct writeback_control *wbc)
1835 int ret = 0;
1836 loff_t size;
1837 unsigned int len;
1838 struct buffer_head *page_bufs = NULL;
1839 struct inode *inode = page->mapping->host;
1840 struct ext4_io_submit io_submit;
1841 bool keep_towrite = false;
1843 trace_ext4_writepage(page);
1844 size = i_size_read(inode);
1845 if (page->index == size >> PAGE_CACHE_SHIFT)
1846 len = size & ~PAGE_CACHE_MASK;
1847 else
1848 len = PAGE_CACHE_SIZE;
1850 page_bufs = page_buffers(page);
1852 * We cannot do block allocation or other extent handling in this
1853 * function. If there are buffers needing that, we have to redirty
1854 * the page. But we may reach here when we do a journal commit via
1855 * journal_submit_inode_data_buffers() and in that case we must write
1856 * allocated buffers to achieve data=ordered mode guarantees.
1858 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1859 ext4_bh_delay_or_unwritten)) {
1860 redirty_page_for_writepage(wbc, page);
1861 if (current->flags & PF_MEMALLOC) {
1863 * For memory cleaning there's no point in writing only
1864 * some buffers. So just bail out. Warn if we came here
1865 * from direct reclaim.
1867 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1868 == PF_MEMALLOC);
1869 unlock_page(page);
1870 return 0;
1872 keep_towrite = true;
1875 if (PageChecked(page) && ext4_should_journal_data(inode))
1877 * It's mmapped pagecache. Add buffers and journal it. There
1878 * doesn't seem much point in redirtying the page here.
1880 return __ext4_journalled_writepage(page, len);
1882 ext4_io_submit_init(&io_submit, wbc);
1883 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1884 if (!io_submit.io_end) {
1885 redirty_page_for_writepage(wbc, page);
1886 unlock_page(page);
1887 return -ENOMEM;
1889 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1890 ext4_io_submit(&io_submit);
1891 /* Drop io_end reference we got from init */
1892 ext4_put_io_end_defer(io_submit.io_end);
1893 return ret;
1896 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1898 int len;
1899 loff_t size = i_size_read(mpd->inode);
1900 int err;
1902 BUG_ON(page->index != mpd->first_page);
1903 if (page->index == size >> PAGE_CACHE_SHIFT)
1904 len = size & ~PAGE_CACHE_MASK;
1905 else
1906 len = PAGE_CACHE_SIZE;
1907 clear_page_dirty_for_io(page);
1908 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1909 if (!err)
1910 mpd->wbc->nr_to_write--;
1911 mpd->first_page++;
1913 return err;
1916 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1919 * mballoc gives us at most this number of blocks...
1920 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1921 * The rest of mballoc seems to handle chunks up to full group size.
1923 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1926 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1928 * @mpd - extent of blocks
1929 * @lblk - logical number of the block in the file
1930 * @bh - buffer head we want to add to the extent
1932 * The function is used to collect contig. blocks in the same state. If the
1933 * buffer doesn't require mapping for writeback and we haven't started the
1934 * extent of buffers to map yet, the function returns 'true' immediately - the
1935 * caller can write the buffer right away. Otherwise the function returns true
1936 * if the block has been added to the extent, false if the block couldn't be
1937 * added.
1939 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1940 struct buffer_head *bh)
1942 struct ext4_map_blocks *map = &mpd->map;
1944 /* Buffer that doesn't need mapping for writeback? */
1945 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1946 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1947 /* So far no extent to map => we write the buffer right away */
1948 if (map->m_len == 0)
1949 return true;
1950 return false;
1953 /* First block in the extent? */
1954 if (map->m_len == 0) {
1955 map->m_lblk = lblk;
1956 map->m_len = 1;
1957 map->m_flags = bh->b_state & BH_FLAGS;
1958 return true;
1961 /* Don't go larger than mballoc is willing to allocate */
1962 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
1963 return false;
1965 /* Can we merge the block to our big extent? */
1966 if (lblk == map->m_lblk + map->m_len &&
1967 (bh->b_state & BH_FLAGS) == map->m_flags) {
1968 map->m_len++;
1969 return true;
1971 return false;
1975 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
1977 * @mpd - extent of blocks for mapping
1978 * @head - the first buffer in the page
1979 * @bh - buffer we should start processing from
1980 * @lblk - logical number of the block in the file corresponding to @bh
1982 * Walk through page buffers from @bh upto @head (exclusive) and either submit
1983 * the page for IO if all buffers in this page were mapped and there's no
1984 * accumulated extent of buffers to map or add buffers in the page to the
1985 * extent of buffers to map. The function returns 1 if the caller can continue
1986 * by processing the next page, 0 if it should stop adding buffers to the
1987 * extent to map because we cannot extend it anymore. It can also return value
1988 * < 0 in case of error during IO submission.
1990 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
1991 struct buffer_head *head,
1992 struct buffer_head *bh,
1993 ext4_lblk_t lblk)
1995 struct inode *inode = mpd->inode;
1996 int err;
1997 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
1998 >> inode->i_blkbits;
2000 do {
2001 BUG_ON(buffer_locked(bh));
2003 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2004 /* Found extent to map? */
2005 if (mpd->map.m_len)
2006 return 0;
2007 /* Everything mapped so far and we hit EOF */
2008 break;
2010 } while (lblk++, (bh = bh->b_this_page) != head);
2011 /* So far everything mapped? Submit the page for IO. */
2012 if (mpd->map.m_len == 0) {
2013 err = mpage_submit_page(mpd, head->b_page);
2014 if (err < 0)
2015 return err;
2017 return lblk < blocks;
2021 * mpage_map_buffers - update buffers corresponding to changed extent and
2022 * submit fully mapped pages for IO
2024 * @mpd - description of extent to map, on return next extent to map
2026 * Scan buffers corresponding to changed extent (we expect corresponding pages
2027 * to be already locked) and update buffer state according to new extent state.
2028 * We map delalloc buffers to their physical location, clear unwritten bits,
2029 * and mark buffers as uninit when we perform writes to unwritten extents
2030 * and do extent conversion after IO is finished. If the last page is not fully
2031 * mapped, we update @map to the next extent in the last page that needs
2032 * mapping. Otherwise we submit the page for IO.
2034 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2036 struct pagevec pvec;
2037 int nr_pages, i;
2038 struct inode *inode = mpd->inode;
2039 struct buffer_head *head, *bh;
2040 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2041 pgoff_t start, end;
2042 ext4_lblk_t lblk;
2043 sector_t pblock;
2044 int err;
2046 start = mpd->map.m_lblk >> bpp_bits;
2047 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2048 lblk = start << bpp_bits;
2049 pblock = mpd->map.m_pblk;
2051 pagevec_init(&pvec, 0);
2052 while (start <= end) {
2053 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2054 PAGEVEC_SIZE);
2055 if (nr_pages == 0)
2056 break;
2057 for (i = 0; i < nr_pages; i++) {
2058 struct page *page = pvec.pages[i];
2060 if (page->index > end)
2061 break;
2062 /* Up to 'end' pages must be contiguous */
2063 BUG_ON(page->index != start);
2064 bh = head = page_buffers(page);
2065 do {
2066 if (lblk < mpd->map.m_lblk)
2067 continue;
2068 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2070 * Buffer after end of mapped extent.
2071 * Find next buffer in the page to map.
2073 mpd->map.m_len = 0;
2074 mpd->map.m_flags = 0;
2076 * FIXME: If dioread_nolock supports
2077 * blocksize < pagesize, we need to make
2078 * sure we add size mapped so far to
2079 * io_end->size as the following call
2080 * can submit the page for IO.
2082 err = mpage_process_page_bufs(mpd, head,
2083 bh, lblk);
2084 pagevec_release(&pvec);
2085 if (err > 0)
2086 err = 0;
2087 return err;
2089 if (buffer_delay(bh)) {
2090 clear_buffer_delay(bh);
2091 bh->b_blocknr = pblock++;
2093 clear_buffer_unwritten(bh);
2094 } while (lblk++, (bh = bh->b_this_page) != head);
2097 * FIXME: This is going to break if dioread_nolock
2098 * supports blocksize < pagesize as we will try to
2099 * convert potentially unmapped parts of inode.
2101 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2102 /* Page fully mapped - let IO run! */
2103 err = mpage_submit_page(mpd, page);
2104 if (err < 0) {
2105 pagevec_release(&pvec);
2106 return err;
2108 start++;
2110 pagevec_release(&pvec);
2112 /* Extent fully mapped and matches with page boundary. We are done. */
2113 mpd->map.m_len = 0;
2114 mpd->map.m_flags = 0;
2115 return 0;
2118 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2120 struct inode *inode = mpd->inode;
2121 struct ext4_map_blocks *map = &mpd->map;
2122 int get_blocks_flags;
2123 int err, dioread_nolock;
2125 trace_ext4_da_write_pages_extent(inode, map);
2127 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2128 * to convert an unwritten extent to be initialized (in the case
2129 * where we have written into one or more preallocated blocks). It is
2130 * possible that we're going to need more metadata blocks than
2131 * previously reserved. However we must not fail because we're in
2132 * writeback and there is nothing we can do about it so it might result
2133 * in data loss. So use reserved blocks to allocate metadata if
2134 * possible.
2136 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2137 * the blocks in question are delalloc blocks. This indicates
2138 * that the blocks and quotas has already been checked when
2139 * the data was copied into the page cache.
2141 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2142 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2143 dioread_nolock = ext4_should_dioread_nolock(inode);
2144 if (dioread_nolock)
2145 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2146 if (map->m_flags & (1 << BH_Delay))
2147 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2149 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2150 if (err < 0)
2151 return err;
2152 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2153 if (!mpd->io_submit.io_end->handle &&
2154 ext4_handle_valid(handle)) {
2155 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2156 handle->h_rsv_handle = NULL;
2158 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2161 BUG_ON(map->m_len == 0);
2162 if (map->m_flags & EXT4_MAP_NEW) {
2163 struct block_device *bdev = inode->i_sb->s_bdev;
2164 int i;
2166 for (i = 0; i < map->m_len; i++)
2167 unmap_underlying_metadata(bdev, map->m_pblk + i);
2169 return 0;
2173 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2174 * mpd->len and submit pages underlying it for IO
2176 * @handle - handle for journal operations
2177 * @mpd - extent to map
2178 * @give_up_on_write - we set this to true iff there is a fatal error and there
2179 * is no hope of writing the data. The caller should discard
2180 * dirty pages to avoid infinite loops.
2182 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2183 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2184 * them to initialized or split the described range from larger unwritten
2185 * extent. Note that we need not map all the described range since allocation
2186 * can return less blocks or the range is covered by more unwritten extents. We
2187 * cannot map more because we are limited by reserved transaction credits. On
2188 * the other hand we always make sure that the last touched page is fully
2189 * mapped so that it can be written out (and thus forward progress is
2190 * guaranteed). After mapping we submit all mapped pages for IO.
2192 static int mpage_map_and_submit_extent(handle_t *handle,
2193 struct mpage_da_data *mpd,
2194 bool *give_up_on_write)
2196 struct inode *inode = mpd->inode;
2197 struct ext4_map_blocks *map = &mpd->map;
2198 int err;
2199 loff_t disksize;
2200 int progress = 0;
2202 mpd->io_submit.io_end->offset =
2203 ((loff_t)map->m_lblk) << inode->i_blkbits;
2204 do {
2205 err = mpage_map_one_extent(handle, mpd);
2206 if (err < 0) {
2207 struct super_block *sb = inode->i_sb;
2209 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2210 goto invalidate_dirty_pages;
2212 * Let the uper layers retry transient errors.
2213 * In the case of ENOSPC, if ext4_count_free_blocks()
2214 * is non-zero, a commit should free up blocks.
2216 if ((err == -ENOMEM) ||
2217 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2218 if (progress)
2219 goto update_disksize;
2220 return err;
2222 ext4_msg(sb, KERN_CRIT,
2223 "Delayed block allocation failed for "
2224 "inode %lu at logical offset %llu with"
2225 " max blocks %u with error %d",
2226 inode->i_ino,
2227 (unsigned long long)map->m_lblk,
2228 (unsigned)map->m_len, -err);
2229 ext4_msg(sb, KERN_CRIT,
2230 "This should not happen!! Data will "
2231 "be lost\n");
2232 if (err == -ENOSPC)
2233 ext4_print_free_blocks(inode);
2234 invalidate_dirty_pages:
2235 *give_up_on_write = true;
2236 return err;
2238 progress = 1;
2240 * Update buffer state, submit mapped pages, and get us new
2241 * extent to map
2243 err = mpage_map_and_submit_buffers(mpd);
2244 if (err < 0)
2245 goto update_disksize;
2246 } while (map->m_len);
2248 update_disksize:
2250 * Update on-disk size after IO is submitted. Races with
2251 * truncate are avoided by checking i_size under i_data_sem.
2253 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2254 if (disksize > EXT4_I(inode)->i_disksize) {
2255 int err2;
2256 loff_t i_size;
2258 down_write(&EXT4_I(inode)->i_data_sem);
2259 i_size = i_size_read(inode);
2260 if (disksize > i_size)
2261 disksize = i_size;
2262 if (disksize > EXT4_I(inode)->i_disksize)
2263 EXT4_I(inode)->i_disksize = disksize;
2264 err2 = ext4_mark_inode_dirty(handle, inode);
2265 up_write(&EXT4_I(inode)->i_data_sem);
2266 if (err2)
2267 ext4_error(inode->i_sb,
2268 "Failed to mark inode %lu dirty",
2269 inode->i_ino);
2270 if (!err)
2271 err = err2;
2273 return err;
2277 * Calculate the total number of credits to reserve for one writepages
2278 * iteration. This is called from ext4_writepages(). We map an extent of
2279 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2280 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2281 * bpp - 1 blocks in bpp different extents.
2283 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2285 int bpp = ext4_journal_blocks_per_page(inode);
2287 return ext4_meta_trans_blocks(inode,
2288 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2292 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2293 * and underlying extent to map
2295 * @mpd - where to look for pages
2297 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2298 * IO immediately. When we find a page which isn't mapped we start accumulating
2299 * extent of buffers underlying these pages that needs mapping (formed by
2300 * either delayed or unwritten buffers). We also lock the pages containing
2301 * these buffers. The extent found is returned in @mpd structure (starting at
2302 * mpd->lblk with length mpd->len blocks).
2304 * Note that this function can attach bios to one io_end structure which are
2305 * neither logically nor physically contiguous. Although it may seem as an
2306 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2307 * case as we need to track IO to all buffers underlying a page in one io_end.
2309 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2311 struct address_space *mapping = mpd->inode->i_mapping;
2312 struct pagevec pvec;
2313 unsigned int nr_pages;
2314 long left = mpd->wbc->nr_to_write;
2315 pgoff_t index = mpd->first_page;
2316 pgoff_t end = mpd->last_page;
2317 int tag;
2318 int i, err = 0;
2319 int blkbits = mpd->inode->i_blkbits;
2320 ext4_lblk_t lblk;
2321 struct buffer_head *head;
2323 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2324 tag = PAGECACHE_TAG_TOWRITE;
2325 else
2326 tag = PAGECACHE_TAG_DIRTY;
2328 pagevec_init(&pvec, 0);
2329 mpd->map.m_len = 0;
2330 mpd->next_page = index;
2331 while (index <= end) {
2332 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2333 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2334 if (nr_pages == 0)
2335 goto out;
2337 for (i = 0; i < nr_pages; i++) {
2338 struct page *page = pvec.pages[i];
2341 * At this point, the page may be truncated or
2342 * invalidated (changing page->mapping to NULL), or
2343 * even swizzled back from swapper_space to tmpfs file
2344 * mapping. However, page->index will not change
2345 * because we have a reference on the page.
2347 if (page->index > end)
2348 goto out;
2351 * Accumulated enough dirty pages? This doesn't apply
2352 * to WB_SYNC_ALL mode. For integrity sync we have to
2353 * keep going because someone may be concurrently
2354 * dirtying pages, and we might have synced a lot of
2355 * newly appeared dirty pages, but have not synced all
2356 * of the old dirty pages.
2358 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2359 goto out;
2361 /* If we can't merge this page, we are done. */
2362 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2363 goto out;
2365 lock_page(page);
2367 * If the page is no longer dirty, or its mapping no
2368 * longer corresponds to inode we are writing (which
2369 * means it has been truncated or invalidated), or the
2370 * page is already under writeback and we are not doing
2371 * a data integrity writeback, skip the page
2373 if (!PageDirty(page) ||
2374 (PageWriteback(page) &&
2375 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2376 unlikely(page->mapping != mapping)) {
2377 unlock_page(page);
2378 continue;
2381 wait_on_page_writeback(page);
2382 BUG_ON(PageWriteback(page));
2384 if (mpd->map.m_len == 0)
2385 mpd->first_page = page->index;
2386 mpd->next_page = page->index + 1;
2387 /* Add all dirty buffers to mpd */
2388 lblk = ((ext4_lblk_t)page->index) <<
2389 (PAGE_CACHE_SHIFT - blkbits);
2390 head = page_buffers(page);
2391 err = mpage_process_page_bufs(mpd, head, head, lblk);
2392 if (err <= 0)
2393 goto out;
2394 err = 0;
2395 left--;
2397 pagevec_release(&pvec);
2398 cond_resched();
2400 return 0;
2401 out:
2402 pagevec_release(&pvec);
2403 return err;
2406 static int __writepage(struct page *page, struct writeback_control *wbc,
2407 void *data)
2409 struct address_space *mapping = data;
2410 int ret = ext4_writepage(page, wbc);
2411 mapping_set_error(mapping, ret);
2412 return ret;
2415 static int ext4_writepages(struct address_space *mapping,
2416 struct writeback_control *wbc)
2418 pgoff_t writeback_index = 0;
2419 long nr_to_write = wbc->nr_to_write;
2420 int range_whole = 0;
2421 int cycled = 1;
2422 handle_t *handle = NULL;
2423 struct mpage_da_data mpd;
2424 struct inode *inode = mapping->host;
2425 int needed_blocks, rsv_blocks = 0, ret = 0;
2426 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2427 bool done;
2428 struct blk_plug plug;
2429 bool give_up_on_write = false;
2431 trace_ext4_writepages(inode, wbc);
2434 * No pages to write? This is mainly a kludge to avoid starting
2435 * a transaction for special inodes like journal inode on last iput()
2436 * because that could violate lock ordering on umount
2438 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2439 goto out_writepages;
2441 if (ext4_should_journal_data(inode)) {
2442 struct blk_plug plug;
2444 blk_start_plug(&plug);
2445 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2446 blk_finish_plug(&plug);
2447 goto out_writepages;
2451 * If the filesystem has aborted, it is read-only, so return
2452 * right away instead of dumping stack traces later on that
2453 * will obscure the real source of the problem. We test
2454 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2455 * the latter could be true if the filesystem is mounted
2456 * read-only, and in that case, ext4_writepages should
2457 * *never* be called, so if that ever happens, we would want
2458 * the stack trace.
2460 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2461 ret = -EROFS;
2462 goto out_writepages;
2465 if (ext4_should_dioread_nolock(inode)) {
2467 * We may need to convert up to one extent per block in
2468 * the page and we may dirty the inode.
2470 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2474 * If we have inline data and arrive here, it means that
2475 * we will soon create the block for the 1st page, so
2476 * we'd better clear the inline data here.
2478 if (ext4_has_inline_data(inode)) {
2479 /* Just inode will be modified... */
2480 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2481 if (IS_ERR(handle)) {
2482 ret = PTR_ERR(handle);
2483 goto out_writepages;
2485 BUG_ON(ext4_test_inode_state(inode,
2486 EXT4_STATE_MAY_INLINE_DATA));
2487 ext4_destroy_inline_data(handle, inode);
2488 ext4_journal_stop(handle);
2491 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2492 range_whole = 1;
2494 if (wbc->range_cyclic) {
2495 writeback_index = mapping->writeback_index;
2496 if (writeback_index)
2497 cycled = 0;
2498 mpd.first_page = writeback_index;
2499 mpd.last_page = -1;
2500 } else {
2501 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2502 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2505 mpd.inode = inode;
2506 mpd.wbc = wbc;
2507 ext4_io_submit_init(&mpd.io_submit, wbc);
2508 retry:
2509 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2510 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2511 done = false;
2512 blk_start_plug(&plug);
2513 while (!done && mpd.first_page <= mpd.last_page) {
2514 /* For each extent of pages we use new io_end */
2515 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2516 if (!mpd.io_submit.io_end) {
2517 ret = -ENOMEM;
2518 break;
2522 * We have two constraints: We find one extent to map and we
2523 * must always write out whole page (makes a difference when
2524 * blocksize < pagesize) so that we don't block on IO when we
2525 * try to write out the rest of the page. Journalled mode is
2526 * not supported by delalloc.
2528 BUG_ON(ext4_should_journal_data(inode));
2529 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2531 /* start a new transaction */
2532 handle = ext4_journal_start_with_reserve(inode,
2533 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2534 if (IS_ERR(handle)) {
2535 ret = PTR_ERR(handle);
2536 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2537 "%ld pages, ino %lu; err %d", __func__,
2538 wbc->nr_to_write, inode->i_ino, ret);
2539 /* Release allocated io_end */
2540 ext4_put_io_end(mpd.io_submit.io_end);
2541 break;
2544 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2545 ret = mpage_prepare_extent_to_map(&mpd);
2546 if (!ret) {
2547 if (mpd.map.m_len)
2548 ret = mpage_map_and_submit_extent(handle, &mpd,
2549 &give_up_on_write);
2550 else {
2552 * We scanned the whole range (or exhausted
2553 * nr_to_write), submitted what was mapped and
2554 * didn't find anything needing mapping. We are
2555 * done.
2557 done = true;
2561 * Caution: If the handle is synchronous,
2562 * ext4_journal_stop() can wait for transaction commit
2563 * to finish which may depend on writeback of pages to
2564 * complete or on page lock to be released. In that
2565 * case, we have to wait until after after we have
2566 * submitted all the IO, released page locks we hold,
2567 * and dropped io_end reference (for extent conversion
2568 * to be able to complete) before stopping the handle.
2570 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2571 ext4_journal_stop(handle);
2572 handle = NULL;
2574 /* Submit prepared bio */
2575 ext4_io_submit(&mpd.io_submit);
2576 /* Unlock pages we didn't use */
2577 mpage_release_unused_pages(&mpd, give_up_on_write);
2579 * Drop our io_end reference we got from init. We have
2580 * to be careful and use deferred io_end finishing if
2581 * we are still holding the transaction as we can
2582 * release the last reference to io_end which may end
2583 * up doing unwritten extent conversion.
2585 if (handle) {
2586 ext4_put_io_end_defer(mpd.io_submit.io_end);
2587 ext4_journal_stop(handle);
2588 } else
2589 ext4_put_io_end(mpd.io_submit.io_end);
2591 if (ret == -ENOSPC && sbi->s_journal) {
2593 * Commit the transaction which would
2594 * free blocks released in the transaction
2595 * and try again
2597 jbd2_journal_force_commit_nested(sbi->s_journal);
2598 ret = 0;
2599 continue;
2601 /* Fatal error - ENOMEM, EIO... */
2602 if (ret)
2603 break;
2605 blk_finish_plug(&plug);
2606 if (!ret && !cycled && wbc->nr_to_write > 0) {
2607 cycled = 1;
2608 mpd.last_page = writeback_index - 1;
2609 mpd.first_page = 0;
2610 goto retry;
2613 /* Update index */
2614 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2616 * Set the writeback_index so that range_cyclic
2617 * mode will write it back later
2619 mapping->writeback_index = mpd.first_page;
2621 out_writepages:
2622 trace_ext4_writepages_result(inode, wbc, ret,
2623 nr_to_write - wbc->nr_to_write);
2624 return ret;
2627 static int ext4_nonda_switch(struct super_block *sb)
2629 s64 free_clusters, dirty_clusters;
2630 struct ext4_sb_info *sbi = EXT4_SB(sb);
2633 * switch to non delalloc mode if we are running low
2634 * on free block. The free block accounting via percpu
2635 * counters can get slightly wrong with percpu_counter_batch getting
2636 * accumulated on each CPU without updating global counters
2637 * Delalloc need an accurate free block accounting. So switch
2638 * to non delalloc when we are near to error range.
2640 free_clusters =
2641 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2642 dirty_clusters =
2643 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2645 * Start pushing delalloc when 1/2 of free blocks are dirty.
2647 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2648 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2650 if (2 * free_clusters < 3 * dirty_clusters ||
2651 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2653 * free block count is less than 150% of dirty blocks
2654 * or free blocks is less than watermark
2656 return 1;
2658 return 0;
2661 /* We always reserve for an inode update; the superblock could be there too */
2662 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2664 if (likely(EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
2665 EXT4_FEATURE_RO_COMPAT_LARGE_FILE)))
2666 return 1;
2668 if (pos + len <= 0x7fffffffULL)
2669 return 1;
2671 /* We might need to update the superblock to set LARGE_FILE */
2672 return 2;
2675 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2676 loff_t pos, unsigned len, unsigned flags,
2677 struct page **pagep, void **fsdata)
2679 int ret, retries = 0;
2680 struct page *page;
2681 pgoff_t index;
2682 struct inode *inode = mapping->host;
2683 handle_t *handle;
2685 index = pos >> PAGE_CACHE_SHIFT;
2687 if (ext4_nonda_switch(inode->i_sb)) {
2688 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2689 return ext4_write_begin(file, mapping, pos,
2690 len, flags, pagep, fsdata);
2692 *fsdata = (void *)0;
2693 trace_ext4_da_write_begin(inode, pos, len, flags);
2695 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2696 ret = ext4_da_write_inline_data_begin(mapping, inode,
2697 pos, len, flags,
2698 pagep, fsdata);
2699 if (ret < 0)
2700 return ret;
2701 if (ret == 1)
2702 return 0;
2706 * grab_cache_page_write_begin() can take a long time if the
2707 * system is thrashing due to memory pressure, or if the page
2708 * is being written back. So grab it first before we start
2709 * the transaction handle. This also allows us to allocate
2710 * the page (if needed) without using GFP_NOFS.
2712 retry_grab:
2713 page = grab_cache_page_write_begin(mapping, index, flags);
2714 if (!page)
2715 return -ENOMEM;
2716 unlock_page(page);
2719 * With delayed allocation, we don't log the i_disksize update
2720 * if there is delayed block allocation. But we still need
2721 * to journalling the i_disksize update if writes to the end
2722 * of file which has an already mapped buffer.
2724 retry_journal:
2725 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2726 ext4_da_write_credits(inode, pos, len));
2727 if (IS_ERR(handle)) {
2728 page_cache_release(page);
2729 return PTR_ERR(handle);
2732 lock_page(page);
2733 if (page->mapping != mapping) {
2734 /* The page got truncated from under us */
2735 unlock_page(page);
2736 page_cache_release(page);
2737 ext4_journal_stop(handle);
2738 goto retry_grab;
2740 /* In case writeback began while the page was unlocked */
2741 wait_for_stable_page(page);
2743 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2744 ret = ext4_block_write_begin(page, pos, len,
2745 ext4_da_get_block_prep);
2746 #else
2747 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2748 #endif
2749 if (ret < 0) {
2750 unlock_page(page);
2751 ext4_journal_stop(handle);
2753 * block_write_begin may have instantiated a few blocks
2754 * outside i_size. Trim these off again. Don't need
2755 * i_size_read because we hold i_mutex.
2757 if (pos + len > inode->i_size)
2758 ext4_truncate_failed_write(inode);
2760 if (ret == -ENOSPC &&
2761 ext4_should_retry_alloc(inode->i_sb, &retries))
2762 goto retry_journal;
2764 page_cache_release(page);
2765 return ret;
2768 *pagep = page;
2769 return ret;
2773 * Check if we should update i_disksize
2774 * when write to the end of file but not require block allocation
2776 static int ext4_da_should_update_i_disksize(struct page *page,
2777 unsigned long offset)
2779 struct buffer_head *bh;
2780 struct inode *inode = page->mapping->host;
2781 unsigned int idx;
2782 int i;
2784 bh = page_buffers(page);
2785 idx = offset >> inode->i_blkbits;
2787 for (i = 0; i < idx; i++)
2788 bh = bh->b_this_page;
2790 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2791 return 0;
2792 return 1;
2795 static int ext4_da_write_end(struct file *file,
2796 struct address_space *mapping,
2797 loff_t pos, unsigned len, unsigned copied,
2798 struct page *page, void *fsdata)
2800 struct inode *inode = mapping->host;
2801 int ret = 0, ret2;
2802 handle_t *handle = ext4_journal_current_handle();
2803 loff_t new_i_size;
2804 unsigned long start, end;
2805 int write_mode = (int)(unsigned long)fsdata;
2807 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2808 return ext4_write_end(file, mapping, pos,
2809 len, copied, page, fsdata);
2811 trace_ext4_da_write_end(inode, pos, len, copied);
2812 start = pos & (PAGE_CACHE_SIZE - 1);
2813 end = start + copied - 1;
2816 * generic_write_end() will run mark_inode_dirty() if i_size
2817 * changes. So let's piggyback the i_disksize mark_inode_dirty
2818 * into that.
2820 new_i_size = pos + copied;
2821 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2822 if (ext4_has_inline_data(inode) ||
2823 ext4_da_should_update_i_disksize(page, end)) {
2824 ext4_update_i_disksize(inode, new_i_size);
2825 /* We need to mark inode dirty even if
2826 * new_i_size is less that inode->i_size
2827 * bu greater than i_disksize.(hint delalloc)
2829 ext4_mark_inode_dirty(handle, inode);
2833 if (write_mode != CONVERT_INLINE_DATA &&
2834 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2835 ext4_has_inline_data(inode))
2836 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2837 page);
2838 else
2839 ret2 = generic_write_end(file, mapping, pos, len, copied,
2840 page, fsdata);
2842 copied = ret2;
2843 if (ret2 < 0)
2844 ret = ret2;
2845 ret2 = ext4_journal_stop(handle);
2846 if (!ret)
2847 ret = ret2;
2849 return ret ? ret : copied;
2852 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2853 unsigned int length)
2856 * Drop reserved blocks
2858 BUG_ON(!PageLocked(page));
2859 if (!page_has_buffers(page))
2860 goto out;
2862 ext4_da_page_release_reservation(page, offset, length);
2864 out:
2865 ext4_invalidatepage(page, offset, length);
2867 return;
2871 * Force all delayed allocation blocks to be allocated for a given inode.
2873 int ext4_alloc_da_blocks(struct inode *inode)
2875 trace_ext4_alloc_da_blocks(inode);
2877 if (!EXT4_I(inode)->i_reserved_data_blocks)
2878 return 0;
2881 * We do something simple for now. The filemap_flush() will
2882 * also start triggering a write of the data blocks, which is
2883 * not strictly speaking necessary (and for users of
2884 * laptop_mode, not even desirable). However, to do otherwise
2885 * would require replicating code paths in:
2887 * ext4_writepages() ->
2888 * write_cache_pages() ---> (via passed in callback function)
2889 * __mpage_da_writepage() -->
2890 * mpage_add_bh_to_extent()
2891 * mpage_da_map_blocks()
2893 * The problem is that write_cache_pages(), located in
2894 * mm/page-writeback.c, marks pages clean in preparation for
2895 * doing I/O, which is not desirable if we're not planning on
2896 * doing I/O at all.
2898 * We could call write_cache_pages(), and then redirty all of
2899 * the pages by calling redirty_page_for_writepage() but that
2900 * would be ugly in the extreme. So instead we would need to
2901 * replicate parts of the code in the above functions,
2902 * simplifying them because we wouldn't actually intend to
2903 * write out the pages, but rather only collect contiguous
2904 * logical block extents, call the multi-block allocator, and
2905 * then update the buffer heads with the block allocations.
2907 * For now, though, we'll cheat by calling filemap_flush(),
2908 * which will map the blocks, and start the I/O, but not
2909 * actually wait for the I/O to complete.
2911 return filemap_flush(inode->i_mapping);
2915 * bmap() is special. It gets used by applications such as lilo and by
2916 * the swapper to find the on-disk block of a specific piece of data.
2918 * Naturally, this is dangerous if the block concerned is still in the
2919 * journal. If somebody makes a swapfile on an ext4 data-journaling
2920 * filesystem and enables swap, then they may get a nasty shock when the
2921 * data getting swapped to that swapfile suddenly gets overwritten by
2922 * the original zero's written out previously to the journal and
2923 * awaiting writeback in the kernel's buffer cache.
2925 * So, if we see any bmap calls here on a modified, data-journaled file,
2926 * take extra steps to flush any blocks which might be in the cache.
2928 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2930 struct inode *inode = mapping->host;
2931 journal_t *journal;
2932 int err;
2935 * We can get here for an inline file via the FIBMAP ioctl
2937 if (ext4_has_inline_data(inode))
2938 return 0;
2940 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2941 test_opt(inode->i_sb, DELALLOC)) {
2943 * With delalloc we want to sync the file
2944 * so that we can make sure we allocate
2945 * blocks for file
2947 filemap_write_and_wait(mapping);
2950 if (EXT4_JOURNAL(inode) &&
2951 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2953 * This is a REALLY heavyweight approach, but the use of
2954 * bmap on dirty files is expected to be extremely rare:
2955 * only if we run lilo or swapon on a freshly made file
2956 * do we expect this to happen.
2958 * (bmap requires CAP_SYS_RAWIO so this does not
2959 * represent an unprivileged user DOS attack --- we'd be
2960 * in trouble if mortal users could trigger this path at
2961 * will.)
2963 * NB. EXT4_STATE_JDATA is not set on files other than
2964 * regular files. If somebody wants to bmap a directory
2965 * or symlink and gets confused because the buffer
2966 * hasn't yet been flushed to disk, they deserve
2967 * everything they get.
2970 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2971 journal = EXT4_JOURNAL(inode);
2972 jbd2_journal_lock_updates(journal);
2973 err = jbd2_journal_flush(journal);
2974 jbd2_journal_unlock_updates(journal);
2976 if (err)
2977 return 0;
2980 return generic_block_bmap(mapping, block, ext4_get_block);
2983 static int ext4_readpage(struct file *file, struct page *page)
2985 int ret = -EAGAIN;
2986 struct inode *inode = page->mapping->host;
2988 trace_ext4_readpage(page);
2990 if (ext4_has_inline_data(inode))
2991 ret = ext4_readpage_inline(inode, page);
2993 if (ret == -EAGAIN)
2994 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
2996 return ret;
2999 static int
3000 ext4_readpages(struct file *file, struct address_space *mapping,
3001 struct list_head *pages, unsigned nr_pages)
3003 struct inode *inode = mapping->host;
3005 /* If the file has inline data, no need to do readpages. */
3006 if (ext4_has_inline_data(inode))
3007 return 0;
3009 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3012 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3013 unsigned int length)
3015 trace_ext4_invalidatepage(page, offset, length);
3017 /* No journalling happens on data buffers when this function is used */
3018 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3020 block_invalidatepage(page, offset, length);
3023 static int __ext4_journalled_invalidatepage(struct page *page,
3024 unsigned int offset,
3025 unsigned int length)
3027 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3029 trace_ext4_journalled_invalidatepage(page, offset, length);
3032 * If it's a full truncate we just forget about the pending dirtying
3034 if (offset == 0 && length == PAGE_CACHE_SIZE)
3035 ClearPageChecked(page);
3037 return jbd2_journal_invalidatepage(journal, page, offset, length);
3040 /* Wrapper for aops... */
3041 static void ext4_journalled_invalidatepage(struct page *page,
3042 unsigned int offset,
3043 unsigned int length)
3045 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3048 static int ext4_releasepage(struct page *page, gfp_t wait)
3050 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3052 trace_ext4_releasepage(page);
3054 /* Page has dirty journalled data -> cannot release */
3055 if (PageChecked(page))
3056 return 0;
3057 if (journal)
3058 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3059 else
3060 return try_to_free_buffers(page);
3064 * ext4_get_block used when preparing for a DIO write or buffer write.
3065 * We allocate an uinitialized extent if blocks haven't been allocated.
3066 * The extent will be converted to initialized after the IO is complete.
3068 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3069 struct buffer_head *bh_result, int create)
3071 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3072 inode->i_ino, create);
3073 return _ext4_get_block(inode, iblock, bh_result,
3074 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3077 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3078 struct buffer_head *bh_result, int create)
3080 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3081 inode->i_ino, create);
3082 return _ext4_get_block(inode, iblock, bh_result,
3083 EXT4_GET_BLOCKS_NO_LOCK);
3086 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3087 ssize_t size, void *private)
3089 ext4_io_end_t *io_end = iocb->private;
3091 /* if not async direct IO just return */
3092 if (!io_end)
3093 return;
3095 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3096 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3097 iocb->private, io_end->inode->i_ino, iocb, offset,
3098 size);
3100 iocb->private = NULL;
3101 io_end->offset = offset;
3102 io_end->size = size;
3103 ext4_put_io_end(io_end);
3107 * For ext4 extent files, ext4 will do direct-io write to holes,
3108 * preallocated extents, and those write extend the file, no need to
3109 * fall back to buffered IO.
3111 * For holes, we fallocate those blocks, mark them as unwritten
3112 * If those blocks were preallocated, we mark sure they are split, but
3113 * still keep the range to write as unwritten.
3115 * The unwritten extents will be converted to written when DIO is completed.
3116 * For async direct IO, since the IO may still pending when return, we
3117 * set up an end_io call back function, which will do the conversion
3118 * when async direct IO completed.
3120 * If the O_DIRECT write will extend the file then add this inode to the
3121 * orphan list. So recovery will truncate it back to the original size
3122 * if the machine crashes during the write.
3125 static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3126 loff_t offset)
3128 struct file *file = iocb->ki_filp;
3129 struct inode *inode = file->f_mapping->host;
3130 ssize_t ret;
3131 size_t count = iov_iter_count(iter);
3132 int overwrite = 0;
3133 get_block_t *get_block_func = NULL;
3134 int dio_flags = 0;
3135 loff_t final_size = offset + count;
3136 ext4_io_end_t *io_end = NULL;
3138 /* Use the old path for reads and writes beyond i_size. */
3139 if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size)
3140 return ext4_ind_direct_IO(iocb, iter, offset);
3142 BUG_ON(iocb->private == NULL);
3145 * Make all waiters for direct IO properly wait also for extent
3146 * conversion. This also disallows race between truncate() and
3147 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3149 if (iov_iter_rw(iter) == WRITE)
3150 inode_dio_begin(inode);
3152 /* If we do a overwrite dio, i_mutex locking can be released */
3153 overwrite = *((int *)iocb->private);
3155 if (overwrite) {
3156 down_read(&EXT4_I(inode)->i_data_sem);
3157 mutex_unlock(&inode->i_mutex);
3161 * We could direct write to holes and fallocate.
3163 * Allocated blocks to fill the hole are marked as
3164 * unwritten to prevent parallel buffered read to expose
3165 * the stale data before DIO complete the data IO.
3167 * As to previously fallocated extents, ext4 get_block will
3168 * just simply mark the buffer mapped but still keep the
3169 * extents unwritten.
3171 * For non AIO case, we will convert those unwritten extents
3172 * to written after return back from blockdev_direct_IO.
3174 * For async DIO, the conversion needs to be deferred when the
3175 * IO is completed. The ext4 end_io callback function will be
3176 * called to take care of the conversion work. Here for async
3177 * case, we allocate an io_end structure to hook to the iocb.
3179 iocb->private = NULL;
3180 if (overwrite) {
3181 get_block_func = ext4_get_block_write_nolock;
3182 } else {
3183 ext4_inode_aio_set(inode, NULL);
3184 if (!is_sync_kiocb(iocb)) {
3185 io_end = ext4_init_io_end(inode, GFP_NOFS);
3186 if (!io_end) {
3187 ret = -ENOMEM;
3188 goto retake_lock;
3191 * Grab reference for DIO. Will be dropped in
3192 * ext4_end_io_dio()
3194 iocb->private = ext4_get_io_end(io_end);
3196 * we save the io structure for current async direct
3197 * IO, so that later ext4_map_blocks() could flag the
3198 * io structure whether there is a unwritten extents
3199 * needs to be converted when IO is completed.
3201 ext4_inode_aio_set(inode, io_end);
3203 get_block_func = ext4_get_block_write;
3204 dio_flags = DIO_LOCKING;
3206 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3207 BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode));
3208 #endif
3209 if (IS_DAX(inode))
3210 ret = dax_do_io(iocb, inode, iter, offset, get_block_func,
3211 ext4_end_io_dio, dio_flags);
3212 else
3213 ret = __blockdev_direct_IO(iocb, inode,
3214 inode->i_sb->s_bdev, iter, offset,
3215 get_block_func,
3216 ext4_end_io_dio, NULL, dio_flags);
3219 * Put our reference to io_end. This can free the io_end structure e.g.
3220 * in sync IO case or in case of error. It can even perform extent
3221 * conversion if all bios we submitted finished before we got here.
3222 * Note that in that case iocb->private can be already set to NULL
3223 * here.
3225 if (io_end) {
3226 ext4_inode_aio_set(inode, NULL);
3227 ext4_put_io_end(io_end);
3229 * When no IO was submitted ext4_end_io_dio() was not
3230 * called so we have to put iocb's reference.
3232 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3233 WARN_ON(iocb->private != io_end);
3234 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3235 ext4_put_io_end(io_end);
3236 iocb->private = NULL;
3239 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3240 EXT4_STATE_DIO_UNWRITTEN)) {
3241 int err;
3243 * for non AIO case, since the IO is already
3244 * completed, we could do the conversion right here
3246 err = ext4_convert_unwritten_extents(NULL, inode,
3247 offset, ret);
3248 if (err < 0)
3249 ret = err;
3250 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3253 retake_lock:
3254 if (iov_iter_rw(iter) == WRITE)
3255 inode_dio_end(inode);
3256 /* take i_mutex locking again if we do a ovewrite dio */
3257 if (overwrite) {
3258 up_read(&EXT4_I(inode)->i_data_sem);
3259 mutex_lock(&inode->i_mutex);
3262 return ret;
3265 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
3266 loff_t offset)
3268 struct file *file = iocb->ki_filp;
3269 struct inode *inode = file->f_mapping->host;
3270 size_t count = iov_iter_count(iter);
3271 ssize_t ret;
3273 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3274 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3275 return 0;
3276 #endif
3279 * If we are doing data journalling we don't support O_DIRECT
3281 if (ext4_should_journal_data(inode))
3282 return 0;
3284 /* Let buffer I/O handle the inline data case. */
3285 if (ext4_has_inline_data(inode))
3286 return 0;
3288 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3289 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3290 ret = ext4_ext_direct_IO(iocb, iter, offset);
3291 else
3292 ret = ext4_ind_direct_IO(iocb, iter, offset);
3293 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3294 return ret;
3298 * Pages can be marked dirty completely asynchronously from ext4's journalling
3299 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3300 * much here because ->set_page_dirty is called under VFS locks. The page is
3301 * not necessarily locked.
3303 * We cannot just dirty the page and leave attached buffers clean, because the
3304 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3305 * or jbddirty because all the journalling code will explode.
3307 * So what we do is to mark the page "pending dirty" and next time writepage
3308 * is called, propagate that into the buffers appropriately.
3310 static int ext4_journalled_set_page_dirty(struct page *page)
3312 SetPageChecked(page);
3313 return __set_page_dirty_nobuffers(page);
3316 static const struct address_space_operations ext4_aops = {
3317 .readpage = ext4_readpage,
3318 .readpages = ext4_readpages,
3319 .writepage = ext4_writepage,
3320 .writepages = ext4_writepages,
3321 .write_begin = ext4_write_begin,
3322 .write_end = ext4_write_end,
3323 .bmap = ext4_bmap,
3324 .invalidatepage = ext4_invalidatepage,
3325 .releasepage = ext4_releasepage,
3326 .direct_IO = ext4_direct_IO,
3327 .migratepage = buffer_migrate_page,
3328 .is_partially_uptodate = block_is_partially_uptodate,
3329 .error_remove_page = generic_error_remove_page,
3332 static const struct address_space_operations ext4_journalled_aops = {
3333 .readpage = ext4_readpage,
3334 .readpages = ext4_readpages,
3335 .writepage = ext4_writepage,
3336 .writepages = ext4_writepages,
3337 .write_begin = ext4_write_begin,
3338 .write_end = ext4_journalled_write_end,
3339 .set_page_dirty = ext4_journalled_set_page_dirty,
3340 .bmap = ext4_bmap,
3341 .invalidatepage = ext4_journalled_invalidatepage,
3342 .releasepage = ext4_releasepage,
3343 .direct_IO = ext4_direct_IO,
3344 .is_partially_uptodate = block_is_partially_uptodate,
3345 .error_remove_page = generic_error_remove_page,
3348 static const struct address_space_operations ext4_da_aops = {
3349 .readpage = ext4_readpage,
3350 .readpages = ext4_readpages,
3351 .writepage = ext4_writepage,
3352 .writepages = ext4_writepages,
3353 .write_begin = ext4_da_write_begin,
3354 .write_end = ext4_da_write_end,
3355 .bmap = ext4_bmap,
3356 .invalidatepage = ext4_da_invalidatepage,
3357 .releasepage = ext4_releasepage,
3358 .direct_IO = ext4_direct_IO,
3359 .migratepage = buffer_migrate_page,
3360 .is_partially_uptodate = block_is_partially_uptodate,
3361 .error_remove_page = generic_error_remove_page,
3364 void ext4_set_aops(struct inode *inode)
3366 switch (ext4_inode_journal_mode(inode)) {
3367 case EXT4_INODE_ORDERED_DATA_MODE:
3368 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3369 break;
3370 case EXT4_INODE_WRITEBACK_DATA_MODE:
3371 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3372 break;
3373 case EXT4_INODE_JOURNAL_DATA_MODE:
3374 inode->i_mapping->a_ops = &ext4_journalled_aops;
3375 return;
3376 default:
3377 BUG();
3379 if (test_opt(inode->i_sb, DELALLOC))
3380 inode->i_mapping->a_ops = &ext4_da_aops;
3381 else
3382 inode->i_mapping->a_ops = &ext4_aops;
3385 static int __ext4_block_zero_page_range(handle_t *handle,
3386 struct address_space *mapping, loff_t from, loff_t length)
3388 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3389 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3390 unsigned blocksize, pos;
3391 ext4_lblk_t iblock;
3392 struct inode *inode = mapping->host;
3393 struct buffer_head *bh;
3394 struct page *page;
3395 int err = 0;
3397 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3398 mapping_gfp_mask(mapping) & ~__GFP_FS);
3399 if (!page)
3400 return -ENOMEM;
3402 blocksize = inode->i_sb->s_blocksize;
3404 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3406 if (!page_has_buffers(page))
3407 create_empty_buffers(page, blocksize, 0);
3409 /* Find the buffer that contains "offset" */
3410 bh = page_buffers(page);
3411 pos = blocksize;
3412 while (offset >= pos) {
3413 bh = bh->b_this_page;
3414 iblock++;
3415 pos += blocksize;
3417 if (buffer_freed(bh)) {
3418 BUFFER_TRACE(bh, "freed: skip");
3419 goto unlock;
3421 if (!buffer_mapped(bh)) {
3422 BUFFER_TRACE(bh, "unmapped");
3423 ext4_get_block(inode, iblock, bh, 0);
3424 /* unmapped? It's a hole - nothing to do */
3425 if (!buffer_mapped(bh)) {
3426 BUFFER_TRACE(bh, "still unmapped");
3427 goto unlock;
3431 /* Ok, it's mapped. Make sure it's up-to-date */
3432 if (PageUptodate(page))
3433 set_buffer_uptodate(bh);
3435 if (!buffer_uptodate(bh)) {
3436 err = -EIO;
3437 ll_rw_block(READ, 1, &bh);
3438 wait_on_buffer(bh);
3439 /* Uhhuh. Read error. Complain and punt. */
3440 if (!buffer_uptodate(bh))
3441 goto unlock;
3442 if (S_ISREG(inode->i_mode) &&
3443 ext4_encrypted_inode(inode)) {
3444 /* We expect the key to be set. */
3445 BUG_ON(!ext4_has_encryption_key(inode));
3446 BUG_ON(blocksize != PAGE_CACHE_SIZE);
3447 WARN_ON_ONCE(ext4_decrypt_one(inode, page));
3450 if (ext4_should_journal_data(inode)) {
3451 BUFFER_TRACE(bh, "get write access");
3452 err = ext4_journal_get_write_access(handle, bh);
3453 if (err)
3454 goto unlock;
3456 zero_user(page, offset, length);
3457 BUFFER_TRACE(bh, "zeroed end of block");
3459 if (ext4_should_journal_data(inode)) {
3460 err = ext4_handle_dirty_metadata(handle, inode, bh);
3461 } else {
3462 err = 0;
3463 mark_buffer_dirty(bh);
3464 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3465 err = ext4_jbd2_file_inode(handle, inode);
3468 unlock:
3469 unlock_page(page);
3470 page_cache_release(page);
3471 return err;
3475 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3476 * starting from file offset 'from'. The range to be zero'd must
3477 * be contained with in one block. If the specified range exceeds
3478 * the end of the block it will be shortened to end of the block
3479 * that cooresponds to 'from'
3481 static int ext4_block_zero_page_range(handle_t *handle,
3482 struct address_space *mapping, loff_t from, loff_t length)
3484 struct inode *inode = mapping->host;
3485 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3486 unsigned blocksize = inode->i_sb->s_blocksize;
3487 unsigned max = blocksize - (offset & (blocksize - 1));
3490 * correct length if it does not fall between
3491 * 'from' and the end of the block
3493 if (length > max || length < 0)
3494 length = max;
3496 if (IS_DAX(inode))
3497 return dax_zero_page_range(inode, from, length, ext4_get_block);
3498 return __ext4_block_zero_page_range(handle, mapping, from, length);
3502 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3503 * up to the end of the block which corresponds to `from'.
3504 * This required during truncate. We need to physically zero the tail end
3505 * of that block so it doesn't yield old data if the file is later grown.
3507 static int ext4_block_truncate_page(handle_t *handle,
3508 struct address_space *mapping, loff_t from)
3510 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3511 unsigned length;
3512 unsigned blocksize;
3513 struct inode *inode = mapping->host;
3515 blocksize = inode->i_sb->s_blocksize;
3516 length = blocksize - (offset & (blocksize - 1));
3518 return ext4_block_zero_page_range(handle, mapping, from, length);
3521 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3522 loff_t lstart, loff_t length)
3524 struct super_block *sb = inode->i_sb;
3525 struct address_space *mapping = inode->i_mapping;
3526 unsigned partial_start, partial_end;
3527 ext4_fsblk_t start, end;
3528 loff_t byte_end = (lstart + length - 1);
3529 int err = 0;
3531 partial_start = lstart & (sb->s_blocksize - 1);
3532 partial_end = byte_end & (sb->s_blocksize - 1);
3534 start = lstart >> sb->s_blocksize_bits;
3535 end = byte_end >> sb->s_blocksize_bits;
3537 /* Handle partial zero within the single block */
3538 if (start == end &&
3539 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3540 err = ext4_block_zero_page_range(handle, mapping,
3541 lstart, length);
3542 return err;
3544 /* Handle partial zero out on the start of the range */
3545 if (partial_start) {
3546 err = ext4_block_zero_page_range(handle, mapping,
3547 lstart, sb->s_blocksize);
3548 if (err)
3549 return err;
3551 /* Handle partial zero out on the end of the range */
3552 if (partial_end != sb->s_blocksize - 1)
3553 err = ext4_block_zero_page_range(handle, mapping,
3554 byte_end - partial_end,
3555 partial_end + 1);
3556 return err;
3559 int ext4_can_truncate(struct inode *inode)
3561 if (S_ISREG(inode->i_mode))
3562 return 1;
3563 if (S_ISDIR(inode->i_mode))
3564 return 1;
3565 if (S_ISLNK(inode->i_mode))
3566 return !ext4_inode_is_fast_symlink(inode);
3567 return 0;
3571 * We have to make sure i_disksize gets properly updated before we truncate
3572 * page cache due to hole punching or zero range. Otherwise i_disksize update
3573 * can get lost as it may have been postponed to submission of writeback but
3574 * that will never happen after we truncate page cache.
3576 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3577 loff_t len)
3579 handle_t *handle;
3580 loff_t size = i_size_read(inode);
3582 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3583 if (offset > size || offset + len < size)
3584 return 0;
3586 if (EXT4_I(inode)->i_disksize >= size)
3587 return 0;
3589 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3590 if (IS_ERR(handle))
3591 return PTR_ERR(handle);
3592 ext4_update_i_disksize(inode, size);
3593 ext4_mark_inode_dirty(handle, inode);
3594 ext4_journal_stop(handle);
3596 return 0;
3600 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3601 * associated with the given offset and length
3603 * @inode: File inode
3604 * @offset: The offset where the hole will begin
3605 * @len: The length of the hole
3607 * Returns: 0 on success or negative on failure
3610 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3612 struct super_block *sb = inode->i_sb;
3613 ext4_lblk_t first_block, stop_block;
3614 struct address_space *mapping = inode->i_mapping;
3615 loff_t first_block_offset, last_block_offset;
3616 handle_t *handle;
3617 unsigned int credits;
3618 int ret = 0;
3620 if (!S_ISREG(inode->i_mode))
3621 return -EOPNOTSUPP;
3623 trace_ext4_punch_hole(inode, offset, length, 0);
3626 * Write out all dirty pages to avoid race conditions
3627 * Then release them.
3629 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3630 ret = filemap_write_and_wait_range(mapping, offset,
3631 offset + length - 1);
3632 if (ret)
3633 return ret;
3636 mutex_lock(&inode->i_mutex);
3638 /* No need to punch hole beyond i_size */
3639 if (offset >= inode->i_size)
3640 goto out_mutex;
3643 * If the hole extends beyond i_size, set the hole
3644 * to end after the page that contains i_size
3646 if (offset + length > inode->i_size) {
3647 length = inode->i_size +
3648 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3649 offset;
3652 if (offset & (sb->s_blocksize - 1) ||
3653 (offset + length) & (sb->s_blocksize - 1)) {
3655 * Attach jinode to inode for jbd2 if we do any zeroing of
3656 * partial block
3658 ret = ext4_inode_attach_jinode(inode);
3659 if (ret < 0)
3660 goto out_mutex;
3664 /* Wait all existing dio workers, newcomers will block on i_mutex */
3665 ext4_inode_block_unlocked_dio(inode);
3666 inode_dio_wait(inode);
3669 * Prevent page faults from reinstantiating pages we have released from
3670 * page cache.
3672 down_write(&EXT4_I(inode)->i_mmap_sem);
3673 first_block_offset = round_up(offset, sb->s_blocksize);
3674 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3676 /* Now release the pages and zero block aligned part of pages*/
3677 if (last_block_offset > first_block_offset) {
3678 ret = ext4_update_disksize_before_punch(inode, offset, length);
3679 if (ret)
3680 goto out_dio;
3681 truncate_pagecache_range(inode, first_block_offset,
3682 last_block_offset);
3685 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3686 credits = ext4_writepage_trans_blocks(inode);
3687 else
3688 credits = ext4_blocks_for_truncate(inode);
3689 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3690 if (IS_ERR(handle)) {
3691 ret = PTR_ERR(handle);
3692 ext4_std_error(sb, ret);
3693 goto out_dio;
3696 ret = ext4_zero_partial_blocks(handle, inode, offset,
3697 length);
3698 if (ret)
3699 goto out_stop;
3701 first_block = (offset + sb->s_blocksize - 1) >>
3702 EXT4_BLOCK_SIZE_BITS(sb);
3703 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3705 /* If there are no blocks to remove, return now */
3706 if (first_block >= stop_block)
3707 goto out_stop;
3709 down_write(&EXT4_I(inode)->i_data_sem);
3710 ext4_discard_preallocations(inode);
3712 ret = ext4_es_remove_extent(inode, first_block,
3713 stop_block - first_block);
3714 if (ret) {
3715 up_write(&EXT4_I(inode)->i_data_sem);
3716 goto out_stop;
3719 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3720 ret = ext4_ext_remove_space(inode, first_block,
3721 stop_block - 1);
3722 else
3723 ret = ext4_ind_remove_space(handle, inode, first_block,
3724 stop_block);
3726 up_write(&EXT4_I(inode)->i_data_sem);
3727 if (IS_SYNC(inode))
3728 ext4_handle_sync(handle);
3730 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3731 ext4_mark_inode_dirty(handle, inode);
3732 out_stop:
3733 ext4_journal_stop(handle);
3734 out_dio:
3735 up_write(&EXT4_I(inode)->i_mmap_sem);
3736 ext4_inode_resume_unlocked_dio(inode);
3737 out_mutex:
3738 mutex_unlock(&inode->i_mutex);
3739 return ret;
3742 int ext4_inode_attach_jinode(struct inode *inode)
3744 struct ext4_inode_info *ei = EXT4_I(inode);
3745 struct jbd2_inode *jinode;
3747 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3748 return 0;
3750 jinode = jbd2_alloc_inode(GFP_KERNEL);
3751 spin_lock(&inode->i_lock);
3752 if (!ei->jinode) {
3753 if (!jinode) {
3754 spin_unlock(&inode->i_lock);
3755 return -ENOMEM;
3757 ei->jinode = jinode;
3758 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3759 jinode = NULL;
3761 spin_unlock(&inode->i_lock);
3762 if (unlikely(jinode != NULL))
3763 jbd2_free_inode(jinode);
3764 return 0;
3768 * ext4_truncate()
3770 * We block out ext4_get_block() block instantiations across the entire
3771 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3772 * simultaneously on behalf of the same inode.
3774 * As we work through the truncate and commit bits of it to the journal there
3775 * is one core, guiding principle: the file's tree must always be consistent on
3776 * disk. We must be able to restart the truncate after a crash.
3778 * The file's tree may be transiently inconsistent in memory (although it
3779 * probably isn't), but whenever we close off and commit a journal transaction,
3780 * the contents of (the filesystem + the journal) must be consistent and
3781 * restartable. It's pretty simple, really: bottom up, right to left (although
3782 * left-to-right works OK too).
3784 * Note that at recovery time, journal replay occurs *before* the restart of
3785 * truncate against the orphan inode list.
3787 * The committed inode has the new, desired i_size (which is the same as
3788 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3789 * that this inode's truncate did not complete and it will again call
3790 * ext4_truncate() to have another go. So there will be instantiated blocks
3791 * to the right of the truncation point in a crashed ext4 filesystem. But
3792 * that's fine - as long as they are linked from the inode, the post-crash
3793 * ext4_truncate() run will find them and release them.
3795 void ext4_truncate(struct inode *inode)
3797 struct ext4_inode_info *ei = EXT4_I(inode);
3798 unsigned int credits;
3799 handle_t *handle;
3800 struct address_space *mapping = inode->i_mapping;
3803 * There is a possibility that we're either freeing the inode
3804 * or it's a completely new inode. In those cases we might not
3805 * have i_mutex locked because it's not necessary.
3807 if (!(inode->i_state & (I_NEW|I_FREEING)))
3808 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3809 trace_ext4_truncate_enter(inode);
3811 if (!ext4_can_truncate(inode))
3812 return;
3814 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3816 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3817 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3819 if (ext4_has_inline_data(inode)) {
3820 int has_inline = 1;
3822 ext4_inline_data_truncate(inode, &has_inline);
3823 if (has_inline)
3824 return;
3827 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3828 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3829 if (ext4_inode_attach_jinode(inode) < 0)
3830 return;
3833 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3834 credits = ext4_writepage_trans_blocks(inode);
3835 else
3836 credits = ext4_blocks_for_truncate(inode);
3838 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3839 if (IS_ERR(handle)) {
3840 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3841 return;
3844 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3845 ext4_block_truncate_page(handle, mapping, inode->i_size);
3848 * We add the inode to the orphan list, so that if this
3849 * truncate spans multiple transactions, and we crash, we will
3850 * resume the truncate when the filesystem recovers. It also
3851 * marks the inode dirty, to catch the new size.
3853 * Implication: the file must always be in a sane, consistent
3854 * truncatable state while each transaction commits.
3856 if (ext4_orphan_add(handle, inode))
3857 goto out_stop;
3859 down_write(&EXT4_I(inode)->i_data_sem);
3861 ext4_discard_preallocations(inode);
3863 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3864 ext4_ext_truncate(handle, inode);
3865 else
3866 ext4_ind_truncate(handle, inode);
3868 up_write(&ei->i_data_sem);
3870 if (IS_SYNC(inode))
3871 ext4_handle_sync(handle);
3873 out_stop:
3875 * If this was a simple ftruncate() and the file will remain alive,
3876 * then we need to clear up the orphan record which we created above.
3877 * However, if this was a real unlink then we were called by
3878 * ext4_evict_inode(), and we allow that function to clean up the
3879 * orphan info for us.
3881 if (inode->i_nlink)
3882 ext4_orphan_del(handle, inode);
3884 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3885 ext4_mark_inode_dirty(handle, inode);
3886 ext4_journal_stop(handle);
3888 trace_ext4_truncate_exit(inode);
3892 * ext4_get_inode_loc returns with an extra refcount against the inode's
3893 * underlying buffer_head on success. If 'in_mem' is true, we have all
3894 * data in memory that is needed to recreate the on-disk version of this
3895 * inode.
3897 static int __ext4_get_inode_loc(struct inode *inode,
3898 struct ext4_iloc *iloc, int in_mem)
3900 struct ext4_group_desc *gdp;
3901 struct buffer_head *bh;
3902 struct super_block *sb = inode->i_sb;
3903 ext4_fsblk_t block;
3904 int inodes_per_block, inode_offset;
3906 iloc->bh = NULL;
3907 if (!ext4_valid_inum(sb, inode->i_ino))
3908 return -EIO;
3910 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3911 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3912 if (!gdp)
3913 return -EIO;
3916 * Figure out the offset within the block group inode table
3918 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3919 inode_offset = ((inode->i_ino - 1) %
3920 EXT4_INODES_PER_GROUP(sb));
3921 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3922 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3924 bh = sb_getblk(sb, block);
3925 if (unlikely(!bh))
3926 return -ENOMEM;
3927 if (!buffer_uptodate(bh)) {
3928 lock_buffer(bh);
3931 * If the buffer has the write error flag, we have failed
3932 * to write out another inode in the same block. In this
3933 * case, we don't have to read the block because we may
3934 * read the old inode data successfully.
3936 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3937 set_buffer_uptodate(bh);
3939 if (buffer_uptodate(bh)) {
3940 /* someone brought it uptodate while we waited */
3941 unlock_buffer(bh);
3942 goto has_buffer;
3946 * If we have all information of the inode in memory and this
3947 * is the only valid inode in the block, we need not read the
3948 * block.
3950 if (in_mem) {
3951 struct buffer_head *bitmap_bh;
3952 int i, start;
3954 start = inode_offset & ~(inodes_per_block - 1);
3956 /* Is the inode bitmap in cache? */
3957 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3958 if (unlikely(!bitmap_bh))
3959 goto make_io;
3962 * If the inode bitmap isn't in cache then the
3963 * optimisation may end up performing two reads instead
3964 * of one, so skip it.
3966 if (!buffer_uptodate(bitmap_bh)) {
3967 brelse(bitmap_bh);
3968 goto make_io;
3970 for (i = start; i < start + inodes_per_block; i++) {
3971 if (i == inode_offset)
3972 continue;
3973 if (ext4_test_bit(i, bitmap_bh->b_data))
3974 break;
3976 brelse(bitmap_bh);
3977 if (i == start + inodes_per_block) {
3978 /* all other inodes are free, so skip I/O */
3979 memset(bh->b_data, 0, bh->b_size);
3980 set_buffer_uptodate(bh);
3981 unlock_buffer(bh);
3982 goto has_buffer;
3986 make_io:
3988 * If we need to do any I/O, try to pre-readahead extra
3989 * blocks from the inode table.
3991 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3992 ext4_fsblk_t b, end, table;
3993 unsigned num;
3994 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3996 table = ext4_inode_table(sb, gdp);
3997 /* s_inode_readahead_blks is always a power of 2 */
3998 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3999 if (table > b)
4000 b = table;
4001 end = b + ra_blks;
4002 num = EXT4_INODES_PER_GROUP(sb);
4003 if (ext4_has_group_desc_csum(sb))
4004 num -= ext4_itable_unused_count(sb, gdp);
4005 table += num / inodes_per_block;
4006 if (end > table)
4007 end = table;
4008 while (b <= end)
4009 sb_breadahead(sb, b++);
4013 * There are other valid inodes in the buffer, this inode
4014 * has in-inode xattrs, or we don't have this inode in memory.
4015 * Read the block from disk.
4017 trace_ext4_load_inode(inode);
4018 get_bh(bh);
4019 bh->b_end_io = end_buffer_read_sync;
4020 submit_bh(READ | REQ_META | REQ_PRIO, bh);
4021 wait_on_buffer(bh);
4022 if (!buffer_uptodate(bh)) {
4023 EXT4_ERROR_INODE_BLOCK(inode, block,
4024 "unable to read itable block");
4025 brelse(bh);
4026 return -EIO;
4029 has_buffer:
4030 iloc->bh = bh;
4031 return 0;
4034 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4036 /* We have all inode data except xattrs in memory here. */
4037 return __ext4_get_inode_loc(inode, iloc,
4038 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4041 void ext4_set_inode_flags(struct inode *inode)
4043 unsigned int flags = EXT4_I(inode)->i_flags;
4044 unsigned int new_fl = 0;
4046 if (flags & EXT4_SYNC_FL)
4047 new_fl |= S_SYNC;
4048 if (flags & EXT4_APPEND_FL)
4049 new_fl |= S_APPEND;
4050 if (flags & EXT4_IMMUTABLE_FL)
4051 new_fl |= S_IMMUTABLE;
4052 if (flags & EXT4_NOATIME_FL)
4053 new_fl |= S_NOATIME;
4054 if (flags & EXT4_DIRSYNC_FL)
4055 new_fl |= S_DIRSYNC;
4056 if (test_opt(inode->i_sb, DAX))
4057 new_fl |= S_DAX;
4058 inode_set_flags(inode, new_fl,
4059 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4062 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4063 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4065 unsigned int vfs_fl;
4066 unsigned long old_fl, new_fl;
4068 do {
4069 vfs_fl = ei->vfs_inode.i_flags;
4070 old_fl = ei->i_flags;
4071 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4072 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4073 EXT4_DIRSYNC_FL);
4074 if (vfs_fl & S_SYNC)
4075 new_fl |= EXT4_SYNC_FL;
4076 if (vfs_fl & S_APPEND)
4077 new_fl |= EXT4_APPEND_FL;
4078 if (vfs_fl & S_IMMUTABLE)
4079 new_fl |= EXT4_IMMUTABLE_FL;
4080 if (vfs_fl & S_NOATIME)
4081 new_fl |= EXT4_NOATIME_FL;
4082 if (vfs_fl & S_DIRSYNC)
4083 new_fl |= EXT4_DIRSYNC_FL;
4084 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4087 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4088 struct ext4_inode_info *ei)
4090 blkcnt_t i_blocks ;
4091 struct inode *inode = &(ei->vfs_inode);
4092 struct super_block *sb = inode->i_sb;
4094 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4095 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4096 /* we are using combined 48 bit field */
4097 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4098 le32_to_cpu(raw_inode->i_blocks_lo);
4099 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4100 /* i_blocks represent file system block size */
4101 return i_blocks << (inode->i_blkbits - 9);
4102 } else {
4103 return i_blocks;
4105 } else {
4106 return le32_to_cpu(raw_inode->i_blocks_lo);
4110 static inline void ext4_iget_extra_inode(struct inode *inode,
4111 struct ext4_inode *raw_inode,
4112 struct ext4_inode_info *ei)
4114 __le32 *magic = (void *)raw_inode +
4115 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4116 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4117 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4118 ext4_find_inline_data_nolock(inode);
4119 } else
4120 EXT4_I(inode)->i_inline_off = 0;
4123 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4125 struct ext4_iloc iloc;
4126 struct ext4_inode *raw_inode;
4127 struct ext4_inode_info *ei;
4128 struct inode *inode;
4129 journal_t *journal = EXT4_SB(sb)->s_journal;
4130 long ret;
4131 int block;
4132 uid_t i_uid;
4133 gid_t i_gid;
4135 inode = iget_locked(sb, ino);
4136 if (!inode)
4137 return ERR_PTR(-ENOMEM);
4138 if (!(inode->i_state & I_NEW))
4139 return inode;
4141 ei = EXT4_I(inode);
4142 iloc.bh = NULL;
4144 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4145 if (ret < 0)
4146 goto bad_inode;
4147 raw_inode = ext4_raw_inode(&iloc);
4149 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4150 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4151 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4152 EXT4_INODE_SIZE(inode->i_sb)) {
4153 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4154 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4155 EXT4_INODE_SIZE(inode->i_sb));
4156 ret = -EIO;
4157 goto bad_inode;
4159 } else
4160 ei->i_extra_isize = 0;
4162 /* Precompute checksum seed for inode metadata */
4163 if (ext4_has_metadata_csum(sb)) {
4164 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4165 __u32 csum;
4166 __le32 inum = cpu_to_le32(inode->i_ino);
4167 __le32 gen = raw_inode->i_generation;
4168 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4169 sizeof(inum));
4170 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4171 sizeof(gen));
4174 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4175 EXT4_ERROR_INODE(inode, "checksum invalid");
4176 ret = -EIO;
4177 goto bad_inode;
4180 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4181 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4182 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4183 if (!(test_opt(inode->i_sb, NO_UID32))) {
4184 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4185 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4187 i_uid_write(inode, i_uid);
4188 i_gid_write(inode, i_gid);
4189 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4191 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4192 ei->i_inline_off = 0;
4193 ei->i_dir_start_lookup = 0;
4194 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4195 /* We now have enough fields to check if the inode was active or not.
4196 * This is needed because nfsd might try to access dead inodes
4197 * the test is that same one that e2fsck uses
4198 * NeilBrown 1999oct15
4200 if (inode->i_nlink == 0) {
4201 if ((inode->i_mode == 0 ||
4202 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4203 ino != EXT4_BOOT_LOADER_INO) {
4204 /* this inode is deleted */
4205 ret = -ESTALE;
4206 goto bad_inode;
4208 /* The only unlinked inodes we let through here have
4209 * valid i_mode and are being read by the orphan
4210 * recovery code: that's fine, we're about to complete
4211 * the process of deleting those.
4212 * OR it is the EXT4_BOOT_LOADER_INO which is
4213 * not initialized on a new filesystem. */
4215 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4216 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4217 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4218 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4219 ei->i_file_acl |=
4220 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4221 inode->i_size = ext4_isize(raw_inode);
4222 ei->i_disksize = inode->i_size;
4223 #ifdef CONFIG_QUOTA
4224 ei->i_reserved_quota = 0;
4225 #endif
4226 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4227 ei->i_block_group = iloc.block_group;
4228 ei->i_last_alloc_group = ~0;
4230 * NOTE! The in-memory inode i_data array is in little-endian order
4231 * even on big-endian machines: we do NOT byteswap the block numbers!
4233 for (block = 0; block < EXT4_N_BLOCKS; block++)
4234 ei->i_data[block] = raw_inode->i_block[block];
4235 INIT_LIST_HEAD(&ei->i_orphan);
4238 * Set transaction id's of transactions that have to be committed
4239 * to finish f[data]sync. We set them to currently running transaction
4240 * as we cannot be sure that the inode or some of its metadata isn't
4241 * part of the transaction - the inode could have been reclaimed and
4242 * now it is reread from disk.
4244 if (journal) {
4245 transaction_t *transaction;
4246 tid_t tid;
4248 read_lock(&journal->j_state_lock);
4249 if (journal->j_running_transaction)
4250 transaction = journal->j_running_transaction;
4251 else
4252 transaction = journal->j_committing_transaction;
4253 if (transaction)
4254 tid = transaction->t_tid;
4255 else
4256 tid = journal->j_commit_sequence;
4257 read_unlock(&journal->j_state_lock);
4258 ei->i_sync_tid = tid;
4259 ei->i_datasync_tid = tid;
4262 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4263 if (ei->i_extra_isize == 0) {
4264 /* The extra space is currently unused. Use it. */
4265 ei->i_extra_isize = sizeof(struct ext4_inode) -
4266 EXT4_GOOD_OLD_INODE_SIZE;
4267 } else {
4268 ext4_iget_extra_inode(inode, raw_inode, ei);
4272 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4273 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4274 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4275 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4277 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4278 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4279 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4280 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4281 inode->i_version |=
4282 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4286 ret = 0;
4287 if (ei->i_file_acl &&
4288 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4289 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4290 ei->i_file_acl);
4291 ret = -EIO;
4292 goto bad_inode;
4293 } else if (!ext4_has_inline_data(inode)) {
4294 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4295 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4296 (S_ISLNK(inode->i_mode) &&
4297 !ext4_inode_is_fast_symlink(inode))))
4298 /* Validate extent which is part of inode */
4299 ret = ext4_ext_check_inode(inode);
4300 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4301 (S_ISLNK(inode->i_mode) &&
4302 !ext4_inode_is_fast_symlink(inode))) {
4303 /* Validate block references which are part of inode */
4304 ret = ext4_ind_check_inode(inode);
4307 if (ret)
4308 goto bad_inode;
4310 if (S_ISREG(inode->i_mode)) {
4311 inode->i_op = &ext4_file_inode_operations;
4312 inode->i_fop = &ext4_file_operations;
4313 ext4_set_aops(inode);
4314 } else if (S_ISDIR(inode->i_mode)) {
4315 inode->i_op = &ext4_dir_inode_operations;
4316 inode->i_fop = &ext4_dir_operations;
4317 } else if (S_ISLNK(inode->i_mode)) {
4318 if (ext4_inode_is_fast_symlink(inode) &&
4319 !ext4_encrypted_inode(inode)) {
4320 inode->i_op = &ext4_fast_symlink_inode_operations;
4321 nd_terminate_link(ei->i_data, inode->i_size,
4322 sizeof(ei->i_data) - 1);
4323 } else {
4324 inode->i_op = &ext4_symlink_inode_operations;
4325 ext4_set_aops(inode);
4327 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4328 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4329 inode->i_op = &ext4_special_inode_operations;
4330 if (raw_inode->i_block[0])
4331 init_special_inode(inode, inode->i_mode,
4332 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4333 else
4334 init_special_inode(inode, inode->i_mode,
4335 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4336 } else if (ino == EXT4_BOOT_LOADER_INO) {
4337 make_bad_inode(inode);
4338 } else {
4339 ret = -EIO;
4340 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4341 goto bad_inode;
4343 brelse(iloc.bh);
4344 ext4_set_inode_flags(inode);
4345 unlock_new_inode(inode);
4346 return inode;
4348 bad_inode:
4349 brelse(iloc.bh);
4350 iget_failed(inode);
4351 return ERR_PTR(ret);
4354 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4356 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4357 return ERR_PTR(-EIO);
4358 return ext4_iget(sb, ino);
4361 static int ext4_inode_blocks_set(handle_t *handle,
4362 struct ext4_inode *raw_inode,
4363 struct ext4_inode_info *ei)
4365 struct inode *inode = &(ei->vfs_inode);
4366 u64 i_blocks = inode->i_blocks;
4367 struct super_block *sb = inode->i_sb;
4369 if (i_blocks <= ~0U) {
4371 * i_blocks can be represented in a 32 bit variable
4372 * as multiple of 512 bytes
4374 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4375 raw_inode->i_blocks_high = 0;
4376 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4377 return 0;
4379 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4380 return -EFBIG;
4382 if (i_blocks <= 0xffffffffffffULL) {
4384 * i_blocks can be represented in a 48 bit variable
4385 * as multiple of 512 bytes
4387 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4388 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4389 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4390 } else {
4391 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4392 /* i_block is stored in file system block size */
4393 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4394 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4395 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4397 return 0;
4400 struct other_inode {
4401 unsigned long orig_ino;
4402 struct ext4_inode *raw_inode;
4405 static int other_inode_match(struct inode * inode, unsigned long ino,
4406 void *data)
4408 struct other_inode *oi = (struct other_inode *) data;
4410 if ((inode->i_ino != ino) ||
4411 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4412 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4413 ((inode->i_state & I_DIRTY_TIME) == 0))
4414 return 0;
4415 spin_lock(&inode->i_lock);
4416 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4417 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4418 (inode->i_state & I_DIRTY_TIME)) {
4419 struct ext4_inode_info *ei = EXT4_I(inode);
4421 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4422 spin_unlock(&inode->i_lock);
4424 spin_lock(&ei->i_raw_lock);
4425 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4426 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4427 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4428 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4429 spin_unlock(&ei->i_raw_lock);
4430 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4431 return -1;
4433 spin_unlock(&inode->i_lock);
4434 return -1;
4438 * Opportunistically update the other time fields for other inodes in
4439 * the same inode table block.
4441 static void ext4_update_other_inodes_time(struct super_block *sb,
4442 unsigned long orig_ino, char *buf)
4444 struct other_inode oi;
4445 unsigned long ino;
4446 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4447 int inode_size = EXT4_INODE_SIZE(sb);
4449 oi.orig_ino = orig_ino;
4451 * Calculate the first inode in the inode table block. Inode
4452 * numbers are one-based. That is, the first inode in a block
4453 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4455 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4456 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4457 if (ino == orig_ino)
4458 continue;
4459 oi.raw_inode = (struct ext4_inode *) buf;
4460 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4465 * Post the struct inode info into an on-disk inode location in the
4466 * buffer-cache. This gobbles the caller's reference to the
4467 * buffer_head in the inode location struct.
4469 * The caller must have write access to iloc->bh.
4471 static int ext4_do_update_inode(handle_t *handle,
4472 struct inode *inode,
4473 struct ext4_iloc *iloc)
4475 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4476 struct ext4_inode_info *ei = EXT4_I(inode);
4477 struct buffer_head *bh = iloc->bh;
4478 struct super_block *sb = inode->i_sb;
4479 int err = 0, rc, block;
4480 int need_datasync = 0, set_large_file = 0;
4481 uid_t i_uid;
4482 gid_t i_gid;
4484 spin_lock(&ei->i_raw_lock);
4486 /* For fields not tracked in the in-memory inode,
4487 * initialise them to zero for new inodes. */
4488 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4489 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4491 ext4_get_inode_flags(ei);
4492 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4493 i_uid = i_uid_read(inode);
4494 i_gid = i_gid_read(inode);
4495 if (!(test_opt(inode->i_sb, NO_UID32))) {
4496 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4497 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4499 * Fix up interoperability with old kernels. Otherwise, old inodes get
4500 * re-used with the upper 16 bits of the uid/gid intact
4502 if (!ei->i_dtime) {
4503 raw_inode->i_uid_high =
4504 cpu_to_le16(high_16_bits(i_uid));
4505 raw_inode->i_gid_high =
4506 cpu_to_le16(high_16_bits(i_gid));
4507 } else {
4508 raw_inode->i_uid_high = 0;
4509 raw_inode->i_gid_high = 0;
4511 } else {
4512 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4513 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4514 raw_inode->i_uid_high = 0;
4515 raw_inode->i_gid_high = 0;
4517 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4519 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4520 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4521 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4522 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4524 err = ext4_inode_blocks_set(handle, raw_inode, ei);
4525 if (err) {
4526 spin_unlock(&ei->i_raw_lock);
4527 goto out_brelse;
4529 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4530 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4531 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4532 raw_inode->i_file_acl_high =
4533 cpu_to_le16(ei->i_file_acl >> 32);
4534 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4535 if (ei->i_disksize != ext4_isize(raw_inode)) {
4536 ext4_isize_set(raw_inode, ei->i_disksize);
4537 need_datasync = 1;
4539 if (ei->i_disksize > 0x7fffffffULL) {
4540 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4541 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4542 EXT4_SB(sb)->s_es->s_rev_level ==
4543 cpu_to_le32(EXT4_GOOD_OLD_REV))
4544 set_large_file = 1;
4546 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4547 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4548 if (old_valid_dev(inode->i_rdev)) {
4549 raw_inode->i_block[0] =
4550 cpu_to_le32(old_encode_dev(inode->i_rdev));
4551 raw_inode->i_block[1] = 0;
4552 } else {
4553 raw_inode->i_block[0] = 0;
4554 raw_inode->i_block[1] =
4555 cpu_to_le32(new_encode_dev(inode->i_rdev));
4556 raw_inode->i_block[2] = 0;
4558 } else if (!ext4_has_inline_data(inode)) {
4559 for (block = 0; block < EXT4_N_BLOCKS; block++)
4560 raw_inode->i_block[block] = ei->i_data[block];
4563 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4564 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4565 if (ei->i_extra_isize) {
4566 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4567 raw_inode->i_version_hi =
4568 cpu_to_le32(inode->i_version >> 32);
4569 raw_inode->i_extra_isize =
4570 cpu_to_le16(ei->i_extra_isize);
4573 ext4_inode_csum_set(inode, raw_inode, ei);
4574 spin_unlock(&ei->i_raw_lock);
4575 if (inode->i_sb->s_flags & MS_LAZYTIME)
4576 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4577 bh->b_data);
4579 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4580 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4581 if (!err)
4582 err = rc;
4583 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4584 if (set_large_file) {
4585 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4586 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4587 if (err)
4588 goto out_brelse;
4589 ext4_update_dynamic_rev(sb);
4590 EXT4_SET_RO_COMPAT_FEATURE(sb,
4591 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4592 ext4_handle_sync(handle);
4593 err = ext4_handle_dirty_super(handle, sb);
4595 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4596 out_brelse:
4597 brelse(bh);
4598 ext4_std_error(inode->i_sb, err);
4599 return err;
4603 * ext4_write_inode()
4605 * We are called from a few places:
4607 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4608 * Here, there will be no transaction running. We wait for any running
4609 * transaction to commit.
4611 * - Within flush work (sys_sync(), kupdate and such).
4612 * We wait on commit, if told to.
4614 * - Within iput_final() -> write_inode_now()
4615 * We wait on commit, if told to.
4617 * In all cases it is actually safe for us to return without doing anything,
4618 * because the inode has been copied into a raw inode buffer in
4619 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4620 * writeback.
4622 * Note that we are absolutely dependent upon all inode dirtiers doing the
4623 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4624 * which we are interested.
4626 * It would be a bug for them to not do this. The code:
4628 * mark_inode_dirty(inode)
4629 * stuff();
4630 * inode->i_size = expr;
4632 * is in error because write_inode() could occur while `stuff()' is running,
4633 * and the new i_size will be lost. Plus the inode will no longer be on the
4634 * superblock's dirty inode list.
4636 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4638 int err;
4640 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4641 return 0;
4643 if (EXT4_SB(inode->i_sb)->s_journal) {
4644 if (ext4_journal_current_handle()) {
4645 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4646 dump_stack();
4647 return -EIO;
4651 * No need to force transaction in WB_SYNC_NONE mode. Also
4652 * ext4_sync_fs() will force the commit after everything is
4653 * written.
4655 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4656 return 0;
4658 err = ext4_force_commit(inode->i_sb);
4659 } else {
4660 struct ext4_iloc iloc;
4662 err = __ext4_get_inode_loc(inode, &iloc, 0);
4663 if (err)
4664 return err;
4666 * sync(2) will flush the whole buffer cache. No need to do
4667 * it here separately for each inode.
4669 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4670 sync_dirty_buffer(iloc.bh);
4671 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4672 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4673 "IO error syncing inode");
4674 err = -EIO;
4676 brelse(iloc.bh);
4678 return err;
4682 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4683 * buffers that are attached to a page stradding i_size and are undergoing
4684 * commit. In that case we have to wait for commit to finish and try again.
4686 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4688 struct page *page;
4689 unsigned offset;
4690 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4691 tid_t commit_tid = 0;
4692 int ret;
4694 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4696 * All buffers in the last page remain valid? Then there's nothing to
4697 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4698 * blocksize case
4700 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4701 return;
4702 while (1) {
4703 page = find_lock_page(inode->i_mapping,
4704 inode->i_size >> PAGE_CACHE_SHIFT);
4705 if (!page)
4706 return;
4707 ret = __ext4_journalled_invalidatepage(page, offset,
4708 PAGE_CACHE_SIZE - offset);
4709 unlock_page(page);
4710 page_cache_release(page);
4711 if (ret != -EBUSY)
4712 return;
4713 commit_tid = 0;
4714 read_lock(&journal->j_state_lock);
4715 if (journal->j_committing_transaction)
4716 commit_tid = journal->j_committing_transaction->t_tid;
4717 read_unlock(&journal->j_state_lock);
4718 if (commit_tid)
4719 jbd2_log_wait_commit(journal, commit_tid);
4724 * ext4_setattr()
4726 * Called from notify_change.
4728 * We want to trap VFS attempts to truncate the file as soon as
4729 * possible. In particular, we want to make sure that when the VFS
4730 * shrinks i_size, we put the inode on the orphan list and modify
4731 * i_disksize immediately, so that during the subsequent flushing of
4732 * dirty pages and freeing of disk blocks, we can guarantee that any
4733 * commit will leave the blocks being flushed in an unused state on
4734 * disk. (On recovery, the inode will get truncated and the blocks will
4735 * be freed, so we have a strong guarantee that no future commit will
4736 * leave these blocks visible to the user.)
4738 * Another thing we have to assure is that if we are in ordered mode
4739 * and inode is still attached to the committing transaction, we must
4740 * we start writeout of all the dirty pages which are being truncated.
4741 * This way we are sure that all the data written in the previous
4742 * transaction are already on disk (truncate waits for pages under
4743 * writeback).
4745 * Called with inode->i_mutex down.
4747 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4749 struct inode *inode = d_inode(dentry);
4750 int error, rc = 0;
4751 int orphan = 0;
4752 const unsigned int ia_valid = attr->ia_valid;
4754 error = setattr_prepare(dentry, attr);
4755 if (error)
4756 return error;
4758 if (is_quota_modification(inode, attr))
4759 dquot_initialize(inode);
4760 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4761 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4762 handle_t *handle;
4764 /* (user+group)*(old+new) structure, inode write (sb,
4765 * inode block, ? - but truncate inode update has it) */
4766 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4767 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4768 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4769 if (IS_ERR(handle)) {
4770 error = PTR_ERR(handle);
4771 goto err_out;
4773 error = dquot_transfer(inode, attr);
4774 if (error) {
4775 ext4_journal_stop(handle);
4776 return error;
4778 /* Update corresponding info in inode so that everything is in
4779 * one transaction */
4780 if (attr->ia_valid & ATTR_UID)
4781 inode->i_uid = attr->ia_uid;
4782 if (attr->ia_valid & ATTR_GID)
4783 inode->i_gid = attr->ia_gid;
4784 error = ext4_mark_inode_dirty(handle, inode);
4785 ext4_journal_stop(handle);
4788 if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
4789 handle_t *handle;
4791 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4792 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4794 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4795 return -EFBIG;
4798 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4799 inode_inc_iversion(inode);
4801 if (S_ISREG(inode->i_mode) &&
4802 (attr->ia_size < inode->i_size)) {
4803 if (ext4_should_order_data(inode)) {
4804 error = ext4_begin_ordered_truncate(inode,
4805 attr->ia_size);
4806 if (error)
4807 goto err_out;
4809 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4810 if (IS_ERR(handle)) {
4811 error = PTR_ERR(handle);
4812 goto err_out;
4814 if (ext4_handle_valid(handle)) {
4815 error = ext4_orphan_add(handle, inode);
4816 orphan = 1;
4818 down_write(&EXT4_I(inode)->i_data_sem);
4819 EXT4_I(inode)->i_disksize = attr->ia_size;
4820 rc = ext4_mark_inode_dirty(handle, inode);
4821 if (!error)
4822 error = rc;
4824 * We have to update i_size under i_data_sem together
4825 * with i_disksize to avoid races with writeback code
4826 * running ext4_wb_update_i_disksize().
4828 if (!error)
4829 i_size_write(inode, attr->ia_size);
4830 up_write(&EXT4_I(inode)->i_data_sem);
4831 ext4_journal_stop(handle);
4832 if (error) {
4833 ext4_orphan_del(NULL, inode);
4834 goto err_out;
4836 } else {
4837 loff_t oldsize = inode->i_size;
4839 i_size_write(inode, attr->ia_size);
4840 pagecache_isize_extended(inode, oldsize, inode->i_size);
4844 * Blocks are going to be removed from the inode. Wait
4845 * for dio in flight. Temporarily disable
4846 * dioread_nolock to prevent livelock.
4848 if (orphan) {
4849 if (!ext4_should_journal_data(inode)) {
4850 ext4_inode_block_unlocked_dio(inode);
4851 inode_dio_wait(inode);
4852 ext4_inode_resume_unlocked_dio(inode);
4853 } else
4854 ext4_wait_for_tail_page_commit(inode);
4856 down_write(&EXT4_I(inode)->i_mmap_sem);
4858 * Truncate pagecache after we've waited for commit
4859 * in data=journal mode to make pages freeable.
4861 truncate_pagecache(inode, inode->i_size);
4862 up_write(&EXT4_I(inode)->i_mmap_sem);
4865 * We want to call ext4_truncate() even if attr->ia_size ==
4866 * inode->i_size for cases like truncation of fallocated space
4868 if (attr->ia_valid & ATTR_SIZE)
4869 ext4_truncate(inode);
4871 if (!rc) {
4872 setattr_copy(inode, attr);
4873 mark_inode_dirty(inode);
4877 * If the call to ext4_truncate failed to get a transaction handle at
4878 * all, we need to clean up the in-core orphan list manually.
4880 if (orphan && inode->i_nlink)
4881 ext4_orphan_del(NULL, inode);
4883 if (!rc && (ia_valid & ATTR_MODE))
4884 rc = posix_acl_chmod(inode, inode->i_mode);
4886 err_out:
4887 ext4_std_error(inode->i_sb, error);
4888 if (!error)
4889 error = rc;
4890 return error;
4893 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4894 struct kstat *stat)
4896 struct inode *inode;
4897 unsigned long long delalloc_blocks;
4899 inode = d_inode(dentry);
4900 generic_fillattr(inode, stat);
4903 * If there is inline data in the inode, the inode will normally not
4904 * have data blocks allocated (it may have an external xattr block).
4905 * Report at least one sector for such files, so tools like tar, rsync,
4906 * others doen't incorrectly think the file is completely sparse.
4908 if (unlikely(ext4_has_inline_data(inode)))
4909 stat->blocks += (stat->size + 511) >> 9;
4912 * We can't update i_blocks if the block allocation is delayed
4913 * otherwise in the case of system crash before the real block
4914 * allocation is done, we will have i_blocks inconsistent with
4915 * on-disk file blocks.
4916 * We always keep i_blocks updated together with real
4917 * allocation. But to not confuse with user, stat
4918 * will return the blocks that include the delayed allocation
4919 * blocks for this file.
4921 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4922 EXT4_I(inode)->i_reserved_data_blocks);
4923 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
4924 return 0;
4927 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4928 int pextents)
4930 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4931 return ext4_ind_trans_blocks(inode, lblocks);
4932 return ext4_ext_index_trans_blocks(inode, pextents);
4936 * Account for index blocks, block groups bitmaps and block group
4937 * descriptor blocks if modify datablocks and index blocks
4938 * worse case, the indexs blocks spread over different block groups
4940 * If datablocks are discontiguous, they are possible to spread over
4941 * different block groups too. If they are contiguous, with flexbg,
4942 * they could still across block group boundary.
4944 * Also account for superblock, inode, quota and xattr blocks
4946 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4947 int pextents)
4949 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4950 int gdpblocks;
4951 int idxblocks;
4952 int ret = 0;
4955 * How many index blocks need to touch to map @lblocks logical blocks
4956 * to @pextents physical extents?
4958 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4960 ret = idxblocks;
4963 * Now let's see how many group bitmaps and group descriptors need
4964 * to account
4966 groups = idxblocks + pextents;
4967 gdpblocks = groups;
4968 if (groups > ngroups)
4969 groups = ngroups;
4970 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4971 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4973 /* bitmaps and block group descriptor blocks */
4974 ret += groups + gdpblocks;
4976 /* Blocks for super block, inode, quota and xattr blocks */
4977 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4979 return ret;
4983 * Calculate the total number of credits to reserve to fit
4984 * the modification of a single pages into a single transaction,
4985 * which may include multiple chunks of block allocations.
4987 * This could be called via ext4_write_begin()
4989 * We need to consider the worse case, when
4990 * one new block per extent.
4992 int ext4_writepage_trans_blocks(struct inode *inode)
4994 int bpp = ext4_journal_blocks_per_page(inode);
4995 int ret;
4997 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4999 /* Account for data blocks for journalled mode */
5000 if (ext4_should_journal_data(inode))
5001 ret += bpp;
5002 return ret;
5006 * Calculate the journal credits for a chunk of data modification.
5008 * This is called from DIO, fallocate or whoever calling
5009 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5011 * journal buffers for data blocks are not included here, as DIO
5012 * and fallocate do no need to journal data buffers.
5014 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5016 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5020 * The caller must have previously called ext4_reserve_inode_write().
5021 * Give this, we know that the caller already has write access to iloc->bh.
5023 int ext4_mark_iloc_dirty(handle_t *handle,
5024 struct inode *inode, struct ext4_iloc *iloc)
5026 int err = 0;
5028 if (IS_I_VERSION(inode))
5029 inode_inc_iversion(inode);
5031 /* the do_update_inode consumes one bh->b_count */
5032 get_bh(iloc->bh);
5034 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5035 err = ext4_do_update_inode(handle, inode, iloc);
5036 put_bh(iloc->bh);
5037 return err;
5041 * On success, We end up with an outstanding reference count against
5042 * iloc->bh. This _must_ be cleaned up later.
5046 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5047 struct ext4_iloc *iloc)
5049 int err;
5051 err = ext4_get_inode_loc(inode, iloc);
5052 if (!err) {
5053 BUFFER_TRACE(iloc->bh, "get_write_access");
5054 err = ext4_journal_get_write_access(handle, iloc->bh);
5055 if (err) {
5056 brelse(iloc->bh);
5057 iloc->bh = NULL;
5060 ext4_std_error(inode->i_sb, err);
5061 return err;
5065 * Expand an inode by new_extra_isize bytes.
5066 * Returns 0 on success or negative error number on failure.
5068 static int ext4_expand_extra_isize(struct inode *inode,
5069 unsigned int new_extra_isize,
5070 struct ext4_iloc iloc,
5071 handle_t *handle)
5073 struct ext4_inode *raw_inode;
5074 struct ext4_xattr_ibody_header *header;
5076 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5077 return 0;
5079 raw_inode = ext4_raw_inode(&iloc);
5081 header = IHDR(inode, raw_inode);
5083 /* No extended attributes present */
5084 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5085 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5086 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5087 new_extra_isize);
5088 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5089 return 0;
5092 /* try to expand with EAs present */
5093 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5094 raw_inode, handle);
5098 * What we do here is to mark the in-core inode as clean with respect to inode
5099 * dirtiness (it may still be data-dirty).
5100 * This means that the in-core inode may be reaped by prune_icache
5101 * without having to perform any I/O. This is a very good thing,
5102 * because *any* task may call prune_icache - even ones which
5103 * have a transaction open against a different journal.
5105 * Is this cheating? Not really. Sure, we haven't written the
5106 * inode out, but prune_icache isn't a user-visible syncing function.
5107 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5108 * we start and wait on commits.
5110 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5112 struct ext4_iloc iloc;
5113 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5114 static unsigned int mnt_count;
5115 int err, ret;
5117 might_sleep();
5118 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5119 err = ext4_reserve_inode_write(handle, inode, &iloc);
5120 if (err)
5121 return err;
5122 if (ext4_handle_valid(handle) &&
5123 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5124 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5126 * We need extra buffer credits since we may write into EA block
5127 * with this same handle. If journal_extend fails, then it will
5128 * only result in a minor loss of functionality for that inode.
5129 * If this is felt to be critical, then e2fsck should be run to
5130 * force a large enough s_min_extra_isize.
5132 if ((jbd2_journal_extend(handle,
5133 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5134 ret = ext4_expand_extra_isize(inode,
5135 sbi->s_want_extra_isize,
5136 iloc, handle);
5137 if (ret) {
5138 ext4_set_inode_state(inode,
5139 EXT4_STATE_NO_EXPAND);
5140 if (mnt_count !=
5141 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5142 ext4_warning(inode->i_sb,
5143 "Unable to expand inode %lu. Delete"
5144 " some EAs or run e2fsck.",
5145 inode->i_ino);
5146 mnt_count =
5147 le16_to_cpu(sbi->s_es->s_mnt_count);
5152 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5156 * ext4_dirty_inode() is called from __mark_inode_dirty()
5158 * We're really interested in the case where a file is being extended.
5159 * i_size has been changed by generic_commit_write() and we thus need
5160 * to include the updated inode in the current transaction.
5162 * Also, dquot_alloc_block() will always dirty the inode when blocks
5163 * are allocated to the file.
5165 * If the inode is marked synchronous, we don't honour that here - doing
5166 * so would cause a commit on atime updates, which we don't bother doing.
5167 * We handle synchronous inodes at the highest possible level.
5169 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5170 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5171 * to copy into the on-disk inode structure are the timestamp files.
5173 void ext4_dirty_inode(struct inode *inode, int flags)
5175 handle_t *handle;
5177 if (flags == I_DIRTY_TIME)
5178 return;
5179 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5180 if (IS_ERR(handle))
5181 goto out;
5183 ext4_mark_inode_dirty(handle, inode);
5185 ext4_journal_stop(handle);
5186 out:
5187 return;
5190 #if 0
5192 * Bind an inode's backing buffer_head into this transaction, to prevent
5193 * it from being flushed to disk early. Unlike
5194 * ext4_reserve_inode_write, this leaves behind no bh reference and
5195 * returns no iloc structure, so the caller needs to repeat the iloc
5196 * lookup to mark the inode dirty later.
5198 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5200 struct ext4_iloc iloc;
5202 int err = 0;
5203 if (handle) {
5204 err = ext4_get_inode_loc(inode, &iloc);
5205 if (!err) {
5206 BUFFER_TRACE(iloc.bh, "get_write_access");
5207 err = jbd2_journal_get_write_access(handle, iloc.bh);
5208 if (!err)
5209 err = ext4_handle_dirty_metadata(handle,
5210 NULL,
5211 iloc.bh);
5212 brelse(iloc.bh);
5215 ext4_std_error(inode->i_sb, err);
5216 return err;
5218 #endif
5220 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5222 journal_t *journal;
5223 handle_t *handle;
5224 int err;
5227 * We have to be very careful here: changing a data block's
5228 * journaling status dynamically is dangerous. If we write a
5229 * data block to the journal, change the status and then delete
5230 * that block, we risk forgetting to revoke the old log record
5231 * from the journal and so a subsequent replay can corrupt data.
5232 * So, first we make sure that the journal is empty and that
5233 * nobody is changing anything.
5236 journal = EXT4_JOURNAL(inode);
5237 if (!journal)
5238 return 0;
5239 if (is_journal_aborted(journal))
5240 return -EROFS;
5241 /* We have to allocate physical blocks for delalloc blocks
5242 * before flushing journal. otherwise delalloc blocks can not
5243 * be allocated any more. even more truncate on delalloc blocks
5244 * could trigger BUG by flushing delalloc blocks in journal.
5245 * There is no delalloc block in non-journal data mode.
5247 if (val && test_opt(inode->i_sb, DELALLOC)) {
5248 err = ext4_alloc_da_blocks(inode);
5249 if (err < 0)
5250 return err;
5253 /* Wait for all existing dio workers */
5254 ext4_inode_block_unlocked_dio(inode);
5255 inode_dio_wait(inode);
5257 jbd2_journal_lock_updates(journal);
5260 * OK, there are no updates running now, and all cached data is
5261 * synced to disk. We are now in a completely consistent state
5262 * which doesn't have anything in the journal, and we know that
5263 * no filesystem updates are running, so it is safe to modify
5264 * the inode's in-core data-journaling state flag now.
5267 if (val)
5268 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5269 else {
5270 err = jbd2_journal_flush(journal);
5271 if (err < 0) {
5272 jbd2_journal_unlock_updates(journal);
5273 ext4_inode_resume_unlocked_dio(inode);
5274 return err;
5276 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5278 ext4_set_aops(inode);
5280 jbd2_journal_unlock_updates(journal);
5281 ext4_inode_resume_unlocked_dio(inode);
5283 /* Finally we can mark the inode as dirty. */
5285 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5286 if (IS_ERR(handle))
5287 return PTR_ERR(handle);
5289 err = ext4_mark_inode_dirty(handle, inode);
5290 ext4_handle_sync(handle);
5291 ext4_journal_stop(handle);
5292 ext4_std_error(inode->i_sb, err);
5294 return err;
5297 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5299 return !buffer_mapped(bh);
5302 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5304 struct page *page = vmf->page;
5305 loff_t size;
5306 unsigned long len;
5307 int ret;
5308 struct file *file = vma->vm_file;
5309 struct inode *inode = file_inode(file);
5310 struct address_space *mapping = inode->i_mapping;
5311 handle_t *handle;
5312 get_block_t *get_block;
5313 int retries = 0;
5315 sb_start_pagefault(inode->i_sb);
5316 file_update_time(vma->vm_file);
5318 down_read(&EXT4_I(inode)->i_mmap_sem);
5319 /* Delalloc case is easy... */
5320 if (test_opt(inode->i_sb, DELALLOC) &&
5321 !ext4_should_journal_data(inode) &&
5322 !ext4_nonda_switch(inode->i_sb)) {
5323 do {
5324 ret = __block_page_mkwrite(vma, vmf,
5325 ext4_da_get_block_prep);
5326 } while (ret == -ENOSPC &&
5327 ext4_should_retry_alloc(inode->i_sb, &retries));
5328 goto out_ret;
5331 lock_page(page);
5332 size = i_size_read(inode);
5333 /* Page got truncated from under us? */
5334 if (page->mapping != mapping || page_offset(page) > size) {
5335 unlock_page(page);
5336 ret = VM_FAULT_NOPAGE;
5337 goto out;
5340 if (page->index == size >> PAGE_CACHE_SHIFT)
5341 len = size & ~PAGE_CACHE_MASK;
5342 else
5343 len = PAGE_CACHE_SIZE;
5345 * Return if we have all the buffers mapped. This avoids the need to do
5346 * journal_start/journal_stop which can block and take a long time
5348 if (page_has_buffers(page)) {
5349 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5350 0, len, NULL,
5351 ext4_bh_unmapped)) {
5352 /* Wait so that we don't change page under IO */
5353 wait_for_stable_page(page);
5354 ret = VM_FAULT_LOCKED;
5355 goto out;
5358 unlock_page(page);
5359 /* OK, we need to fill the hole... */
5360 if (ext4_should_dioread_nolock(inode))
5361 get_block = ext4_get_block_write;
5362 else
5363 get_block = ext4_get_block;
5364 retry_alloc:
5365 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5366 ext4_writepage_trans_blocks(inode));
5367 if (IS_ERR(handle)) {
5368 ret = VM_FAULT_SIGBUS;
5369 goto out;
5371 ret = __block_page_mkwrite(vma, vmf, get_block);
5372 if (!ret && ext4_should_journal_data(inode)) {
5373 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5374 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5375 unlock_page(page);
5376 ret = VM_FAULT_SIGBUS;
5377 ext4_journal_stop(handle);
5378 goto out;
5380 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5382 ext4_journal_stop(handle);
5383 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5384 goto retry_alloc;
5385 out_ret:
5386 ret = block_page_mkwrite_return(ret);
5387 out:
5388 up_read(&EXT4_I(inode)->i_mmap_sem);
5389 sb_end_pagefault(inode->i_sb);
5390 return ret;
5393 int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5395 struct inode *inode = file_inode(vma->vm_file);
5396 int err;
5398 down_read(&EXT4_I(inode)->i_mmap_sem);
5399 err = filemap_fault(vma, vmf);
5400 up_read(&EXT4_I(inode)->i_mmap_sem);
5402 return err;