ext4: do not delete unlinked inode from orphan list on failed truncate
[linux-stable.git] / fs / ext4 / inode.c
blob862766a1b080e8f9b32b109c00b3f3696d883954
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * linux/fs/ext4/inode.c
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
10 * from
12 * linux/fs/minix/inode.c
14 * Copyright (C) 1991, 1992 Linus Torvalds
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
22 #include <linux/fs.h>
23 #include <linux/time.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/dax.h>
27 #include <linux/quotaops.h>
28 #include <linux/string.h>
29 #include <linux/buffer_head.h>
30 #include <linux/writeback.h>
31 #include <linux/pagevec.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/uio.h>
35 #include <linux/bio.h>
36 #include <linux/workqueue.h>
37 #include <linux/kernel.h>
38 #include <linux/printk.h>
39 #include <linux/slab.h>
40 #include <linux/bitops.h>
41 #include <linux/iomap.h>
43 #include "ext4_jbd2.h"
44 #include "xattr.h"
45 #include "acl.h"
46 #include "truncate.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 __u32 csum;
57 __u16 dummy_csum = 0;
58 int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 unsigned int csum_size = sizeof(dummy_csum);
61 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 offset += csum_size;
64 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 EXT4_GOOD_OLD_INODE_SIZE - offset);
67 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 offset = offsetof(struct ext4_inode, i_checksum_hi);
69 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 EXT4_GOOD_OLD_INODE_SIZE,
71 offset - EXT4_GOOD_OLD_INODE_SIZE);
72 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74 csum_size);
75 offset += csum_size;
77 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 EXT4_INODE_SIZE(inode->i_sb) - offset);
81 return csum;
84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 struct ext4_inode_info *ei)
87 __u32 provided, calculated;
89 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 cpu_to_le32(EXT4_OS_LINUX) ||
91 !ext4_has_metadata_csum(inode->i_sb))
92 return 1;
94 provided = le16_to_cpu(raw->i_checksum_lo);
95 calculated = ext4_inode_csum(inode, raw, ei);
96 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
99 else
100 calculated &= 0xFFFF;
102 return provided == calculated;
105 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 struct ext4_inode_info *ei)
108 __u32 csum;
110 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 cpu_to_le32(EXT4_OS_LINUX) ||
112 !ext4_has_metadata_csum(inode->i_sb))
113 return;
115 csum = ext4_inode_csum(inode, raw, ei);
116 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
123 loff_t new_size)
125 trace_ext4_begin_ordered_truncate(inode, new_size);
127 * If jinode is zero, then we never opened the file for
128 * writing, so there's no need to call
129 * jbd2_journal_begin_ordered_truncate() since there's no
130 * outstanding writes we need to flush.
132 if (!EXT4_I(inode)->jinode)
133 return 0;
134 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 EXT4_I(inode)->jinode,
136 new_size);
139 static void ext4_invalidatepage(struct page *page, unsigned int offset,
140 unsigned int length);
141 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
142 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
143 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
144 int pextents);
147 * Test whether an inode is a fast symlink.
148 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
150 int ext4_inode_is_fast_symlink(struct inode *inode)
152 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
153 int ea_blocks = EXT4_I(inode)->i_file_acl ?
154 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
156 if (ext4_has_inline_data(inode))
157 return 0;
159 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
161 return S_ISLNK(inode->i_mode) && inode->i_size &&
162 (inode->i_size < EXT4_N_BLOCKS * 4);
166 * Restart the transaction associated with *handle. This does a commit,
167 * so before we call here everything must be consistently dirtied against
168 * this transaction.
170 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
171 int nblocks)
173 int ret;
176 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
177 * moment, get_block can be called only for blocks inside i_size since
178 * page cache has been already dropped and writes are blocked by
179 * i_mutex. So we can safely drop the i_data_sem here.
181 BUG_ON(EXT4_JOURNAL(inode) == NULL);
182 jbd_debug(2, "restarting handle %p\n", handle);
183 up_write(&EXT4_I(inode)->i_data_sem);
184 ret = ext4_journal_restart(handle, nblocks);
185 down_write(&EXT4_I(inode)->i_data_sem);
186 ext4_discard_preallocations(inode);
188 return ret;
192 * Called at the last iput() if i_nlink is zero.
194 void ext4_evict_inode(struct inode *inode)
196 handle_t *handle;
197 int err;
198 int extra_credits = 3;
199 struct ext4_xattr_inode_array *ea_inode_array = NULL;
201 trace_ext4_evict_inode(inode);
203 if (inode->i_nlink) {
205 * When journalling data dirty buffers are tracked only in the
206 * journal. So although mm thinks everything is clean and
207 * ready for reaping the inode might still have some pages to
208 * write in the running transaction or waiting to be
209 * checkpointed. Thus calling jbd2_journal_invalidatepage()
210 * (via truncate_inode_pages()) to discard these buffers can
211 * cause data loss. Also even if we did not discard these
212 * buffers, we would have no way to find them after the inode
213 * is reaped and thus user could see stale data if he tries to
214 * read them before the transaction is checkpointed. So be
215 * careful and force everything to disk here... We use
216 * ei->i_datasync_tid to store the newest transaction
217 * containing inode's data.
219 * Note that directories do not have this problem because they
220 * don't use page cache.
222 if (inode->i_ino != EXT4_JOURNAL_INO &&
223 ext4_should_journal_data(inode) &&
224 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
225 inode->i_data.nrpages) {
226 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
227 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
229 jbd2_complete_transaction(journal, commit_tid);
230 filemap_write_and_wait(&inode->i_data);
232 truncate_inode_pages_final(&inode->i_data);
234 goto no_delete;
237 if (is_bad_inode(inode))
238 goto no_delete;
239 dquot_initialize(inode);
241 if (ext4_should_order_data(inode))
242 ext4_begin_ordered_truncate(inode, 0);
243 truncate_inode_pages_final(&inode->i_data);
246 * Protect us against freezing - iput() caller didn't have to have any
247 * protection against it
249 sb_start_intwrite(inode->i_sb);
251 if (!IS_NOQUOTA(inode))
252 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
254 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
255 ext4_blocks_for_truncate(inode)+extra_credits);
256 if (IS_ERR(handle)) {
257 ext4_std_error(inode->i_sb, PTR_ERR(handle));
259 * If we're going to skip the normal cleanup, we still need to
260 * make sure that the in-core orphan linked list is properly
261 * cleaned up.
263 ext4_orphan_del(NULL, inode);
264 sb_end_intwrite(inode->i_sb);
265 goto no_delete;
268 if (IS_SYNC(inode))
269 ext4_handle_sync(handle);
272 * Set inode->i_size to 0 before calling ext4_truncate(). We need
273 * special handling of symlinks here because i_size is used to
274 * determine whether ext4_inode_info->i_data contains symlink data or
275 * block mappings. Setting i_size to 0 will remove its fast symlink
276 * status. Erase i_data so that it becomes a valid empty block map.
278 if (ext4_inode_is_fast_symlink(inode))
279 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
280 inode->i_size = 0;
281 err = ext4_mark_inode_dirty(handle, inode);
282 if (err) {
283 ext4_warning(inode->i_sb,
284 "couldn't mark inode dirty (err %d)", err);
285 goto stop_handle;
287 if (inode->i_blocks) {
288 err = ext4_truncate(inode);
289 if (err) {
290 ext4_error(inode->i_sb,
291 "couldn't truncate inode %lu (err %d)",
292 inode->i_ino, err);
293 goto stop_handle;
297 /* Remove xattr references. */
298 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
299 extra_credits);
300 if (err) {
301 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
302 stop_handle:
303 ext4_journal_stop(handle);
304 ext4_orphan_del(NULL, inode);
305 sb_end_intwrite(inode->i_sb);
306 ext4_xattr_inode_array_free(ea_inode_array);
307 goto no_delete;
311 * Kill off the orphan record which ext4_truncate created.
312 * AKPM: I think this can be inside the above `if'.
313 * Note that ext4_orphan_del() has to be able to cope with the
314 * deletion of a non-existent orphan - this is because we don't
315 * know if ext4_truncate() actually created an orphan record.
316 * (Well, we could do this if we need to, but heck - it works)
318 ext4_orphan_del(handle, inode);
319 EXT4_I(inode)->i_dtime = get_seconds();
322 * One subtle ordering requirement: if anything has gone wrong
323 * (transaction abort, IO errors, whatever), then we can still
324 * do these next steps (the fs will already have been marked as
325 * having errors), but we can't free the inode if the mark_dirty
326 * fails.
328 if (ext4_mark_inode_dirty(handle, inode))
329 /* If that failed, just do the required in-core inode clear. */
330 ext4_clear_inode(inode);
331 else
332 ext4_free_inode(handle, inode);
333 ext4_journal_stop(handle);
334 sb_end_intwrite(inode->i_sb);
335 ext4_xattr_inode_array_free(ea_inode_array);
336 return;
337 no_delete:
338 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
341 #ifdef CONFIG_QUOTA
342 qsize_t *ext4_get_reserved_space(struct inode *inode)
344 return &EXT4_I(inode)->i_reserved_quota;
346 #endif
349 * Called with i_data_sem down, which is important since we can call
350 * ext4_discard_preallocations() from here.
352 void ext4_da_update_reserve_space(struct inode *inode,
353 int used, int quota_claim)
355 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
356 struct ext4_inode_info *ei = EXT4_I(inode);
358 spin_lock(&ei->i_block_reservation_lock);
359 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
360 if (unlikely(used > ei->i_reserved_data_blocks)) {
361 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
362 "with only %d reserved data blocks",
363 __func__, inode->i_ino, used,
364 ei->i_reserved_data_blocks);
365 WARN_ON(1);
366 used = ei->i_reserved_data_blocks;
369 /* Update per-inode reservations */
370 ei->i_reserved_data_blocks -= used;
371 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
373 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
375 /* Update quota subsystem for data blocks */
376 if (quota_claim)
377 dquot_claim_block(inode, EXT4_C2B(sbi, used));
378 else {
380 * We did fallocate with an offset that is already delayed
381 * allocated. So on delayed allocated writeback we should
382 * not re-claim the quota for fallocated blocks.
384 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
388 * If we have done all the pending block allocations and if
389 * there aren't any writers on the inode, we can discard the
390 * inode's preallocations.
392 if ((ei->i_reserved_data_blocks == 0) &&
393 (atomic_read(&inode->i_writecount) == 0))
394 ext4_discard_preallocations(inode);
397 static int __check_block_validity(struct inode *inode, const char *func,
398 unsigned int line,
399 struct ext4_map_blocks *map)
401 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
402 map->m_len)) {
403 ext4_error_inode(inode, func, line, map->m_pblk,
404 "lblock %lu mapped to illegal pblock %llu "
405 "(length %d)", (unsigned long) map->m_lblk,
406 map->m_pblk, map->m_len);
407 return -EFSCORRUPTED;
409 return 0;
412 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
413 ext4_lblk_t len)
415 int ret;
417 if (ext4_encrypted_inode(inode))
418 return fscrypt_zeroout_range(inode, lblk, pblk, len);
420 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
421 if (ret > 0)
422 ret = 0;
424 return ret;
427 #define check_block_validity(inode, map) \
428 __check_block_validity((inode), __func__, __LINE__, (map))
430 #ifdef ES_AGGRESSIVE_TEST
431 static void ext4_map_blocks_es_recheck(handle_t *handle,
432 struct inode *inode,
433 struct ext4_map_blocks *es_map,
434 struct ext4_map_blocks *map,
435 int flags)
437 int retval;
439 map->m_flags = 0;
441 * There is a race window that the result is not the same.
442 * e.g. xfstests #223 when dioread_nolock enables. The reason
443 * is that we lookup a block mapping in extent status tree with
444 * out taking i_data_sem. So at the time the unwritten extent
445 * could be converted.
447 down_read(&EXT4_I(inode)->i_data_sem);
448 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
449 retval = ext4_ext_map_blocks(handle, inode, map, flags &
450 EXT4_GET_BLOCKS_KEEP_SIZE);
451 } else {
452 retval = ext4_ind_map_blocks(handle, inode, map, flags &
453 EXT4_GET_BLOCKS_KEEP_SIZE);
455 up_read((&EXT4_I(inode)->i_data_sem));
458 * We don't check m_len because extent will be collpased in status
459 * tree. So the m_len might not equal.
461 if (es_map->m_lblk != map->m_lblk ||
462 es_map->m_flags != map->m_flags ||
463 es_map->m_pblk != map->m_pblk) {
464 printk("ES cache assertion failed for inode: %lu "
465 "es_cached ex [%d/%d/%llu/%x] != "
466 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
467 inode->i_ino, es_map->m_lblk, es_map->m_len,
468 es_map->m_pblk, es_map->m_flags, map->m_lblk,
469 map->m_len, map->m_pblk, map->m_flags,
470 retval, flags);
473 #endif /* ES_AGGRESSIVE_TEST */
476 * The ext4_map_blocks() function tries to look up the requested blocks,
477 * and returns if the blocks are already mapped.
479 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
480 * and store the allocated blocks in the result buffer head and mark it
481 * mapped.
483 * If file type is extents based, it will call ext4_ext_map_blocks(),
484 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
485 * based files
487 * On success, it returns the number of blocks being mapped or allocated. if
488 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
489 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
491 * It returns 0 if plain look up failed (blocks have not been allocated), in
492 * that case, @map is returned as unmapped but we still do fill map->m_len to
493 * indicate the length of a hole starting at map->m_lblk.
495 * It returns the error in case of allocation failure.
497 int ext4_map_blocks(handle_t *handle, struct inode *inode,
498 struct ext4_map_blocks *map, int flags)
500 struct extent_status es;
501 int retval;
502 int ret = 0;
503 #ifdef ES_AGGRESSIVE_TEST
504 struct ext4_map_blocks orig_map;
506 memcpy(&orig_map, map, sizeof(*map));
507 #endif
509 map->m_flags = 0;
510 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
511 "logical block %lu\n", inode->i_ino, flags, map->m_len,
512 (unsigned long) map->m_lblk);
515 * ext4_map_blocks returns an int, and m_len is an unsigned int
517 if (unlikely(map->m_len > INT_MAX))
518 map->m_len = INT_MAX;
520 /* We can handle the block number less than EXT_MAX_BLOCKS */
521 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
522 return -EFSCORRUPTED;
524 /* Lookup extent status tree firstly */
525 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
526 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
527 map->m_pblk = ext4_es_pblock(&es) +
528 map->m_lblk - es.es_lblk;
529 map->m_flags |= ext4_es_is_written(&es) ?
530 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
531 retval = es.es_len - (map->m_lblk - es.es_lblk);
532 if (retval > map->m_len)
533 retval = map->m_len;
534 map->m_len = retval;
535 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
536 map->m_pblk = 0;
537 retval = es.es_len - (map->m_lblk - es.es_lblk);
538 if (retval > map->m_len)
539 retval = map->m_len;
540 map->m_len = retval;
541 retval = 0;
542 } else {
543 BUG_ON(1);
545 #ifdef ES_AGGRESSIVE_TEST
546 ext4_map_blocks_es_recheck(handle, inode, map,
547 &orig_map, flags);
548 #endif
549 goto found;
553 * Try to see if we can get the block without requesting a new
554 * file system block.
556 down_read(&EXT4_I(inode)->i_data_sem);
557 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
558 retval = ext4_ext_map_blocks(handle, inode, map, flags &
559 EXT4_GET_BLOCKS_KEEP_SIZE);
560 } else {
561 retval = ext4_ind_map_blocks(handle, inode, map, flags &
562 EXT4_GET_BLOCKS_KEEP_SIZE);
564 if (retval > 0) {
565 unsigned int status;
567 if (unlikely(retval != map->m_len)) {
568 ext4_warning(inode->i_sb,
569 "ES len assertion failed for inode "
570 "%lu: retval %d != map->m_len %d",
571 inode->i_ino, retval, map->m_len);
572 WARN_ON(1);
575 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
576 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
577 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
578 !(status & EXTENT_STATUS_WRITTEN) &&
579 ext4_find_delalloc_range(inode, map->m_lblk,
580 map->m_lblk + map->m_len - 1))
581 status |= EXTENT_STATUS_DELAYED;
582 ret = ext4_es_insert_extent(inode, map->m_lblk,
583 map->m_len, map->m_pblk, status);
584 if (ret < 0)
585 retval = ret;
587 up_read((&EXT4_I(inode)->i_data_sem));
589 found:
590 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
591 ret = check_block_validity(inode, map);
592 if (ret != 0)
593 return ret;
596 /* If it is only a block(s) look up */
597 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
598 return retval;
601 * Returns if the blocks have already allocated
603 * Note that if blocks have been preallocated
604 * ext4_ext_get_block() returns the create = 0
605 * with buffer head unmapped.
607 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
609 * If we need to convert extent to unwritten
610 * we continue and do the actual work in
611 * ext4_ext_map_blocks()
613 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
614 return retval;
617 * Here we clear m_flags because after allocating an new extent,
618 * it will be set again.
620 map->m_flags &= ~EXT4_MAP_FLAGS;
623 * New blocks allocate and/or writing to unwritten extent
624 * will possibly result in updating i_data, so we take
625 * the write lock of i_data_sem, and call get_block()
626 * with create == 1 flag.
628 down_write(&EXT4_I(inode)->i_data_sem);
631 * We need to check for EXT4 here because migrate
632 * could have changed the inode type in between
634 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
635 retval = ext4_ext_map_blocks(handle, inode, map, flags);
636 } else {
637 retval = ext4_ind_map_blocks(handle, inode, map, flags);
639 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
641 * We allocated new blocks which will result in
642 * i_data's format changing. Force the migrate
643 * to fail by clearing migrate flags
645 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
649 * Update reserved blocks/metadata blocks after successful
650 * block allocation which had been deferred till now. We don't
651 * support fallocate for non extent files. So we can update
652 * reserve space here.
654 if ((retval > 0) &&
655 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
656 ext4_da_update_reserve_space(inode, retval, 1);
659 if (retval > 0) {
660 unsigned int status;
662 if (unlikely(retval != map->m_len)) {
663 ext4_warning(inode->i_sb,
664 "ES len assertion failed for inode "
665 "%lu: retval %d != map->m_len %d",
666 inode->i_ino, retval, map->m_len);
667 WARN_ON(1);
671 * We have to zeroout blocks before inserting them into extent
672 * status tree. Otherwise someone could look them up there and
673 * use them before they are really zeroed. We also have to
674 * unmap metadata before zeroing as otherwise writeback can
675 * overwrite zeros with stale data from block device.
677 if (flags & EXT4_GET_BLOCKS_ZERO &&
678 map->m_flags & EXT4_MAP_MAPPED &&
679 map->m_flags & EXT4_MAP_NEW) {
680 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
681 map->m_len);
682 ret = ext4_issue_zeroout(inode, map->m_lblk,
683 map->m_pblk, map->m_len);
684 if (ret) {
685 retval = ret;
686 goto out_sem;
691 * If the extent has been zeroed out, we don't need to update
692 * extent status tree.
694 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
695 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
696 if (ext4_es_is_written(&es))
697 goto out_sem;
699 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
700 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
701 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
702 !(status & EXTENT_STATUS_WRITTEN) &&
703 ext4_find_delalloc_range(inode, map->m_lblk,
704 map->m_lblk + map->m_len - 1))
705 status |= EXTENT_STATUS_DELAYED;
706 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
707 map->m_pblk, status);
708 if (ret < 0) {
709 retval = ret;
710 goto out_sem;
714 out_sem:
715 up_write((&EXT4_I(inode)->i_data_sem));
716 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
717 ret = check_block_validity(inode, map);
718 if (ret != 0)
719 return ret;
722 * Inodes with freshly allocated blocks where contents will be
723 * visible after transaction commit must be on transaction's
724 * ordered data list.
726 if (map->m_flags & EXT4_MAP_NEW &&
727 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
728 !(flags & EXT4_GET_BLOCKS_ZERO) &&
729 !ext4_is_quota_file(inode) &&
730 ext4_should_order_data(inode)) {
731 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
732 ret = ext4_jbd2_inode_add_wait(handle, inode);
733 else
734 ret = ext4_jbd2_inode_add_write(handle, inode);
735 if (ret)
736 return ret;
739 return retval;
743 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
744 * we have to be careful as someone else may be manipulating b_state as well.
746 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
748 unsigned long old_state;
749 unsigned long new_state;
751 flags &= EXT4_MAP_FLAGS;
753 /* Dummy buffer_head? Set non-atomically. */
754 if (!bh->b_page) {
755 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
756 return;
759 * Someone else may be modifying b_state. Be careful! This is ugly but
760 * once we get rid of using bh as a container for mapping information
761 * to pass to / from get_block functions, this can go away.
763 do {
764 old_state = READ_ONCE(bh->b_state);
765 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
766 } while (unlikely(
767 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
770 static int _ext4_get_block(struct inode *inode, sector_t iblock,
771 struct buffer_head *bh, int flags)
773 struct ext4_map_blocks map;
774 int ret = 0;
776 if (ext4_has_inline_data(inode))
777 return -ERANGE;
779 map.m_lblk = iblock;
780 map.m_len = bh->b_size >> inode->i_blkbits;
782 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
783 flags);
784 if (ret > 0) {
785 map_bh(bh, inode->i_sb, map.m_pblk);
786 ext4_update_bh_state(bh, map.m_flags);
787 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
788 ret = 0;
789 } else if (ret == 0) {
790 /* hole case, need to fill in bh->b_size */
791 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
793 return ret;
796 int ext4_get_block(struct inode *inode, sector_t iblock,
797 struct buffer_head *bh, int create)
799 return _ext4_get_block(inode, iblock, bh,
800 create ? EXT4_GET_BLOCKS_CREATE : 0);
804 * Get block function used when preparing for buffered write if we require
805 * creating an unwritten extent if blocks haven't been allocated. The extent
806 * will be converted to written after the IO is complete.
808 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
809 struct buffer_head *bh_result, int create)
811 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
812 inode->i_ino, create);
813 return _ext4_get_block(inode, iblock, bh_result,
814 EXT4_GET_BLOCKS_IO_CREATE_EXT);
817 /* Maximum number of blocks we map for direct IO at once. */
818 #define DIO_MAX_BLOCKS 4096
821 * Get blocks function for the cases that need to start a transaction -
822 * generally difference cases of direct IO and DAX IO. It also handles retries
823 * in case of ENOSPC.
825 static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
826 struct buffer_head *bh_result, int flags)
828 int dio_credits;
829 handle_t *handle;
830 int retries = 0;
831 int ret;
833 /* Trim mapping request to maximum we can map at once for DIO */
834 if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
835 bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
836 dio_credits = ext4_chunk_trans_blocks(inode,
837 bh_result->b_size >> inode->i_blkbits);
838 retry:
839 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
840 if (IS_ERR(handle))
841 return PTR_ERR(handle);
843 ret = _ext4_get_block(inode, iblock, bh_result, flags);
844 ext4_journal_stop(handle);
846 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
847 goto retry;
848 return ret;
851 /* Get block function for DIO reads and writes to inodes without extents */
852 int ext4_dio_get_block(struct inode *inode, sector_t iblock,
853 struct buffer_head *bh, int create)
855 /* We don't expect handle for direct IO */
856 WARN_ON_ONCE(ext4_journal_current_handle());
858 if (!create)
859 return _ext4_get_block(inode, iblock, bh, 0);
860 return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
864 * Get block function for AIO DIO writes when we create unwritten extent if
865 * blocks are not allocated yet. The extent will be converted to written
866 * after IO is complete.
868 static int ext4_dio_get_block_unwritten_async(struct inode *inode,
869 sector_t iblock, struct buffer_head *bh_result, int create)
871 int ret;
873 /* We don't expect handle for direct IO */
874 WARN_ON_ONCE(ext4_journal_current_handle());
876 ret = ext4_get_block_trans(inode, iblock, bh_result,
877 EXT4_GET_BLOCKS_IO_CREATE_EXT);
880 * When doing DIO using unwritten extents, we need io_end to convert
881 * unwritten extents to written on IO completion. We allocate io_end
882 * once we spot unwritten extent and store it in b_private. Generic
883 * DIO code keeps b_private set and furthermore passes the value to
884 * our completion callback in 'private' argument.
886 if (!ret && buffer_unwritten(bh_result)) {
887 if (!bh_result->b_private) {
888 ext4_io_end_t *io_end;
890 io_end = ext4_init_io_end(inode, GFP_KERNEL);
891 if (!io_end)
892 return -ENOMEM;
893 bh_result->b_private = io_end;
894 ext4_set_io_unwritten_flag(inode, io_end);
896 set_buffer_defer_completion(bh_result);
899 return ret;
903 * Get block function for non-AIO DIO writes when we create unwritten extent if
904 * blocks are not allocated yet. The extent will be converted to written
905 * after IO is complete by ext4_direct_IO_write().
907 static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
908 sector_t iblock, struct buffer_head *bh_result, int create)
910 int ret;
912 /* We don't expect handle for direct IO */
913 WARN_ON_ONCE(ext4_journal_current_handle());
915 ret = ext4_get_block_trans(inode, iblock, bh_result,
916 EXT4_GET_BLOCKS_IO_CREATE_EXT);
919 * Mark inode as having pending DIO writes to unwritten extents.
920 * ext4_direct_IO_write() checks this flag and converts extents to
921 * written.
923 if (!ret && buffer_unwritten(bh_result))
924 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
926 return ret;
929 static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
930 struct buffer_head *bh_result, int create)
932 int ret;
934 ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
935 inode->i_ino, create);
936 /* We don't expect handle for direct IO */
937 WARN_ON_ONCE(ext4_journal_current_handle());
939 ret = _ext4_get_block(inode, iblock, bh_result, 0);
941 * Blocks should have been preallocated! ext4_file_write_iter() checks
942 * that.
944 WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
946 return ret;
951 * `handle' can be NULL if create is zero
953 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
954 ext4_lblk_t block, int map_flags)
956 struct ext4_map_blocks map;
957 struct buffer_head *bh;
958 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
959 int err;
961 J_ASSERT(handle != NULL || create == 0);
963 map.m_lblk = block;
964 map.m_len = 1;
965 err = ext4_map_blocks(handle, inode, &map, map_flags);
967 if (err == 0)
968 return create ? ERR_PTR(-ENOSPC) : NULL;
969 if (err < 0)
970 return ERR_PTR(err);
972 bh = sb_getblk(inode->i_sb, map.m_pblk);
973 if (unlikely(!bh))
974 return ERR_PTR(-ENOMEM);
975 if (map.m_flags & EXT4_MAP_NEW) {
976 J_ASSERT(create != 0);
977 J_ASSERT(handle != NULL);
980 * Now that we do not always journal data, we should
981 * keep in mind whether this should always journal the
982 * new buffer as metadata. For now, regular file
983 * writes use ext4_get_block instead, so it's not a
984 * problem.
986 lock_buffer(bh);
987 BUFFER_TRACE(bh, "call get_create_access");
988 err = ext4_journal_get_create_access(handle, bh);
989 if (unlikely(err)) {
990 unlock_buffer(bh);
991 goto errout;
993 if (!buffer_uptodate(bh)) {
994 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
995 set_buffer_uptodate(bh);
997 unlock_buffer(bh);
998 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
999 err = ext4_handle_dirty_metadata(handle, inode, bh);
1000 if (unlikely(err))
1001 goto errout;
1002 } else
1003 BUFFER_TRACE(bh, "not a new buffer");
1004 return bh;
1005 errout:
1006 brelse(bh);
1007 return ERR_PTR(err);
1010 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1011 ext4_lblk_t block, int map_flags)
1013 struct buffer_head *bh;
1015 bh = ext4_getblk(handle, inode, block, map_flags);
1016 if (IS_ERR(bh))
1017 return bh;
1018 if (!bh || buffer_uptodate(bh))
1019 return bh;
1020 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
1021 wait_on_buffer(bh);
1022 if (buffer_uptodate(bh))
1023 return bh;
1024 put_bh(bh);
1025 return ERR_PTR(-EIO);
1028 /* Read a contiguous batch of blocks. */
1029 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1030 bool wait, struct buffer_head **bhs)
1032 int i, err;
1034 for (i = 0; i < bh_count; i++) {
1035 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1036 if (IS_ERR(bhs[i])) {
1037 err = PTR_ERR(bhs[i]);
1038 bh_count = i;
1039 goto out_brelse;
1043 for (i = 0; i < bh_count; i++)
1044 /* Note that NULL bhs[i] is valid because of holes. */
1045 if (bhs[i] && !buffer_uptodate(bhs[i]))
1046 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
1047 &bhs[i]);
1049 if (!wait)
1050 return 0;
1052 for (i = 0; i < bh_count; i++)
1053 if (bhs[i])
1054 wait_on_buffer(bhs[i]);
1056 for (i = 0; i < bh_count; i++) {
1057 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1058 err = -EIO;
1059 goto out_brelse;
1062 return 0;
1064 out_brelse:
1065 for (i = 0; i < bh_count; i++) {
1066 brelse(bhs[i]);
1067 bhs[i] = NULL;
1069 return err;
1072 int ext4_walk_page_buffers(handle_t *handle,
1073 struct buffer_head *head,
1074 unsigned from,
1075 unsigned to,
1076 int *partial,
1077 int (*fn)(handle_t *handle,
1078 struct buffer_head *bh))
1080 struct buffer_head *bh;
1081 unsigned block_start, block_end;
1082 unsigned blocksize = head->b_size;
1083 int err, ret = 0;
1084 struct buffer_head *next;
1086 for (bh = head, block_start = 0;
1087 ret == 0 && (bh != head || !block_start);
1088 block_start = block_end, bh = next) {
1089 next = bh->b_this_page;
1090 block_end = block_start + blocksize;
1091 if (block_end <= from || block_start >= to) {
1092 if (partial && !buffer_uptodate(bh))
1093 *partial = 1;
1094 continue;
1096 err = (*fn)(handle, bh);
1097 if (!ret)
1098 ret = err;
1100 return ret;
1104 * To preserve ordering, it is essential that the hole instantiation and
1105 * the data write be encapsulated in a single transaction. We cannot
1106 * close off a transaction and start a new one between the ext4_get_block()
1107 * and the commit_write(). So doing the jbd2_journal_start at the start of
1108 * prepare_write() is the right place.
1110 * Also, this function can nest inside ext4_writepage(). In that case, we
1111 * *know* that ext4_writepage() has generated enough buffer credits to do the
1112 * whole page. So we won't block on the journal in that case, which is good,
1113 * because the caller may be PF_MEMALLOC.
1115 * By accident, ext4 can be reentered when a transaction is open via
1116 * quota file writes. If we were to commit the transaction while thus
1117 * reentered, there can be a deadlock - we would be holding a quota
1118 * lock, and the commit would never complete if another thread had a
1119 * transaction open and was blocking on the quota lock - a ranking
1120 * violation.
1122 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1123 * will _not_ run commit under these circumstances because handle->h_ref
1124 * is elevated. We'll still have enough credits for the tiny quotafile
1125 * write.
1127 int do_journal_get_write_access(handle_t *handle,
1128 struct buffer_head *bh)
1130 int dirty = buffer_dirty(bh);
1131 int ret;
1133 if (!buffer_mapped(bh) || buffer_freed(bh))
1134 return 0;
1136 * __block_write_begin() could have dirtied some buffers. Clean
1137 * the dirty bit as jbd2_journal_get_write_access() could complain
1138 * otherwise about fs integrity issues. Setting of the dirty bit
1139 * by __block_write_begin() isn't a real problem here as we clear
1140 * the bit before releasing a page lock and thus writeback cannot
1141 * ever write the buffer.
1143 if (dirty)
1144 clear_buffer_dirty(bh);
1145 BUFFER_TRACE(bh, "get write access");
1146 ret = ext4_journal_get_write_access(handle, bh);
1147 if (!ret && dirty)
1148 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1149 return ret;
1152 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1153 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1154 get_block_t *get_block)
1156 unsigned from = pos & (PAGE_SIZE - 1);
1157 unsigned to = from + len;
1158 struct inode *inode = page->mapping->host;
1159 unsigned block_start, block_end;
1160 sector_t block;
1161 int err = 0;
1162 unsigned blocksize = inode->i_sb->s_blocksize;
1163 unsigned bbits;
1164 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1165 bool decrypt = false;
1167 BUG_ON(!PageLocked(page));
1168 BUG_ON(from > PAGE_SIZE);
1169 BUG_ON(to > PAGE_SIZE);
1170 BUG_ON(from > to);
1172 if (!page_has_buffers(page))
1173 create_empty_buffers(page, blocksize, 0);
1174 head = page_buffers(page);
1175 bbits = ilog2(blocksize);
1176 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1178 for (bh = head, block_start = 0; bh != head || !block_start;
1179 block++, block_start = block_end, bh = bh->b_this_page) {
1180 block_end = block_start + blocksize;
1181 if (block_end <= from || block_start >= to) {
1182 if (PageUptodate(page)) {
1183 if (!buffer_uptodate(bh))
1184 set_buffer_uptodate(bh);
1186 continue;
1188 if (buffer_new(bh))
1189 clear_buffer_new(bh);
1190 if (!buffer_mapped(bh)) {
1191 WARN_ON(bh->b_size != blocksize);
1192 err = get_block(inode, block, bh, 1);
1193 if (err)
1194 break;
1195 if (buffer_new(bh)) {
1196 clean_bdev_bh_alias(bh);
1197 if (PageUptodate(page)) {
1198 clear_buffer_new(bh);
1199 set_buffer_uptodate(bh);
1200 mark_buffer_dirty(bh);
1201 continue;
1203 if (block_end > to || block_start < from)
1204 zero_user_segments(page, to, block_end,
1205 block_start, from);
1206 continue;
1209 if (PageUptodate(page)) {
1210 if (!buffer_uptodate(bh))
1211 set_buffer_uptodate(bh);
1212 continue;
1214 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1215 !buffer_unwritten(bh) &&
1216 (block_start < from || block_end > to)) {
1217 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1218 *wait_bh++ = bh;
1219 decrypt = ext4_encrypted_inode(inode) &&
1220 S_ISREG(inode->i_mode);
1224 * If we issued read requests, let them complete.
1226 while (wait_bh > wait) {
1227 wait_on_buffer(*--wait_bh);
1228 if (!buffer_uptodate(*wait_bh))
1229 err = -EIO;
1231 if (unlikely(err))
1232 page_zero_new_buffers(page, from, to);
1233 else if (decrypt)
1234 err = fscrypt_decrypt_page(page->mapping->host, page,
1235 PAGE_SIZE, 0, page->index);
1236 return err;
1238 #endif
1240 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1241 loff_t pos, unsigned len, unsigned flags,
1242 struct page **pagep, void **fsdata)
1244 struct inode *inode = mapping->host;
1245 int ret, needed_blocks;
1246 handle_t *handle;
1247 int retries = 0;
1248 struct page *page;
1249 pgoff_t index;
1250 unsigned from, to;
1252 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1253 return -EIO;
1255 trace_ext4_write_begin(inode, pos, len, flags);
1257 * Reserve one block more for addition to orphan list in case
1258 * we allocate blocks but write fails for some reason
1260 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1261 index = pos >> PAGE_SHIFT;
1262 from = pos & (PAGE_SIZE - 1);
1263 to = from + len;
1265 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1266 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1267 flags, pagep);
1268 if (ret < 0)
1269 return ret;
1270 if (ret == 1)
1271 return 0;
1275 * grab_cache_page_write_begin() can take a long time if the
1276 * system is thrashing due to memory pressure, or if the page
1277 * is being written back. So grab it first before we start
1278 * the transaction handle. This also allows us to allocate
1279 * the page (if needed) without using GFP_NOFS.
1281 retry_grab:
1282 page = grab_cache_page_write_begin(mapping, index, flags);
1283 if (!page)
1284 return -ENOMEM;
1285 unlock_page(page);
1287 retry_journal:
1288 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1289 if (IS_ERR(handle)) {
1290 put_page(page);
1291 return PTR_ERR(handle);
1294 lock_page(page);
1295 if (page->mapping != mapping) {
1296 /* The page got truncated from under us */
1297 unlock_page(page);
1298 put_page(page);
1299 ext4_journal_stop(handle);
1300 goto retry_grab;
1302 /* In case writeback began while the page was unlocked */
1303 wait_for_stable_page(page);
1305 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1306 if (ext4_should_dioread_nolock(inode))
1307 ret = ext4_block_write_begin(page, pos, len,
1308 ext4_get_block_unwritten);
1309 else
1310 ret = ext4_block_write_begin(page, pos, len,
1311 ext4_get_block);
1312 #else
1313 if (ext4_should_dioread_nolock(inode))
1314 ret = __block_write_begin(page, pos, len,
1315 ext4_get_block_unwritten);
1316 else
1317 ret = __block_write_begin(page, pos, len, ext4_get_block);
1318 #endif
1319 if (!ret && ext4_should_journal_data(inode)) {
1320 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1321 from, to, NULL,
1322 do_journal_get_write_access);
1325 if (ret) {
1326 unlock_page(page);
1328 * __block_write_begin may have instantiated a few blocks
1329 * outside i_size. Trim these off again. Don't need
1330 * i_size_read because we hold i_mutex.
1332 * Add inode to orphan list in case we crash before
1333 * truncate finishes
1335 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1336 ext4_orphan_add(handle, inode);
1338 ext4_journal_stop(handle);
1339 if (pos + len > inode->i_size) {
1340 ext4_truncate_failed_write(inode);
1342 * If truncate failed early the inode might
1343 * still be on the orphan list; we need to
1344 * make sure the inode is removed from the
1345 * orphan list in that case.
1347 if (inode->i_nlink)
1348 ext4_orphan_del(NULL, inode);
1351 if (ret == -ENOSPC &&
1352 ext4_should_retry_alloc(inode->i_sb, &retries))
1353 goto retry_journal;
1354 put_page(page);
1355 return ret;
1357 *pagep = page;
1358 return ret;
1361 /* For write_end() in data=journal mode */
1362 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1364 int ret;
1365 if (!buffer_mapped(bh) || buffer_freed(bh))
1366 return 0;
1367 set_buffer_uptodate(bh);
1368 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1369 clear_buffer_meta(bh);
1370 clear_buffer_prio(bh);
1371 return ret;
1375 * We need to pick up the new inode size which generic_commit_write gave us
1376 * `file' can be NULL - eg, when called from page_symlink().
1378 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1379 * buffers are managed internally.
1381 static int ext4_write_end(struct file *file,
1382 struct address_space *mapping,
1383 loff_t pos, unsigned len, unsigned copied,
1384 struct page *page, void *fsdata)
1386 handle_t *handle = ext4_journal_current_handle();
1387 struct inode *inode = mapping->host;
1388 loff_t old_size = inode->i_size;
1389 int ret = 0, ret2;
1390 int i_size_changed = 0;
1391 int inline_data = ext4_has_inline_data(inode);
1393 trace_ext4_write_end(inode, pos, len, copied);
1394 if (inline_data) {
1395 ret = ext4_write_inline_data_end(inode, pos, len,
1396 copied, page);
1397 if (ret < 0) {
1398 unlock_page(page);
1399 put_page(page);
1400 goto errout;
1402 copied = ret;
1403 } else
1404 copied = block_write_end(file, mapping, pos,
1405 len, copied, page, fsdata);
1407 * it's important to update i_size while still holding page lock:
1408 * page writeout could otherwise come in and zero beyond i_size.
1410 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1411 unlock_page(page);
1412 put_page(page);
1414 if (old_size < pos)
1415 pagecache_isize_extended(inode, old_size, pos);
1417 * Don't mark the inode dirty under page lock. First, it unnecessarily
1418 * makes the holding time of page lock longer. Second, it forces lock
1419 * ordering of page lock and transaction start for journaling
1420 * filesystems.
1422 if (i_size_changed || inline_data)
1423 ext4_mark_inode_dirty(handle, inode);
1425 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1426 /* if we have allocated more blocks and copied
1427 * less. We will have blocks allocated outside
1428 * inode->i_size. So truncate them
1430 ext4_orphan_add(handle, inode);
1431 errout:
1432 ret2 = ext4_journal_stop(handle);
1433 if (!ret)
1434 ret = ret2;
1436 if (pos + len > inode->i_size) {
1437 ext4_truncate_failed_write(inode);
1439 * If truncate failed early the inode might still be
1440 * on the orphan list; we need to make sure the inode
1441 * is removed from the orphan list in that case.
1443 if (inode->i_nlink)
1444 ext4_orphan_del(NULL, inode);
1447 return ret ? ret : copied;
1451 * This is a private version of page_zero_new_buffers() which doesn't
1452 * set the buffer to be dirty, since in data=journalled mode we need
1453 * to call ext4_handle_dirty_metadata() instead.
1455 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1456 struct page *page,
1457 unsigned from, unsigned to)
1459 unsigned int block_start = 0, block_end;
1460 struct buffer_head *head, *bh;
1462 bh = head = page_buffers(page);
1463 do {
1464 block_end = block_start + bh->b_size;
1465 if (buffer_new(bh)) {
1466 if (block_end > from && block_start < to) {
1467 if (!PageUptodate(page)) {
1468 unsigned start, size;
1470 start = max(from, block_start);
1471 size = min(to, block_end) - start;
1473 zero_user(page, start, size);
1474 write_end_fn(handle, bh);
1476 clear_buffer_new(bh);
1479 block_start = block_end;
1480 bh = bh->b_this_page;
1481 } while (bh != head);
1484 static int ext4_journalled_write_end(struct file *file,
1485 struct address_space *mapping,
1486 loff_t pos, unsigned len, unsigned copied,
1487 struct page *page, void *fsdata)
1489 handle_t *handle = ext4_journal_current_handle();
1490 struct inode *inode = mapping->host;
1491 loff_t old_size = inode->i_size;
1492 int ret = 0, ret2;
1493 int partial = 0;
1494 unsigned from, to;
1495 int size_changed = 0;
1496 int inline_data = ext4_has_inline_data(inode);
1498 trace_ext4_journalled_write_end(inode, pos, len, copied);
1499 from = pos & (PAGE_SIZE - 1);
1500 to = from + len;
1502 BUG_ON(!ext4_handle_valid(handle));
1504 if (inline_data) {
1505 ret = ext4_write_inline_data_end(inode, pos, len,
1506 copied, page);
1507 if (ret < 0) {
1508 unlock_page(page);
1509 put_page(page);
1510 goto errout;
1512 copied = ret;
1513 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1514 copied = 0;
1515 ext4_journalled_zero_new_buffers(handle, page, from, to);
1516 } else {
1517 if (unlikely(copied < len))
1518 ext4_journalled_zero_new_buffers(handle, page,
1519 from + copied, to);
1520 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1521 from + copied, &partial,
1522 write_end_fn);
1523 if (!partial)
1524 SetPageUptodate(page);
1526 size_changed = ext4_update_inode_size(inode, pos + copied);
1527 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1528 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1529 unlock_page(page);
1530 put_page(page);
1532 if (old_size < pos)
1533 pagecache_isize_extended(inode, old_size, pos);
1535 if (size_changed || inline_data) {
1536 ret2 = ext4_mark_inode_dirty(handle, inode);
1537 if (!ret)
1538 ret = ret2;
1541 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1542 /* if we have allocated more blocks and copied
1543 * less. We will have blocks allocated outside
1544 * inode->i_size. So truncate them
1546 ext4_orphan_add(handle, inode);
1548 errout:
1549 ret2 = ext4_journal_stop(handle);
1550 if (!ret)
1551 ret = ret2;
1552 if (pos + len > inode->i_size) {
1553 ext4_truncate_failed_write(inode);
1555 * If truncate failed early the inode might still be
1556 * on the orphan list; we need to make sure the inode
1557 * is removed from the orphan list in that case.
1559 if (inode->i_nlink)
1560 ext4_orphan_del(NULL, inode);
1563 return ret ? ret : copied;
1567 * Reserve space for a single cluster
1569 static int ext4_da_reserve_space(struct inode *inode)
1571 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1572 struct ext4_inode_info *ei = EXT4_I(inode);
1573 int ret;
1576 * We will charge metadata quota at writeout time; this saves
1577 * us from metadata over-estimation, though we may go over by
1578 * a small amount in the end. Here we just reserve for data.
1580 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1581 if (ret)
1582 return ret;
1584 spin_lock(&ei->i_block_reservation_lock);
1585 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1586 spin_unlock(&ei->i_block_reservation_lock);
1587 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1588 return -ENOSPC;
1590 ei->i_reserved_data_blocks++;
1591 trace_ext4_da_reserve_space(inode);
1592 spin_unlock(&ei->i_block_reservation_lock);
1594 return 0; /* success */
1597 static void ext4_da_release_space(struct inode *inode, int to_free)
1599 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1600 struct ext4_inode_info *ei = EXT4_I(inode);
1602 if (!to_free)
1603 return; /* Nothing to release, exit */
1605 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1607 trace_ext4_da_release_space(inode, to_free);
1608 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1610 * if there aren't enough reserved blocks, then the
1611 * counter is messed up somewhere. Since this
1612 * function is called from invalidate page, it's
1613 * harmless to return without any action.
1615 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1616 "ino %lu, to_free %d with only %d reserved "
1617 "data blocks", inode->i_ino, to_free,
1618 ei->i_reserved_data_blocks);
1619 WARN_ON(1);
1620 to_free = ei->i_reserved_data_blocks;
1622 ei->i_reserved_data_blocks -= to_free;
1624 /* update fs dirty data blocks counter */
1625 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1627 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1629 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1632 static void ext4_da_page_release_reservation(struct page *page,
1633 unsigned int offset,
1634 unsigned int length)
1636 int to_release = 0, contiguous_blks = 0;
1637 struct buffer_head *head, *bh;
1638 unsigned int curr_off = 0;
1639 struct inode *inode = page->mapping->host;
1640 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1641 unsigned int stop = offset + length;
1642 int num_clusters;
1643 ext4_fsblk_t lblk;
1645 BUG_ON(stop > PAGE_SIZE || stop < length);
1647 head = page_buffers(page);
1648 bh = head;
1649 do {
1650 unsigned int next_off = curr_off + bh->b_size;
1652 if (next_off > stop)
1653 break;
1655 if ((offset <= curr_off) && (buffer_delay(bh))) {
1656 to_release++;
1657 contiguous_blks++;
1658 clear_buffer_delay(bh);
1659 } else if (contiguous_blks) {
1660 lblk = page->index <<
1661 (PAGE_SHIFT - inode->i_blkbits);
1662 lblk += (curr_off >> inode->i_blkbits) -
1663 contiguous_blks;
1664 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1665 contiguous_blks = 0;
1667 curr_off = next_off;
1668 } while ((bh = bh->b_this_page) != head);
1670 if (contiguous_blks) {
1671 lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
1672 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1673 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1676 /* If we have released all the blocks belonging to a cluster, then we
1677 * need to release the reserved space for that cluster. */
1678 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1679 while (num_clusters > 0) {
1680 lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
1681 ((num_clusters - 1) << sbi->s_cluster_bits);
1682 if (sbi->s_cluster_ratio == 1 ||
1683 !ext4_find_delalloc_cluster(inode, lblk))
1684 ext4_da_release_space(inode, 1);
1686 num_clusters--;
1691 * Delayed allocation stuff
1694 struct mpage_da_data {
1695 struct inode *inode;
1696 struct writeback_control *wbc;
1698 pgoff_t first_page; /* The first page to write */
1699 pgoff_t next_page; /* Current page to examine */
1700 pgoff_t last_page; /* Last page to examine */
1702 * Extent to map - this can be after first_page because that can be
1703 * fully mapped. We somewhat abuse m_flags to store whether the extent
1704 * is delalloc or unwritten.
1706 struct ext4_map_blocks map;
1707 struct ext4_io_submit io_submit; /* IO submission data */
1708 unsigned int do_map:1;
1711 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1712 bool invalidate)
1714 int nr_pages, i;
1715 pgoff_t index, end;
1716 struct pagevec pvec;
1717 struct inode *inode = mpd->inode;
1718 struct address_space *mapping = inode->i_mapping;
1720 /* This is necessary when next_page == 0. */
1721 if (mpd->first_page >= mpd->next_page)
1722 return;
1724 index = mpd->first_page;
1725 end = mpd->next_page - 1;
1726 if (invalidate) {
1727 ext4_lblk_t start, last;
1728 start = index << (PAGE_SHIFT - inode->i_blkbits);
1729 last = end << (PAGE_SHIFT - inode->i_blkbits);
1730 ext4_es_remove_extent(inode, start, last - start + 1);
1733 pagevec_init(&pvec, 0);
1734 while (index <= end) {
1735 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1736 if (nr_pages == 0)
1737 break;
1738 for (i = 0; i < nr_pages; i++) {
1739 struct page *page = pvec.pages[i];
1741 BUG_ON(!PageLocked(page));
1742 BUG_ON(PageWriteback(page));
1743 if (invalidate) {
1744 if (page_mapped(page))
1745 clear_page_dirty_for_io(page);
1746 block_invalidatepage(page, 0, PAGE_SIZE);
1747 ClearPageUptodate(page);
1749 unlock_page(page);
1751 pagevec_release(&pvec);
1755 static void ext4_print_free_blocks(struct inode *inode)
1757 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1758 struct super_block *sb = inode->i_sb;
1759 struct ext4_inode_info *ei = EXT4_I(inode);
1761 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1762 EXT4_C2B(EXT4_SB(inode->i_sb),
1763 ext4_count_free_clusters(sb)));
1764 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1765 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1766 (long long) EXT4_C2B(EXT4_SB(sb),
1767 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1768 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1769 (long long) EXT4_C2B(EXT4_SB(sb),
1770 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1771 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1772 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1773 ei->i_reserved_data_blocks);
1774 return;
1777 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1779 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1783 * This function is grabs code from the very beginning of
1784 * ext4_map_blocks, but assumes that the caller is from delayed write
1785 * time. This function looks up the requested blocks and sets the
1786 * buffer delay bit under the protection of i_data_sem.
1788 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1789 struct ext4_map_blocks *map,
1790 struct buffer_head *bh)
1792 struct extent_status es;
1793 int retval;
1794 sector_t invalid_block = ~((sector_t) 0xffff);
1795 #ifdef ES_AGGRESSIVE_TEST
1796 struct ext4_map_blocks orig_map;
1798 memcpy(&orig_map, map, sizeof(*map));
1799 #endif
1801 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1802 invalid_block = ~0;
1804 map->m_flags = 0;
1805 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1806 "logical block %lu\n", inode->i_ino, map->m_len,
1807 (unsigned long) map->m_lblk);
1809 /* Lookup extent status tree firstly */
1810 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1811 if (ext4_es_is_hole(&es)) {
1812 retval = 0;
1813 down_read(&EXT4_I(inode)->i_data_sem);
1814 goto add_delayed;
1818 * Delayed extent could be allocated by fallocate.
1819 * So we need to check it.
1821 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1822 map_bh(bh, inode->i_sb, invalid_block);
1823 set_buffer_new(bh);
1824 set_buffer_delay(bh);
1825 return 0;
1828 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1829 retval = es.es_len - (iblock - es.es_lblk);
1830 if (retval > map->m_len)
1831 retval = map->m_len;
1832 map->m_len = retval;
1833 if (ext4_es_is_written(&es))
1834 map->m_flags |= EXT4_MAP_MAPPED;
1835 else if (ext4_es_is_unwritten(&es))
1836 map->m_flags |= EXT4_MAP_UNWRITTEN;
1837 else
1838 BUG_ON(1);
1840 #ifdef ES_AGGRESSIVE_TEST
1841 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1842 #endif
1843 return retval;
1847 * Try to see if we can get the block without requesting a new
1848 * file system block.
1850 down_read(&EXT4_I(inode)->i_data_sem);
1851 if (ext4_has_inline_data(inode))
1852 retval = 0;
1853 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1854 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1855 else
1856 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1858 add_delayed:
1859 if (retval == 0) {
1860 int ret;
1862 * XXX: __block_prepare_write() unmaps passed block,
1863 * is it OK?
1866 * If the block was allocated from previously allocated cluster,
1867 * then we don't need to reserve it again. However we still need
1868 * to reserve metadata for every block we're going to write.
1870 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1871 !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1872 ret = ext4_da_reserve_space(inode);
1873 if (ret) {
1874 /* not enough space to reserve */
1875 retval = ret;
1876 goto out_unlock;
1880 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1881 ~0, EXTENT_STATUS_DELAYED);
1882 if (ret) {
1883 retval = ret;
1884 goto out_unlock;
1887 map_bh(bh, inode->i_sb, invalid_block);
1888 set_buffer_new(bh);
1889 set_buffer_delay(bh);
1890 } else if (retval > 0) {
1891 int ret;
1892 unsigned int status;
1894 if (unlikely(retval != map->m_len)) {
1895 ext4_warning(inode->i_sb,
1896 "ES len assertion failed for inode "
1897 "%lu: retval %d != map->m_len %d",
1898 inode->i_ino, retval, map->m_len);
1899 WARN_ON(1);
1902 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1903 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1904 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1905 map->m_pblk, status);
1906 if (ret != 0)
1907 retval = ret;
1910 out_unlock:
1911 up_read((&EXT4_I(inode)->i_data_sem));
1913 return retval;
1917 * This is a special get_block_t callback which is used by
1918 * ext4_da_write_begin(). It will either return mapped block or
1919 * reserve space for a single block.
1921 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1922 * We also have b_blocknr = -1 and b_bdev initialized properly
1924 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1925 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1926 * initialized properly.
1928 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1929 struct buffer_head *bh, int create)
1931 struct ext4_map_blocks map;
1932 int ret = 0;
1934 BUG_ON(create == 0);
1935 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1937 map.m_lblk = iblock;
1938 map.m_len = 1;
1941 * first, we need to know whether the block is allocated already
1942 * preallocated blocks are unmapped but should treated
1943 * the same as allocated blocks.
1945 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1946 if (ret <= 0)
1947 return ret;
1949 map_bh(bh, inode->i_sb, map.m_pblk);
1950 ext4_update_bh_state(bh, map.m_flags);
1952 if (buffer_unwritten(bh)) {
1953 /* A delayed write to unwritten bh should be marked
1954 * new and mapped. Mapped ensures that we don't do
1955 * get_block multiple times when we write to the same
1956 * offset and new ensures that we do proper zero out
1957 * for partial write.
1959 set_buffer_new(bh);
1960 set_buffer_mapped(bh);
1962 return 0;
1965 static int bget_one(handle_t *handle, struct buffer_head *bh)
1967 get_bh(bh);
1968 return 0;
1971 static int bput_one(handle_t *handle, struct buffer_head *bh)
1973 put_bh(bh);
1974 return 0;
1977 static int __ext4_journalled_writepage(struct page *page,
1978 unsigned int len)
1980 struct address_space *mapping = page->mapping;
1981 struct inode *inode = mapping->host;
1982 struct buffer_head *page_bufs = NULL;
1983 handle_t *handle = NULL;
1984 int ret = 0, err = 0;
1985 int inline_data = ext4_has_inline_data(inode);
1986 struct buffer_head *inode_bh = NULL;
1988 ClearPageChecked(page);
1990 if (inline_data) {
1991 BUG_ON(page->index != 0);
1992 BUG_ON(len > ext4_get_max_inline_size(inode));
1993 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1994 if (inode_bh == NULL)
1995 goto out;
1996 } else {
1997 page_bufs = page_buffers(page);
1998 if (!page_bufs) {
1999 BUG();
2000 goto out;
2002 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2003 NULL, bget_one);
2006 * We need to release the page lock before we start the
2007 * journal, so grab a reference so the page won't disappear
2008 * out from under us.
2010 get_page(page);
2011 unlock_page(page);
2013 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2014 ext4_writepage_trans_blocks(inode));
2015 if (IS_ERR(handle)) {
2016 ret = PTR_ERR(handle);
2017 put_page(page);
2018 goto out_no_pagelock;
2020 BUG_ON(!ext4_handle_valid(handle));
2022 lock_page(page);
2023 put_page(page);
2024 if (page->mapping != mapping) {
2025 /* The page got truncated from under us */
2026 ext4_journal_stop(handle);
2027 ret = 0;
2028 goto out;
2031 if (inline_data) {
2032 ret = ext4_mark_inode_dirty(handle, inode);
2033 } else {
2034 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2035 do_journal_get_write_access);
2037 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2038 write_end_fn);
2040 if (ret == 0)
2041 ret = err;
2042 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2043 err = ext4_journal_stop(handle);
2044 if (!ret)
2045 ret = err;
2047 if (!ext4_has_inline_data(inode))
2048 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
2049 NULL, bput_one);
2050 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2051 out:
2052 unlock_page(page);
2053 out_no_pagelock:
2054 brelse(inode_bh);
2055 return ret;
2059 * Note that we don't need to start a transaction unless we're journaling data
2060 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2061 * need to file the inode to the transaction's list in ordered mode because if
2062 * we are writing back data added by write(), the inode is already there and if
2063 * we are writing back data modified via mmap(), no one guarantees in which
2064 * transaction the data will hit the disk. In case we are journaling data, we
2065 * cannot start transaction directly because transaction start ranks above page
2066 * lock so we have to do some magic.
2068 * This function can get called via...
2069 * - ext4_writepages after taking page lock (have journal handle)
2070 * - journal_submit_inode_data_buffers (no journal handle)
2071 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2072 * - grab_page_cache when doing write_begin (have journal handle)
2074 * We don't do any block allocation in this function. If we have page with
2075 * multiple blocks we need to write those buffer_heads that are mapped. This
2076 * is important for mmaped based write. So if we do with blocksize 1K
2077 * truncate(f, 1024);
2078 * a = mmap(f, 0, 4096);
2079 * a[0] = 'a';
2080 * truncate(f, 4096);
2081 * we have in the page first buffer_head mapped via page_mkwrite call back
2082 * but other buffer_heads would be unmapped but dirty (dirty done via the
2083 * do_wp_page). So writepage should write the first block. If we modify
2084 * the mmap area beyond 1024 we will again get a page_fault and the
2085 * page_mkwrite callback will do the block allocation and mark the
2086 * buffer_heads mapped.
2088 * We redirty the page if we have any buffer_heads that is either delay or
2089 * unwritten in the page.
2091 * We can get recursively called as show below.
2093 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2094 * ext4_writepage()
2096 * But since we don't do any block allocation we should not deadlock.
2097 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2099 static int ext4_writepage(struct page *page,
2100 struct writeback_control *wbc)
2102 int ret = 0;
2103 loff_t size;
2104 unsigned int len;
2105 struct buffer_head *page_bufs = NULL;
2106 struct inode *inode = page->mapping->host;
2107 struct ext4_io_submit io_submit;
2108 bool keep_towrite = false;
2110 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2111 ext4_invalidatepage(page, 0, PAGE_SIZE);
2112 unlock_page(page);
2113 return -EIO;
2116 trace_ext4_writepage(page);
2117 size = i_size_read(inode);
2118 if (page->index == size >> PAGE_SHIFT)
2119 len = size & ~PAGE_MASK;
2120 else
2121 len = PAGE_SIZE;
2123 page_bufs = page_buffers(page);
2125 * We cannot do block allocation or other extent handling in this
2126 * function. If there are buffers needing that, we have to redirty
2127 * the page. But we may reach here when we do a journal commit via
2128 * journal_submit_inode_data_buffers() and in that case we must write
2129 * allocated buffers to achieve data=ordered mode guarantees.
2131 * Also, if there is only one buffer per page (the fs block
2132 * size == the page size), if one buffer needs block
2133 * allocation or needs to modify the extent tree to clear the
2134 * unwritten flag, we know that the page can't be written at
2135 * all, so we might as well refuse the write immediately.
2136 * Unfortunately if the block size != page size, we can't as
2137 * easily detect this case using ext4_walk_page_buffers(), but
2138 * for the extremely common case, this is an optimization that
2139 * skips a useless round trip through ext4_bio_write_page().
2141 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2142 ext4_bh_delay_or_unwritten)) {
2143 redirty_page_for_writepage(wbc, page);
2144 if ((current->flags & PF_MEMALLOC) ||
2145 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2147 * For memory cleaning there's no point in writing only
2148 * some buffers. So just bail out. Warn if we came here
2149 * from direct reclaim.
2151 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2152 == PF_MEMALLOC);
2153 unlock_page(page);
2154 return 0;
2156 keep_towrite = true;
2159 if (PageChecked(page) && ext4_should_journal_data(inode))
2161 * It's mmapped pagecache. Add buffers and journal it. There
2162 * doesn't seem much point in redirtying the page here.
2164 return __ext4_journalled_writepage(page, len);
2166 ext4_io_submit_init(&io_submit, wbc);
2167 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2168 if (!io_submit.io_end) {
2169 redirty_page_for_writepage(wbc, page);
2170 unlock_page(page);
2171 return -ENOMEM;
2173 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2174 ext4_io_submit(&io_submit);
2175 /* Drop io_end reference we got from init */
2176 ext4_put_io_end_defer(io_submit.io_end);
2177 return ret;
2180 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2182 int len;
2183 loff_t size;
2184 int err;
2186 BUG_ON(page->index != mpd->first_page);
2187 clear_page_dirty_for_io(page);
2189 * We have to be very careful here! Nothing protects writeback path
2190 * against i_size changes and the page can be writeably mapped into
2191 * page tables. So an application can be growing i_size and writing
2192 * data through mmap while writeback runs. clear_page_dirty_for_io()
2193 * write-protects our page in page tables and the page cannot get
2194 * written to again until we release page lock. So only after
2195 * clear_page_dirty_for_io() we are safe to sample i_size for
2196 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2197 * on the barrier provided by TestClearPageDirty in
2198 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2199 * after page tables are updated.
2201 size = i_size_read(mpd->inode);
2202 if (page->index == size >> PAGE_SHIFT)
2203 len = size & ~PAGE_MASK;
2204 else
2205 len = PAGE_SIZE;
2206 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2207 if (!err)
2208 mpd->wbc->nr_to_write--;
2209 mpd->first_page++;
2211 return err;
2214 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2217 * mballoc gives us at most this number of blocks...
2218 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2219 * The rest of mballoc seems to handle chunks up to full group size.
2221 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2224 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2226 * @mpd - extent of blocks
2227 * @lblk - logical number of the block in the file
2228 * @bh - buffer head we want to add to the extent
2230 * The function is used to collect contig. blocks in the same state. If the
2231 * buffer doesn't require mapping for writeback and we haven't started the
2232 * extent of buffers to map yet, the function returns 'true' immediately - the
2233 * caller can write the buffer right away. Otherwise the function returns true
2234 * if the block has been added to the extent, false if the block couldn't be
2235 * added.
2237 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2238 struct buffer_head *bh)
2240 struct ext4_map_blocks *map = &mpd->map;
2242 /* Buffer that doesn't need mapping for writeback? */
2243 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2244 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2245 /* So far no extent to map => we write the buffer right away */
2246 if (map->m_len == 0)
2247 return true;
2248 return false;
2251 /* First block in the extent? */
2252 if (map->m_len == 0) {
2253 /* We cannot map unless handle is started... */
2254 if (!mpd->do_map)
2255 return false;
2256 map->m_lblk = lblk;
2257 map->m_len = 1;
2258 map->m_flags = bh->b_state & BH_FLAGS;
2259 return true;
2262 /* Don't go larger than mballoc is willing to allocate */
2263 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2264 return false;
2266 /* Can we merge the block to our big extent? */
2267 if (lblk == map->m_lblk + map->m_len &&
2268 (bh->b_state & BH_FLAGS) == map->m_flags) {
2269 map->m_len++;
2270 return true;
2272 return false;
2276 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2278 * @mpd - extent of blocks for mapping
2279 * @head - the first buffer in the page
2280 * @bh - buffer we should start processing from
2281 * @lblk - logical number of the block in the file corresponding to @bh
2283 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2284 * the page for IO if all buffers in this page were mapped and there's no
2285 * accumulated extent of buffers to map or add buffers in the page to the
2286 * extent of buffers to map. The function returns 1 if the caller can continue
2287 * by processing the next page, 0 if it should stop adding buffers to the
2288 * extent to map because we cannot extend it anymore. It can also return value
2289 * < 0 in case of error during IO submission.
2291 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2292 struct buffer_head *head,
2293 struct buffer_head *bh,
2294 ext4_lblk_t lblk)
2296 struct inode *inode = mpd->inode;
2297 int err;
2298 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2299 >> inode->i_blkbits;
2301 do {
2302 BUG_ON(buffer_locked(bh));
2304 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2305 /* Found extent to map? */
2306 if (mpd->map.m_len)
2307 return 0;
2308 /* Buffer needs mapping and handle is not started? */
2309 if (!mpd->do_map)
2310 return 0;
2311 /* Everything mapped so far and we hit EOF */
2312 break;
2314 } while (lblk++, (bh = bh->b_this_page) != head);
2315 /* So far everything mapped? Submit the page for IO. */
2316 if (mpd->map.m_len == 0) {
2317 err = mpage_submit_page(mpd, head->b_page);
2318 if (err < 0)
2319 return err;
2321 return lblk < blocks;
2325 * mpage_map_buffers - update buffers corresponding to changed extent and
2326 * submit fully mapped pages for IO
2328 * @mpd - description of extent to map, on return next extent to map
2330 * Scan buffers corresponding to changed extent (we expect corresponding pages
2331 * to be already locked) and update buffer state according to new extent state.
2332 * We map delalloc buffers to their physical location, clear unwritten bits,
2333 * and mark buffers as uninit when we perform writes to unwritten extents
2334 * and do extent conversion after IO is finished. If the last page is not fully
2335 * mapped, we update @map to the next extent in the last page that needs
2336 * mapping. Otherwise we submit the page for IO.
2338 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2340 struct pagevec pvec;
2341 int nr_pages, i;
2342 struct inode *inode = mpd->inode;
2343 struct buffer_head *head, *bh;
2344 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2345 pgoff_t start, end;
2346 ext4_lblk_t lblk;
2347 sector_t pblock;
2348 int err;
2350 start = mpd->map.m_lblk >> bpp_bits;
2351 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2352 lblk = start << bpp_bits;
2353 pblock = mpd->map.m_pblk;
2355 pagevec_init(&pvec, 0);
2356 while (start <= end) {
2357 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2358 &start, end);
2359 if (nr_pages == 0)
2360 break;
2361 for (i = 0; i < nr_pages; i++) {
2362 struct page *page = pvec.pages[i];
2364 bh = head = page_buffers(page);
2365 do {
2366 if (lblk < mpd->map.m_lblk)
2367 continue;
2368 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2370 * Buffer after end of mapped extent.
2371 * Find next buffer in the page to map.
2373 mpd->map.m_len = 0;
2374 mpd->map.m_flags = 0;
2376 * FIXME: If dioread_nolock supports
2377 * blocksize < pagesize, we need to make
2378 * sure we add size mapped so far to
2379 * io_end->size as the following call
2380 * can submit the page for IO.
2382 err = mpage_process_page_bufs(mpd, head,
2383 bh, lblk);
2384 pagevec_release(&pvec);
2385 if (err > 0)
2386 err = 0;
2387 return err;
2389 if (buffer_delay(bh)) {
2390 clear_buffer_delay(bh);
2391 bh->b_blocknr = pblock++;
2393 clear_buffer_unwritten(bh);
2394 } while (lblk++, (bh = bh->b_this_page) != head);
2397 * FIXME: This is going to break if dioread_nolock
2398 * supports blocksize < pagesize as we will try to
2399 * convert potentially unmapped parts of inode.
2401 mpd->io_submit.io_end->size += PAGE_SIZE;
2402 /* Page fully mapped - let IO run! */
2403 err = mpage_submit_page(mpd, page);
2404 if (err < 0) {
2405 pagevec_release(&pvec);
2406 return err;
2409 pagevec_release(&pvec);
2411 /* Extent fully mapped and matches with page boundary. We are done. */
2412 mpd->map.m_len = 0;
2413 mpd->map.m_flags = 0;
2414 return 0;
2417 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2419 struct inode *inode = mpd->inode;
2420 struct ext4_map_blocks *map = &mpd->map;
2421 int get_blocks_flags;
2422 int err, dioread_nolock;
2424 trace_ext4_da_write_pages_extent(inode, map);
2426 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2427 * to convert an unwritten extent to be initialized (in the case
2428 * where we have written into one or more preallocated blocks). It is
2429 * possible that we're going to need more metadata blocks than
2430 * previously reserved. However we must not fail because we're in
2431 * writeback and there is nothing we can do about it so it might result
2432 * in data loss. So use reserved blocks to allocate metadata if
2433 * possible.
2435 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2436 * the blocks in question are delalloc blocks. This indicates
2437 * that the blocks and quotas has already been checked when
2438 * the data was copied into the page cache.
2440 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2441 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2442 EXT4_GET_BLOCKS_IO_SUBMIT;
2443 dioread_nolock = ext4_should_dioread_nolock(inode);
2444 if (dioread_nolock)
2445 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2446 if (map->m_flags & (1 << BH_Delay))
2447 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2449 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2450 if (err < 0)
2451 return err;
2452 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2453 if (!mpd->io_submit.io_end->handle &&
2454 ext4_handle_valid(handle)) {
2455 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2456 handle->h_rsv_handle = NULL;
2458 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2461 BUG_ON(map->m_len == 0);
2462 if (map->m_flags & EXT4_MAP_NEW) {
2463 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
2464 map->m_len);
2466 return 0;
2470 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2471 * mpd->len and submit pages underlying it for IO
2473 * @handle - handle for journal operations
2474 * @mpd - extent to map
2475 * @give_up_on_write - we set this to true iff there is a fatal error and there
2476 * is no hope of writing the data. The caller should discard
2477 * dirty pages to avoid infinite loops.
2479 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2480 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2481 * them to initialized or split the described range from larger unwritten
2482 * extent. Note that we need not map all the described range since allocation
2483 * can return less blocks or the range is covered by more unwritten extents. We
2484 * cannot map more because we are limited by reserved transaction credits. On
2485 * the other hand we always make sure that the last touched page is fully
2486 * mapped so that it can be written out (and thus forward progress is
2487 * guaranteed). After mapping we submit all mapped pages for IO.
2489 static int mpage_map_and_submit_extent(handle_t *handle,
2490 struct mpage_da_data *mpd,
2491 bool *give_up_on_write)
2493 struct inode *inode = mpd->inode;
2494 struct ext4_map_blocks *map = &mpd->map;
2495 int err;
2496 loff_t disksize;
2497 int progress = 0;
2499 mpd->io_submit.io_end->offset =
2500 ((loff_t)map->m_lblk) << inode->i_blkbits;
2501 do {
2502 err = mpage_map_one_extent(handle, mpd);
2503 if (err < 0) {
2504 struct super_block *sb = inode->i_sb;
2506 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2507 EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2508 goto invalidate_dirty_pages;
2510 * Let the uper layers retry transient errors.
2511 * In the case of ENOSPC, if ext4_count_free_blocks()
2512 * is non-zero, a commit should free up blocks.
2514 if ((err == -ENOMEM) ||
2515 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2516 if (progress)
2517 goto update_disksize;
2518 return err;
2520 ext4_msg(sb, KERN_CRIT,
2521 "Delayed block allocation failed for "
2522 "inode %lu at logical offset %llu with"
2523 " max blocks %u with error %d",
2524 inode->i_ino,
2525 (unsigned long long)map->m_lblk,
2526 (unsigned)map->m_len, -err);
2527 ext4_msg(sb, KERN_CRIT,
2528 "This should not happen!! Data will "
2529 "be lost\n");
2530 if (err == -ENOSPC)
2531 ext4_print_free_blocks(inode);
2532 invalidate_dirty_pages:
2533 *give_up_on_write = true;
2534 return err;
2536 progress = 1;
2538 * Update buffer state, submit mapped pages, and get us new
2539 * extent to map
2541 err = mpage_map_and_submit_buffers(mpd);
2542 if (err < 0)
2543 goto update_disksize;
2544 } while (map->m_len);
2546 update_disksize:
2548 * Update on-disk size after IO is submitted. Races with
2549 * truncate are avoided by checking i_size under i_data_sem.
2551 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2552 if (disksize > EXT4_I(inode)->i_disksize) {
2553 int err2;
2554 loff_t i_size;
2556 down_write(&EXT4_I(inode)->i_data_sem);
2557 i_size = i_size_read(inode);
2558 if (disksize > i_size)
2559 disksize = i_size;
2560 if (disksize > EXT4_I(inode)->i_disksize)
2561 EXT4_I(inode)->i_disksize = disksize;
2562 up_write(&EXT4_I(inode)->i_data_sem);
2563 err2 = ext4_mark_inode_dirty(handle, inode);
2564 if (err2)
2565 ext4_error(inode->i_sb,
2566 "Failed to mark inode %lu dirty",
2567 inode->i_ino);
2568 if (!err)
2569 err = err2;
2571 return err;
2575 * Calculate the total number of credits to reserve for one writepages
2576 * iteration. This is called from ext4_writepages(). We map an extent of
2577 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2578 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2579 * bpp - 1 blocks in bpp different extents.
2581 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2583 int bpp = ext4_journal_blocks_per_page(inode);
2585 return ext4_meta_trans_blocks(inode,
2586 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2590 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2591 * and underlying extent to map
2593 * @mpd - where to look for pages
2595 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2596 * IO immediately. When we find a page which isn't mapped we start accumulating
2597 * extent of buffers underlying these pages that needs mapping (formed by
2598 * either delayed or unwritten buffers). We also lock the pages containing
2599 * these buffers. The extent found is returned in @mpd structure (starting at
2600 * mpd->lblk with length mpd->len blocks).
2602 * Note that this function can attach bios to one io_end structure which are
2603 * neither logically nor physically contiguous. Although it may seem as an
2604 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2605 * case as we need to track IO to all buffers underlying a page in one io_end.
2607 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2609 struct address_space *mapping = mpd->inode->i_mapping;
2610 struct pagevec pvec;
2611 unsigned int nr_pages;
2612 long left = mpd->wbc->nr_to_write;
2613 pgoff_t index = mpd->first_page;
2614 pgoff_t end = mpd->last_page;
2615 int tag;
2616 int i, err = 0;
2617 int blkbits = mpd->inode->i_blkbits;
2618 ext4_lblk_t lblk;
2619 struct buffer_head *head;
2621 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2622 tag = PAGECACHE_TAG_TOWRITE;
2623 else
2624 tag = PAGECACHE_TAG_DIRTY;
2626 pagevec_init(&pvec, 0);
2627 mpd->map.m_len = 0;
2628 mpd->next_page = index;
2629 while (index <= end) {
2630 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2631 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2632 if (nr_pages == 0)
2633 goto out;
2635 for (i = 0; i < nr_pages; i++) {
2636 struct page *page = pvec.pages[i];
2639 * At this point, the page may be truncated or
2640 * invalidated (changing page->mapping to NULL), or
2641 * even swizzled back from swapper_space to tmpfs file
2642 * mapping. However, page->index will not change
2643 * because we have a reference on the page.
2645 if (page->index > end)
2646 goto out;
2649 * Accumulated enough dirty pages? This doesn't apply
2650 * to WB_SYNC_ALL mode. For integrity sync we have to
2651 * keep going because someone may be concurrently
2652 * dirtying pages, and we might have synced a lot of
2653 * newly appeared dirty pages, but have not synced all
2654 * of the old dirty pages.
2656 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2657 goto out;
2659 /* If we can't merge this page, we are done. */
2660 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2661 goto out;
2663 lock_page(page);
2665 * If the page is no longer dirty, or its mapping no
2666 * longer corresponds to inode we are writing (which
2667 * means it has been truncated or invalidated), or the
2668 * page is already under writeback and we are not doing
2669 * a data integrity writeback, skip the page
2671 if (!PageDirty(page) ||
2672 (PageWriteback(page) &&
2673 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2674 unlikely(page->mapping != mapping)) {
2675 unlock_page(page);
2676 continue;
2679 wait_on_page_writeback(page);
2680 BUG_ON(PageWriteback(page));
2682 if (mpd->map.m_len == 0)
2683 mpd->first_page = page->index;
2684 mpd->next_page = page->index + 1;
2685 /* Add all dirty buffers to mpd */
2686 lblk = ((ext4_lblk_t)page->index) <<
2687 (PAGE_SHIFT - blkbits);
2688 head = page_buffers(page);
2689 err = mpage_process_page_bufs(mpd, head, head, lblk);
2690 if (err <= 0)
2691 goto out;
2692 err = 0;
2693 left--;
2695 pagevec_release(&pvec);
2696 cond_resched();
2698 return 0;
2699 out:
2700 pagevec_release(&pvec);
2701 return err;
2704 static int __writepage(struct page *page, struct writeback_control *wbc,
2705 void *data)
2707 struct address_space *mapping = data;
2708 int ret = ext4_writepage(page, wbc);
2709 mapping_set_error(mapping, ret);
2710 return ret;
2713 static int ext4_writepages(struct address_space *mapping,
2714 struct writeback_control *wbc)
2716 pgoff_t writeback_index = 0;
2717 long nr_to_write = wbc->nr_to_write;
2718 int range_whole = 0;
2719 int cycled = 1;
2720 handle_t *handle = NULL;
2721 struct mpage_da_data mpd;
2722 struct inode *inode = mapping->host;
2723 int needed_blocks, rsv_blocks = 0, ret = 0;
2724 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2725 bool done;
2726 struct blk_plug plug;
2727 bool give_up_on_write = false;
2729 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2730 return -EIO;
2732 percpu_down_read(&sbi->s_journal_flag_rwsem);
2733 trace_ext4_writepages(inode, wbc);
2735 if (dax_mapping(mapping)) {
2736 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
2737 wbc);
2738 goto out_writepages;
2742 * No pages to write? This is mainly a kludge to avoid starting
2743 * a transaction for special inodes like journal inode on last iput()
2744 * because that could violate lock ordering on umount
2746 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2747 goto out_writepages;
2749 if (ext4_should_journal_data(inode)) {
2750 struct blk_plug plug;
2752 blk_start_plug(&plug);
2753 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2754 blk_finish_plug(&plug);
2755 goto out_writepages;
2759 * If the filesystem has aborted, it is read-only, so return
2760 * right away instead of dumping stack traces later on that
2761 * will obscure the real source of the problem. We test
2762 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2763 * the latter could be true if the filesystem is mounted
2764 * read-only, and in that case, ext4_writepages should
2765 * *never* be called, so if that ever happens, we would want
2766 * the stack trace.
2768 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2769 sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2770 ret = -EROFS;
2771 goto out_writepages;
2774 if (ext4_should_dioread_nolock(inode)) {
2776 * We may need to convert up to one extent per block in
2777 * the page and we may dirty the inode.
2779 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2780 PAGE_SIZE >> inode->i_blkbits);
2784 * If we have inline data and arrive here, it means that
2785 * we will soon create the block for the 1st page, so
2786 * we'd better clear the inline data here.
2788 if (ext4_has_inline_data(inode)) {
2789 /* Just inode will be modified... */
2790 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2791 if (IS_ERR(handle)) {
2792 ret = PTR_ERR(handle);
2793 goto out_writepages;
2795 BUG_ON(ext4_test_inode_state(inode,
2796 EXT4_STATE_MAY_INLINE_DATA));
2797 ext4_destroy_inline_data(handle, inode);
2798 ext4_journal_stop(handle);
2801 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2802 range_whole = 1;
2804 if (wbc->range_cyclic) {
2805 writeback_index = mapping->writeback_index;
2806 if (writeback_index)
2807 cycled = 0;
2808 mpd.first_page = writeback_index;
2809 mpd.last_page = -1;
2810 } else {
2811 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2812 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2815 mpd.inode = inode;
2816 mpd.wbc = wbc;
2817 ext4_io_submit_init(&mpd.io_submit, wbc);
2818 retry:
2819 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2820 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2821 done = false;
2822 blk_start_plug(&plug);
2825 * First writeback pages that don't need mapping - we can avoid
2826 * starting a transaction unnecessarily and also avoid being blocked
2827 * in the block layer on device congestion while having transaction
2828 * started.
2830 mpd.do_map = 0;
2831 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2832 if (!mpd.io_submit.io_end) {
2833 ret = -ENOMEM;
2834 goto unplug;
2836 ret = mpage_prepare_extent_to_map(&mpd);
2837 /* Submit prepared bio */
2838 ext4_io_submit(&mpd.io_submit);
2839 ext4_put_io_end_defer(mpd.io_submit.io_end);
2840 mpd.io_submit.io_end = NULL;
2841 /* Unlock pages we didn't use */
2842 mpage_release_unused_pages(&mpd, false);
2843 if (ret < 0)
2844 goto unplug;
2846 while (!done && mpd.first_page <= mpd.last_page) {
2847 /* For each extent of pages we use new io_end */
2848 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2849 if (!mpd.io_submit.io_end) {
2850 ret = -ENOMEM;
2851 break;
2855 * We have two constraints: We find one extent to map and we
2856 * must always write out whole page (makes a difference when
2857 * blocksize < pagesize) so that we don't block on IO when we
2858 * try to write out the rest of the page. Journalled mode is
2859 * not supported by delalloc.
2861 BUG_ON(ext4_should_journal_data(inode));
2862 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2864 /* start a new transaction */
2865 handle = ext4_journal_start_with_reserve(inode,
2866 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2867 if (IS_ERR(handle)) {
2868 ret = PTR_ERR(handle);
2869 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2870 "%ld pages, ino %lu; err %d", __func__,
2871 wbc->nr_to_write, inode->i_ino, ret);
2872 /* Release allocated io_end */
2873 ext4_put_io_end(mpd.io_submit.io_end);
2874 mpd.io_submit.io_end = NULL;
2875 break;
2877 mpd.do_map = 1;
2879 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2880 ret = mpage_prepare_extent_to_map(&mpd);
2881 if (!ret) {
2882 if (mpd.map.m_len)
2883 ret = mpage_map_and_submit_extent(handle, &mpd,
2884 &give_up_on_write);
2885 else {
2887 * We scanned the whole range (or exhausted
2888 * nr_to_write), submitted what was mapped and
2889 * didn't find anything needing mapping. We are
2890 * done.
2892 done = true;
2896 * Caution: If the handle is synchronous,
2897 * ext4_journal_stop() can wait for transaction commit
2898 * to finish which may depend on writeback of pages to
2899 * complete or on page lock to be released. In that
2900 * case, we have to wait until after after we have
2901 * submitted all the IO, released page locks we hold,
2902 * and dropped io_end reference (for extent conversion
2903 * to be able to complete) before stopping the handle.
2905 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2906 ext4_journal_stop(handle);
2907 handle = NULL;
2908 mpd.do_map = 0;
2910 /* Submit prepared bio */
2911 ext4_io_submit(&mpd.io_submit);
2912 /* Unlock pages we didn't use */
2913 mpage_release_unused_pages(&mpd, give_up_on_write);
2915 * Drop our io_end reference we got from init. We have
2916 * to be careful and use deferred io_end finishing if
2917 * we are still holding the transaction as we can
2918 * release the last reference to io_end which may end
2919 * up doing unwritten extent conversion.
2921 if (handle) {
2922 ext4_put_io_end_defer(mpd.io_submit.io_end);
2923 ext4_journal_stop(handle);
2924 } else
2925 ext4_put_io_end(mpd.io_submit.io_end);
2926 mpd.io_submit.io_end = NULL;
2928 if (ret == -ENOSPC && sbi->s_journal) {
2930 * Commit the transaction which would
2931 * free blocks released in the transaction
2932 * and try again
2934 jbd2_journal_force_commit_nested(sbi->s_journal);
2935 ret = 0;
2936 continue;
2938 /* Fatal error - ENOMEM, EIO... */
2939 if (ret)
2940 break;
2942 unplug:
2943 blk_finish_plug(&plug);
2944 if (!ret && !cycled && wbc->nr_to_write > 0) {
2945 cycled = 1;
2946 mpd.last_page = writeback_index - 1;
2947 mpd.first_page = 0;
2948 goto retry;
2951 /* Update index */
2952 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2954 * Set the writeback_index so that range_cyclic
2955 * mode will write it back later
2957 mapping->writeback_index = mpd.first_page;
2959 out_writepages:
2960 trace_ext4_writepages_result(inode, wbc, ret,
2961 nr_to_write - wbc->nr_to_write);
2962 percpu_up_read(&sbi->s_journal_flag_rwsem);
2963 return ret;
2966 static int ext4_nonda_switch(struct super_block *sb)
2968 s64 free_clusters, dirty_clusters;
2969 struct ext4_sb_info *sbi = EXT4_SB(sb);
2972 * switch to non delalloc mode if we are running low
2973 * on free block. The free block accounting via percpu
2974 * counters can get slightly wrong with percpu_counter_batch getting
2975 * accumulated on each CPU without updating global counters
2976 * Delalloc need an accurate free block accounting. So switch
2977 * to non delalloc when we are near to error range.
2979 free_clusters =
2980 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2981 dirty_clusters =
2982 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2984 * Start pushing delalloc when 1/2 of free blocks are dirty.
2986 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2987 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2989 if (2 * free_clusters < 3 * dirty_clusters ||
2990 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2992 * free block count is less than 150% of dirty blocks
2993 * or free blocks is less than watermark
2995 return 1;
2997 return 0;
3000 /* We always reserve for an inode update; the superblock could be there too */
3001 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
3003 if (likely(ext4_has_feature_large_file(inode->i_sb)))
3004 return 1;
3006 if (pos + len <= 0x7fffffffULL)
3007 return 1;
3009 /* We might need to update the superblock to set LARGE_FILE */
3010 return 2;
3013 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3014 loff_t pos, unsigned len, unsigned flags,
3015 struct page **pagep, void **fsdata)
3017 int ret, retries = 0;
3018 struct page *page;
3019 pgoff_t index;
3020 struct inode *inode = mapping->host;
3021 handle_t *handle;
3023 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3024 return -EIO;
3026 index = pos >> PAGE_SHIFT;
3028 if (ext4_nonda_switch(inode->i_sb) ||
3029 S_ISLNK(inode->i_mode)) {
3030 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3031 return ext4_write_begin(file, mapping, pos,
3032 len, flags, pagep, fsdata);
3034 *fsdata = (void *)0;
3035 trace_ext4_da_write_begin(inode, pos, len, flags);
3037 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3038 ret = ext4_da_write_inline_data_begin(mapping, inode,
3039 pos, len, flags,
3040 pagep, fsdata);
3041 if (ret < 0)
3042 return ret;
3043 if (ret == 1)
3044 return 0;
3048 * grab_cache_page_write_begin() can take a long time if the
3049 * system is thrashing due to memory pressure, or if the page
3050 * is being written back. So grab it first before we start
3051 * the transaction handle. This also allows us to allocate
3052 * the page (if needed) without using GFP_NOFS.
3054 retry_grab:
3055 page = grab_cache_page_write_begin(mapping, index, flags);
3056 if (!page)
3057 return -ENOMEM;
3058 unlock_page(page);
3061 * With delayed allocation, we don't log the i_disksize update
3062 * if there is delayed block allocation. But we still need
3063 * to journalling the i_disksize update if writes to the end
3064 * of file which has an already mapped buffer.
3066 retry_journal:
3067 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3068 ext4_da_write_credits(inode, pos, len));
3069 if (IS_ERR(handle)) {
3070 put_page(page);
3071 return PTR_ERR(handle);
3074 lock_page(page);
3075 if (page->mapping != mapping) {
3076 /* The page got truncated from under us */
3077 unlock_page(page);
3078 put_page(page);
3079 ext4_journal_stop(handle);
3080 goto retry_grab;
3082 /* In case writeback began while the page was unlocked */
3083 wait_for_stable_page(page);
3085 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3086 ret = ext4_block_write_begin(page, pos, len,
3087 ext4_da_get_block_prep);
3088 #else
3089 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3090 #endif
3091 if (ret < 0) {
3092 unlock_page(page);
3093 ext4_journal_stop(handle);
3095 * block_write_begin may have instantiated a few blocks
3096 * outside i_size. Trim these off again. Don't need
3097 * i_size_read because we hold i_mutex.
3099 if (pos + len > inode->i_size)
3100 ext4_truncate_failed_write(inode);
3102 if (ret == -ENOSPC &&
3103 ext4_should_retry_alloc(inode->i_sb, &retries))
3104 goto retry_journal;
3106 put_page(page);
3107 return ret;
3110 *pagep = page;
3111 return ret;
3115 * Check if we should update i_disksize
3116 * when write to the end of file but not require block allocation
3118 static int ext4_da_should_update_i_disksize(struct page *page,
3119 unsigned long offset)
3121 struct buffer_head *bh;
3122 struct inode *inode = page->mapping->host;
3123 unsigned int idx;
3124 int i;
3126 bh = page_buffers(page);
3127 idx = offset >> inode->i_blkbits;
3129 for (i = 0; i < idx; i++)
3130 bh = bh->b_this_page;
3132 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3133 return 0;
3134 return 1;
3137 static int ext4_da_write_end(struct file *file,
3138 struct address_space *mapping,
3139 loff_t pos, unsigned len, unsigned copied,
3140 struct page *page, void *fsdata)
3142 struct inode *inode = mapping->host;
3143 int ret = 0, ret2;
3144 handle_t *handle = ext4_journal_current_handle();
3145 loff_t new_i_size;
3146 unsigned long start, end;
3147 int write_mode = (int)(unsigned long)fsdata;
3149 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3150 return ext4_write_end(file, mapping, pos,
3151 len, copied, page, fsdata);
3153 trace_ext4_da_write_end(inode, pos, len, copied);
3154 start = pos & (PAGE_SIZE - 1);
3155 end = start + copied - 1;
3158 * generic_write_end() will run mark_inode_dirty() if i_size
3159 * changes. So let's piggyback the i_disksize mark_inode_dirty
3160 * into that.
3162 new_i_size = pos + copied;
3163 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3164 if (ext4_has_inline_data(inode) ||
3165 ext4_da_should_update_i_disksize(page, end)) {
3166 ext4_update_i_disksize(inode, new_i_size);
3167 /* We need to mark inode dirty even if
3168 * new_i_size is less that inode->i_size
3169 * bu greater than i_disksize.(hint delalloc)
3171 ext4_mark_inode_dirty(handle, inode);
3175 if (write_mode != CONVERT_INLINE_DATA &&
3176 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3177 ext4_has_inline_data(inode))
3178 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3179 page);
3180 else
3181 ret2 = generic_write_end(file, mapping, pos, len, copied,
3182 page, fsdata);
3184 copied = ret2;
3185 if (ret2 < 0)
3186 ret = ret2;
3187 ret2 = ext4_journal_stop(handle);
3188 if (!ret)
3189 ret = ret2;
3191 return ret ? ret : copied;
3194 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
3195 unsigned int length)
3198 * Drop reserved blocks
3200 BUG_ON(!PageLocked(page));
3201 if (!page_has_buffers(page))
3202 goto out;
3204 ext4_da_page_release_reservation(page, offset, length);
3206 out:
3207 ext4_invalidatepage(page, offset, length);
3209 return;
3213 * Force all delayed allocation blocks to be allocated for a given inode.
3215 int ext4_alloc_da_blocks(struct inode *inode)
3217 trace_ext4_alloc_da_blocks(inode);
3219 if (!EXT4_I(inode)->i_reserved_data_blocks)
3220 return 0;
3223 * We do something simple for now. The filemap_flush() will
3224 * also start triggering a write of the data blocks, which is
3225 * not strictly speaking necessary (and for users of
3226 * laptop_mode, not even desirable). However, to do otherwise
3227 * would require replicating code paths in:
3229 * ext4_writepages() ->
3230 * write_cache_pages() ---> (via passed in callback function)
3231 * __mpage_da_writepage() -->
3232 * mpage_add_bh_to_extent()
3233 * mpage_da_map_blocks()
3235 * The problem is that write_cache_pages(), located in
3236 * mm/page-writeback.c, marks pages clean in preparation for
3237 * doing I/O, which is not desirable if we're not planning on
3238 * doing I/O at all.
3240 * We could call write_cache_pages(), and then redirty all of
3241 * the pages by calling redirty_page_for_writepage() but that
3242 * would be ugly in the extreme. So instead we would need to
3243 * replicate parts of the code in the above functions,
3244 * simplifying them because we wouldn't actually intend to
3245 * write out the pages, but rather only collect contiguous
3246 * logical block extents, call the multi-block allocator, and
3247 * then update the buffer heads with the block allocations.
3249 * For now, though, we'll cheat by calling filemap_flush(),
3250 * which will map the blocks, and start the I/O, but not
3251 * actually wait for the I/O to complete.
3253 return filemap_flush(inode->i_mapping);
3257 * bmap() is special. It gets used by applications such as lilo and by
3258 * the swapper to find the on-disk block of a specific piece of data.
3260 * Naturally, this is dangerous if the block concerned is still in the
3261 * journal. If somebody makes a swapfile on an ext4 data-journaling
3262 * filesystem and enables swap, then they may get a nasty shock when the
3263 * data getting swapped to that swapfile suddenly gets overwritten by
3264 * the original zero's written out previously to the journal and
3265 * awaiting writeback in the kernel's buffer cache.
3267 * So, if we see any bmap calls here on a modified, data-journaled file,
3268 * take extra steps to flush any blocks which might be in the cache.
3270 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3272 struct inode *inode = mapping->host;
3273 journal_t *journal;
3274 int err;
3277 * We can get here for an inline file via the FIBMAP ioctl
3279 if (ext4_has_inline_data(inode))
3280 return 0;
3282 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3283 test_opt(inode->i_sb, DELALLOC)) {
3285 * With delalloc we want to sync the file
3286 * so that we can make sure we allocate
3287 * blocks for file
3289 filemap_write_and_wait(mapping);
3292 if (EXT4_JOURNAL(inode) &&
3293 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3295 * This is a REALLY heavyweight approach, but the use of
3296 * bmap on dirty files is expected to be extremely rare:
3297 * only if we run lilo or swapon on a freshly made file
3298 * do we expect this to happen.
3300 * (bmap requires CAP_SYS_RAWIO so this does not
3301 * represent an unprivileged user DOS attack --- we'd be
3302 * in trouble if mortal users could trigger this path at
3303 * will.)
3305 * NB. EXT4_STATE_JDATA is not set on files other than
3306 * regular files. If somebody wants to bmap a directory
3307 * or symlink and gets confused because the buffer
3308 * hasn't yet been flushed to disk, they deserve
3309 * everything they get.
3312 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3313 journal = EXT4_JOURNAL(inode);
3314 jbd2_journal_lock_updates(journal);
3315 err = jbd2_journal_flush(journal);
3316 jbd2_journal_unlock_updates(journal);
3318 if (err)
3319 return 0;
3322 return generic_block_bmap(mapping, block, ext4_get_block);
3325 static int ext4_readpage(struct file *file, struct page *page)
3327 int ret = -EAGAIN;
3328 struct inode *inode = page->mapping->host;
3330 trace_ext4_readpage(page);
3332 if (ext4_has_inline_data(inode))
3333 ret = ext4_readpage_inline(inode, page);
3335 if (ret == -EAGAIN)
3336 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3338 return ret;
3341 static int
3342 ext4_readpages(struct file *file, struct address_space *mapping,
3343 struct list_head *pages, unsigned nr_pages)
3345 struct inode *inode = mapping->host;
3347 /* If the file has inline data, no need to do readpages. */
3348 if (ext4_has_inline_data(inode))
3349 return 0;
3351 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3354 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3355 unsigned int length)
3357 trace_ext4_invalidatepage(page, offset, length);
3359 /* No journalling happens on data buffers when this function is used */
3360 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3362 block_invalidatepage(page, offset, length);
3365 static int __ext4_journalled_invalidatepage(struct page *page,
3366 unsigned int offset,
3367 unsigned int length)
3369 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3371 trace_ext4_journalled_invalidatepage(page, offset, length);
3374 * If it's a full truncate we just forget about the pending dirtying
3376 if (offset == 0 && length == PAGE_SIZE)
3377 ClearPageChecked(page);
3379 return jbd2_journal_invalidatepage(journal, page, offset, length);
3382 /* Wrapper for aops... */
3383 static void ext4_journalled_invalidatepage(struct page *page,
3384 unsigned int offset,
3385 unsigned int length)
3387 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3390 static int ext4_releasepage(struct page *page, gfp_t wait)
3392 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3394 trace_ext4_releasepage(page);
3396 /* Page has dirty journalled data -> cannot release */
3397 if (PageChecked(page))
3398 return 0;
3399 if (journal)
3400 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3401 else
3402 return try_to_free_buffers(page);
3405 #ifdef CONFIG_FS_DAX
3406 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3407 unsigned flags, struct iomap *iomap)
3409 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3410 unsigned int blkbits = inode->i_blkbits;
3411 unsigned long first_block, last_block;
3412 struct ext4_map_blocks map;
3413 int ret;
3415 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3416 return -EINVAL;
3417 first_block = offset >> blkbits;
3418 last_block = min_t(loff_t, (offset + length - 1) >> blkbits,
3419 EXT4_MAX_LOGICAL_BLOCK);
3421 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3422 return -ERANGE;
3424 map.m_lblk = first_block;
3425 map.m_len = last_block - first_block + 1;
3427 if (!(flags & IOMAP_WRITE)) {
3428 ret = ext4_map_blocks(NULL, inode, &map, 0);
3429 } else {
3430 int dio_credits;
3431 handle_t *handle;
3432 int retries = 0;
3434 /* Trim mapping request to maximum we can map at once for DIO */
3435 if (map.m_len > DIO_MAX_BLOCKS)
3436 map.m_len = DIO_MAX_BLOCKS;
3437 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3438 retry:
3440 * Either we allocate blocks and then we don't get unwritten
3441 * extent so we have reserved enough credits, or the blocks
3442 * are already allocated and unwritten and in that case
3443 * extent conversion fits in the credits as well.
3445 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3446 dio_credits);
3447 if (IS_ERR(handle))
3448 return PTR_ERR(handle);
3450 ret = ext4_map_blocks(handle, inode, &map,
3451 EXT4_GET_BLOCKS_CREATE_ZERO);
3452 if (ret < 0) {
3453 ext4_journal_stop(handle);
3454 if (ret == -ENOSPC &&
3455 ext4_should_retry_alloc(inode->i_sb, &retries))
3456 goto retry;
3457 return ret;
3461 * If we added blocks beyond i_size, we need to make sure they
3462 * will get truncated if we crash before updating i_size in
3463 * ext4_iomap_end(). For faults we don't need to do that (and
3464 * even cannot because for orphan list operations inode_lock is
3465 * required) - if we happen to instantiate block beyond i_size,
3466 * it is because we race with truncate which has already added
3467 * the inode to the orphan list.
3469 if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3470 (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
3471 int err;
3473 err = ext4_orphan_add(handle, inode);
3474 if (err < 0) {
3475 ext4_journal_stop(handle);
3476 return err;
3479 ext4_journal_stop(handle);
3482 iomap->flags = 0;
3483 iomap->bdev = inode->i_sb->s_bdev;
3484 iomap->dax_dev = sbi->s_daxdev;
3485 iomap->offset = first_block << blkbits;
3487 if (ret == 0) {
3488 iomap->type = IOMAP_HOLE;
3489 iomap->blkno = IOMAP_NULL_BLOCK;
3490 iomap->length = (u64)map.m_len << blkbits;
3491 } else {
3492 if (map.m_flags & EXT4_MAP_MAPPED) {
3493 iomap->type = IOMAP_MAPPED;
3494 } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3495 iomap->type = IOMAP_UNWRITTEN;
3496 } else {
3497 WARN_ON_ONCE(1);
3498 return -EIO;
3500 iomap->blkno = (sector_t)map.m_pblk << (blkbits - 9);
3501 iomap->length = (u64)map.m_len << blkbits;
3504 if (map.m_flags & EXT4_MAP_NEW)
3505 iomap->flags |= IOMAP_F_NEW;
3506 return 0;
3509 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3510 ssize_t written, unsigned flags, struct iomap *iomap)
3512 int ret = 0;
3513 handle_t *handle;
3514 int blkbits = inode->i_blkbits;
3515 bool truncate = false;
3517 if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
3518 return 0;
3520 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3521 if (IS_ERR(handle)) {
3522 ret = PTR_ERR(handle);
3523 goto orphan_del;
3525 if (ext4_update_inode_size(inode, offset + written))
3526 ext4_mark_inode_dirty(handle, inode);
3528 * We may need to truncate allocated but not written blocks beyond EOF.
3530 if (iomap->offset + iomap->length >
3531 ALIGN(inode->i_size, 1 << blkbits)) {
3532 ext4_lblk_t written_blk, end_blk;
3534 written_blk = (offset + written) >> blkbits;
3535 end_blk = (offset + length) >> blkbits;
3536 if (written_blk < end_blk && ext4_can_truncate(inode))
3537 truncate = true;
3540 * Remove inode from orphan list if we were extending a inode and
3541 * everything went fine.
3543 if (!truncate && inode->i_nlink &&
3544 !list_empty(&EXT4_I(inode)->i_orphan))
3545 ext4_orphan_del(handle, inode);
3546 ext4_journal_stop(handle);
3547 if (truncate) {
3548 ext4_truncate_failed_write(inode);
3549 orphan_del:
3551 * If truncate failed early the inode might still be on the
3552 * orphan list; we need to make sure the inode is removed from
3553 * the orphan list in that case.
3555 if (inode->i_nlink)
3556 ext4_orphan_del(NULL, inode);
3558 return ret;
3561 const struct iomap_ops ext4_iomap_ops = {
3562 .iomap_begin = ext4_iomap_begin,
3563 .iomap_end = ext4_iomap_end,
3566 #endif
3568 static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3569 ssize_t size, void *private)
3571 ext4_io_end_t *io_end = private;
3573 /* if not async direct IO just return */
3574 if (!io_end)
3575 return 0;
3577 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3578 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3579 io_end, io_end->inode->i_ino, iocb, offset, size);
3582 * Error during AIO DIO. We cannot convert unwritten extents as the
3583 * data was not written. Just clear the unwritten flag and drop io_end.
3585 if (size <= 0) {
3586 ext4_clear_io_unwritten_flag(io_end);
3587 size = 0;
3589 io_end->offset = offset;
3590 io_end->size = size;
3591 ext4_put_io_end(io_end);
3593 return 0;
3597 * Handling of direct IO writes.
3599 * For ext4 extent files, ext4 will do direct-io write even to holes,
3600 * preallocated extents, and those write extend the file, no need to
3601 * fall back to buffered IO.
3603 * For holes, we fallocate those blocks, mark them as unwritten
3604 * If those blocks were preallocated, we mark sure they are split, but
3605 * still keep the range to write as unwritten.
3607 * The unwritten extents will be converted to written when DIO is completed.
3608 * For async direct IO, since the IO may still pending when return, we
3609 * set up an end_io call back function, which will do the conversion
3610 * when async direct IO completed.
3612 * If the O_DIRECT write will extend the file then add this inode to the
3613 * orphan list. So recovery will truncate it back to the original size
3614 * if the machine crashes during the write.
3617 static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
3619 struct file *file = iocb->ki_filp;
3620 struct inode *inode = file->f_mapping->host;
3621 ssize_t ret;
3622 loff_t offset = iocb->ki_pos;
3623 size_t count = iov_iter_count(iter);
3624 int overwrite = 0;
3625 get_block_t *get_block_func = NULL;
3626 int dio_flags = 0;
3627 loff_t final_size = offset + count;
3628 int orphan = 0;
3629 handle_t *handle;
3631 if (final_size > inode->i_size) {
3632 /* Credits for sb + inode write */
3633 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3634 if (IS_ERR(handle)) {
3635 ret = PTR_ERR(handle);
3636 goto out;
3638 ret = ext4_orphan_add(handle, inode);
3639 if (ret) {
3640 ext4_journal_stop(handle);
3641 goto out;
3643 orphan = 1;
3644 ext4_update_i_disksize(inode, inode->i_size);
3645 ext4_journal_stop(handle);
3648 BUG_ON(iocb->private == NULL);
3651 * Make all waiters for direct IO properly wait also for extent
3652 * conversion. This also disallows race between truncate() and
3653 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3655 inode_dio_begin(inode);
3657 /* If we do a overwrite dio, i_mutex locking can be released */
3658 overwrite = *((int *)iocb->private);
3660 if (overwrite)
3661 inode_unlock(inode);
3664 * For extent mapped files we could direct write to holes and fallocate.
3666 * Allocated blocks to fill the hole are marked as unwritten to prevent
3667 * parallel buffered read to expose the stale data before DIO complete
3668 * the data IO.
3670 * As to previously fallocated extents, ext4 get_block will just simply
3671 * mark the buffer mapped but still keep the extents unwritten.
3673 * For non AIO case, we will convert those unwritten extents to written
3674 * after return back from blockdev_direct_IO. That way we save us from
3675 * allocating io_end structure and also the overhead of offloading
3676 * the extent convertion to a workqueue.
3678 * For async DIO, the conversion needs to be deferred when the
3679 * IO is completed. The ext4 end_io callback function will be
3680 * called to take care of the conversion work. Here for async
3681 * case, we allocate an io_end structure to hook to the iocb.
3683 iocb->private = NULL;
3684 if (overwrite)
3685 get_block_func = ext4_dio_get_block_overwrite;
3686 else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
3687 round_down(offset, i_blocksize(inode)) >= inode->i_size) {
3688 get_block_func = ext4_dio_get_block;
3689 dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3690 } else if (is_sync_kiocb(iocb)) {
3691 get_block_func = ext4_dio_get_block_unwritten_sync;
3692 dio_flags = DIO_LOCKING;
3693 } else {
3694 get_block_func = ext4_dio_get_block_unwritten_async;
3695 dio_flags = DIO_LOCKING;
3697 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3698 get_block_func, ext4_end_io_dio, NULL,
3699 dio_flags);
3701 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3702 EXT4_STATE_DIO_UNWRITTEN)) {
3703 int err;
3705 * for non AIO case, since the IO is already
3706 * completed, we could do the conversion right here
3708 err = ext4_convert_unwritten_extents(NULL, inode,
3709 offset, ret);
3710 if (err < 0)
3711 ret = err;
3712 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3715 inode_dio_end(inode);
3716 /* take i_mutex locking again if we do a ovewrite dio */
3717 if (overwrite)
3718 inode_lock(inode);
3720 if (ret < 0 && final_size > inode->i_size)
3721 ext4_truncate_failed_write(inode);
3723 /* Handle extending of i_size after direct IO write */
3724 if (orphan) {
3725 int err;
3727 /* Credits for sb + inode write */
3728 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3729 if (IS_ERR(handle)) {
3731 * We wrote the data but cannot extend
3732 * i_size. Bail out. In async io case, we do
3733 * not return error here because we have
3734 * already submmitted the corresponding
3735 * bio. Returning error here makes the caller
3736 * think that this IO is done and failed
3737 * resulting in race with bio's completion
3738 * handler.
3740 if (!ret)
3741 ret = PTR_ERR(handle);
3742 if (inode->i_nlink)
3743 ext4_orphan_del(NULL, inode);
3745 goto out;
3747 if (inode->i_nlink)
3748 ext4_orphan_del(handle, inode);
3749 if (ret > 0) {
3750 loff_t end = offset + ret;
3751 if (end > inode->i_size) {
3752 ext4_update_i_disksize(inode, end);
3753 i_size_write(inode, end);
3755 * We're going to return a positive `ret'
3756 * here due to non-zero-length I/O, so there's
3757 * no way of reporting error returns from
3758 * ext4_mark_inode_dirty() to userspace. So
3759 * ignore it.
3761 ext4_mark_inode_dirty(handle, inode);
3764 err = ext4_journal_stop(handle);
3765 if (ret == 0)
3766 ret = err;
3768 out:
3769 return ret;
3772 static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
3774 struct address_space *mapping = iocb->ki_filp->f_mapping;
3775 struct inode *inode = mapping->host;
3776 size_t count = iov_iter_count(iter);
3777 ssize_t ret;
3780 * Shared inode_lock is enough for us - it protects against concurrent
3781 * writes & truncates and since we take care of writing back page cache,
3782 * we are protected against page writeback as well.
3784 inode_lock_shared(inode);
3785 ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
3786 iocb->ki_pos + count - 1);
3787 if (ret)
3788 goto out_unlock;
3789 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
3790 iter, ext4_dio_get_block, NULL, NULL, 0);
3791 out_unlock:
3792 inode_unlock_shared(inode);
3793 return ret;
3796 static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
3798 struct file *file = iocb->ki_filp;
3799 struct inode *inode = file->f_mapping->host;
3800 size_t count = iov_iter_count(iter);
3801 loff_t offset = iocb->ki_pos;
3802 ssize_t ret;
3804 #ifdef CONFIG_EXT4_FS_ENCRYPTION
3805 if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
3806 return 0;
3807 #endif
3810 * If we are doing data journalling we don't support O_DIRECT
3812 if (ext4_should_journal_data(inode))
3813 return 0;
3815 /* Let buffer I/O handle the inline data case. */
3816 if (ext4_has_inline_data(inode))
3817 return 0;
3819 /* DAX uses iomap path now */
3820 if (WARN_ON_ONCE(IS_DAX(inode)))
3821 return 0;
3823 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
3824 if (iov_iter_rw(iter) == READ)
3825 ret = ext4_direct_IO_read(iocb, iter);
3826 else
3827 ret = ext4_direct_IO_write(iocb, iter);
3828 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
3829 return ret;
3833 * Pages can be marked dirty completely asynchronously from ext4's journalling
3834 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3835 * much here because ->set_page_dirty is called under VFS locks. The page is
3836 * not necessarily locked.
3838 * We cannot just dirty the page and leave attached buffers clean, because the
3839 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3840 * or jbddirty because all the journalling code will explode.
3842 * So what we do is to mark the page "pending dirty" and next time writepage
3843 * is called, propagate that into the buffers appropriately.
3845 static int ext4_journalled_set_page_dirty(struct page *page)
3847 SetPageChecked(page);
3848 return __set_page_dirty_nobuffers(page);
3851 static int ext4_set_page_dirty(struct page *page)
3853 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3854 WARN_ON_ONCE(!page_has_buffers(page));
3855 return __set_page_dirty_buffers(page);
3858 static const struct address_space_operations ext4_aops = {
3859 .readpage = ext4_readpage,
3860 .readpages = ext4_readpages,
3861 .writepage = ext4_writepage,
3862 .writepages = ext4_writepages,
3863 .write_begin = ext4_write_begin,
3864 .write_end = ext4_write_end,
3865 .set_page_dirty = ext4_set_page_dirty,
3866 .bmap = ext4_bmap,
3867 .invalidatepage = ext4_invalidatepage,
3868 .releasepage = ext4_releasepage,
3869 .direct_IO = ext4_direct_IO,
3870 .migratepage = buffer_migrate_page,
3871 .is_partially_uptodate = block_is_partially_uptodate,
3872 .error_remove_page = generic_error_remove_page,
3875 static const struct address_space_operations ext4_journalled_aops = {
3876 .readpage = ext4_readpage,
3877 .readpages = ext4_readpages,
3878 .writepage = ext4_writepage,
3879 .writepages = ext4_writepages,
3880 .write_begin = ext4_write_begin,
3881 .write_end = ext4_journalled_write_end,
3882 .set_page_dirty = ext4_journalled_set_page_dirty,
3883 .bmap = ext4_bmap,
3884 .invalidatepage = ext4_journalled_invalidatepage,
3885 .releasepage = ext4_releasepage,
3886 .direct_IO = ext4_direct_IO,
3887 .is_partially_uptodate = block_is_partially_uptodate,
3888 .error_remove_page = generic_error_remove_page,
3891 static const struct address_space_operations ext4_da_aops = {
3892 .readpage = ext4_readpage,
3893 .readpages = ext4_readpages,
3894 .writepage = ext4_writepage,
3895 .writepages = ext4_writepages,
3896 .write_begin = ext4_da_write_begin,
3897 .write_end = ext4_da_write_end,
3898 .set_page_dirty = ext4_set_page_dirty,
3899 .bmap = ext4_bmap,
3900 .invalidatepage = ext4_da_invalidatepage,
3901 .releasepage = ext4_releasepage,
3902 .direct_IO = ext4_direct_IO,
3903 .migratepage = buffer_migrate_page,
3904 .is_partially_uptodate = block_is_partially_uptodate,
3905 .error_remove_page = generic_error_remove_page,
3908 void ext4_set_aops(struct inode *inode)
3910 switch (ext4_inode_journal_mode(inode)) {
3911 case EXT4_INODE_ORDERED_DATA_MODE:
3912 case EXT4_INODE_WRITEBACK_DATA_MODE:
3913 break;
3914 case EXT4_INODE_JOURNAL_DATA_MODE:
3915 inode->i_mapping->a_ops = &ext4_journalled_aops;
3916 return;
3917 default:
3918 BUG();
3920 if (test_opt(inode->i_sb, DELALLOC))
3921 inode->i_mapping->a_ops = &ext4_da_aops;
3922 else
3923 inode->i_mapping->a_ops = &ext4_aops;
3926 static int __ext4_block_zero_page_range(handle_t *handle,
3927 struct address_space *mapping, loff_t from, loff_t length)
3929 ext4_fsblk_t index = from >> PAGE_SHIFT;
3930 unsigned offset = from & (PAGE_SIZE-1);
3931 unsigned blocksize, pos;
3932 ext4_lblk_t iblock;
3933 struct inode *inode = mapping->host;
3934 struct buffer_head *bh;
3935 struct page *page;
3936 int err = 0;
3938 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3939 mapping_gfp_constraint(mapping, ~__GFP_FS));
3940 if (!page)
3941 return -ENOMEM;
3943 blocksize = inode->i_sb->s_blocksize;
3945 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3947 if (!page_has_buffers(page))
3948 create_empty_buffers(page, blocksize, 0);
3950 /* Find the buffer that contains "offset" */
3951 bh = page_buffers(page);
3952 pos = blocksize;
3953 while (offset >= pos) {
3954 bh = bh->b_this_page;
3955 iblock++;
3956 pos += blocksize;
3958 if (buffer_freed(bh)) {
3959 BUFFER_TRACE(bh, "freed: skip");
3960 goto unlock;
3962 if (!buffer_mapped(bh)) {
3963 BUFFER_TRACE(bh, "unmapped");
3964 ext4_get_block(inode, iblock, bh, 0);
3965 /* unmapped? It's a hole - nothing to do */
3966 if (!buffer_mapped(bh)) {
3967 BUFFER_TRACE(bh, "still unmapped");
3968 goto unlock;
3972 /* Ok, it's mapped. Make sure it's up-to-date */
3973 if (PageUptodate(page))
3974 set_buffer_uptodate(bh);
3976 if (!buffer_uptodate(bh)) {
3977 err = -EIO;
3978 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
3979 wait_on_buffer(bh);
3980 /* Uhhuh. Read error. Complain and punt. */
3981 if (!buffer_uptodate(bh))
3982 goto unlock;
3983 if (S_ISREG(inode->i_mode) &&
3984 ext4_encrypted_inode(inode)) {
3985 /* We expect the key to be set. */
3986 BUG_ON(!fscrypt_has_encryption_key(inode));
3987 BUG_ON(blocksize != PAGE_SIZE);
3988 WARN_ON_ONCE(fscrypt_decrypt_page(page->mapping->host,
3989 page, PAGE_SIZE, 0, page->index));
3992 if (ext4_should_journal_data(inode)) {
3993 BUFFER_TRACE(bh, "get write access");
3994 err = ext4_journal_get_write_access(handle, bh);
3995 if (err)
3996 goto unlock;
3998 zero_user(page, offset, length);
3999 BUFFER_TRACE(bh, "zeroed end of block");
4001 if (ext4_should_journal_data(inode)) {
4002 err = ext4_handle_dirty_metadata(handle, inode, bh);
4003 } else {
4004 err = 0;
4005 mark_buffer_dirty(bh);
4006 if (ext4_should_order_data(inode))
4007 err = ext4_jbd2_inode_add_write(handle, inode);
4010 unlock:
4011 unlock_page(page);
4012 put_page(page);
4013 return err;
4017 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4018 * starting from file offset 'from'. The range to be zero'd must
4019 * be contained with in one block. If the specified range exceeds
4020 * the end of the block it will be shortened to end of the block
4021 * that cooresponds to 'from'
4023 static int ext4_block_zero_page_range(handle_t *handle,
4024 struct address_space *mapping, loff_t from, loff_t length)
4026 struct inode *inode = mapping->host;
4027 unsigned offset = from & (PAGE_SIZE-1);
4028 unsigned blocksize = inode->i_sb->s_blocksize;
4029 unsigned max = blocksize - (offset & (blocksize - 1));
4032 * correct length if it does not fall between
4033 * 'from' and the end of the block
4035 if (length > max || length < 0)
4036 length = max;
4038 if (IS_DAX(inode)) {
4039 return iomap_zero_range(inode, from, length, NULL,
4040 &ext4_iomap_ops);
4042 return __ext4_block_zero_page_range(handle, mapping, from, length);
4046 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4047 * up to the end of the block which corresponds to `from'.
4048 * This required during truncate. We need to physically zero the tail end
4049 * of that block so it doesn't yield old data if the file is later grown.
4051 static int ext4_block_truncate_page(handle_t *handle,
4052 struct address_space *mapping, loff_t from)
4054 unsigned offset = from & (PAGE_SIZE-1);
4055 unsigned length;
4056 unsigned blocksize;
4057 struct inode *inode = mapping->host;
4059 /* If we are processing an encrypted inode during orphan list handling */
4060 if (ext4_encrypted_inode(inode) && !fscrypt_has_encryption_key(inode))
4061 return 0;
4063 blocksize = inode->i_sb->s_blocksize;
4064 length = blocksize - (offset & (blocksize - 1));
4066 return ext4_block_zero_page_range(handle, mapping, from, length);
4069 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4070 loff_t lstart, loff_t length)
4072 struct super_block *sb = inode->i_sb;
4073 struct address_space *mapping = inode->i_mapping;
4074 unsigned partial_start, partial_end;
4075 ext4_fsblk_t start, end;
4076 loff_t byte_end = (lstart + length - 1);
4077 int err = 0;
4079 partial_start = lstart & (sb->s_blocksize - 1);
4080 partial_end = byte_end & (sb->s_blocksize - 1);
4082 start = lstart >> sb->s_blocksize_bits;
4083 end = byte_end >> sb->s_blocksize_bits;
4085 /* Handle partial zero within the single block */
4086 if (start == end &&
4087 (partial_start || (partial_end != sb->s_blocksize - 1))) {
4088 err = ext4_block_zero_page_range(handle, mapping,
4089 lstart, length);
4090 return err;
4092 /* Handle partial zero out on the start of the range */
4093 if (partial_start) {
4094 err = ext4_block_zero_page_range(handle, mapping,
4095 lstart, sb->s_blocksize);
4096 if (err)
4097 return err;
4099 /* Handle partial zero out on the end of the range */
4100 if (partial_end != sb->s_blocksize - 1)
4101 err = ext4_block_zero_page_range(handle, mapping,
4102 byte_end - partial_end,
4103 partial_end + 1);
4104 return err;
4107 int ext4_can_truncate(struct inode *inode)
4109 if (S_ISREG(inode->i_mode))
4110 return 1;
4111 if (S_ISDIR(inode->i_mode))
4112 return 1;
4113 if (S_ISLNK(inode->i_mode))
4114 return !ext4_inode_is_fast_symlink(inode);
4115 return 0;
4119 * We have to make sure i_disksize gets properly updated before we truncate
4120 * page cache due to hole punching or zero range. Otherwise i_disksize update
4121 * can get lost as it may have been postponed to submission of writeback but
4122 * that will never happen after we truncate page cache.
4124 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4125 loff_t len)
4127 handle_t *handle;
4128 loff_t size = i_size_read(inode);
4130 WARN_ON(!inode_is_locked(inode));
4131 if (offset > size || offset + len < size)
4132 return 0;
4134 if (EXT4_I(inode)->i_disksize >= size)
4135 return 0;
4137 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4138 if (IS_ERR(handle))
4139 return PTR_ERR(handle);
4140 ext4_update_i_disksize(inode, size);
4141 ext4_mark_inode_dirty(handle, inode);
4142 ext4_journal_stop(handle);
4144 return 0;
4148 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4149 * associated with the given offset and length
4151 * @inode: File inode
4152 * @offset: The offset where the hole will begin
4153 * @len: The length of the hole
4155 * Returns: 0 on success or negative on failure
4158 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
4160 struct super_block *sb = inode->i_sb;
4161 ext4_lblk_t first_block, stop_block;
4162 struct address_space *mapping = inode->i_mapping;
4163 loff_t first_block_offset, last_block_offset;
4164 handle_t *handle;
4165 unsigned int credits;
4166 int ret = 0;
4168 if (!S_ISREG(inode->i_mode))
4169 return -EOPNOTSUPP;
4171 trace_ext4_punch_hole(inode, offset, length, 0);
4174 * Write out all dirty pages to avoid race conditions
4175 * Then release them.
4177 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4178 ret = filemap_write_and_wait_range(mapping, offset,
4179 offset + length - 1);
4180 if (ret)
4181 return ret;
4184 inode_lock(inode);
4186 /* No need to punch hole beyond i_size */
4187 if (offset >= inode->i_size)
4188 goto out_mutex;
4191 * If the hole extends beyond i_size, set the hole
4192 * to end after the page that contains i_size
4194 if (offset + length > inode->i_size) {
4195 length = inode->i_size +
4196 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4197 offset;
4200 if (offset & (sb->s_blocksize - 1) ||
4201 (offset + length) & (sb->s_blocksize - 1)) {
4203 * Attach jinode to inode for jbd2 if we do any zeroing of
4204 * partial block
4206 ret = ext4_inode_attach_jinode(inode);
4207 if (ret < 0)
4208 goto out_mutex;
4212 /* Wait all existing dio workers, newcomers will block on i_mutex */
4213 ext4_inode_block_unlocked_dio(inode);
4214 inode_dio_wait(inode);
4217 * Prevent page faults from reinstantiating pages we have released from
4218 * page cache.
4220 down_write(&EXT4_I(inode)->i_mmap_sem);
4221 first_block_offset = round_up(offset, sb->s_blocksize);
4222 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4224 /* Now release the pages and zero block aligned part of pages*/
4225 if (last_block_offset > first_block_offset) {
4226 ret = ext4_update_disksize_before_punch(inode, offset, length);
4227 if (ret)
4228 goto out_dio;
4229 truncate_pagecache_range(inode, first_block_offset,
4230 last_block_offset);
4233 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4234 credits = ext4_writepage_trans_blocks(inode);
4235 else
4236 credits = ext4_blocks_for_truncate(inode);
4237 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4238 if (IS_ERR(handle)) {
4239 ret = PTR_ERR(handle);
4240 ext4_std_error(sb, ret);
4241 goto out_dio;
4244 ret = ext4_zero_partial_blocks(handle, inode, offset,
4245 length);
4246 if (ret)
4247 goto out_stop;
4249 first_block = (offset + sb->s_blocksize - 1) >>
4250 EXT4_BLOCK_SIZE_BITS(sb);
4251 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4253 /* If there are blocks to remove, do it */
4254 if (stop_block > first_block) {
4256 down_write(&EXT4_I(inode)->i_data_sem);
4257 ext4_discard_preallocations(inode);
4259 ret = ext4_es_remove_extent(inode, first_block,
4260 stop_block - first_block);
4261 if (ret) {
4262 up_write(&EXT4_I(inode)->i_data_sem);
4263 goto out_stop;
4266 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4267 ret = ext4_ext_remove_space(inode, first_block,
4268 stop_block - 1);
4269 else
4270 ret = ext4_ind_remove_space(handle, inode, first_block,
4271 stop_block);
4273 up_write(&EXT4_I(inode)->i_data_sem);
4275 if (IS_SYNC(inode))
4276 ext4_handle_sync(handle);
4278 inode->i_mtime = inode->i_ctime = current_time(inode);
4279 ext4_mark_inode_dirty(handle, inode);
4280 if (ret >= 0)
4281 ext4_update_inode_fsync_trans(handle, inode, 1);
4282 out_stop:
4283 ext4_journal_stop(handle);
4284 out_dio:
4285 up_write(&EXT4_I(inode)->i_mmap_sem);
4286 ext4_inode_resume_unlocked_dio(inode);
4287 out_mutex:
4288 inode_unlock(inode);
4289 return ret;
4292 int ext4_inode_attach_jinode(struct inode *inode)
4294 struct ext4_inode_info *ei = EXT4_I(inode);
4295 struct jbd2_inode *jinode;
4297 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4298 return 0;
4300 jinode = jbd2_alloc_inode(GFP_KERNEL);
4301 spin_lock(&inode->i_lock);
4302 if (!ei->jinode) {
4303 if (!jinode) {
4304 spin_unlock(&inode->i_lock);
4305 return -ENOMEM;
4307 ei->jinode = jinode;
4308 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4309 jinode = NULL;
4311 spin_unlock(&inode->i_lock);
4312 if (unlikely(jinode != NULL))
4313 jbd2_free_inode(jinode);
4314 return 0;
4318 * ext4_truncate()
4320 * We block out ext4_get_block() block instantiations across the entire
4321 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4322 * simultaneously on behalf of the same inode.
4324 * As we work through the truncate and commit bits of it to the journal there
4325 * is one core, guiding principle: the file's tree must always be consistent on
4326 * disk. We must be able to restart the truncate after a crash.
4328 * The file's tree may be transiently inconsistent in memory (although it
4329 * probably isn't), but whenever we close off and commit a journal transaction,
4330 * the contents of (the filesystem + the journal) must be consistent and
4331 * restartable. It's pretty simple, really: bottom up, right to left (although
4332 * left-to-right works OK too).
4334 * Note that at recovery time, journal replay occurs *before* the restart of
4335 * truncate against the orphan inode list.
4337 * The committed inode has the new, desired i_size (which is the same as
4338 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4339 * that this inode's truncate did not complete and it will again call
4340 * ext4_truncate() to have another go. So there will be instantiated blocks
4341 * to the right of the truncation point in a crashed ext4 filesystem. But
4342 * that's fine - as long as they are linked from the inode, the post-crash
4343 * ext4_truncate() run will find them and release them.
4345 int ext4_truncate(struct inode *inode)
4347 struct ext4_inode_info *ei = EXT4_I(inode);
4348 unsigned int credits;
4349 int err = 0;
4350 handle_t *handle;
4351 struct address_space *mapping = inode->i_mapping;
4354 * There is a possibility that we're either freeing the inode
4355 * or it's a completely new inode. In those cases we might not
4356 * have i_mutex locked because it's not necessary.
4358 if (!(inode->i_state & (I_NEW|I_FREEING)))
4359 WARN_ON(!inode_is_locked(inode));
4360 trace_ext4_truncate_enter(inode);
4362 if (!ext4_can_truncate(inode))
4363 return 0;
4365 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4367 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4368 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4370 if (ext4_has_inline_data(inode)) {
4371 int has_inline = 1;
4373 err = ext4_inline_data_truncate(inode, &has_inline);
4374 if (err)
4375 return err;
4376 if (has_inline)
4377 return 0;
4380 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4381 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4382 if (ext4_inode_attach_jinode(inode) < 0)
4383 return 0;
4386 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4387 credits = ext4_writepage_trans_blocks(inode);
4388 else
4389 credits = ext4_blocks_for_truncate(inode);
4391 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4392 if (IS_ERR(handle))
4393 return PTR_ERR(handle);
4395 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4396 ext4_block_truncate_page(handle, mapping, inode->i_size);
4399 * We add the inode to the orphan list, so that if this
4400 * truncate spans multiple transactions, and we crash, we will
4401 * resume the truncate when the filesystem recovers. It also
4402 * marks the inode dirty, to catch the new size.
4404 * Implication: the file must always be in a sane, consistent
4405 * truncatable state while each transaction commits.
4407 err = ext4_orphan_add(handle, inode);
4408 if (err)
4409 goto out_stop;
4411 down_write(&EXT4_I(inode)->i_data_sem);
4413 ext4_discard_preallocations(inode);
4415 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4416 err = ext4_ext_truncate(handle, inode);
4417 else
4418 ext4_ind_truncate(handle, inode);
4420 up_write(&ei->i_data_sem);
4421 if (err)
4422 goto out_stop;
4424 if (IS_SYNC(inode))
4425 ext4_handle_sync(handle);
4427 out_stop:
4429 * If this was a simple ftruncate() and the file will remain alive,
4430 * then we need to clear up the orphan record which we created above.
4431 * However, if this was a real unlink then we were called by
4432 * ext4_evict_inode(), and we allow that function to clean up the
4433 * orphan info for us.
4435 if (inode->i_nlink)
4436 ext4_orphan_del(handle, inode);
4438 inode->i_mtime = inode->i_ctime = current_time(inode);
4439 ext4_mark_inode_dirty(handle, inode);
4440 ext4_journal_stop(handle);
4442 trace_ext4_truncate_exit(inode);
4443 return err;
4447 * ext4_get_inode_loc returns with an extra refcount against the inode's
4448 * underlying buffer_head on success. If 'in_mem' is true, we have all
4449 * data in memory that is needed to recreate the on-disk version of this
4450 * inode.
4452 static int __ext4_get_inode_loc(struct inode *inode,
4453 struct ext4_iloc *iloc, int in_mem)
4455 struct ext4_group_desc *gdp;
4456 struct buffer_head *bh;
4457 struct super_block *sb = inode->i_sb;
4458 ext4_fsblk_t block;
4459 int inodes_per_block, inode_offset;
4461 iloc->bh = NULL;
4462 if (inode->i_ino < EXT4_ROOT_INO ||
4463 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4464 return -EFSCORRUPTED;
4466 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4467 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4468 if (!gdp)
4469 return -EIO;
4472 * Figure out the offset within the block group inode table
4474 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4475 inode_offset = ((inode->i_ino - 1) %
4476 EXT4_INODES_PER_GROUP(sb));
4477 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4478 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4480 bh = sb_getblk(sb, block);
4481 if (unlikely(!bh))
4482 return -ENOMEM;
4483 if (!buffer_uptodate(bh)) {
4484 lock_buffer(bh);
4487 * If the buffer has the write error flag, we have failed
4488 * to write out another inode in the same block. In this
4489 * case, we don't have to read the block because we may
4490 * read the old inode data successfully.
4492 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4493 set_buffer_uptodate(bh);
4495 if (buffer_uptodate(bh)) {
4496 /* someone brought it uptodate while we waited */
4497 unlock_buffer(bh);
4498 goto has_buffer;
4502 * If we have all information of the inode in memory and this
4503 * is the only valid inode in the block, we need not read the
4504 * block.
4506 if (in_mem) {
4507 struct buffer_head *bitmap_bh;
4508 int i, start;
4510 start = inode_offset & ~(inodes_per_block - 1);
4512 /* Is the inode bitmap in cache? */
4513 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4514 if (unlikely(!bitmap_bh))
4515 goto make_io;
4518 * If the inode bitmap isn't in cache then the
4519 * optimisation may end up performing two reads instead
4520 * of one, so skip it.
4522 if (!buffer_uptodate(bitmap_bh)) {
4523 brelse(bitmap_bh);
4524 goto make_io;
4526 for (i = start; i < start + inodes_per_block; i++) {
4527 if (i == inode_offset)
4528 continue;
4529 if (ext4_test_bit(i, bitmap_bh->b_data))
4530 break;
4532 brelse(bitmap_bh);
4533 if (i == start + inodes_per_block) {
4534 /* all other inodes are free, so skip I/O */
4535 memset(bh->b_data, 0, bh->b_size);
4536 set_buffer_uptodate(bh);
4537 unlock_buffer(bh);
4538 goto has_buffer;
4542 make_io:
4544 * If we need to do any I/O, try to pre-readahead extra
4545 * blocks from the inode table.
4547 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4548 ext4_fsblk_t b, end, table;
4549 unsigned num;
4550 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4552 table = ext4_inode_table(sb, gdp);
4553 /* s_inode_readahead_blks is always a power of 2 */
4554 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4555 if (table > b)
4556 b = table;
4557 end = b + ra_blks;
4558 num = EXT4_INODES_PER_GROUP(sb);
4559 if (ext4_has_group_desc_csum(sb))
4560 num -= ext4_itable_unused_count(sb, gdp);
4561 table += num / inodes_per_block;
4562 if (end > table)
4563 end = table;
4564 while (b <= end)
4565 sb_breadahead(sb, b++);
4569 * There are other valid inodes in the buffer, this inode
4570 * has in-inode xattrs, or we don't have this inode in memory.
4571 * Read the block from disk.
4573 trace_ext4_load_inode(inode);
4574 get_bh(bh);
4575 bh->b_end_io = end_buffer_read_sync;
4576 submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
4577 wait_on_buffer(bh);
4578 if (!buffer_uptodate(bh)) {
4579 EXT4_ERROR_INODE_BLOCK(inode, block,
4580 "unable to read itable block");
4581 brelse(bh);
4582 return -EIO;
4585 has_buffer:
4586 iloc->bh = bh;
4587 return 0;
4590 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4592 /* We have all inode data except xattrs in memory here. */
4593 return __ext4_get_inode_loc(inode, iloc,
4594 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4597 void ext4_set_inode_flags(struct inode *inode)
4599 unsigned int flags = EXT4_I(inode)->i_flags;
4600 unsigned int new_fl = 0;
4602 if (flags & EXT4_SYNC_FL)
4603 new_fl |= S_SYNC;
4604 if (flags & EXT4_APPEND_FL)
4605 new_fl |= S_APPEND;
4606 if (flags & EXT4_IMMUTABLE_FL)
4607 new_fl |= S_IMMUTABLE;
4608 if (flags & EXT4_NOATIME_FL)
4609 new_fl |= S_NOATIME;
4610 if (flags & EXT4_DIRSYNC_FL)
4611 new_fl |= S_DIRSYNC;
4612 if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode) &&
4613 !ext4_should_journal_data(inode) && !ext4_has_inline_data(inode) &&
4614 !ext4_encrypted_inode(inode))
4615 new_fl |= S_DAX;
4616 inode_set_flags(inode, new_fl,
4617 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4620 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4621 struct ext4_inode_info *ei)
4623 blkcnt_t i_blocks ;
4624 struct inode *inode = &(ei->vfs_inode);
4625 struct super_block *sb = inode->i_sb;
4627 if (ext4_has_feature_huge_file(sb)) {
4628 /* we are using combined 48 bit field */
4629 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4630 le32_to_cpu(raw_inode->i_blocks_lo);
4631 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4632 /* i_blocks represent file system block size */
4633 return i_blocks << (inode->i_blkbits - 9);
4634 } else {
4635 return i_blocks;
4637 } else {
4638 return le32_to_cpu(raw_inode->i_blocks_lo);
4642 static inline int ext4_iget_extra_inode(struct inode *inode,
4643 struct ext4_inode *raw_inode,
4644 struct ext4_inode_info *ei)
4646 __le32 *magic = (void *)raw_inode +
4647 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4649 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4650 EXT4_INODE_SIZE(inode->i_sb) &&
4651 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4652 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4653 return ext4_find_inline_data_nolock(inode);
4654 } else
4655 EXT4_I(inode)->i_inline_off = 0;
4656 return 0;
4659 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4661 if (!ext4_has_feature_project(inode->i_sb))
4662 return -EOPNOTSUPP;
4663 *projid = EXT4_I(inode)->i_projid;
4664 return 0;
4667 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4669 struct ext4_iloc iloc;
4670 struct ext4_inode *raw_inode;
4671 struct ext4_inode_info *ei;
4672 struct inode *inode;
4673 journal_t *journal = EXT4_SB(sb)->s_journal;
4674 long ret;
4675 loff_t size;
4676 int block;
4677 uid_t i_uid;
4678 gid_t i_gid;
4679 projid_t i_projid;
4681 inode = iget_locked(sb, ino);
4682 if (!inode)
4683 return ERR_PTR(-ENOMEM);
4684 if (!(inode->i_state & I_NEW))
4685 return inode;
4687 ei = EXT4_I(inode);
4688 iloc.bh = NULL;
4690 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4691 if (ret < 0)
4692 goto bad_inode;
4693 raw_inode = ext4_raw_inode(&iloc);
4695 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4696 EXT4_ERROR_INODE(inode, "root inode unallocated");
4697 ret = -EFSCORRUPTED;
4698 goto bad_inode;
4701 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4702 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4703 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4704 EXT4_INODE_SIZE(inode->i_sb) ||
4705 (ei->i_extra_isize & 3)) {
4706 EXT4_ERROR_INODE(inode,
4707 "bad extra_isize %u (inode size %u)",
4708 ei->i_extra_isize,
4709 EXT4_INODE_SIZE(inode->i_sb));
4710 ret = -EFSCORRUPTED;
4711 goto bad_inode;
4713 } else
4714 ei->i_extra_isize = 0;
4716 /* Precompute checksum seed for inode metadata */
4717 if (ext4_has_metadata_csum(sb)) {
4718 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4719 __u32 csum;
4720 __le32 inum = cpu_to_le32(inode->i_ino);
4721 __le32 gen = raw_inode->i_generation;
4722 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4723 sizeof(inum));
4724 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4725 sizeof(gen));
4728 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4729 EXT4_ERROR_INODE(inode, "checksum invalid");
4730 ret = -EFSBADCRC;
4731 goto bad_inode;
4734 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4735 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4736 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4737 if (ext4_has_feature_project(sb) &&
4738 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4739 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4740 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4741 else
4742 i_projid = EXT4_DEF_PROJID;
4744 if (!(test_opt(inode->i_sb, NO_UID32))) {
4745 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4746 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4748 i_uid_write(inode, i_uid);
4749 i_gid_write(inode, i_gid);
4750 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4751 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4753 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4754 ei->i_inline_off = 0;
4755 ei->i_dir_start_lookup = 0;
4756 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4757 /* We now have enough fields to check if the inode was active or not.
4758 * This is needed because nfsd might try to access dead inodes
4759 * the test is that same one that e2fsck uses
4760 * NeilBrown 1999oct15
4762 if (inode->i_nlink == 0) {
4763 if ((inode->i_mode == 0 ||
4764 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4765 ino != EXT4_BOOT_LOADER_INO) {
4766 /* this inode is deleted */
4767 ret = -ESTALE;
4768 goto bad_inode;
4770 /* The only unlinked inodes we let through here have
4771 * valid i_mode and are being read by the orphan
4772 * recovery code: that's fine, we're about to complete
4773 * the process of deleting those.
4774 * OR it is the EXT4_BOOT_LOADER_INO which is
4775 * not initialized on a new filesystem. */
4777 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4778 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4779 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4780 if (ext4_has_feature_64bit(sb))
4781 ei->i_file_acl |=
4782 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4783 inode->i_size = ext4_isize(sb, raw_inode);
4784 if ((size = i_size_read(inode)) < 0) {
4785 EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
4786 ret = -EFSCORRUPTED;
4787 goto bad_inode;
4789 ei->i_disksize = inode->i_size;
4790 #ifdef CONFIG_QUOTA
4791 ei->i_reserved_quota = 0;
4792 #endif
4793 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4794 ei->i_block_group = iloc.block_group;
4795 ei->i_last_alloc_group = ~0;
4797 * NOTE! The in-memory inode i_data array is in little-endian order
4798 * even on big-endian machines: we do NOT byteswap the block numbers!
4800 for (block = 0; block < EXT4_N_BLOCKS; block++)
4801 ei->i_data[block] = raw_inode->i_block[block];
4802 INIT_LIST_HEAD(&ei->i_orphan);
4805 * Set transaction id's of transactions that have to be committed
4806 * to finish f[data]sync. We set them to currently running transaction
4807 * as we cannot be sure that the inode or some of its metadata isn't
4808 * part of the transaction - the inode could have been reclaimed and
4809 * now it is reread from disk.
4811 if (journal) {
4812 transaction_t *transaction;
4813 tid_t tid;
4815 read_lock(&journal->j_state_lock);
4816 if (journal->j_running_transaction)
4817 transaction = journal->j_running_transaction;
4818 else
4819 transaction = journal->j_committing_transaction;
4820 if (transaction)
4821 tid = transaction->t_tid;
4822 else
4823 tid = journal->j_commit_sequence;
4824 read_unlock(&journal->j_state_lock);
4825 ei->i_sync_tid = tid;
4826 ei->i_datasync_tid = tid;
4829 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4830 if (ei->i_extra_isize == 0) {
4831 /* The extra space is currently unused. Use it. */
4832 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4833 ei->i_extra_isize = sizeof(struct ext4_inode) -
4834 EXT4_GOOD_OLD_INODE_SIZE;
4835 } else {
4836 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4837 if (ret)
4838 goto bad_inode;
4842 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4843 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4844 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4845 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4847 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4848 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4849 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4850 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4851 inode->i_version |=
4852 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4856 ret = 0;
4857 if (ei->i_file_acl &&
4858 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4859 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4860 ei->i_file_acl);
4861 ret = -EFSCORRUPTED;
4862 goto bad_inode;
4863 } else if (!ext4_has_inline_data(inode)) {
4864 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4865 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4866 (S_ISLNK(inode->i_mode) &&
4867 !ext4_inode_is_fast_symlink(inode))))
4868 /* Validate extent which is part of inode */
4869 ret = ext4_ext_check_inode(inode);
4870 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4871 (S_ISLNK(inode->i_mode) &&
4872 !ext4_inode_is_fast_symlink(inode))) {
4873 /* Validate block references which are part of inode */
4874 ret = ext4_ind_check_inode(inode);
4877 if (ret)
4878 goto bad_inode;
4880 if (S_ISREG(inode->i_mode)) {
4881 inode->i_op = &ext4_file_inode_operations;
4882 inode->i_fop = &ext4_file_operations;
4883 ext4_set_aops(inode);
4884 } else if (S_ISDIR(inode->i_mode)) {
4885 inode->i_op = &ext4_dir_inode_operations;
4886 inode->i_fop = &ext4_dir_operations;
4887 } else if (S_ISLNK(inode->i_mode)) {
4888 if (ext4_encrypted_inode(inode)) {
4889 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4890 ext4_set_aops(inode);
4891 } else if (ext4_inode_is_fast_symlink(inode)) {
4892 inode->i_link = (char *)ei->i_data;
4893 inode->i_op = &ext4_fast_symlink_inode_operations;
4894 nd_terminate_link(ei->i_data, inode->i_size,
4895 sizeof(ei->i_data) - 1);
4896 } else {
4897 inode->i_op = &ext4_symlink_inode_operations;
4898 ext4_set_aops(inode);
4900 inode_nohighmem(inode);
4901 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4902 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4903 inode->i_op = &ext4_special_inode_operations;
4904 if (raw_inode->i_block[0])
4905 init_special_inode(inode, inode->i_mode,
4906 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4907 else
4908 init_special_inode(inode, inode->i_mode,
4909 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4910 } else if (ino == EXT4_BOOT_LOADER_INO) {
4911 make_bad_inode(inode);
4912 } else {
4913 ret = -EFSCORRUPTED;
4914 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4915 goto bad_inode;
4917 brelse(iloc.bh);
4918 ext4_set_inode_flags(inode);
4920 unlock_new_inode(inode);
4921 return inode;
4923 bad_inode:
4924 brelse(iloc.bh);
4925 iget_failed(inode);
4926 return ERR_PTR(ret);
4929 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4931 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4932 return ERR_PTR(-EFSCORRUPTED);
4933 return ext4_iget(sb, ino);
4936 static int ext4_inode_blocks_set(handle_t *handle,
4937 struct ext4_inode *raw_inode,
4938 struct ext4_inode_info *ei)
4940 struct inode *inode = &(ei->vfs_inode);
4941 u64 i_blocks = inode->i_blocks;
4942 struct super_block *sb = inode->i_sb;
4944 if (i_blocks <= ~0U) {
4946 * i_blocks can be represented in a 32 bit variable
4947 * as multiple of 512 bytes
4949 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4950 raw_inode->i_blocks_high = 0;
4951 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4952 return 0;
4954 if (!ext4_has_feature_huge_file(sb))
4955 return -EFBIG;
4957 if (i_blocks <= 0xffffffffffffULL) {
4959 * i_blocks can be represented in a 48 bit variable
4960 * as multiple of 512 bytes
4962 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4963 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4964 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4965 } else {
4966 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4967 /* i_block is stored in file system block size */
4968 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4969 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4970 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4972 return 0;
4975 struct other_inode {
4976 unsigned long orig_ino;
4977 struct ext4_inode *raw_inode;
4980 static int other_inode_match(struct inode * inode, unsigned long ino,
4981 void *data)
4983 struct other_inode *oi = (struct other_inode *) data;
4985 if ((inode->i_ino != ino) ||
4986 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4987 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4988 ((inode->i_state & I_DIRTY_TIME) == 0))
4989 return 0;
4990 spin_lock(&inode->i_lock);
4991 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4992 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4993 (inode->i_state & I_DIRTY_TIME)) {
4994 struct ext4_inode_info *ei = EXT4_I(inode);
4996 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4997 spin_unlock(&inode->i_lock);
4999 spin_lock(&ei->i_raw_lock);
5000 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
5001 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
5002 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
5003 ext4_inode_csum_set(inode, oi->raw_inode, ei);
5004 spin_unlock(&ei->i_raw_lock);
5005 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
5006 return -1;
5008 spin_unlock(&inode->i_lock);
5009 return -1;
5013 * Opportunistically update the other time fields for other inodes in
5014 * the same inode table block.
5016 static void ext4_update_other_inodes_time(struct super_block *sb,
5017 unsigned long orig_ino, char *buf)
5019 struct other_inode oi;
5020 unsigned long ino;
5021 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5022 int inode_size = EXT4_INODE_SIZE(sb);
5024 oi.orig_ino = orig_ino;
5026 * Calculate the first inode in the inode table block. Inode
5027 * numbers are one-based. That is, the first inode in a block
5028 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5030 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5031 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5032 if (ino == orig_ino)
5033 continue;
5034 oi.raw_inode = (struct ext4_inode *) buf;
5035 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
5040 * Post the struct inode info into an on-disk inode location in the
5041 * buffer-cache. This gobbles the caller's reference to the
5042 * buffer_head in the inode location struct.
5044 * The caller must have write access to iloc->bh.
5046 static int ext4_do_update_inode(handle_t *handle,
5047 struct inode *inode,
5048 struct ext4_iloc *iloc)
5050 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5051 struct ext4_inode_info *ei = EXT4_I(inode);
5052 struct buffer_head *bh = iloc->bh;
5053 struct super_block *sb = inode->i_sb;
5054 int err = 0, rc, block;
5055 int need_datasync = 0, set_large_file = 0;
5056 uid_t i_uid;
5057 gid_t i_gid;
5058 projid_t i_projid;
5060 spin_lock(&ei->i_raw_lock);
5062 /* For fields not tracked in the in-memory inode,
5063 * initialise them to zero for new inodes. */
5064 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5065 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5067 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5068 i_uid = i_uid_read(inode);
5069 i_gid = i_gid_read(inode);
5070 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5071 if (!(test_opt(inode->i_sb, NO_UID32))) {
5072 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5073 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5075 * Fix up interoperability with old kernels. Otherwise, old inodes get
5076 * re-used with the upper 16 bits of the uid/gid intact
5078 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5079 raw_inode->i_uid_high = 0;
5080 raw_inode->i_gid_high = 0;
5081 } else {
5082 raw_inode->i_uid_high =
5083 cpu_to_le16(high_16_bits(i_uid));
5084 raw_inode->i_gid_high =
5085 cpu_to_le16(high_16_bits(i_gid));
5087 } else {
5088 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5089 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5090 raw_inode->i_uid_high = 0;
5091 raw_inode->i_gid_high = 0;
5093 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5095 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5096 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5097 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5098 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5100 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5101 if (err) {
5102 spin_unlock(&ei->i_raw_lock);
5103 goto out_brelse;
5105 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5106 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5107 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5108 raw_inode->i_file_acl_high =
5109 cpu_to_le16(ei->i_file_acl >> 32);
5110 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5111 if (ei->i_disksize != ext4_isize(inode->i_sb, raw_inode)) {
5112 ext4_isize_set(raw_inode, ei->i_disksize);
5113 need_datasync = 1;
5115 if (ei->i_disksize > 0x7fffffffULL) {
5116 if (!ext4_has_feature_large_file(sb) ||
5117 EXT4_SB(sb)->s_es->s_rev_level ==
5118 cpu_to_le32(EXT4_GOOD_OLD_REV))
5119 set_large_file = 1;
5121 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5122 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5123 if (old_valid_dev(inode->i_rdev)) {
5124 raw_inode->i_block[0] =
5125 cpu_to_le32(old_encode_dev(inode->i_rdev));
5126 raw_inode->i_block[1] = 0;
5127 } else {
5128 raw_inode->i_block[0] = 0;
5129 raw_inode->i_block[1] =
5130 cpu_to_le32(new_encode_dev(inode->i_rdev));
5131 raw_inode->i_block[2] = 0;
5133 } else if (!ext4_has_inline_data(inode)) {
5134 for (block = 0; block < EXT4_N_BLOCKS; block++)
5135 raw_inode->i_block[block] = ei->i_data[block];
5138 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5139 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5140 if (ei->i_extra_isize) {
5141 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5142 raw_inode->i_version_hi =
5143 cpu_to_le32(inode->i_version >> 32);
5144 raw_inode->i_extra_isize =
5145 cpu_to_le16(ei->i_extra_isize);
5149 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5150 i_projid != EXT4_DEF_PROJID);
5152 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5153 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5154 raw_inode->i_projid = cpu_to_le32(i_projid);
5156 ext4_inode_csum_set(inode, raw_inode, ei);
5157 spin_unlock(&ei->i_raw_lock);
5158 if (inode->i_sb->s_flags & MS_LAZYTIME)
5159 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5160 bh->b_data);
5162 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5163 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5164 if (!err)
5165 err = rc;
5166 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5167 if (set_large_file) {
5168 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5169 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5170 if (err)
5171 goto out_brelse;
5172 ext4_update_dynamic_rev(sb);
5173 ext4_set_feature_large_file(sb);
5174 ext4_handle_sync(handle);
5175 err = ext4_handle_dirty_super(handle, sb);
5177 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5178 out_brelse:
5179 brelse(bh);
5180 ext4_std_error(inode->i_sb, err);
5181 return err;
5185 * ext4_write_inode()
5187 * We are called from a few places:
5189 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5190 * Here, there will be no transaction running. We wait for any running
5191 * transaction to commit.
5193 * - Within flush work (sys_sync(), kupdate and such).
5194 * We wait on commit, if told to.
5196 * - Within iput_final() -> write_inode_now()
5197 * We wait on commit, if told to.
5199 * In all cases it is actually safe for us to return without doing anything,
5200 * because the inode has been copied into a raw inode buffer in
5201 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5202 * writeback.
5204 * Note that we are absolutely dependent upon all inode dirtiers doing the
5205 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5206 * which we are interested.
5208 * It would be a bug for them to not do this. The code:
5210 * mark_inode_dirty(inode)
5211 * stuff();
5212 * inode->i_size = expr;
5214 * is in error because write_inode() could occur while `stuff()' is running,
5215 * and the new i_size will be lost. Plus the inode will no longer be on the
5216 * superblock's dirty inode list.
5218 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5220 int err;
5222 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5223 sb_rdonly(inode->i_sb))
5224 return 0;
5226 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5227 return -EIO;
5229 if (EXT4_SB(inode->i_sb)->s_journal) {
5230 if (ext4_journal_current_handle()) {
5231 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5232 dump_stack();
5233 return -EIO;
5237 * No need to force transaction in WB_SYNC_NONE mode. Also
5238 * ext4_sync_fs() will force the commit after everything is
5239 * written.
5241 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5242 return 0;
5244 err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5245 EXT4_I(inode)->i_sync_tid);
5246 } else {
5247 struct ext4_iloc iloc;
5249 err = __ext4_get_inode_loc(inode, &iloc, 0);
5250 if (err)
5251 return err;
5253 * sync(2) will flush the whole buffer cache. No need to do
5254 * it here separately for each inode.
5256 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5257 sync_dirty_buffer(iloc.bh);
5258 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5259 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5260 "IO error syncing inode");
5261 err = -EIO;
5263 brelse(iloc.bh);
5265 return err;
5269 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5270 * buffers that are attached to a page stradding i_size and are undergoing
5271 * commit. In that case we have to wait for commit to finish and try again.
5273 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5275 struct page *page;
5276 unsigned offset;
5277 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5278 tid_t commit_tid = 0;
5279 int ret;
5281 offset = inode->i_size & (PAGE_SIZE - 1);
5283 * All buffers in the last page remain valid? Then there's nothing to
5284 * do. We do the check mainly to optimize the common PAGE_SIZE ==
5285 * blocksize case
5287 if (offset > PAGE_SIZE - i_blocksize(inode))
5288 return;
5289 while (1) {
5290 page = find_lock_page(inode->i_mapping,
5291 inode->i_size >> PAGE_SHIFT);
5292 if (!page)
5293 return;
5294 ret = __ext4_journalled_invalidatepage(page, offset,
5295 PAGE_SIZE - offset);
5296 unlock_page(page);
5297 put_page(page);
5298 if (ret != -EBUSY)
5299 return;
5300 commit_tid = 0;
5301 read_lock(&journal->j_state_lock);
5302 if (journal->j_committing_transaction)
5303 commit_tid = journal->j_committing_transaction->t_tid;
5304 read_unlock(&journal->j_state_lock);
5305 if (commit_tid)
5306 jbd2_log_wait_commit(journal, commit_tid);
5311 * ext4_setattr()
5313 * Called from notify_change.
5315 * We want to trap VFS attempts to truncate the file as soon as
5316 * possible. In particular, we want to make sure that when the VFS
5317 * shrinks i_size, we put the inode on the orphan list and modify
5318 * i_disksize immediately, so that during the subsequent flushing of
5319 * dirty pages and freeing of disk blocks, we can guarantee that any
5320 * commit will leave the blocks being flushed in an unused state on
5321 * disk. (On recovery, the inode will get truncated and the blocks will
5322 * be freed, so we have a strong guarantee that no future commit will
5323 * leave these blocks visible to the user.)
5325 * Another thing we have to assure is that if we are in ordered mode
5326 * and inode is still attached to the committing transaction, we must
5327 * we start writeout of all the dirty pages which are being truncated.
5328 * This way we are sure that all the data written in the previous
5329 * transaction are already on disk (truncate waits for pages under
5330 * writeback).
5332 * Called with inode->i_mutex down.
5334 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5336 struct inode *inode = d_inode(dentry);
5337 int error, rc = 0;
5338 int orphan = 0;
5339 const unsigned int ia_valid = attr->ia_valid;
5341 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5342 return -EIO;
5344 error = setattr_prepare(dentry, attr);
5345 if (error)
5346 return error;
5348 if (is_quota_modification(inode, attr)) {
5349 error = dquot_initialize(inode);
5350 if (error)
5351 return error;
5353 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5354 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5355 handle_t *handle;
5357 /* (user+group)*(old+new) structure, inode write (sb,
5358 * inode block, ? - but truncate inode update has it) */
5359 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5360 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5361 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5362 if (IS_ERR(handle)) {
5363 error = PTR_ERR(handle);
5364 goto err_out;
5367 /* dquot_transfer() calls back ext4_get_inode_usage() which
5368 * counts xattr inode references.
5370 down_read(&EXT4_I(inode)->xattr_sem);
5371 error = dquot_transfer(inode, attr);
5372 up_read(&EXT4_I(inode)->xattr_sem);
5374 if (error) {
5375 ext4_journal_stop(handle);
5376 return error;
5378 /* Update corresponding info in inode so that everything is in
5379 * one transaction */
5380 if (attr->ia_valid & ATTR_UID)
5381 inode->i_uid = attr->ia_uid;
5382 if (attr->ia_valid & ATTR_GID)
5383 inode->i_gid = attr->ia_gid;
5384 error = ext4_mark_inode_dirty(handle, inode);
5385 ext4_journal_stop(handle);
5388 if (attr->ia_valid & ATTR_SIZE) {
5389 handle_t *handle;
5390 loff_t oldsize = inode->i_size;
5391 int shrink = (attr->ia_size <= inode->i_size);
5393 if (ext4_encrypted_inode(inode)) {
5394 error = fscrypt_get_encryption_info(inode);
5395 if (error)
5396 return error;
5397 if (!fscrypt_has_encryption_key(inode))
5398 return -ENOKEY;
5401 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5402 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5404 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5405 return -EFBIG;
5407 if (!S_ISREG(inode->i_mode))
5408 return -EINVAL;
5410 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5411 inode_inc_iversion(inode);
5413 if (ext4_should_order_data(inode) &&
5414 (attr->ia_size < inode->i_size)) {
5415 error = ext4_begin_ordered_truncate(inode,
5416 attr->ia_size);
5417 if (error)
5418 goto err_out;
5420 if (attr->ia_size != inode->i_size) {
5421 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5422 if (IS_ERR(handle)) {
5423 error = PTR_ERR(handle);
5424 goto err_out;
5426 if (ext4_handle_valid(handle) && shrink) {
5427 error = ext4_orphan_add(handle, inode);
5428 orphan = 1;
5431 * Update c/mtime on truncate up, ext4_truncate() will
5432 * update c/mtime in shrink case below
5434 if (!shrink) {
5435 inode->i_mtime = current_time(inode);
5436 inode->i_ctime = inode->i_mtime;
5438 down_write(&EXT4_I(inode)->i_data_sem);
5439 EXT4_I(inode)->i_disksize = attr->ia_size;
5440 rc = ext4_mark_inode_dirty(handle, inode);
5441 if (!error)
5442 error = rc;
5444 * We have to update i_size under i_data_sem together
5445 * with i_disksize to avoid races with writeback code
5446 * running ext4_wb_update_i_disksize().
5448 if (!error)
5449 i_size_write(inode, attr->ia_size);
5450 up_write(&EXT4_I(inode)->i_data_sem);
5451 ext4_journal_stop(handle);
5452 if (error) {
5453 if (orphan && inode->i_nlink)
5454 ext4_orphan_del(NULL, inode);
5455 goto err_out;
5458 if (!shrink)
5459 pagecache_isize_extended(inode, oldsize, inode->i_size);
5462 * Blocks are going to be removed from the inode. Wait
5463 * for dio in flight. Temporarily disable
5464 * dioread_nolock to prevent livelock.
5466 if (orphan) {
5467 if (!ext4_should_journal_data(inode)) {
5468 ext4_inode_block_unlocked_dio(inode);
5469 inode_dio_wait(inode);
5470 ext4_inode_resume_unlocked_dio(inode);
5471 } else
5472 ext4_wait_for_tail_page_commit(inode);
5474 down_write(&EXT4_I(inode)->i_mmap_sem);
5476 * Truncate pagecache after we've waited for commit
5477 * in data=journal mode to make pages freeable.
5479 truncate_pagecache(inode, inode->i_size);
5480 if (shrink) {
5481 rc = ext4_truncate(inode);
5482 if (rc)
5483 error = rc;
5485 up_write(&EXT4_I(inode)->i_mmap_sem);
5488 if (!error) {
5489 setattr_copy(inode, attr);
5490 mark_inode_dirty(inode);
5494 * If the call to ext4_truncate failed to get a transaction handle at
5495 * all, we need to clean up the in-core orphan list manually.
5497 if (orphan && inode->i_nlink)
5498 ext4_orphan_del(NULL, inode);
5500 if (!error && (ia_valid & ATTR_MODE))
5501 rc = posix_acl_chmod(inode, inode->i_mode);
5503 err_out:
5504 ext4_std_error(inode->i_sb, error);
5505 if (!error)
5506 error = rc;
5507 return error;
5510 int ext4_getattr(const struct path *path, struct kstat *stat,
5511 u32 request_mask, unsigned int query_flags)
5513 struct inode *inode = d_inode(path->dentry);
5514 struct ext4_inode *raw_inode;
5515 struct ext4_inode_info *ei = EXT4_I(inode);
5516 unsigned int flags;
5518 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5519 stat->result_mask |= STATX_BTIME;
5520 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5521 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5524 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5525 if (flags & EXT4_APPEND_FL)
5526 stat->attributes |= STATX_ATTR_APPEND;
5527 if (flags & EXT4_COMPR_FL)
5528 stat->attributes |= STATX_ATTR_COMPRESSED;
5529 if (flags & EXT4_ENCRYPT_FL)
5530 stat->attributes |= STATX_ATTR_ENCRYPTED;
5531 if (flags & EXT4_IMMUTABLE_FL)
5532 stat->attributes |= STATX_ATTR_IMMUTABLE;
5533 if (flags & EXT4_NODUMP_FL)
5534 stat->attributes |= STATX_ATTR_NODUMP;
5536 stat->attributes_mask |= (STATX_ATTR_APPEND |
5537 STATX_ATTR_COMPRESSED |
5538 STATX_ATTR_ENCRYPTED |
5539 STATX_ATTR_IMMUTABLE |
5540 STATX_ATTR_NODUMP);
5542 generic_fillattr(inode, stat);
5543 return 0;
5546 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5547 u32 request_mask, unsigned int query_flags)
5549 struct inode *inode = d_inode(path->dentry);
5550 u64 delalloc_blocks;
5552 ext4_getattr(path, stat, request_mask, query_flags);
5555 * If there is inline data in the inode, the inode will normally not
5556 * have data blocks allocated (it may have an external xattr block).
5557 * Report at least one sector for such files, so tools like tar, rsync,
5558 * others don't incorrectly think the file is completely sparse.
5560 if (unlikely(ext4_has_inline_data(inode)))
5561 stat->blocks += (stat->size + 511) >> 9;
5564 * We can't update i_blocks if the block allocation is delayed
5565 * otherwise in the case of system crash before the real block
5566 * allocation is done, we will have i_blocks inconsistent with
5567 * on-disk file blocks.
5568 * We always keep i_blocks updated together with real
5569 * allocation. But to not confuse with user, stat
5570 * will return the blocks that include the delayed allocation
5571 * blocks for this file.
5573 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5574 EXT4_I(inode)->i_reserved_data_blocks);
5575 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5576 return 0;
5579 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5580 int pextents)
5582 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5583 return ext4_ind_trans_blocks(inode, lblocks);
5584 return ext4_ext_index_trans_blocks(inode, pextents);
5588 * Account for index blocks, block groups bitmaps and block group
5589 * descriptor blocks if modify datablocks and index blocks
5590 * worse case, the indexs blocks spread over different block groups
5592 * If datablocks are discontiguous, they are possible to spread over
5593 * different block groups too. If they are contiguous, with flexbg,
5594 * they could still across block group boundary.
5596 * Also account for superblock, inode, quota and xattr blocks
5598 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5599 int pextents)
5601 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5602 int gdpblocks;
5603 int idxblocks;
5604 int ret = 0;
5607 * How many index blocks need to touch to map @lblocks logical blocks
5608 * to @pextents physical extents?
5610 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5612 ret = idxblocks;
5615 * Now let's see how many group bitmaps and group descriptors need
5616 * to account
5618 groups = idxblocks + pextents;
5619 gdpblocks = groups;
5620 if (groups > ngroups)
5621 groups = ngroups;
5622 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5623 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5625 /* bitmaps and block group descriptor blocks */
5626 ret += groups + gdpblocks;
5628 /* Blocks for super block, inode, quota and xattr blocks */
5629 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5631 return ret;
5635 * Calculate the total number of credits to reserve to fit
5636 * the modification of a single pages into a single transaction,
5637 * which may include multiple chunks of block allocations.
5639 * This could be called via ext4_write_begin()
5641 * We need to consider the worse case, when
5642 * one new block per extent.
5644 int ext4_writepage_trans_blocks(struct inode *inode)
5646 int bpp = ext4_journal_blocks_per_page(inode);
5647 int ret;
5649 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5651 /* Account for data blocks for journalled mode */
5652 if (ext4_should_journal_data(inode))
5653 ret += bpp;
5654 return ret;
5658 * Calculate the journal credits for a chunk of data modification.
5660 * This is called from DIO, fallocate or whoever calling
5661 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5663 * journal buffers for data blocks are not included here, as DIO
5664 * and fallocate do no need to journal data buffers.
5666 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5668 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5672 * The caller must have previously called ext4_reserve_inode_write().
5673 * Give this, we know that the caller already has write access to iloc->bh.
5675 int ext4_mark_iloc_dirty(handle_t *handle,
5676 struct inode *inode, struct ext4_iloc *iloc)
5678 int err = 0;
5680 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5681 put_bh(iloc->bh);
5682 return -EIO;
5684 if (IS_I_VERSION(inode))
5685 inode_inc_iversion(inode);
5687 /* the do_update_inode consumes one bh->b_count */
5688 get_bh(iloc->bh);
5690 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5691 err = ext4_do_update_inode(handle, inode, iloc);
5692 put_bh(iloc->bh);
5693 return err;
5697 * On success, We end up with an outstanding reference count against
5698 * iloc->bh. This _must_ be cleaned up later.
5702 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5703 struct ext4_iloc *iloc)
5705 int err;
5707 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5708 return -EIO;
5710 err = ext4_get_inode_loc(inode, iloc);
5711 if (!err) {
5712 BUFFER_TRACE(iloc->bh, "get_write_access");
5713 err = ext4_journal_get_write_access(handle, iloc->bh);
5714 if (err) {
5715 brelse(iloc->bh);
5716 iloc->bh = NULL;
5719 ext4_std_error(inode->i_sb, err);
5720 return err;
5723 static int __ext4_expand_extra_isize(struct inode *inode,
5724 unsigned int new_extra_isize,
5725 struct ext4_iloc *iloc,
5726 handle_t *handle, int *no_expand)
5728 struct ext4_inode *raw_inode;
5729 struct ext4_xattr_ibody_header *header;
5730 int error;
5732 raw_inode = ext4_raw_inode(iloc);
5734 header = IHDR(inode, raw_inode);
5736 /* No extended attributes present */
5737 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5738 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5739 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5740 EXT4_I(inode)->i_extra_isize, 0,
5741 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5742 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5743 return 0;
5746 /* try to expand with EAs present */
5747 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5748 raw_inode, handle);
5749 if (error) {
5751 * Inode size expansion failed; don't try again
5753 *no_expand = 1;
5756 return error;
5760 * Expand an inode by new_extra_isize bytes.
5761 * Returns 0 on success or negative error number on failure.
5763 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5764 unsigned int new_extra_isize,
5765 struct ext4_iloc iloc,
5766 handle_t *handle)
5768 int no_expand;
5769 int error;
5771 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5772 return -EOVERFLOW;
5775 * In nojournal mode, we can immediately attempt to expand
5776 * the inode. When journaled, we first need to obtain extra
5777 * buffer credits since we may write into the EA block
5778 * with this same handle. If journal_extend fails, then it will
5779 * only result in a minor loss of functionality for that inode.
5780 * If this is felt to be critical, then e2fsck should be run to
5781 * force a large enough s_min_extra_isize.
5783 if (ext4_handle_valid(handle) &&
5784 jbd2_journal_extend(handle,
5785 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
5786 return -ENOSPC;
5788 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5789 return -EBUSY;
5791 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5792 handle, &no_expand);
5793 ext4_write_unlock_xattr(inode, &no_expand);
5795 return error;
5798 int ext4_expand_extra_isize(struct inode *inode,
5799 unsigned int new_extra_isize,
5800 struct ext4_iloc *iloc)
5802 handle_t *handle;
5803 int no_expand;
5804 int error, rc;
5806 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5807 brelse(iloc->bh);
5808 return -EOVERFLOW;
5811 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5812 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5813 if (IS_ERR(handle)) {
5814 error = PTR_ERR(handle);
5815 brelse(iloc->bh);
5816 return error;
5819 ext4_write_lock_xattr(inode, &no_expand);
5821 BUFFER_TRACE(iloc->bh, "get_write_access");
5822 error = ext4_journal_get_write_access(handle, iloc->bh);
5823 if (error) {
5824 brelse(iloc->bh);
5825 goto out_stop;
5828 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5829 handle, &no_expand);
5831 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5832 if (!error)
5833 error = rc;
5835 ext4_write_unlock_xattr(inode, &no_expand);
5836 out_stop:
5837 ext4_journal_stop(handle);
5838 return error;
5842 * What we do here is to mark the in-core inode as clean with respect to inode
5843 * dirtiness (it may still be data-dirty).
5844 * This means that the in-core inode may be reaped by prune_icache
5845 * without having to perform any I/O. This is a very good thing,
5846 * because *any* task may call prune_icache - even ones which
5847 * have a transaction open against a different journal.
5849 * Is this cheating? Not really. Sure, we haven't written the
5850 * inode out, but prune_icache isn't a user-visible syncing function.
5851 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5852 * we start and wait on commits.
5854 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5856 struct ext4_iloc iloc;
5857 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5858 int err;
5860 might_sleep();
5861 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5862 err = ext4_reserve_inode_write(handle, inode, &iloc);
5863 if (err)
5864 return err;
5866 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5867 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5868 iloc, handle);
5870 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5874 * ext4_dirty_inode() is called from __mark_inode_dirty()
5876 * We're really interested in the case where a file is being extended.
5877 * i_size has been changed by generic_commit_write() and we thus need
5878 * to include the updated inode in the current transaction.
5880 * Also, dquot_alloc_block() will always dirty the inode when blocks
5881 * are allocated to the file.
5883 * If the inode is marked synchronous, we don't honour that here - doing
5884 * so would cause a commit on atime updates, which we don't bother doing.
5885 * We handle synchronous inodes at the highest possible level.
5887 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
5888 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5889 * to copy into the on-disk inode structure are the timestamp files.
5891 void ext4_dirty_inode(struct inode *inode, int flags)
5893 handle_t *handle;
5895 if (flags == I_DIRTY_TIME)
5896 return;
5897 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5898 if (IS_ERR(handle))
5899 goto out;
5901 ext4_mark_inode_dirty(handle, inode);
5903 ext4_journal_stop(handle);
5904 out:
5905 return;
5908 #if 0
5910 * Bind an inode's backing buffer_head into this transaction, to prevent
5911 * it from being flushed to disk early. Unlike
5912 * ext4_reserve_inode_write, this leaves behind no bh reference and
5913 * returns no iloc structure, so the caller needs to repeat the iloc
5914 * lookup to mark the inode dirty later.
5916 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5918 struct ext4_iloc iloc;
5920 int err = 0;
5921 if (handle) {
5922 err = ext4_get_inode_loc(inode, &iloc);
5923 if (!err) {
5924 BUFFER_TRACE(iloc.bh, "get_write_access");
5925 err = jbd2_journal_get_write_access(handle, iloc.bh);
5926 if (!err)
5927 err = ext4_handle_dirty_metadata(handle,
5928 NULL,
5929 iloc.bh);
5930 brelse(iloc.bh);
5933 ext4_std_error(inode->i_sb, err);
5934 return err;
5936 #endif
5938 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5940 journal_t *journal;
5941 handle_t *handle;
5942 int err;
5943 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5946 * We have to be very careful here: changing a data block's
5947 * journaling status dynamically is dangerous. If we write a
5948 * data block to the journal, change the status and then delete
5949 * that block, we risk forgetting to revoke the old log record
5950 * from the journal and so a subsequent replay can corrupt data.
5951 * So, first we make sure that the journal is empty and that
5952 * nobody is changing anything.
5955 journal = EXT4_JOURNAL(inode);
5956 if (!journal)
5957 return 0;
5958 if (is_journal_aborted(journal))
5959 return -EROFS;
5961 /* Wait for all existing dio workers */
5962 ext4_inode_block_unlocked_dio(inode);
5963 inode_dio_wait(inode);
5966 * Before flushing the journal and switching inode's aops, we have
5967 * to flush all dirty data the inode has. There can be outstanding
5968 * delayed allocations, there can be unwritten extents created by
5969 * fallocate or buffered writes in dioread_nolock mode covered by
5970 * dirty data which can be converted only after flushing the dirty
5971 * data (and journalled aops don't know how to handle these cases).
5973 if (val) {
5974 down_write(&EXT4_I(inode)->i_mmap_sem);
5975 err = filemap_write_and_wait(inode->i_mapping);
5976 if (err < 0) {
5977 up_write(&EXT4_I(inode)->i_mmap_sem);
5978 ext4_inode_resume_unlocked_dio(inode);
5979 return err;
5983 percpu_down_write(&sbi->s_journal_flag_rwsem);
5984 jbd2_journal_lock_updates(journal);
5987 * OK, there are no updates running now, and all cached data is
5988 * synced to disk. We are now in a completely consistent state
5989 * which doesn't have anything in the journal, and we know that
5990 * no filesystem updates are running, so it is safe to modify
5991 * the inode's in-core data-journaling state flag now.
5994 if (val)
5995 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5996 else {
5997 err = jbd2_journal_flush(journal);
5998 if (err < 0) {
5999 jbd2_journal_unlock_updates(journal);
6000 percpu_up_write(&sbi->s_journal_flag_rwsem);
6001 ext4_inode_resume_unlocked_dio(inode);
6002 return err;
6004 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6006 ext4_set_aops(inode);
6008 jbd2_journal_unlock_updates(journal);
6009 percpu_up_write(&sbi->s_journal_flag_rwsem);
6011 if (val)
6012 up_write(&EXT4_I(inode)->i_mmap_sem);
6013 ext4_inode_resume_unlocked_dio(inode);
6015 /* Finally we can mark the inode as dirty. */
6017 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6018 if (IS_ERR(handle))
6019 return PTR_ERR(handle);
6021 err = ext4_mark_inode_dirty(handle, inode);
6022 ext4_handle_sync(handle);
6023 ext4_journal_stop(handle);
6024 ext4_std_error(inode->i_sb, err);
6026 return err;
6029 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6031 return !buffer_mapped(bh);
6034 int ext4_page_mkwrite(struct vm_fault *vmf)
6036 struct vm_area_struct *vma = vmf->vma;
6037 struct page *page = vmf->page;
6038 loff_t size;
6039 unsigned long len;
6040 int ret;
6041 struct file *file = vma->vm_file;
6042 struct inode *inode = file_inode(file);
6043 struct address_space *mapping = inode->i_mapping;
6044 handle_t *handle;
6045 get_block_t *get_block;
6046 int retries = 0;
6048 sb_start_pagefault(inode->i_sb);
6049 file_update_time(vma->vm_file);
6051 down_read(&EXT4_I(inode)->i_mmap_sem);
6053 ret = ext4_convert_inline_data(inode);
6054 if (ret)
6055 goto out_ret;
6057 /* Delalloc case is easy... */
6058 if (test_opt(inode->i_sb, DELALLOC) &&
6059 !ext4_should_journal_data(inode) &&
6060 !ext4_nonda_switch(inode->i_sb)) {
6061 do {
6062 ret = block_page_mkwrite(vma, vmf,
6063 ext4_da_get_block_prep);
6064 } while (ret == -ENOSPC &&
6065 ext4_should_retry_alloc(inode->i_sb, &retries));
6066 goto out_ret;
6069 lock_page(page);
6070 size = i_size_read(inode);
6071 /* Page got truncated from under us? */
6072 if (page->mapping != mapping || page_offset(page) > size) {
6073 unlock_page(page);
6074 ret = VM_FAULT_NOPAGE;
6075 goto out;
6078 if (page->index == size >> PAGE_SHIFT)
6079 len = size & ~PAGE_MASK;
6080 else
6081 len = PAGE_SIZE;
6083 * Return if we have all the buffers mapped. This avoids the need to do
6084 * journal_start/journal_stop which can block and take a long time
6086 if (page_has_buffers(page)) {
6087 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6088 0, len, NULL,
6089 ext4_bh_unmapped)) {
6090 /* Wait so that we don't change page under IO */
6091 wait_for_stable_page(page);
6092 ret = VM_FAULT_LOCKED;
6093 goto out;
6096 unlock_page(page);
6097 /* OK, we need to fill the hole... */
6098 if (ext4_should_dioread_nolock(inode))
6099 get_block = ext4_get_block_unwritten;
6100 else
6101 get_block = ext4_get_block;
6102 retry_alloc:
6103 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6104 ext4_writepage_trans_blocks(inode));
6105 if (IS_ERR(handle)) {
6106 ret = VM_FAULT_SIGBUS;
6107 goto out;
6109 ret = block_page_mkwrite(vma, vmf, get_block);
6110 if (!ret && ext4_should_journal_data(inode)) {
6111 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
6112 PAGE_SIZE, NULL, do_journal_get_write_access)) {
6113 unlock_page(page);
6114 ret = VM_FAULT_SIGBUS;
6115 ext4_journal_stop(handle);
6116 goto out;
6118 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6120 ext4_journal_stop(handle);
6121 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6122 goto retry_alloc;
6123 out_ret:
6124 ret = block_page_mkwrite_return(ret);
6125 out:
6126 up_read(&EXT4_I(inode)->i_mmap_sem);
6127 sb_end_pagefault(inode->i_sb);
6128 return ret;
6131 int ext4_filemap_fault(struct vm_fault *vmf)
6133 struct inode *inode = file_inode(vmf->vma->vm_file);
6134 int err;
6136 down_read(&EXT4_I(inode)->i_mmap_sem);
6137 err = filemap_fault(vmf);
6138 up_read(&EXT4_I(inode)->i_mmap_sem);
6140 return err;
6144 * Find the first extent at or after @lblk in an inode that is not a hole.
6145 * Search for @map_len blocks at most. The extent is returned in @result.
6147 * The function returns 1 if we found an extent. The function returns 0 in
6148 * case there is no extent at or after @lblk and in that case also sets
6149 * @result->es_len to 0. In case of error, the error code is returned.
6151 int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
6152 unsigned int map_len, struct extent_status *result)
6154 struct ext4_map_blocks map;
6155 struct extent_status es = {};
6156 int ret;
6158 map.m_lblk = lblk;
6159 map.m_len = map_len;
6162 * For non-extent based files this loop may iterate several times since
6163 * we do not determine full hole size.
6165 while (map.m_len > 0) {
6166 ret = ext4_map_blocks(NULL, inode, &map, 0);
6167 if (ret < 0)
6168 return ret;
6169 /* There's extent covering m_lblk? Just return it. */
6170 if (ret > 0) {
6171 int status;
6173 ext4_es_store_pblock(result, map.m_pblk);
6174 result->es_lblk = map.m_lblk;
6175 result->es_len = map.m_len;
6176 if (map.m_flags & EXT4_MAP_UNWRITTEN)
6177 status = EXTENT_STATUS_UNWRITTEN;
6178 else
6179 status = EXTENT_STATUS_WRITTEN;
6180 ext4_es_store_status(result, status);
6181 return 1;
6183 ext4_es_find_delayed_extent_range(inode, map.m_lblk,
6184 map.m_lblk + map.m_len - 1,
6185 &es);
6186 /* Is delalloc data before next block in extent tree? */
6187 if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
6188 ext4_lblk_t offset = 0;
6190 if (es.es_lblk < lblk)
6191 offset = lblk - es.es_lblk;
6192 result->es_lblk = es.es_lblk + offset;
6193 ext4_es_store_pblock(result,
6194 ext4_es_pblock(&es) + offset);
6195 result->es_len = es.es_len - offset;
6196 ext4_es_store_status(result, ext4_es_status(&es));
6198 return 1;
6200 /* There's a hole at m_lblk, advance us after it */
6201 map.m_lblk += map.m_len;
6202 map_len -= map.m_len;
6203 map.m_len = map_len;
6204 cond_resched();
6206 result->es_len = 0;
6207 return 0;