ext4: Fix ext4_should_journal_data() for EA inodes
[linux-block.git] / fs / ext4 / inode.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
ac27a0ec 2/*
617ba13b 3 * linux/fs/ext4/inode.c
ac27a0ec
DK
4 *
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)
9 *
10 * from
11 *
12 * linux/fs/minix/inode.c
13 *
14 * Copyright (C) 1991, 1992 Linus Torvalds
15 *
ac27a0ec
DK
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
18 *
617ba13b 19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
ac27a0ec
DK
20 */
21
ac27a0ec
DK
22#include <linux/fs.h>
23#include <linux/time.h>
ac27a0ec
DK
24#include <linux/highuid.h>
25#include <linux/pagemap.h>
c94c2acf 26#include <linux/dax.h>
ac27a0ec
DK
27#include <linux/quotaops.h>
28#include <linux/string.h>
29#include <linux/buffer_head.h>
30#include <linux/writeback.h>
64769240 31#include <linux/pagevec.h>
ac27a0ec 32#include <linux/mpage.h>
e83c1397 33#include <linux/namei.h>
ac27a0ec
DK
34#include <linux/uio.h>
35#include <linux/bio.h>
4c0425ff 36#include <linux/workqueue.h>
744692dc 37#include <linux/kernel.h>
6db26ffc 38#include <linux/printk.h>
5a0e3ad6 39#include <linux/slab.h>
00a1a053 40#include <linux/bitops.h>
364443cb 41#include <linux/iomap.h>
ae5e165d 42#include <linux/iversion.h>
9bffad1e 43
3dcf5451 44#include "ext4_jbd2.h"
ac27a0ec
DK
45#include "xattr.h"
46#include "acl.h"
9f125d64 47#include "truncate.h"
ac27a0ec 48
9bffad1e
TT
49#include <trace/events/ext4.h>
50
a1d6cc56
AK
51#define MPAGE_DA_EXTENT_TAIL 0x01
52
814525f4
DW
53static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
54 struct ext4_inode_info *ei)
55{
56 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
814525f4 57 __u32 csum;
b47820ed
DJ
58 __u16 dummy_csum = 0;
59 int offset = offsetof(struct ext4_inode, i_checksum_lo);
60 unsigned int csum_size = sizeof(dummy_csum);
814525f4 61
b47820ed
DJ
62 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
63 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
64 offset += csum_size;
65 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
66 EXT4_GOOD_OLD_INODE_SIZE - offset);
814525f4 67
b47820ed
DJ
68 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
69 offset = offsetof(struct ext4_inode, i_checksum_hi);
70 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
71 EXT4_GOOD_OLD_INODE_SIZE,
72 offset - EXT4_GOOD_OLD_INODE_SIZE);
73 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
74 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
75 csum_size);
76 offset += csum_size;
b47820ed 77 }
05ac5aa1
DJ
78 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
79 EXT4_INODE_SIZE(inode->i_sb) - offset);
814525f4
DW
80 }
81
814525f4
DW
82 return csum;
83}
84
85static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
86 struct ext4_inode_info *ei)
87{
88 __u32 provided, calculated;
89
90 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
91 cpu_to_le32(EXT4_OS_LINUX) ||
9aa5d32b 92 !ext4_has_metadata_csum(inode->i_sb))
814525f4
DW
93 return 1;
94
95 provided = le16_to_cpu(raw->i_checksum_lo);
96 calculated = ext4_inode_csum(inode, raw, ei);
97 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
98 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
99 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 else
101 calculated &= 0xFFFF;
102
103 return provided == calculated;
104}
105
106static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
107 struct ext4_inode_info *ei)
108{
109 __u32 csum;
110
111 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
112 cpu_to_le32(EXT4_OS_LINUX) ||
9aa5d32b 113 !ext4_has_metadata_csum(inode->i_sb))
814525f4
DW
114 return;
115
116 csum = ext4_inode_csum(inode, raw, ei);
117 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
118 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
119 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
120 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
121}
122
678aaf48
JK
123static inline int ext4_begin_ordered_truncate(struct inode *inode,
124 loff_t new_size)
125{
7ff9c073 126 trace_ext4_begin_ordered_truncate(inode, new_size);
8aefcd55
TT
127 /*
128 * If jinode is zero, then we never opened the file for
129 * writing, so there's no need to call
130 * jbd2_journal_begin_ordered_truncate() since there's no
131 * outstanding writes we need to flush.
132 */
133 if (!EXT4_I(inode)->jinode)
134 return 0;
135 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
136 EXT4_I(inode)->jinode,
137 new_size);
678aaf48
JK
138}
139
d47992f8
LC
140static void ext4_invalidatepage(struct page *page, unsigned int offset,
141 unsigned int length);
cb20d518
TT
142static int __ext4_journalled_writepage(struct page *page, unsigned int len);
143static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
dec214d0
TE
144static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
145 int pextents);
64769240 146
ac27a0ec
DK
147/*
148 * Test whether an inode is a fast symlink.
407cd7fb 149 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
ac27a0ec 150 */
f348c252 151int ext4_inode_is_fast_symlink(struct inode *inode)
ac27a0ec 152{
fc82228a
AK
153 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
154 int ea_blocks = EXT4_I(inode)->i_file_acl ?
155 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
156
157 if (ext4_has_inline_data(inode))
158 return 0;
159
160 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
161 }
407cd7fb
TE
162 return S_ISLNK(inode->i_mode) && inode->i_size &&
163 (inode->i_size < EXT4_N_BLOCKS * 4);
ac27a0ec
DK
164}
165
ac27a0ec
DK
166/*
167 * Restart the transaction associated with *handle. This does a commit,
168 * so before we call here everything must be consistently dirtied against
169 * this transaction.
170 */
fa5d1113 171int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
487caeef 172 int nblocks)
ac27a0ec 173{
487caeef
JK
174 int ret;
175
176 /*
e35fd660 177 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
487caeef
JK
178 * moment, get_block can be called only for blocks inside i_size since
179 * page cache has been already dropped and writes are blocked by
180 * i_mutex. So we can safely drop the i_data_sem here.
181 */
0390131b 182 BUG_ON(EXT4_JOURNAL(inode) == NULL);
ac27a0ec 183 jbd_debug(2, "restarting handle %p\n", handle);
487caeef 184 up_write(&EXT4_I(inode)->i_data_sem);
8e8eaabe 185 ret = ext4_journal_restart(handle, nblocks);
487caeef 186 down_write(&EXT4_I(inode)->i_data_sem);
fa5d1113 187 ext4_discard_preallocations(inode);
487caeef
JK
188
189 return ret;
ac27a0ec
DK
190}
191
192/*
193 * Called at the last iput() if i_nlink is zero.
194 */
0930fcc1 195void ext4_evict_inode(struct inode *inode)
ac27a0ec
DK
196{
197 handle_t *handle;
bc965ab3 198 int err;
65db869c
JK
199 /*
200 * Credits for final inode cleanup and freeing:
201 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
202 * (xattr block freeing), bitmap, group descriptor (inode freeing)
203 */
204 int extra_credits = 6;
0421a189 205 struct ext4_xattr_inode_array *ea_inode_array = NULL;
ac27a0ec 206
7ff9c073 207 trace_ext4_evict_inode(inode);
2581fdc8 208
0930fcc1 209 if (inode->i_nlink) {
2d859db3
JK
210 /*
211 * When journalling data dirty buffers are tracked only in the
212 * journal. So although mm thinks everything is clean and
213 * ready for reaping the inode might still have some pages to
214 * write in the running transaction or waiting to be
215 * checkpointed. Thus calling jbd2_journal_invalidatepage()
216 * (via truncate_inode_pages()) to discard these buffers can
217 * cause data loss. Also even if we did not discard these
218 * buffers, we would have no way to find them after the inode
219 * is reaped and thus user could see stale data if he tries to
220 * read them before the transaction is checkpointed. So be
221 * careful and force everything to disk here... We use
222 * ei->i_datasync_tid to store the newest transaction
223 * containing inode's data.
224 *
225 * Note that directories do not have this problem because they
226 * don't use page cache.
227 */
6a7fd522
VN
228 if (inode->i_ino != EXT4_JOURNAL_INO &&
229 ext4_should_journal_data(inode) &&
3abb1a0f
JK
230 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
231 inode->i_data.nrpages) {
2d859db3
JK
232 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
233 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
234
d76a3a77 235 jbd2_complete_transaction(journal, commit_tid);
2d859db3
JK
236 filemap_write_and_wait(&inode->i_data);
237 }
91b0abe3 238 truncate_inode_pages_final(&inode->i_data);
5dc23bdd 239
0930fcc1
AV
240 goto no_delete;
241 }
242
e2bfb088
TT
243 if (is_bad_inode(inode))
244 goto no_delete;
245 dquot_initialize(inode);
907f4554 246
678aaf48
JK
247 if (ext4_should_order_data(inode))
248 ext4_begin_ordered_truncate(inode, 0);
91b0abe3 249 truncate_inode_pages_final(&inode->i_data);
ac27a0ec 250
8e8ad8a5
JK
251 /*
252 * Protect us against freezing - iput() caller didn't have to have any
253 * protection against it
254 */
255 sb_start_intwrite(inode->i_sb);
e50e5129 256
30a7eb97
TE
257 if (!IS_NOQUOTA(inode))
258 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
259
65db869c
JK
260 /*
261 * Block bitmap, group descriptor, and inode are accounted in both
262 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
263 */
30a7eb97 264 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
65db869c 265 ext4_blocks_for_truncate(inode) + extra_credits - 3);
ac27a0ec 266 if (IS_ERR(handle)) {
bc965ab3 267 ext4_std_error(inode->i_sb, PTR_ERR(handle));
ac27a0ec
DK
268 /*
269 * If we're going to skip the normal cleanup, we still need to
270 * make sure that the in-core orphan linked list is properly
271 * cleaned up.
272 */
617ba13b 273 ext4_orphan_del(NULL, inode);
8e8ad8a5 274 sb_end_intwrite(inode->i_sb);
ac27a0ec
DK
275 goto no_delete;
276 }
30a7eb97 277
ac27a0ec 278 if (IS_SYNC(inode))
0390131b 279 ext4_handle_sync(handle);
407cd7fb
TE
280
281 /*
282 * Set inode->i_size to 0 before calling ext4_truncate(). We need
283 * special handling of symlinks here because i_size is used to
284 * determine whether ext4_inode_info->i_data contains symlink data or
285 * block mappings. Setting i_size to 0 will remove its fast symlink
286 * status. Erase i_data so that it becomes a valid empty block map.
287 */
288 if (ext4_inode_is_fast_symlink(inode))
289 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
ac27a0ec 290 inode->i_size = 0;
bc965ab3
TT
291 err = ext4_mark_inode_dirty(handle, inode);
292 if (err) {
12062ddd 293 ext4_warning(inode->i_sb,
bc965ab3
TT
294 "couldn't mark inode dirty (err %d)", err);
295 goto stop_handle;
296 }
2c98eb5e
TT
297 if (inode->i_blocks) {
298 err = ext4_truncate(inode);
299 if (err) {
300 ext4_error(inode->i_sb,
301 "couldn't truncate inode %lu (err %d)",
302 inode->i_ino, err);
303 goto stop_handle;
304 }
305 }
bc965ab3 306
30a7eb97
TE
307 /* Remove xattr references. */
308 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
309 extra_credits);
310 if (err) {
311 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
312stop_handle:
313 ext4_journal_stop(handle);
314 ext4_orphan_del(NULL, inode);
315 sb_end_intwrite(inode->i_sb);
316 ext4_xattr_inode_array_free(ea_inode_array);
317 goto no_delete;
bc965ab3
TT
318 }
319
ac27a0ec 320 /*
617ba13b 321 * Kill off the orphan record which ext4_truncate created.
ac27a0ec 322 * AKPM: I think this can be inside the above `if'.
617ba13b 323 * Note that ext4_orphan_del() has to be able to cope with the
ac27a0ec 324 * deletion of a non-existent orphan - this is because we don't
617ba13b 325 * know if ext4_truncate() actually created an orphan record.
ac27a0ec
DK
326 * (Well, we could do this if we need to, but heck - it works)
327 */
617ba13b 328 ext4_orphan_del(handle, inode);
5ffff834 329 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
ac27a0ec
DK
330
331 /*
332 * One subtle ordering requirement: if anything has gone wrong
333 * (transaction abort, IO errors, whatever), then we can still
334 * do these next steps (the fs will already have been marked as
335 * having errors), but we can't free the inode if the mark_dirty
336 * fails.
337 */
617ba13b 338 if (ext4_mark_inode_dirty(handle, inode))
ac27a0ec 339 /* If that failed, just do the required in-core inode clear. */
0930fcc1 340 ext4_clear_inode(inode);
ac27a0ec 341 else
617ba13b
MC
342 ext4_free_inode(handle, inode);
343 ext4_journal_stop(handle);
8e8ad8a5 344 sb_end_intwrite(inode->i_sb);
0421a189 345 ext4_xattr_inode_array_free(ea_inode_array);
ac27a0ec
DK
346 return;
347no_delete:
0930fcc1 348 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
ac27a0ec
DK
349}
350
a9e7f447
DM
351#ifdef CONFIG_QUOTA
352qsize_t *ext4_get_reserved_space(struct inode *inode)
60e58e0f 353{
a9e7f447 354 return &EXT4_I(inode)->i_reserved_quota;
60e58e0f 355}
a9e7f447 356#endif
9d0be502 357
0637c6f4
TT
358/*
359 * Called with i_data_sem down, which is important since we can call
360 * ext4_discard_preallocations() from here.
361 */
5f634d06
AK
362void ext4_da_update_reserve_space(struct inode *inode,
363 int used, int quota_claim)
12219aea
AK
364{
365 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 366 struct ext4_inode_info *ei = EXT4_I(inode);
0637c6f4
TT
367
368 spin_lock(&ei->i_block_reservation_lock);
d8990240 369 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
0637c6f4 370 if (unlikely(used > ei->i_reserved_data_blocks)) {
8de5c325 371 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
1084f252 372 "with only %d reserved data blocks",
0637c6f4
TT
373 __func__, inode->i_ino, used,
374 ei->i_reserved_data_blocks);
375 WARN_ON(1);
376 used = ei->i_reserved_data_blocks;
377 }
12219aea 378
0637c6f4
TT
379 /* Update per-inode reservations */
380 ei->i_reserved_data_blocks -= used;
71d4f7d0 381 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
6bc6e63f 382
12219aea 383 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
60e58e0f 384
72b8ab9d
ES
385 /* Update quota subsystem for data blocks */
386 if (quota_claim)
7b415bf6 387 dquot_claim_block(inode, EXT4_C2B(sbi, used));
72b8ab9d 388 else {
5f634d06
AK
389 /*
390 * We did fallocate with an offset that is already delayed
391 * allocated. So on delayed allocated writeback we should
72b8ab9d 392 * not re-claim the quota for fallocated blocks.
5f634d06 393 */
7b415bf6 394 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
5f634d06 395 }
d6014301
AK
396
397 /*
398 * If we have done all the pending block allocations and if
399 * there aren't any writers on the inode, we can discard the
400 * inode's preallocations.
401 */
0637c6f4 402 if ((ei->i_reserved_data_blocks == 0) &&
82dd124c 403 !inode_is_open_for_write(inode))
d6014301 404 ext4_discard_preallocations(inode);
12219aea
AK
405}
406
e29136f8 407static int __check_block_validity(struct inode *inode, const char *func,
c398eda0
TT
408 unsigned int line,
409 struct ext4_map_blocks *map)
6fd058f7 410{
345c0dbf
TT
411 if (ext4_has_feature_journal(inode->i_sb) &&
412 (inode->i_ino ==
413 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
414 return 0;
24676da4
TT
415 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
416 map->m_len)) {
c398eda0 417 ext4_error_inode(inode, func, line, map->m_pblk,
bdbd6ce0 418 "lblock %lu mapped to illegal pblock %llu "
c398eda0 419 "(length %d)", (unsigned long) map->m_lblk,
bdbd6ce0 420 map->m_pblk, map->m_len);
6a797d27 421 return -EFSCORRUPTED;
6fd058f7
TT
422 }
423 return 0;
424}
425
53085fac
JK
426int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
427 ext4_lblk_t len)
428{
429 int ret;
430
592ddec7 431 if (IS_ENCRYPTED(inode))
a7550b30 432 return fscrypt_zeroout_range(inode, lblk, pblk, len);
53085fac
JK
433
434 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
435 if (ret > 0)
436 ret = 0;
437
438 return ret;
439}
440
e29136f8 441#define check_block_validity(inode, map) \
c398eda0 442 __check_block_validity((inode), __func__, __LINE__, (map))
e29136f8 443
921f266b
DM
444#ifdef ES_AGGRESSIVE_TEST
445static void ext4_map_blocks_es_recheck(handle_t *handle,
446 struct inode *inode,
447 struct ext4_map_blocks *es_map,
448 struct ext4_map_blocks *map,
449 int flags)
450{
451 int retval;
452
453 map->m_flags = 0;
454 /*
455 * There is a race window that the result is not the same.
456 * e.g. xfstests #223 when dioread_nolock enables. The reason
457 * is that we lookup a block mapping in extent status tree with
458 * out taking i_data_sem. So at the time the unwritten extent
459 * could be converted.
460 */
2dcba478 461 down_read(&EXT4_I(inode)->i_data_sem);
921f266b
DM
462 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
463 retval = ext4_ext_map_blocks(handle, inode, map, flags &
464 EXT4_GET_BLOCKS_KEEP_SIZE);
465 } else {
466 retval = ext4_ind_map_blocks(handle, inode, map, flags &
467 EXT4_GET_BLOCKS_KEEP_SIZE);
468 }
2dcba478 469 up_read((&EXT4_I(inode)->i_data_sem));
921f266b
DM
470
471 /*
472 * We don't check m_len because extent will be collpased in status
473 * tree. So the m_len might not equal.
474 */
475 if (es_map->m_lblk != map->m_lblk ||
476 es_map->m_flags != map->m_flags ||
477 es_map->m_pblk != map->m_pblk) {
bdafe42a 478 printk("ES cache assertion failed for inode: %lu "
921f266b
DM
479 "es_cached ex [%d/%d/%llu/%x] != "
480 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
481 inode->i_ino, es_map->m_lblk, es_map->m_len,
482 es_map->m_pblk, es_map->m_flags, map->m_lblk,
483 map->m_len, map->m_pblk, map->m_flags,
484 retval, flags);
485 }
486}
487#endif /* ES_AGGRESSIVE_TEST */
488
f5ab0d1f 489/*
e35fd660 490 * The ext4_map_blocks() function tries to look up the requested blocks,
2b2d6d01 491 * and returns if the blocks are already mapped.
f5ab0d1f 492 *
f5ab0d1f
MC
493 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
494 * and store the allocated blocks in the result buffer head and mark it
495 * mapped.
496 *
e35fd660
TT
497 * If file type is extents based, it will call ext4_ext_map_blocks(),
498 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
f5ab0d1f
MC
499 * based files
500 *
facab4d9
JK
501 * On success, it returns the number of blocks being mapped or allocated. if
502 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
503 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
f5ab0d1f
MC
504 *
505 * It returns 0 if plain look up failed (blocks have not been allocated), in
facab4d9
JK
506 * that case, @map is returned as unmapped but we still do fill map->m_len to
507 * indicate the length of a hole starting at map->m_lblk.
f5ab0d1f
MC
508 *
509 * It returns the error in case of allocation failure.
510 */
e35fd660
TT
511int ext4_map_blocks(handle_t *handle, struct inode *inode,
512 struct ext4_map_blocks *map, int flags)
0e855ac8 513{
d100eef2 514 struct extent_status es;
0e855ac8 515 int retval;
b8a86845 516 int ret = 0;
921f266b
DM
517#ifdef ES_AGGRESSIVE_TEST
518 struct ext4_map_blocks orig_map;
519
520 memcpy(&orig_map, map, sizeof(*map));
521#endif
f5ab0d1f 522
e35fd660
TT
523 map->m_flags = 0;
524 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
525 "logical block %lu\n", inode->i_ino, flags, map->m_len,
526 (unsigned long) map->m_lblk);
d100eef2 527
e861b5e9
TT
528 /*
529 * ext4_map_blocks returns an int, and m_len is an unsigned int
530 */
531 if (unlikely(map->m_len > INT_MAX))
532 map->m_len = INT_MAX;
533
4adb6ab3
KM
534 /* We can handle the block number less than EXT_MAX_BLOCKS */
535 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
6a797d27 536 return -EFSCORRUPTED;
4adb6ab3 537
d100eef2 538 /* Lookup extent status tree firstly */
bb5835ed 539 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
d100eef2
ZL
540 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
541 map->m_pblk = ext4_es_pblock(&es) +
542 map->m_lblk - es.es_lblk;
543 map->m_flags |= ext4_es_is_written(&es) ?
544 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
545 retval = es.es_len - (map->m_lblk - es.es_lblk);
546 if (retval > map->m_len)
547 retval = map->m_len;
548 map->m_len = retval;
549 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
facab4d9
JK
550 map->m_pblk = 0;
551 retval = es.es_len - (map->m_lblk - es.es_lblk);
552 if (retval > map->m_len)
553 retval = map->m_len;
554 map->m_len = retval;
d100eef2
ZL
555 retval = 0;
556 } else {
1e83bc81 557 BUG();
d100eef2 558 }
921f266b
DM
559#ifdef ES_AGGRESSIVE_TEST
560 ext4_map_blocks_es_recheck(handle, inode, map,
561 &orig_map, flags);
562#endif
d100eef2
ZL
563 goto found;
564 }
565
4df3d265 566 /*
b920c755
TT
567 * Try to see if we can get the block without requesting a new
568 * file system block.
4df3d265 569 */
2dcba478 570 down_read(&EXT4_I(inode)->i_data_sem);
12e9b892 571 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
a4e5d88b
DM
572 retval = ext4_ext_map_blocks(handle, inode, map, flags &
573 EXT4_GET_BLOCKS_KEEP_SIZE);
0e855ac8 574 } else {
a4e5d88b
DM
575 retval = ext4_ind_map_blocks(handle, inode, map, flags &
576 EXT4_GET_BLOCKS_KEEP_SIZE);
0e855ac8 577 }
f7fec032 578 if (retval > 0) {
3be78c73 579 unsigned int status;
f7fec032 580
44fb851d
ZL
581 if (unlikely(retval != map->m_len)) {
582 ext4_warning(inode->i_sb,
583 "ES len assertion failed for inode "
584 "%lu: retval %d != map->m_len %d",
585 inode->i_ino, retval, map->m_len);
586 WARN_ON(1);
921f266b 587 }
921f266b 588
f7fec032
ZL
589 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
590 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
591 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
d2dc317d 592 !(status & EXTENT_STATUS_WRITTEN) &&
ad431025
EW
593 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
594 map->m_lblk + map->m_len - 1))
f7fec032
ZL
595 status |= EXTENT_STATUS_DELAYED;
596 ret = ext4_es_insert_extent(inode, map->m_lblk,
597 map->m_len, map->m_pblk, status);
598 if (ret < 0)
599 retval = ret;
600 }
2dcba478 601 up_read((&EXT4_I(inode)->i_data_sem));
f5ab0d1f 602
d100eef2 603found:
e35fd660 604 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
b8a86845 605 ret = check_block_validity(inode, map);
6fd058f7
TT
606 if (ret != 0)
607 return ret;
608 }
609
f5ab0d1f 610 /* If it is only a block(s) look up */
c2177057 611 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
f5ab0d1f
MC
612 return retval;
613
614 /*
615 * Returns if the blocks have already allocated
616 *
617 * Note that if blocks have been preallocated
df3ab170 618 * ext4_ext_get_block() returns the create = 0
f5ab0d1f
MC
619 * with buffer head unmapped.
620 */
e35fd660 621 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
b8a86845
LC
622 /*
623 * If we need to convert extent to unwritten
624 * we continue and do the actual work in
625 * ext4_ext_map_blocks()
626 */
627 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
628 return retval;
4df3d265 629
2a8964d6 630 /*
a25a4e1a
ZL
631 * Here we clear m_flags because after allocating an new extent,
632 * it will be set again.
2a8964d6 633 */
a25a4e1a 634 map->m_flags &= ~EXT4_MAP_FLAGS;
2a8964d6 635
4df3d265 636 /*
556615dc 637 * New blocks allocate and/or writing to unwritten extent
f5ab0d1f 638 * will possibly result in updating i_data, so we take
d91bd2c1 639 * the write lock of i_data_sem, and call get_block()
f5ab0d1f 640 * with create == 1 flag.
4df3d265 641 */
c8b459f4 642 down_write(&EXT4_I(inode)->i_data_sem);
d2a17637 643
4df3d265
AK
644 /*
645 * We need to check for EXT4 here because migrate
646 * could have changed the inode type in between
647 */
12e9b892 648 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
e35fd660 649 retval = ext4_ext_map_blocks(handle, inode, map, flags);
0e855ac8 650 } else {
e35fd660 651 retval = ext4_ind_map_blocks(handle, inode, map, flags);
267e4db9 652
e35fd660 653 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
267e4db9
AK
654 /*
655 * We allocated new blocks which will result in
656 * i_data's format changing. Force the migrate
657 * to fail by clearing migrate flags
658 */
19f5fb7a 659 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
267e4db9 660 }
d2a17637 661
5f634d06
AK
662 /*
663 * Update reserved blocks/metadata blocks after successful
664 * block allocation which had been deferred till now. We don't
665 * support fallocate for non extent files. So we can update
666 * reserve space here.
667 */
668 if ((retval > 0) &&
1296cc85 669 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
5f634d06
AK
670 ext4_da_update_reserve_space(inode, retval, 1);
671 }
2ac3b6e0 672
f7fec032 673 if (retval > 0) {
3be78c73 674 unsigned int status;
f7fec032 675
44fb851d
ZL
676 if (unlikely(retval != map->m_len)) {
677 ext4_warning(inode->i_sb,
678 "ES len assertion failed for inode "
679 "%lu: retval %d != map->m_len %d",
680 inode->i_ino, retval, map->m_len);
681 WARN_ON(1);
921f266b 682 }
921f266b 683
c86d8db3
JK
684 /*
685 * We have to zeroout blocks before inserting them into extent
686 * status tree. Otherwise someone could look them up there and
9b623df6
JK
687 * use them before they are really zeroed. We also have to
688 * unmap metadata before zeroing as otherwise writeback can
689 * overwrite zeros with stale data from block device.
c86d8db3
JK
690 */
691 if (flags & EXT4_GET_BLOCKS_ZERO &&
692 map->m_flags & EXT4_MAP_MAPPED &&
693 map->m_flags & EXT4_MAP_NEW) {
694 ret = ext4_issue_zeroout(inode, map->m_lblk,
695 map->m_pblk, map->m_len);
696 if (ret) {
697 retval = ret;
698 goto out_sem;
699 }
700 }
701
adb23551
ZL
702 /*
703 * If the extent has been zeroed out, we don't need to update
704 * extent status tree.
705 */
706 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
bb5835ed 707 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
adb23551 708 if (ext4_es_is_written(&es))
c86d8db3 709 goto out_sem;
adb23551 710 }
f7fec032
ZL
711 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
712 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
713 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
d2dc317d 714 !(status & EXTENT_STATUS_WRITTEN) &&
ad431025
EW
715 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
716 map->m_lblk + map->m_len - 1))
f7fec032
ZL
717 status |= EXTENT_STATUS_DELAYED;
718 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
719 map->m_pblk, status);
c86d8db3 720 if (ret < 0) {
f7fec032 721 retval = ret;
c86d8db3
JK
722 goto out_sem;
723 }
5356f261
AK
724 }
725
c86d8db3 726out_sem:
4df3d265 727 up_write((&EXT4_I(inode)->i_data_sem));
e35fd660 728 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
b8a86845 729 ret = check_block_validity(inode, map);
6fd058f7
TT
730 if (ret != 0)
731 return ret;
06bd3c36
JK
732
733 /*
734 * Inodes with freshly allocated blocks where contents will be
735 * visible after transaction commit must be on transaction's
736 * ordered data list.
737 */
738 if (map->m_flags & EXT4_MAP_NEW &&
739 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
740 !(flags & EXT4_GET_BLOCKS_ZERO) &&
02749a4c 741 !ext4_is_quota_file(inode) &&
06bd3c36 742 ext4_should_order_data(inode)) {
73131fbb
RZ
743 loff_t start_byte =
744 (loff_t)map->m_lblk << inode->i_blkbits;
745 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
746
ee0876bc 747 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
73131fbb
RZ
748 ret = ext4_jbd2_inode_add_wait(handle, inode,
749 start_byte, length);
ee0876bc 750 else
73131fbb
RZ
751 ret = ext4_jbd2_inode_add_write(handle, inode,
752 start_byte, length);
06bd3c36
JK
753 if (ret)
754 return ret;
755 }
6fd058f7 756 }
0e855ac8
AK
757 return retval;
758}
759
ed8ad838
JK
760/*
761 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
762 * we have to be careful as someone else may be manipulating b_state as well.
763 */
764static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
765{
766 unsigned long old_state;
767 unsigned long new_state;
768
769 flags &= EXT4_MAP_FLAGS;
770
771 /* Dummy buffer_head? Set non-atomically. */
772 if (!bh->b_page) {
773 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
774 return;
775 }
776 /*
777 * Someone else may be modifying b_state. Be careful! This is ugly but
778 * once we get rid of using bh as a container for mapping information
779 * to pass to / from get_block functions, this can go away.
780 */
781 do {
782 old_state = READ_ONCE(bh->b_state);
783 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
784 } while (unlikely(
785 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
786}
787
2ed88685
TT
788static int _ext4_get_block(struct inode *inode, sector_t iblock,
789 struct buffer_head *bh, int flags)
ac27a0ec 790{
2ed88685 791 struct ext4_map_blocks map;
efe70c29 792 int ret = 0;
ac27a0ec 793
46c7f254
TM
794 if (ext4_has_inline_data(inode))
795 return -ERANGE;
796
2ed88685
TT
797 map.m_lblk = iblock;
798 map.m_len = bh->b_size >> inode->i_blkbits;
799
efe70c29
JK
800 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
801 flags);
7fb5409d 802 if (ret > 0) {
2ed88685 803 map_bh(bh, inode->i_sb, map.m_pblk);
ed8ad838 804 ext4_update_bh_state(bh, map.m_flags);
2ed88685 805 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
7fb5409d 806 ret = 0;
547edce3
RZ
807 } else if (ret == 0) {
808 /* hole case, need to fill in bh->b_size */
809 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
ac27a0ec
DK
810 }
811 return ret;
812}
813
2ed88685
TT
814int ext4_get_block(struct inode *inode, sector_t iblock,
815 struct buffer_head *bh, int create)
816{
817 return _ext4_get_block(inode, iblock, bh,
818 create ? EXT4_GET_BLOCKS_CREATE : 0);
819}
820
705965bd
JK
821/*
822 * Get block function used when preparing for buffered write if we require
823 * creating an unwritten extent if blocks haven't been allocated. The extent
824 * will be converted to written after the IO is complete.
825 */
826int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
827 struct buffer_head *bh_result, int create)
828{
829 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
830 inode->i_ino, create);
831 return _ext4_get_block(inode, iblock, bh_result,
832 EXT4_GET_BLOCKS_IO_CREATE_EXT);
833}
834
efe70c29
JK
835/* Maximum number of blocks we map for direct IO at once. */
836#define DIO_MAX_BLOCKS 4096
837
e84dfbe2
JK
838/*
839 * Get blocks function for the cases that need to start a transaction -
840 * generally difference cases of direct IO and DAX IO. It also handles retries
841 * in case of ENOSPC.
842 */
843static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
844 struct buffer_head *bh_result, int flags)
efe70c29
JK
845{
846 int dio_credits;
e84dfbe2
JK
847 handle_t *handle;
848 int retries = 0;
849 int ret;
efe70c29
JK
850
851 /* Trim mapping request to maximum we can map at once for DIO */
852 if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
853 bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
854 dio_credits = ext4_chunk_trans_blocks(inode,
855 bh_result->b_size >> inode->i_blkbits);
e84dfbe2
JK
856retry:
857 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
858 if (IS_ERR(handle))
859 return PTR_ERR(handle);
860
861 ret = _ext4_get_block(inode, iblock, bh_result, flags);
862 ext4_journal_stop(handle);
863
864 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
865 goto retry;
866 return ret;
efe70c29
JK
867}
868
705965bd
JK
869/* Get block function for DIO reads and writes to inodes without extents */
870int ext4_dio_get_block(struct inode *inode, sector_t iblock,
871 struct buffer_head *bh, int create)
872{
efe70c29
JK
873 /* We don't expect handle for direct IO */
874 WARN_ON_ONCE(ext4_journal_current_handle());
875
e84dfbe2
JK
876 if (!create)
877 return _ext4_get_block(inode, iblock, bh, 0);
878 return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
705965bd
JK
879}
880
881/*
109811c2 882 * Get block function for AIO DIO writes when we create unwritten extent if
705965bd
JK
883 * blocks are not allocated yet. The extent will be converted to written
884 * after IO is complete.
885 */
109811c2
JK
886static int ext4_dio_get_block_unwritten_async(struct inode *inode,
887 sector_t iblock, struct buffer_head *bh_result, int create)
705965bd 888{
efe70c29
JK
889 int ret;
890
efe70c29
JK
891 /* We don't expect handle for direct IO */
892 WARN_ON_ONCE(ext4_journal_current_handle());
893
e84dfbe2
JK
894 ret = ext4_get_block_trans(inode, iblock, bh_result,
895 EXT4_GET_BLOCKS_IO_CREATE_EXT);
efe70c29 896
109811c2
JK
897 /*
898 * When doing DIO using unwritten extents, we need io_end to convert
899 * unwritten extents to written on IO completion. We allocate io_end
900 * once we spot unwritten extent and store it in b_private. Generic
901 * DIO code keeps b_private set and furthermore passes the value to
902 * our completion callback in 'private' argument.
903 */
904 if (!ret && buffer_unwritten(bh_result)) {
905 if (!bh_result->b_private) {
906 ext4_io_end_t *io_end;
907
908 io_end = ext4_init_io_end(inode, GFP_KERNEL);
909 if (!io_end)
910 return -ENOMEM;
911 bh_result->b_private = io_end;
912 ext4_set_io_unwritten_flag(inode, io_end);
913 }
efe70c29 914 set_buffer_defer_completion(bh_result);
efe70c29
JK
915 }
916
917 return ret;
705965bd
JK
918}
919
109811c2
JK
920/*
921 * Get block function for non-AIO DIO writes when we create unwritten extent if
922 * blocks are not allocated yet. The extent will be converted to written
1e21196c 923 * after IO is complete by ext4_direct_IO_write().
109811c2
JK
924 */
925static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
926 sector_t iblock, struct buffer_head *bh_result, int create)
927{
109811c2
JK
928 int ret;
929
930 /* We don't expect handle for direct IO */
931 WARN_ON_ONCE(ext4_journal_current_handle());
932
e84dfbe2
JK
933 ret = ext4_get_block_trans(inode, iblock, bh_result,
934 EXT4_GET_BLOCKS_IO_CREATE_EXT);
109811c2
JK
935
936 /*
937 * Mark inode as having pending DIO writes to unwritten extents.
1e21196c 938 * ext4_direct_IO_write() checks this flag and converts extents to
109811c2
JK
939 * written.
940 */
941 if (!ret && buffer_unwritten(bh_result))
942 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
943
944 return ret;
945}
946
705965bd
JK
947static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
948 struct buffer_head *bh_result, int create)
949{
950 int ret;
951
952 ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
953 inode->i_ino, create);
efe70c29
JK
954 /* We don't expect handle for direct IO */
955 WARN_ON_ONCE(ext4_journal_current_handle());
956
705965bd
JK
957 ret = _ext4_get_block(inode, iblock, bh_result, 0);
958 /*
959 * Blocks should have been preallocated! ext4_file_write_iter() checks
960 * that.
961 */
efe70c29 962 WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
705965bd
JK
963
964 return ret;
965}
966
967
ac27a0ec
DK
968/*
969 * `handle' can be NULL if create is zero
970 */
617ba13b 971struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
c5e298ae 972 ext4_lblk_t block, int map_flags)
ac27a0ec 973{
2ed88685
TT
974 struct ext4_map_blocks map;
975 struct buffer_head *bh;
c5e298ae 976 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
10560082 977 int err;
ac27a0ec
DK
978
979 J_ASSERT(handle != NULL || create == 0);
980
2ed88685
TT
981 map.m_lblk = block;
982 map.m_len = 1;
c5e298ae 983 err = ext4_map_blocks(handle, inode, &map, map_flags);
ac27a0ec 984
10560082
TT
985 if (err == 0)
986 return create ? ERR_PTR(-ENOSPC) : NULL;
2ed88685 987 if (err < 0)
10560082 988 return ERR_PTR(err);
2ed88685
TT
989
990 bh = sb_getblk(inode->i_sb, map.m_pblk);
10560082
TT
991 if (unlikely(!bh))
992 return ERR_PTR(-ENOMEM);
2ed88685
TT
993 if (map.m_flags & EXT4_MAP_NEW) {
994 J_ASSERT(create != 0);
995 J_ASSERT(handle != NULL);
ac27a0ec 996
2ed88685
TT
997 /*
998 * Now that we do not always journal data, we should
999 * keep in mind whether this should always journal the
1000 * new buffer as metadata. For now, regular file
1001 * writes use ext4_get_block instead, so it's not a
1002 * problem.
1003 */
1004 lock_buffer(bh);
1005 BUFFER_TRACE(bh, "call get_create_access");
10560082
TT
1006 err = ext4_journal_get_create_access(handle, bh);
1007 if (unlikely(err)) {
1008 unlock_buffer(bh);
1009 goto errout;
1010 }
1011 if (!buffer_uptodate(bh)) {
2ed88685
TT
1012 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1013 set_buffer_uptodate(bh);
ac27a0ec 1014 }
2ed88685
TT
1015 unlock_buffer(bh);
1016 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1017 err = ext4_handle_dirty_metadata(handle, inode, bh);
10560082
TT
1018 if (unlikely(err))
1019 goto errout;
1020 } else
2ed88685 1021 BUFFER_TRACE(bh, "not a new buffer");
2ed88685 1022 return bh;
10560082
TT
1023errout:
1024 brelse(bh);
1025 return ERR_PTR(err);
ac27a0ec
DK
1026}
1027
617ba13b 1028struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
c5e298ae 1029 ext4_lblk_t block, int map_flags)
ac27a0ec 1030{
af5bc92d 1031 struct buffer_head *bh;
ac27a0ec 1032
c5e298ae 1033 bh = ext4_getblk(handle, inode, block, map_flags);
1c215028 1034 if (IS_ERR(bh))
ac27a0ec 1035 return bh;
7963e5ac 1036 if (!bh || ext4_buffer_uptodate(bh))
ac27a0ec 1037 return bh;
dfec8a14 1038 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
ac27a0ec
DK
1039 wait_on_buffer(bh);
1040 if (buffer_uptodate(bh))
1041 return bh;
1042 put_bh(bh);
1c215028 1043 return ERR_PTR(-EIO);
ac27a0ec
DK
1044}
1045
9699d4f9
TE
1046/* Read a contiguous batch of blocks. */
1047int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
1048 bool wait, struct buffer_head **bhs)
1049{
1050 int i, err;
1051
1052 for (i = 0; i < bh_count; i++) {
1053 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
1054 if (IS_ERR(bhs[i])) {
1055 err = PTR_ERR(bhs[i]);
1056 bh_count = i;
1057 goto out_brelse;
1058 }
1059 }
1060
1061 for (i = 0; i < bh_count; i++)
1062 /* Note that NULL bhs[i] is valid because of holes. */
7963e5ac 1063 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
9699d4f9
TE
1064 ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
1065 &bhs[i]);
1066
1067 if (!wait)
1068 return 0;
1069
1070 for (i = 0; i < bh_count; i++)
1071 if (bhs[i])
1072 wait_on_buffer(bhs[i]);
1073
1074 for (i = 0; i < bh_count; i++) {
1075 if (bhs[i] && !buffer_uptodate(bhs[i])) {
1076 err = -EIO;
1077 goto out_brelse;
1078 }
1079 }
1080 return 0;
1081
1082out_brelse:
1083 for (i = 0; i < bh_count; i++) {
1084 brelse(bhs[i]);
1085 bhs[i] = NULL;
1086 }
1087 return err;
1088}
1089
f19d5870
TM
1090int ext4_walk_page_buffers(handle_t *handle,
1091 struct buffer_head *head,
1092 unsigned from,
1093 unsigned to,
1094 int *partial,
1095 int (*fn)(handle_t *handle,
1096 struct buffer_head *bh))
ac27a0ec
DK
1097{
1098 struct buffer_head *bh;
1099 unsigned block_start, block_end;
1100 unsigned blocksize = head->b_size;
1101 int err, ret = 0;
1102 struct buffer_head *next;
1103
af5bc92d
TT
1104 for (bh = head, block_start = 0;
1105 ret == 0 && (bh != head || !block_start);
de9a55b8 1106 block_start = block_end, bh = next) {
ac27a0ec
DK
1107 next = bh->b_this_page;
1108 block_end = block_start + blocksize;
1109 if (block_end <= from || block_start >= to) {
1110 if (partial && !buffer_uptodate(bh))
1111 *partial = 1;
1112 continue;
1113 }
1114 err = (*fn)(handle, bh);
1115 if (!ret)
1116 ret = err;
1117 }
1118 return ret;
1119}
1120
1121/*
1122 * To preserve ordering, it is essential that the hole instantiation and
1123 * the data write be encapsulated in a single transaction. We cannot
617ba13b 1124 * close off a transaction and start a new one between the ext4_get_block()
dab291af 1125 * and the commit_write(). So doing the jbd2_journal_start at the start of
ac27a0ec
DK
1126 * prepare_write() is the right place.
1127 *
36ade451
JK
1128 * Also, this function can nest inside ext4_writepage(). In that case, we
1129 * *know* that ext4_writepage() has generated enough buffer credits to do the
1130 * whole page. So we won't block on the journal in that case, which is good,
1131 * because the caller may be PF_MEMALLOC.
ac27a0ec 1132 *
617ba13b 1133 * By accident, ext4 can be reentered when a transaction is open via
ac27a0ec
DK
1134 * quota file writes. If we were to commit the transaction while thus
1135 * reentered, there can be a deadlock - we would be holding a quota
1136 * lock, and the commit would never complete if another thread had a
1137 * transaction open and was blocking on the quota lock - a ranking
1138 * violation.
1139 *
dab291af 1140 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
ac27a0ec
DK
1141 * will _not_ run commit under these circumstances because handle->h_ref
1142 * is elevated. We'll still have enough credits for the tiny quotafile
1143 * write.
1144 */
f19d5870
TM
1145int do_journal_get_write_access(handle_t *handle,
1146 struct buffer_head *bh)
ac27a0ec 1147{
56d35a4c
JK
1148 int dirty = buffer_dirty(bh);
1149 int ret;
1150
ac27a0ec
DK
1151 if (!buffer_mapped(bh) || buffer_freed(bh))
1152 return 0;
56d35a4c 1153 /*
ebdec241 1154 * __block_write_begin() could have dirtied some buffers. Clean
56d35a4c
JK
1155 * the dirty bit as jbd2_journal_get_write_access() could complain
1156 * otherwise about fs integrity issues. Setting of the dirty bit
ebdec241 1157 * by __block_write_begin() isn't a real problem here as we clear
56d35a4c
JK
1158 * the bit before releasing a page lock and thus writeback cannot
1159 * ever write the buffer.
1160 */
1161 if (dirty)
1162 clear_buffer_dirty(bh);
5d601255 1163 BUFFER_TRACE(bh, "get write access");
56d35a4c
JK
1164 ret = ext4_journal_get_write_access(handle, bh);
1165 if (!ret && dirty)
1166 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1167 return ret;
ac27a0ec
DK
1168}
1169
643fa961 1170#ifdef CONFIG_FS_ENCRYPTION
2058f83a
MH
1171static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1172 get_block_t *get_block)
1173{
09cbfeaf 1174 unsigned from = pos & (PAGE_SIZE - 1);
2058f83a
MH
1175 unsigned to = from + len;
1176 struct inode *inode = page->mapping->host;
1177 unsigned block_start, block_end;
1178 sector_t block;
1179 int err = 0;
1180 unsigned blocksize = inode->i_sb->s_blocksize;
1181 unsigned bbits;
0b578f35
CR
1182 struct buffer_head *bh, *head, *wait[2];
1183 int nr_wait = 0;
1184 int i;
2058f83a
MH
1185
1186 BUG_ON(!PageLocked(page));
09cbfeaf
KS
1187 BUG_ON(from > PAGE_SIZE);
1188 BUG_ON(to > PAGE_SIZE);
2058f83a
MH
1189 BUG_ON(from > to);
1190
1191 if (!page_has_buffers(page))
1192 create_empty_buffers(page, blocksize, 0);
1193 head = page_buffers(page);
1194 bbits = ilog2(blocksize);
09cbfeaf 1195 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
2058f83a
MH
1196
1197 for (bh = head, block_start = 0; bh != head || !block_start;
1198 block++, block_start = block_end, bh = bh->b_this_page) {
1199 block_end = block_start + blocksize;
1200 if (block_end <= from || block_start >= to) {
1201 if (PageUptodate(page)) {
1202 if (!buffer_uptodate(bh))
1203 set_buffer_uptodate(bh);
1204 }
1205 continue;
1206 }
1207 if (buffer_new(bh))
1208 clear_buffer_new(bh);
1209 if (!buffer_mapped(bh)) {
1210 WARN_ON(bh->b_size != blocksize);
1211 err = get_block(inode, block, bh, 1);
1212 if (err)
1213 break;
1214 if (buffer_new(bh)) {
2058f83a
MH
1215 if (PageUptodate(page)) {
1216 clear_buffer_new(bh);
1217 set_buffer_uptodate(bh);
1218 mark_buffer_dirty(bh);
1219 continue;
1220 }
1221 if (block_end > to || block_start < from)
1222 zero_user_segments(page, to, block_end,
1223 block_start, from);
1224 continue;
1225 }
1226 }
1227 if (PageUptodate(page)) {
1228 if (!buffer_uptodate(bh))
1229 set_buffer_uptodate(bh);
1230 continue;
1231 }
1232 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1233 !buffer_unwritten(bh) &&
1234 (block_start < from || block_end > to)) {
dfec8a14 1235 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
0b578f35 1236 wait[nr_wait++] = bh;
2058f83a
MH
1237 }
1238 }
1239 /*
1240 * If we issued read requests, let them complete.
1241 */
0b578f35
CR
1242 for (i = 0; i < nr_wait; i++) {
1243 wait_on_buffer(wait[i]);
1244 if (!buffer_uptodate(wait[i]))
2058f83a
MH
1245 err = -EIO;
1246 }
7e0785fc 1247 if (unlikely(err)) {
2058f83a 1248 page_zero_new_buffers(page, from, to);
0b578f35
CR
1249 } else if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) {
1250 for (i = 0; i < nr_wait; i++) {
1251 int err2;
1252
1253 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1254 bh_offset(wait[i]));
1255 if (err2) {
1256 clear_buffer_uptodate(wait[i]);
1257 err = err2;
1258 }
1259 }
7e0785fc
CR
1260 }
1261
2058f83a
MH
1262 return err;
1263}
1264#endif
1265
bfc1af65 1266static int ext4_write_begin(struct file *file, struct address_space *mapping,
de9a55b8
TT
1267 loff_t pos, unsigned len, unsigned flags,
1268 struct page **pagep, void **fsdata)
ac27a0ec 1269{
af5bc92d 1270 struct inode *inode = mapping->host;
1938a150 1271 int ret, needed_blocks;
ac27a0ec
DK
1272 handle_t *handle;
1273 int retries = 0;
af5bc92d 1274 struct page *page;
de9a55b8 1275 pgoff_t index;
af5bc92d 1276 unsigned from, to;
bfc1af65 1277
0db1ff22
TT
1278 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1279 return -EIO;
1280
9bffad1e 1281 trace_ext4_write_begin(inode, pos, len, flags);
1938a150
AK
1282 /*
1283 * Reserve one block more for addition to orphan list in case
1284 * we allocate blocks but write fails for some reason
1285 */
1286 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
09cbfeaf
KS
1287 index = pos >> PAGE_SHIFT;
1288 from = pos & (PAGE_SIZE - 1);
af5bc92d 1289 to = from + len;
ac27a0ec 1290
f19d5870
TM
1291 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1292 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1293 flags, pagep);
1294 if (ret < 0)
47564bfb
TT
1295 return ret;
1296 if (ret == 1)
1297 return 0;
f19d5870
TM
1298 }
1299
47564bfb
TT
1300 /*
1301 * grab_cache_page_write_begin() can take a long time if the
1302 * system is thrashing due to memory pressure, or if the page
1303 * is being written back. So grab it first before we start
1304 * the transaction handle. This also allows us to allocate
1305 * the page (if needed) without using GFP_NOFS.
1306 */
1307retry_grab:
1308 page = grab_cache_page_write_begin(mapping, index, flags);
1309 if (!page)
1310 return -ENOMEM;
1311 unlock_page(page);
1312
1313retry_journal:
9924a92a 1314 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
af5bc92d 1315 if (IS_ERR(handle)) {
09cbfeaf 1316 put_page(page);
47564bfb 1317 return PTR_ERR(handle);
7479d2b9 1318 }
ac27a0ec 1319
47564bfb
TT
1320 lock_page(page);
1321 if (page->mapping != mapping) {
1322 /* The page got truncated from under us */
1323 unlock_page(page);
09cbfeaf 1324 put_page(page);
cf108bca 1325 ext4_journal_stop(handle);
47564bfb 1326 goto retry_grab;
cf108bca 1327 }
7afe5aa5
DM
1328 /* In case writeback began while the page was unlocked */
1329 wait_for_stable_page(page);
cf108bca 1330
643fa961 1331#ifdef CONFIG_FS_ENCRYPTION
2058f83a
MH
1332 if (ext4_should_dioread_nolock(inode))
1333 ret = ext4_block_write_begin(page, pos, len,
705965bd 1334 ext4_get_block_unwritten);
2058f83a
MH
1335 else
1336 ret = ext4_block_write_begin(page, pos, len,
1337 ext4_get_block);
1338#else
744692dc 1339 if (ext4_should_dioread_nolock(inode))
705965bd
JK
1340 ret = __block_write_begin(page, pos, len,
1341 ext4_get_block_unwritten);
744692dc 1342 else
6e1db88d 1343 ret = __block_write_begin(page, pos, len, ext4_get_block);
2058f83a 1344#endif
bfc1af65 1345 if (!ret && ext4_should_journal_data(inode)) {
f19d5870
TM
1346 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1347 from, to, NULL,
1348 do_journal_get_write_access);
ac27a0ec 1349 }
bfc1af65
NP
1350
1351 if (ret) {
c93d8f88
EB
1352 bool extended = (pos + len > inode->i_size) &&
1353 !ext4_verity_in_progress(inode);
1354
af5bc92d 1355 unlock_page(page);
ae4d5372 1356 /*
6e1db88d 1357 * __block_write_begin may have instantiated a few blocks
ae4d5372
AK
1358 * outside i_size. Trim these off again. Don't need
1359 * i_size_read because we hold i_mutex.
1938a150
AK
1360 *
1361 * Add inode to orphan list in case we crash before
1362 * truncate finishes
ae4d5372 1363 */
c93d8f88 1364 if (extended && ext4_can_truncate(inode))
1938a150
AK
1365 ext4_orphan_add(handle, inode);
1366
1367 ext4_journal_stop(handle);
c93d8f88 1368 if (extended) {
b9a4207d 1369 ext4_truncate_failed_write(inode);
de9a55b8 1370 /*
ffacfa7a 1371 * If truncate failed early the inode might
1938a150
AK
1372 * still be on the orphan list; we need to
1373 * make sure the inode is removed from the
1374 * orphan list in that case.
1375 */
1376 if (inode->i_nlink)
1377 ext4_orphan_del(NULL, inode);
1378 }
bfc1af65 1379
47564bfb
TT
1380 if (ret == -ENOSPC &&
1381 ext4_should_retry_alloc(inode->i_sb, &retries))
1382 goto retry_journal;
09cbfeaf 1383 put_page(page);
47564bfb
TT
1384 return ret;
1385 }
1386 *pagep = page;
ac27a0ec
DK
1387 return ret;
1388}
1389
bfc1af65
NP
1390/* For write_end() in data=journal mode */
1391static int write_end_fn(handle_t *handle, struct buffer_head *bh)
ac27a0ec 1392{
13fca323 1393 int ret;
ac27a0ec
DK
1394 if (!buffer_mapped(bh) || buffer_freed(bh))
1395 return 0;
1396 set_buffer_uptodate(bh);
13fca323
TT
1397 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1398 clear_buffer_meta(bh);
1399 clear_buffer_prio(bh);
1400 return ret;
ac27a0ec
DK
1401}
1402
eed4333f
ZL
1403/*
1404 * We need to pick up the new inode size which generic_commit_write gave us
1405 * `file' can be NULL - eg, when called from page_symlink().
1406 *
1407 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1408 * buffers are managed internally.
1409 */
1410static int ext4_write_end(struct file *file,
1411 struct address_space *mapping,
1412 loff_t pos, unsigned len, unsigned copied,
1413 struct page *page, void *fsdata)
f8514083 1414{
f8514083 1415 handle_t *handle = ext4_journal_current_handle();
eed4333f 1416 struct inode *inode = mapping->host;
0572639f 1417 loff_t old_size = inode->i_size;
eed4333f
ZL
1418 int ret = 0, ret2;
1419 int i_size_changed = 0;
362eca70 1420 int inline_data = ext4_has_inline_data(inode);
c93d8f88 1421 bool verity = ext4_verity_in_progress(inode);
eed4333f
ZL
1422
1423 trace_ext4_write_end(inode, pos, len, copied);
362eca70 1424 if (inline_data) {
42c832de
TT
1425 ret = ext4_write_inline_data_end(inode, pos, len,
1426 copied, page);
eb5efbcb
TT
1427 if (ret < 0) {
1428 unlock_page(page);
1429 put_page(page);
42c832de 1430 goto errout;
eb5efbcb 1431 }
42c832de
TT
1432 copied = ret;
1433 } else
f19d5870
TM
1434 copied = block_write_end(file, mapping, pos,
1435 len, copied, page, fsdata);
f8514083 1436 /*
4631dbf6 1437 * it's important to update i_size while still holding page lock:
f8514083 1438 * page writeout could otherwise come in and zero beyond i_size.
c93d8f88
EB
1439 *
1440 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1441 * blocks are being written past EOF, so skip the i_size update.
f8514083 1442 */
c93d8f88
EB
1443 if (!verity)
1444 i_size_changed = ext4_update_inode_size(inode, pos + copied);
f8514083 1445 unlock_page(page);
09cbfeaf 1446 put_page(page);
f8514083 1447
c93d8f88 1448 if (old_size < pos && !verity)
0572639f 1449 pagecache_isize_extended(inode, old_size, pos);
f8514083
AK
1450 /*
1451 * Don't mark the inode dirty under page lock. First, it unnecessarily
1452 * makes the holding time of page lock longer. Second, it forces lock
1453 * ordering of page lock and transaction start for journaling
1454 * filesystems.
1455 */
362eca70 1456 if (i_size_changed || inline_data)
f8514083
AK
1457 ext4_mark_inode_dirty(handle, inode);
1458
c93d8f88 1459 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
f8514083
AK
1460 /* if we have allocated more blocks and copied
1461 * less. We will have blocks allocated outside
1462 * inode->i_size. So truncate them
1463 */
1464 ext4_orphan_add(handle, inode);
74d553aa 1465errout:
617ba13b 1466 ret2 = ext4_journal_stop(handle);
ac27a0ec
DK
1467 if (!ret)
1468 ret = ret2;
bfc1af65 1469
c93d8f88 1470 if (pos + len > inode->i_size && !verity) {
b9a4207d 1471 ext4_truncate_failed_write(inode);
de9a55b8 1472 /*
ffacfa7a 1473 * If truncate failed early the inode might still be
f8514083
AK
1474 * on the orphan list; we need to make sure the inode
1475 * is removed from the orphan list in that case.
1476 */
1477 if (inode->i_nlink)
1478 ext4_orphan_del(NULL, inode);
1479 }
1480
bfc1af65 1481 return ret ? ret : copied;
ac27a0ec
DK
1482}
1483
b90197b6
TT
1484/*
1485 * This is a private version of page_zero_new_buffers() which doesn't
1486 * set the buffer to be dirty, since in data=journalled mode we need
1487 * to call ext4_handle_dirty_metadata() instead.
1488 */
3b136499
JK
1489static void ext4_journalled_zero_new_buffers(handle_t *handle,
1490 struct page *page,
1491 unsigned from, unsigned to)
b90197b6
TT
1492{
1493 unsigned int block_start = 0, block_end;
1494 struct buffer_head *head, *bh;
1495
1496 bh = head = page_buffers(page);
1497 do {
1498 block_end = block_start + bh->b_size;
1499 if (buffer_new(bh)) {
1500 if (block_end > from && block_start < to) {
1501 if (!PageUptodate(page)) {
1502 unsigned start, size;
1503
1504 start = max(from, block_start);
1505 size = min(to, block_end) - start;
1506
1507 zero_user(page, start, size);
3b136499 1508 write_end_fn(handle, bh);
b90197b6
TT
1509 }
1510 clear_buffer_new(bh);
1511 }
1512 }
1513 block_start = block_end;
1514 bh = bh->b_this_page;
1515 } while (bh != head);
1516}
1517
bfc1af65 1518static int ext4_journalled_write_end(struct file *file,
de9a55b8
TT
1519 struct address_space *mapping,
1520 loff_t pos, unsigned len, unsigned copied,
1521 struct page *page, void *fsdata)
ac27a0ec 1522{
617ba13b 1523 handle_t *handle = ext4_journal_current_handle();
bfc1af65 1524 struct inode *inode = mapping->host;
0572639f 1525 loff_t old_size = inode->i_size;
ac27a0ec
DK
1526 int ret = 0, ret2;
1527 int partial = 0;
bfc1af65 1528 unsigned from, to;
4631dbf6 1529 int size_changed = 0;
362eca70 1530 int inline_data = ext4_has_inline_data(inode);
c93d8f88 1531 bool verity = ext4_verity_in_progress(inode);
ac27a0ec 1532
9bffad1e 1533 trace_ext4_journalled_write_end(inode, pos, len, copied);
09cbfeaf 1534 from = pos & (PAGE_SIZE - 1);
bfc1af65
NP
1535 to = from + len;
1536
441c8508
CW
1537 BUG_ON(!ext4_handle_valid(handle));
1538
362eca70 1539 if (inline_data) {
eb5efbcb
TT
1540 ret = ext4_write_inline_data_end(inode, pos, len,
1541 copied, page);
1542 if (ret < 0) {
1543 unlock_page(page);
1544 put_page(page);
1545 goto errout;
1546 }
1547 copied = ret;
1548 } else if (unlikely(copied < len) && !PageUptodate(page)) {
3b136499
JK
1549 copied = 0;
1550 ext4_journalled_zero_new_buffers(handle, page, from, to);
1551 } else {
1552 if (unlikely(copied < len))
1553 ext4_journalled_zero_new_buffers(handle, page,
1554 from + copied, to);
3fdcfb66 1555 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
3b136499
JK
1556 from + copied, &partial,
1557 write_end_fn);
3fdcfb66
TM
1558 if (!partial)
1559 SetPageUptodate(page);
1560 }
c93d8f88
EB
1561 if (!verity)
1562 size_changed = ext4_update_inode_size(inode, pos + copied);
19f5fb7a 1563 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2d859db3 1564 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
4631dbf6 1565 unlock_page(page);
09cbfeaf 1566 put_page(page);
4631dbf6 1567
c93d8f88 1568 if (old_size < pos && !verity)
0572639f
XW
1569 pagecache_isize_extended(inode, old_size, pos);
1570
362eca70 1571 if (size_changed || inline_data) {
617ba13b 1572 ret2 = ext4_mark_inode_dirty(handle, inode);
ac27a0ec
DK
1573 if (!ret)
1574 ret = ret2;
1575 }
bfc1af65 1576
c93d8f88 1577 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
f8514083
AK
1578 /* if we have allocated more blocks and copied
1579 * less. We will have blocks allocated outside
1580 * inode->i_size. So truncate them
1581 */
1582 ext4_orphan_add(handle, inode);
1583
eb5efbcb 1584errout:
617ba13b 1585 ret2 = ext4_journal_stop(handle);
ac27a0ec
DK
1586 if (!ret)
1587 ret = ret2;
c93d8f88 1588 if (pos + len > inode->i_size && !verity) {
b9a4207d 1589 ext4_truncate_failed_write(inode);
de9a55b8 1590 /*
ffacfa7a 1591 * If truncate failed early the inode might still be
f8514083
AK
1592 * on the orphan list; we need to make sure the inode
1593 * is removed from the orphan list in that case.
1594 */
1595 if (inode->i_nlink)
1596 ext4_orphan_del(NULL, inode);
1597 }
bfc1af65
NP
1598
1599 return ret ? ret : copied;
ac27a0ec 1600}
d2a17637 1601
9d0be502 1602/*
c27e43a1 1603 * Reserve space for a single cluster
9d0be502 1604 */
c27e43a1 1605static int ext4_da_reserve_space(struct inode *inode)
d2a17637 1606{
60e58e0f 1607 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 1608 struct ext4_inode_info *ei = EXT4_I(inode);
5dd4056d 1609 int ret;
03179fe9
TT
1610
1611 /*
1612 * We will charge metadata quota at writeout time; this saves
1613 * us from metadata over-estimation, though we may go over by
1614 * a small amount in the end. Here we just reserve for data.
1615 */
1616 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1617 if (ret)
1618 return ret;
d2a17637 1619
0637c6f4 1620 spin_lock(&ei->i_block_reservation_lock);
71d4f7d0 1621 if (ext4_claim_free_clusters(sbi, 1, 0)) {
03179fe9 1622 spin_unlock(&ei->i_block_reservation_lock);
03179fe9 1623 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
d2a17637
MC
1624 return -ENOSPC;
1625 }
9d0be502 1626 ei->i_reserved_data_blocks++;
c27e43a1 1627 trace_ext4_da_reserve_space(inode);
0637c6f4 1628 spin_unlock(&ei->i_block_reservation_lock);
39bc680a 1629
d2a17637
MC
1630 return 0; /* success */
1631}
1632
f456767d 1633void ext4_da_release_space(struct inode *inode, int to_free)
d2a17637
MC
1634{
1635 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
0637c6f4 1636 struct ext4_inode_info *ei = EXT4_I(inode);
d2a17637 1637
cd213226
MC
1638 if (!to_free)
1639 return; /* Nothing to release, exit */
1640
d2a17637 1641 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
cd213226 1642
5a58ec87 1643 trace_ext4_da_release_space(inode, to_free);
0637c6f4 1644 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
cd213226 1645 /*
0637c6f4
TT
1646 * if there aren't enough reserved blocks, then the
1647 * counter is messed up somewhere. Since this
1648 * function is called from invalidate page, it's
1649 * harmless to return without any action.
cd213226 1650 */
8de5c325 1651 ext4_warning(inode->i_sb, "ext4_da_release_space: "
0637c6f4 1652 "ino %lu, to_free %d with only %d reserved "
1084f252 1653 "data blocks", inode->i_ino, to_free,
0637c6f4
TT
1654 ei->i_reserved_data_blocks);
1655 WARN_ON(1);
1656 to_free = ei->i_reserved_data_blocks;
cd213226 1657 }
0637c6f4 1658 ei->i_reserved_data_blocks -= to_free;
cd213226 1659
72b8ab9d 1660 /* update fs dirty data blocks counter */
57042651 1661 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
d2a17637 1662
d2a17637 1663 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
60e58e0f 1664
7b415bf6 1665 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
d2a17637
MC
1666}
1667
64769240
AT
1668/*
1669 * Delayed allocation stuff
1670 */
1671
4e7ea81d
JK
1672struct mpage_da_data {
1673 struct inode *inode;
1674 struct writeback_control *wbc;
6b523df4 1675
4e7ea81d
JK
1676 pgoff_t first_page; /* The first page to write */
1677 pgoff_t next_page; /* Current page to examine */
1678 pgoff_t last_page; /* Last page to examine */
791b7f08 1679 /*
4e7ea81d
JK
1680 * Extent to map - this can be after first_page because that can be
1681 * fully mapped. We somewhat abuse m_flags to store whether the extent
1682 * is delalloc or unwritten.
791b7f08 1683 */
4e7ea81d
JK
1684 struct ext4_map_blocks map;
1685 struct ext4_io_submit io_submit; /* IO submission data */
dddbd6ac 1686 unsigned int do_map:1;
4e7ea81d 1687};
64769240 1688
4e7ea81d
JK
1689static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1690 bool invalidate)
c4a0c46e
AK
1691{
1692 int nr_pages, i;
1693 pgoff_t index, end;
1694 struct pagevec pvec;
1695 struct inode *inode = mpd->inode;
1696 struct address_space *mapping = inode->i_mapping;
4e7ea81d
JK
1697
1698 /* This is necessary when next_page == 0. */
1699 if (mpd->first_page >= mpd->next_page)
1700 return;
c4a0c46e 1701
c7f5938a
CW
1702 index = mpd->first_page;
1703 end = mpd->next_page - 1;
4e7ea81d
JK
1704 if (invalidate) {
1705 ext4_lblk_t start, last;
09cbfeaf
KS
1706 start = index << (PAGE_SHIFT - inode->i_blkbits);
1707 last = end << (PAGE_SHIFT - inode->i_blkbits);
4e7ea81d
JK
1708 ext4_es_remove_extent(inode, start, last - start + 1);
1709 }
51865fda 1710
86679820 1711 pagevec_init(&pvec);
c4a0c46e 1712 while (index <= end) {
397162ff 1713 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
c4a0c46e
AK
1714 if (nr_pages == 0)
1715 break;
1716 for (i = 0; i < nr_pages; i++) {
1717 struct page *page = pvec.pages[i];
2b85a617 1718
c4a0c46e
AK
1719 BUG_ON(!PageLocked(page));
1720 BUG_ON(PageWriteback(page));
4e7ea81d 1721 if (invalidate) {
4e800c03 1722 if (page_mapped(page))
1723 clear_page_dirty_for_io(page);
09cbfeaf 1724 block_invalidatepage(page, 0, PAGE_SIZE);
4e7ea81d
JK
1725 ClearPageUptodate(page);
1726 }
c4a0c46e
AK
1727 unlock_page(page);
1728 }
9b1d0998 1729 pagevec_release(&pvec);
c4a0c46e 1730 }
c4a0c46e
AK
1731}
1732
df22291f
AK
1733static void ext4_print_free_blocks(struct inode *inode)
1734{
1735 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
92b97816 1736 struct super_block *sb = inode->i_sb;
f78ee70d 1737 struct ext4_inode_info *ei = EXT4_I(inode);
92b97816
TT
1738
1739 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
5dee5437 1740 EXT4_C2B(EXT4_SB(inode->i_sb),
f78ee70d 1741 ext4_count_free_clusters(sb)));
92b97816
TT
1742 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1743 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
f78ee70d 1744 (long long) EXT4_C2B(EXT4_SB(sb),
57042651 1745 percpu_counter_sum(&sbi->s_freeclusters_counter)));
92b97816 1746 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
f78ee70d 1747 (long long) EXT4_C2B(EXT4_SB(sb),
7b415bf6 1748 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
92b97816
TT
1749 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1750 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
f78ee70d 1751 ei->i_reserved_data_blocks);
df22291f
AK
1752 return;
1753}
1754
c364b22c 1755static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
29fa89d0 1756{
c364b22c 1757 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
29fa89d0
AK
1758}
1759
0b02f4c0
EW
1760/*
1761 * ext4_insert_delayed_block - adds a delayed block to the extents status
1762 * tree, incrementing the reserved cluster/block
1763 * count or making a pending reservation
1764 * where needed
1765 *
1766 * @inode - file containing the newly added block
1767 * @lblk - logical block to be added
1768 *
1769 * Returns 0 on success, negative error code on failure.
1770 */
1771static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1772{
1773 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1774 int ret;
1775 bool allocated = false;
1776
1777 /*
1778 * If the cluster containing lblk is shared with a delayed,
1779 * written, or unwritten extent in a bigalloc file system, it's
1780 * already been accounted for and does not need to be reserved.
1781 * A pending reservation must be made for the cluster if it's
1782 * shared with a written or unwritten extent and doesn't already
1783 * have one. Written and unwritten extents can be purged from the
1784 * extents status tree if the system is under memory pressure, so
1785 * it's necessary to examine the extent tree if a search of the
1786 * extents status tree doesn't get a match.
1787 */
1788 if (sbi->s_cluster_ratio == 1) {
1789 ret = ext4_da_reserve_space(inode);
1790 if (ret != 0) /* ENOSPC */
1791 goto errout;
1792 } else { /* bigalloc */
1793 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1794 if (!ext4_es_scan_clu(inode,
1795 &ext4_es_is_mapped, lblk)) {
1796 ret = ext4_clu_mapped(inode,
1797 EXT4_B2C(sbi, lblk));
1798 if (ret < 0)
1799 goto errout;
1800 if (ret == 0) {
1801 ret = ext4_da_reserve_space(inode);
1802 if (ret != 0) /* ENOSPC */
1803 goto errout;
1804 } else {
1805 allocated = true;
1806 }
1807 } else {
1808 allocated = true;
1809 }
1810 }
1811 }
1812
1813 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1814
1815errout:
1816 return ret;
1817}
1818
5356f261
AK
1819/*
1820 * This function is grabs code from the very beginning of
1821 * ext4_map_blocks, but assumes that the caller is from delayed write
1822 * time. This function looks up the requested blocks and sets the
1823 * buffer delay bit under the protection of i_data_sem.
1824 */
1825static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1826 struct ext4_map_blocks *map,
1827 struct buffer_head *bh)
1828{
d100eef2 1829 struct extent_status es;
5356f261
AK
1830 int retval;
1831 sector_t invalid_block = ~((sector_t) 0xffff);
921f266b
DM
1832#ifdef ES_AGGRESSIVE_TEST
1833 struct ext4_map_blocks orig_map;
1834
1835 memcpy(&orig_map, map, sizeof(*map));
1836#endif
5356f261
AK
1837
1838 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1839 invalid_block = ~0;
1840
1841 map->m_flags = 0;
1842 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1843 "logical block %lu\n", inode->i_ino, map->m_len,
1844 (unsigned long) map->m_lblk);
d100eef2
ZL
1845
1846 /* Lookup extent status tree firstly */
bb5835ed 1847 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
d100eef2
ZL
1848 if (ext4_es_is_hole(&es)) {
1849 retval = 0;
c8b459f4 1850 down_read(&EXT4_I(inode)->i_data_sem);
d100eef2
ZL
1851 goto add_delayed;
1852 }
1853
1854 /*
1855 * Delayed extent could be allocated by fallocate.
1856 * So we need to check it.
1857 */
1858 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1859 map_bh(bh, inode->i_sb, invalid_block);
1860 set_buffer_new(bh);
1861 set_buffer_delay(bh);
1862 return 0;
1863 }
1864
1865 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1866 retval = es.es_len - (iblock - es.es_lblk);
1867 if (retval > map->m_len)
1868 retval = map->m_len;
1869 map->m_len = retval;
1870 if (ext4_es_is_written(&es))
1871 map->m_flags |= EXT4_MAP_MAPPED;
1872 else if (ext4_es_is_unwritten(&es))
1873 map->m_flags |= EXT4_MAP_UNWRITTEN;
1874 else
1e83bc81 1875 BUG();
d100eef2 1876
921f266b
DM
1877#ifdef ES_AGGRESSIVE_TEST
1878 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1879#endif
d100eef2
ZL
1880 return retval;
1881 }
1882
5356f261
AK
1883 /*
1884 * Try to see if we can get the block without requesting a new
1885 * file system block.
1886 */
c8b459f4 1887 down_read(&EXT4_I(inode)->i_data_sem);
cbd7584e 1888 if (ext4_has_inline_data(inode))
9c3569b5 1889 retval = 0;
cbd7584e 1890 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
2f8e0a7c 1891 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
5356f261 1892 else
2f8e0a7c 1893 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
5356f261 1894
d100eef2 1895add_delayed:
5356f261 1896 if (retval == 0) {
f7fec032 1897 int ret;
ad431025 1898
5356f261
AK
1899 /*
1900 * XXX: __block_prepare_write() unmaps passed block,
1901 * is it OK?
1902 */
5356f261 1903
0b02f4c0
EW
1904 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1905 if (ret != 0) {
f7fec032 1906 retval = ret;
51865fda 1907 goto out_unlock;
f7fec032 1908 }
51865fda 1909
5356f261
AK
1910 map_bh(bh, inode->i_sb, invalid_block);
1911 set_buffer_new(bh);
1912 set_buffer_delay(bh);
f7fec032
ZL
1913 } else if (retval > 0) {
1914 int ret;
3be78c73 1915 unsigned int status;
f7fec032 1916
44fb851d
ZL
1917 if (unlikely(retval != map->m_len)) {
1918 ext4_warning(inode->i_sb,
1919 "ES len assertion failed for inode "
1920 "%lu: retval %d != map->m_len %d",
1921 inode->i_ino, retval, map->m_len);
1922 WARN_ON(1);
921f266b 1923 }
921f266b 1924
f7fec032
ZL
1925 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1926 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1927 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1928 map->m_pblk, status);
1929 if (ret != 0)
1930 retval = ret;
5356f261
AK
1931 }
1932
1933out_unlock:
1934 up_read((&EXT4_I(inode)->i_data_sem));
1935
1936 return retval;
1937}
1938
64769240 1939/*
d91bd2c1 1940 * This is a special get_block_t callback which is used by
b920c755
TT
1941 * ext4_da_write_begin(). It will either return mapped block or
1942 * reserve space for a single block.
29fa89d0
AK
1943 *
1944 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1945 * We also have b_blocknr = -1 and b_bdev initialized properly
1946 *
1947 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1948 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1949 * initialized properly.
64769240 1950 */
9c3569b5
TM
1951int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1952 struct buffer_head *bh, int create)
64769240 1953{
2ed88685 1954 struct ext4_map_blocks map;
64769240
AT
1955 int ret = 0;
1956
1957 BUG_ON(create == 0);
2ed88685
TT
1958 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1959
1960 map.m_lblk = iblock;
1961 map.m_len = 1;
64769240
AT
1962
1963 /*
1964 * first, we need to know whether the block is allocated already
1965 * preallocated blocks are unmapped but should treated
1966 * the same as allocated blocks.
1967 */
5356f261
AK
1968 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1969 if (ret <= 0)
2ed88685 1970 return ret;
64769240 1971
2ed88685 1972 map_bh(bh, inode->i_sb, map.m_pblk);
ed8ad838 1973 ext4_update_bh_state(bh, map.m_flags);
2ed88685
TT
1974
1975 if (buffer_unwritten(bh)) {
1976 /* A delayed write to unwritten bh should be marked
1977 * new and mapped. Mapped ensures that we don't do
1978 * get_block multiple times when we write to the same
1979 * offset and new ensures that we do proper zero out
1980 * for partial write.
1981 */
1982 set_buffer_new(bh);
c8205636 1983 set_buffer_mapped(bh);
2ed88685
TT
1984 }
1985 return 0;
64769240 1986}
61628a3f 1987
62e086be
AK
1988static int bget_one(handle_t *handle, struct buffer_head *bh)
1989{
1990 get_bh(bh);
1991 return 0;
1992}
1993
1994static int bput_one(handle_t *handle, struct buffer_head *bh)
1995{
1996 put_bh(bh);
1997 return 0;
1998}
1999
2000static int __ext4_journalled_writepage(struct page *page,
62e086be
AK
2001 unsigned int len)
2002{
2003 struct address_space *mapping = page->mapping;
2004 struct inode *inode = mapping->host;
3fdcfb66 2005 struct buffer_head *page_bufs = NULL;
62e086be 2006 handle_t *handle = NULL;
3fdcfb66
TM
2007 int ret = 0, err = 0;
2008 int inline_data = ext4_has_inline_data(inode);
2009 struct buffer_head *inode_bh = NULL;
62e086be 2010
cb20d518 2011 ClearPageChecked(page);
3fdcfb66
TM
2012
2013 if (inline_data) {
2014 BUG_ON(page->index != 0);
2015 BUG_ON(len > ext4_get_max_inline_size(inode));
2016 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
2017 if (inode_bh == NULL)
2018 goto out;
2019 } else {
2020 page_bufs = page_buffers(page);
2021 if (!page_bufs) {
2022 BUG();
2023 goto out;
2024 }
2025 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2026 NULL, bget_one);
2027 }
bdf96838
TT
2028 /*
2029 * We need to release the page lock before we start the
2030 * journal, so grab a reference so the page won't disappear
2031 * out from under us.
2032 */
2033 get_page(page);
62e086be
AK
2034 unlock_page(page);
2035
9924a92a
TT
2036 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2037 ext4_writepage_trans_blocks(inode));
62e086be
AK
2038 if (IS_ERR(handle)) {
2039 ret = PTR_ERR(handle);
bdf96838
TT
2040 put_page(page);
2041 goto out_no_pagelock;
62e086be 2042 }
441c8508
CW
2043 BUG_ON(!ext4_handle_valid(handle));
2044
bdf96838
TT
2045 lock_page(page);
2046 put_page(page);
2047 if (page->mapping != mapping) {
2048 /* The page got truncated from under us */
2049 ext4_journal_stop(handle);
2050 ret = 0;
2051 goto out;
2052 }
2053
3fdcfb66 2054 if (inline_data) {
362eca70 2055 ret = ext4_mark_inode_dirty(handle, inode);
3fdcfb66
TM
2056 } else {
2057 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2058 do_journal_get_write_access);
2059
2060 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2061 write_end_fn);
2062 }
62e086be
AK
2063 if (ret == 0)
2064 ret = err;
2d859db3 2065 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
62e086be
AK
2066 err = ext4_journal_stop(handle);
2067 if (!ret)
2068 ret = err;
2069
3fdcfb66 2070 if (!ext4_has_inline_data(inode))
8c9367fd 2071 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
3fdcfb66 2072 NULL, bput_one);
19f5fb7a 2073 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
62e086be 2074out:
bdf96838
TT
2075 unlock_page(page);
2076out_no_pagelock:
3fdcfb66 2077 brelse(inode_bh);
62e086be
AK
2078 return ret;
2079}
2080
61628a3f 2081/*
43ce1d23
AK
2082 * Note that we don't need to start a transaction unless we're journaling data
2083 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2084 * need to file the inode to the transaction's list in ordered mode because if
2085 * we are writing back data added by write(), the inode is already there and if
25985edc 2086 * we are writing back data modified via mmap(), no one guarantees in which
43ce1d23
AK
2087 * transaction the data will hit the disk. In case we are journaling data, we
2088 * cannot start transaction directly because transaction start ranks above page
2089 * lock so we have to do some magic.
2090 *
b920c755 2091 * This function can get called via...
20970ba6 2092 * - ext4_writepages after taking page lock (have journal handle)
b920c755 2093 * - journal_submit_inode_data_buffers (no journal handle)
f6463b0d 2094 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
b920c755 2095 * - grab_page_cache when doing write_begin (have journal handle)
43ce1d23
AK
2096 *
2097 * We don't do any block allocation in this function. If we have page with
2098 * multiple blocks we need to write those buffer_heads that are mapped. This
2099 * is important for mmaped based write. So if we do with blocksize 1K
2100 * truncate(f, 1024);
2101 * a = mmap(f, 0, 4096);
2102 * a[0] = 'a';
2103 * truncate(f, 4096);
2104 * we have in the page first buffer_head mapped via page_mkwrite call back
90802ed9 2105 * but other buffer_heads would be unmapped but dirty (dirty done via the
43ce1d23
AK
2106 * do_wp_page). So writepage should write the first block. If we modify
2107 * the mmap area beyond 1024 we will again get a page_fault and the
2108 * page_mkwrite callback will do the block allocation and mark the
2109 * buffer_heads mapped.
2110 *
2111 * We redirty the page if we have any buffer_heads that is either delay or
2112 * unwritten in the page.
2113 *
2114 * We can get recursively called as show below.
2115 *
2116 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2117 * ext4_writepage()
2118 *
2119 * But since we don't do any block allocation we should not deadlock.
2120 * Page also have the dirty flag cleared so we don't get recurive page_lock.
61628a3f 2121 */
43ce1d23 2122static int ext4_writepage(struct page *page,
62e086be 2123 struct writeback_control *wbc)
64769240 2124{
f8bec370 2125 int ret = 0;
61628a3f 2126 loff_t size;
498e5f24 2127 unsigned int len;
744692dc 2128 struct buffer_head *page_bufs = NULL;
61628a3f 2129 struct inode *inode = page->mapping->host;
36ade451 2130 struct ext4_io_submit io_submit;
1c8349a1 2131 bool keep_towrite = false;
61628a3f 2132
0db1ff22
TT
2133 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2134 ext4_invalidatepage(page, 0, PAGE_SIZE);
2135 unlock_page(page);
2136 return -EIO;
2137 }
2138
a9c667f8 2139 trace_ext4_writepage(page);
f0e6c985 2140 size = i_size_read(inode);
c93d8f88
EB
2141 if (page->index == size >> PAGE_SHIFT &&
2142 !ext4_verity_in_progress(inode))
09cbfeaf 2143 len = size & ~PAGE_MASK;
f0e6c985 2144 else
09cbfeaf 2145 len = PAGE_SIZE;
64769240 2146
a42afc5f 2147 page_bufs = page_buffers(page);
a42afc5f 2148 /*
fe386132
JK
2149 * We cannot do block allocation or other extent handling in this
2150 * function. If there are buffers needing that, we have to redirty
2151 * the page. But we may reach here when we do a journal commit via
2152 * journal_submit_inode_data_buffers() and in that case we must write
2153 * allocated buffers to achieve data=ordered mode guarantees.
cccd147a
TT
2154 *
2155 * Also, if there is only one buffer per page (the fs block
2156 * size == the page size), if one buffer needs block
2157 * allocation or needs to modify the extent tree to clear the
2158 * unwritten flag, we know that the page can't be written at
2159 * all, so we might as well refuse the write immediately.
2160 * Unfortunately if the block size != page size, we can't as
2161 * easily detect this case using ext4_walk_page_buffers(), but
2162 * for the extremely common case, this is an optimization that
2163 * skips a useless round trip through ext4_bio_write_page().
a42afc5f 2164 */
f19d5870
TM
2165 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2166 ext4_bh_delay_or_unwritten)) {
f8bec370 2167 redirty_page_for_writepage(wbc, page);
cccd147a 2168 if ((current->flags & PF_MEMALLOC) ||
09cbfeaf 2169 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
fe386132
JK
2170 /*
2171 * For memory cleaning there's no point in writing only
2172 * some buffers. So just bail out. Warn if we came here
2173 * from direct reclaim.
2174 */
2175 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2176 == PF_MEMALLOC);
f0e6c985
AK
2177 unlock_page(page);
2178 return 0;
2179 }
1c8349a1 2180 keep_towrite = true;
a42afc5f 2181 }
64769240 2182
cb20d518 2183 if (PageChecked(page) && ext4_should_journal_data(inode))
43ce1d23
AK
2184 /*
2185 * It's mmapped pagecache. Add buffers and journal it. There
2186 * doesn't seem much point in redirtying the page here.
2187 */
3f0ca309 2188 return __ext4_journalled_writepage(page, len);
43ce1d23 2189
97a851ed
JK
2190 ext4_io_submit_init(&io_submit, wbc);
2191 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2192 if (!io_submit.io_end) {
2193 redirty_page_for_writepage(wbc, page);
2194 unlock_page(page);
2195 return -ENOMEM;
2196 }
1c8349a1 2197 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
36ade451 2198 ext4_io_submit(&io_submit);
97a851ed
JK
2199 /* Drop io_end reference we got from init */
2200 ext4_put_io_end_defer(io_submit.io_end);
64769240
AT
2201 return ret;
2202}
2203
5f1132b2
JK
2204static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2205{
2206 int len;
a056bdaa 2207 loff_t size;
5f1132b2
JK
2208 int err;
2209
2210 BUG_ON(page->index != mpd->first_page);
a056bdaa
JK
2211 clear_page_dirty_for_io(page);
2212 /*
2213 * We have to be very careful here! Nothing protects writeback path
2214 * against i_size changes and the page can be writeably mapped into
2215 * page tables. So an application can be growing i_size and writing
2216 * data through mmap while writeback runs. clear_page_dirty_for_io()
2217 * write-protects our page in page tables and the page cannot get
2218 * written to again until we release page lock. So only after
2219 * clear_page_dirty_for_io() we are safe to sample i_size for
2220 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2221 * on the barrier provided by TestClearPageDirty in
2222 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2223 * after page tables are updated.
2224 */
2225 size = i_size_read(mpd->inode);
c93d8f88
EB
2226 if (page->index == size >> PAGE_SHIFT &&
2227 !ext4_verity_in_progress(mpd->inode))
09cbfeaf 2228 len = size & ~PAGE_MASK;
5f1132b2 2229 else
09cbfeaf 2230 len = PAGE_SIZE;
1c8349a1 2231 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
5f1132b2
JK
2232 if (!err)
2233 mpd->wbc->nr_to_write--;
2234 mpd->first_page++;
2235
2236 return err;
2237}
2238
4e7ea81d
JK
2239#define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2240
61628a3f 2241/*
fffb2739
JK
2242 * mballoc gives us at most this number of blocks...
2243 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
70261f56 2244 * The rest of mballoc seems to handle chunks up to full group size.
61628a3f 2245 */
fffb2739 2246#define MAX_WRITEPAGES_EXTENT_LEN 2048
525f4ed8 2247
4e7ea81d
JK
2248/*
2249 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2250 *
2251 * @mpd - extent of blocks
2252 * @lblk - logical number of the block in the file
09930042 2253 * @bh - buffer head we want to add to the extent
4e7ea81d 2254 *
09930042
JK
2255 * The function is used to collect contig. blocks in the same state. If the
2256 * buffer doesn't require mapping for writeback and we haven't started the
2257 * extent of buffers to map yet, the function returns 'true' immediately - the
2258 * caller can write the buffer right away. Otherwise the function returns true
2259 * if the block has been added to the extent, false if the block couldn't be
2260 * added.
4e7ea81d 2261 */
09930042
JK
2262static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2263 struct buffer_head *bh)
4e7ea81d
JK
2264{
2265 struct ext4_map_blocks *map = &mpd->map;
2266
09930042
JK
2267 /* Buffer that doesn't need mapping for writeback? */
2268 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2269 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2270 /* So far no extent to map => we write the buffer right away */
2271 if (map->m_len == 0)
2272 return true;
2273 return false;
2274 }
4e7ea81d
JK
2275
2276 /* First block in the extent? */
2277 if (map->m_len == 0) {
dddbd6ac
JK
2278 /* We cannot map unless handle is started... */
2279 if (!mpd->do_map)
2280 return false;
4e7ea81d
JK
2281 map->m_lblk = lblk;
2282 map->m_len = 1;
09930042
JK
2283 map->m_flags = bh->b_state & BH_FLAGS;
2284 return true;
4e7ea81d
JK
2285 }
2286
09930042
JK
2287 /* Don't go larger than mballoc is willing to allocate */
2288 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2289 return false;
2290
4e7ea81d
JK
2291 /* Can we merge the block to our big extent? */
2292 if (lblk == map->m_lblk + map->m_len &&
09930042 2293 (bh->b_state & BH_FLAGS) == map->m_flags) {
4e7ea81d 2294 map->m_len++;
09930042 2295 return true;
4e7ea81d 2296 }
09930042 2297 return false;
4e7ea81d
JK
2298}
2299
5f1132b2
JK
2300/*
2301 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2302 *
2303 * @mpd - extent of blocks for mapping
2304 * @head - the first buffer in the page
2305 * @bh - buffer we should start processing from
2306 * @lblk - logical number of the block in the file corresponding to @bh
2307 *
2308 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2309 * the page for IO if all buffers in this page were mapped and there's no
2310 * accumulated extent of buffers to map or add buffers in the page to the
2311 * extent of buffers to map. The function returns 1 if the caller can continue
2312 * by processing the next page, 0 if it should stop adding buffers to the
2313 * extent to map because we cannot extend it anymore. It can also return value
2314 * < 0 in case of error during IO submission.
2315 */
2316static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2317 struct buffer_head *head,
2318 struct buffer_head *bh,
2319 ext4_lblk_t lblk)
4e7ea81d
JK
2320{
2321 struct inode *inode = mpd->inode;
5f1132b2 2322 int err;
93407472 2323 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
4e7ea81d
JK
2324 >> inode->i_blkbits;
2325
c93d8f88
EB
2326 if (ext4_verity_in_progress(inode))
2327 blocks = EXT_MAX_BLOCKS;
2328
4e7ea81d
JK
2329 do {
2330 BUG_ON(buffer_locked(bh));
2331
09930042 2332 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
4e7ea81d
JK
2333 /* Found extent to map? */
2334 if (mpd->map.m_len)
5f1132b2 2335 return 0;
dddbd6ac
JK
2336 /* Buffer needs mapping and handle is not started? */
2337 if (!mpd->do_map)
2338 return 0;
09930042 2339 /* Everything mapped so far and we hit EOF */
5f1132b2 2340 break;
4e7ea81d 2341 }
4e7ea81d 2342 } while (lblk++, (bh = bh->b_this_page) != head);
5f1132b2
JK
2343 /* So far everything mapped? Submit the page for IO. */
2344 if (mpd->map.m_len == 0) {
2345 err = mpage_submit_page(mpd, head->b_page);
2346 if (err < 0)
2347 return err;
2348 }
2349 return lblk < blocks;
4e7ea81d
JK
2350}
2351
2352/*
2353 * mpage_map_buffers - update buffers corresponding to changed extent and
2354 * submit fully mapped pages for IO
2355 *
2356 * @mpd - description of extent to map, on return next extent to map
2357 *
2358 * Scan buffers corresponding to changed extent (we expect corresponding pages
2359 * to be already locked) and update buffer state according to new extent state.
2360 * We map delalloc buffers to their physical location, clear unwritten bits,
556615dc 2361 * and mark buffers as uninit when we perform writes to unwritten extents
4e7ea81d
JK
2362 * and do extent conversion after IO is finished. If the last page is not fully
2363 * mapped, we update @map to the next extent in the last page that needs
2364 * mapping. Otherwise we submit the page for IO.
2365 */
2366static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2367{
2368 struct pagevec pvec;
2369 int nr_pages, i;
2370 struct inode *inode = mpd->inode;
2371 struct buffer_head *head, *bh;
09cbfeaf 2372 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
4e7ea81d
JK
2373 pgoff_t start, end;
2374 ext4_lblk_t lblk;
2375 sector_t pblock;
2376 int err;
2377
2378 start = mpd->map.m_lblk >> bpp_bits;
2379 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2380 lblk = start << bpp_bits;
2381 pblock = mpd->map.m_pblk;
2382
86679820 2383 pagevec_init(&pvec);
4e7ea81d 2384 while (start <= end) {
2b85a617 2385 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
397162ff 2386 &start, end);
4e7ea81d
JK
2387 if (nr_pages == 0)
2388 break;
2389 for (i = 0; i < nr_pages; i++) {
2390 struct page *page = pvec.pages[i];
2391
4e7ea81d
JK
2392 bh = head = page_buffers(page);
2393 do {
2394 if (lblk < mpd->map.m_lblk)
2395 continue;
2396 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2397 /*
2398 * Buffer after end of mapped extent.
2399 * Find next buffer in the page to map.
2400 */
2401 mpd->map.m_len = 0;
2402 mpd->map.m_flags = 0;
5f1132b2
JK
2403 /*
2404 * FIXME: If dioread_nolock supports
2405 * blocksize < pagesize, we need to make
2406 * sure we add size mapped so far to
2407 * io_end->size as the following call
2408 * can submit the page for IO.
2409 */
2410 err = mpage_process_page_bufs(mpd, head,
2411 bh, lblk);
4e7ea81d 2412 pagevec_release(&pvec);
5f1132b2
JK
2413 if (err > 0)
2414 err = 0;
2415 return err;
4e7ea81d
JK
2416 }
2417 if (buffer_delay(bh)) {
2418 clear_buffer_delay(bh);
2419 bh->b_blocknr = pblock++;
2420 }
4e7ea81d 2421 clear_buffer_unwritten(bh);
5f1132b2 2422 } while (lblk++, (bh = bh->b_this_page) != head);
4e7ea81d
JK
2423
2424 /*
2425 * FIXME: This is going to break if dioread_nolock
2426 * supports blocksize < pagesize as we will try to
2427 * convert potentially unmapped parts of inode.
2428 */
09cbfeaf 2429 mpd->io_submit.io_end->size += PAGE_SIZE;
4e7ea81d
JK
2430 /* Page fully mapped - let IO run! */
2431 err = mpage_submit_page(mpd, page);
2432 if (err < 0) {
2433 pagevec_release(&pvec);
2434 return err;
2435 }
4e7ea81d
JK
2436 }
2437 pagevec_release(&pvec);
2438 }
2439 /* Extent fully mapped and matches with page boundary. We are done. */
2440 mpd->map.m_len = 0;
2441 mpd->map.m_flags = 0;
2442 return 0;
2443}
2444
2445static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2446{
2447 struct inode *inode = mpd->inode;
2448 struct ext4_map_blocks *map = &mpd->map;
2449 int get_blocks_flags;
090f32ee 2450 int err, dioread_nolock;
4e7ea81d
JK
2451
2452 trace_ext4_da_write_pages_extent(inode, map);
2453 /*
2454 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
556615dc 2455 * to convert an unwritten extent to be initialized (in the case
4e7ea81d
JK
2456 * where we have written into one or more preallocated blocks). It is
2457 * possible that we're going to need more metadata blocks than
2458 * previously reserved. However we must not fail because we're in
2459 * writeback and there is nothing we can do about it so it might result
2460 * in data loss. So use reserved blocks to allocate metadata if
2461 * possible.
2462 *
754cfed6
TT
2463 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2464 * the blocks in question are delalloc blocks. This indicates
2465 * that the blocks and quotas has already been checked when
2466 * the data was copied into the page cache.
4e7ea81d
JK
2467 */
2468 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
ee0876bc
JK
2469 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2470 EXT4_GET_BLOCKS_IO_SUBMIT;
090f32ee
LC
2471 dioread_nolock = ext4_should_dioread_nolock(inode);
2472 if (dioread_nolock)
4e7ea81d
JK
2473 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2474 if (map->m_flags & (1 << BH_Delay))
2475 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2476
2477 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2478 if (err < 0)
2479 return err;
090f32ee 2480 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
6b523df4
JK
2481 if (!mpd->io_submit.io_end->handle &&
2482 ext4_handle_valid(handle)) {
2483 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2484 handle->h_rsv_handle = NULL;
2485 }
3613d228 2486 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
6b523df4 2487 }
4e7ea81d
JK
2488
2489 BUG_ON(map->m_len == 0);
4e7ea81d
JK
2490 return 0;
2491}
2492
2493/*
2494 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2495 * mpd->len and submit pages underlying it for IO
2496 *
2497 * @handle - handle for journal operations
2498 * @mpd - extent to map
7534e854
JK
2499 * @give_up_on_write - we set this to true iff there is a fatal error and there
2500 * is no hope of writing the data. The caller should discard
2501 * dirty pages to avoid infinite loops.
4e7ea81d
JK
2502 *
2503 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2504 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2505 * them to initialized or split the described range from larger unwritten
2506 * extent. Note that we need not map all the described range since allocation
2507 * can return less blocks or the range is covered by more unwritten extents. We
2508 * cannot map more because we are limited by reserved transaction credits. On
2509 * the other hand we always make sure that the last touched page is fully
2510 * mapped so that it can be written out (and thus forward progress is
2511 * guaranteed). After mapping we submit all mapped pages for IO.
2512 */
2513static int mpage_map_and_submit_extent(handle_t *handle,
cb530541
TT
2514 struct mpage_da_data *mpd,
2515 bool *give_up_on_write)
4e7ea81d
JK
2516{
2517 struct inode *inode = mpd->inode;
2518 struct ext4_map_blocks *map = &mpd->map;
2519 int err;
2520 loff_t disksize;
6603120e 2521 int progress = 0;
4e7ea81d
JK
2522
2523 mpd->io_submit.io_end->offset =
2524 ((loff_t)map->m_lblk) << inode->i_blkbits;
27d7c4ed 2525 do {
4e7ea81d
JK
2526 err = mpage_map_one_extent(handle, mpd);
2527 if (err < 0) {
2528 struct super_block *sb = inode->i_sb;
2529
0db1ff22
TT
2530 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2531 EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
cb530541 2532 goto invalidate_dirty_pages;
4e7ea81d 2533 /*
cb530541
TT
2534 * Let the uper layers retry transient errors.
2535 * In the case of ENOSPC, if ext4_count_free_blocks()
2536 * is non-zero, a commit should free up blocks.
4e7ea81d 2537 */
cb530541 2538 if ((err == -ENOMEM) ||
6603120e
DM
2539 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2540 if (progress)
2541 goto update_disksize;
cb530541 2542 return err;
6603120e 2543 }
cb530541
TT
2544 ext4_msg(sb, KERN_CRIT,
2545 "Delayed block allocation failed for "
2546 "inode %lu at logical offset %llu with"
2547 " max blocks %u with error %d",
2548 inode->i_ino,
2549 (unsigned long long)map->m_lblk,
2550 (unsigned)map->m_len, -err);
2551 ext4_msg(sb, KERN_CRIT,
2552 "This should not happen!! Data will "
2553 "be lost\n");
2554 if (err == -ENOSPC)
2555 ext4_print_free_blocks(inode);
2556 invalidate_dirty_pages:
2557 *give_up_on_write = true;
4e7ea81d
JK
2558 return err;
2559 }
6603120e 2560 progress = 1;
4e7ea81d
JK
2561 /*
2562 * Update buffer state, submit mapped pages, and get us new
2563 * extent to map
2564 */
2565 err = mpage_map_and_submit_buffers(mpd);
2566 if (err < 0)
6603120e 2567 goto update_disksize;
27d7c4ed 2568 } while (map->m_len);
4e7ea81d 2569
6603120e 2570update_disksize:
622cad13
TT
2571 /*
2572 * Update on-disk size after IO is submitted. Races with
2573 * truncate are avoided by checking i_size under i_data_sem.
2574 */
09cbfeaf 2575 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
4e7ea81d
JK
2576 if (disksize > EXT4_I(inode)->i_disksize) {
2577 int err2;
622cad13
TT
2578 loff_t i_size;
2579
2580 down_write(&EXT4_I(inode)->i_data_sem);
2581 i_size = i_size_read(inode);
2582 if (disksize > i_size)
2583 disksize = i_size;
2584 if (disksize > EXT4_I(inode)->i_disksize)
2585 EXT4_I(inode)->i_disksize = disksize;
622cad13 2586 up_write(&EXT4_I(inode)->i_data_sem);
b907f2d5 2587 err2 = ext4_mark_inode_dirty(handle, inode);
4e7ea81d
JK
2588 if (err2)
2589 ext4_error(inode->i_sb,
2590 "Failed to mark inode %lu dirty",
2591 inode->i_ino);
2592 if (!err)
2593 err = err2;
2594 }
2595 return err;
2596}
2597
fffb2739
JK
2598/*
2599 * Calculate the total number of credits to reserve for one writepages
20970ba6 2600 * iteration. This is called from ext4_writepages(). We map an extent of
70261f56 2601 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
fffb2739
JK
2602 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2603 * bpp - 1 blocks in bpp different extents.
2604 */
525f4ed8
MC
2605static int ext4_da_writepages_trans_blocks(struct inode *inode)
2606{
fffb2739 2607 int bpp = ext4_journal_blocks_per_page(inode);
525f4ed8 2608
fffb2739
JK
2609 return ext4_meta_trans_blocks(inode,
2610 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
525f4ed8 2611}
61628a3f 2612
8e48dcfb 2613/*
4e7ea81d
JK
2614 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2615 * and underlying extent to map
2616 *
2617 * @mpd - where to look for pages
2618 *
2619 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2620 * IO immediately. When we find a page which isn't mapped we start accumulating
2621 * extent of buffers underlying these pages that needs mapping (formed by
2622 * either delayed or unwritten buffers). We also lock the pages containing
2623 * these buffers. The extent found is returned in @mpd structure (starting at
2624 * mpd->lblk with length mpd->len blocks).
2625 *
2626 * Note that this function can attach bios to one io_end structure which are
2627 * neither logically nor physically contiguous. Although it may seem as an
2628 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2629 * case as we need to track IO to all buffers underlying a page in one io_end.
8e48dcfb 2630 */
4e7ea81d 2631static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
8e48dcfb 2632{
4e7ea81d
JK
2633 struct address_space *mapping = mpd->inode->i_mapping;
2634 struct pagevec pvec;
2635 unsigned int nr_pages;
aeac589a 2636 long left = mpd->wbc->nr_to_write;
4e7ea81d
JK
2637 pgoff_t index = mpd->first_page;
2638 pgoff_t end = mpd->last_page;
10bbd235 2639 xa_mark_t tag;
4e7ea81d
JK
2640 int i, err = 0;
2641 int blkbits = mpd->inode->i_blkbits;
2642 ext4_lblk_t lblk;
2643 struct buffer_head *head;
8e48dcfb 2644
4e7ea81d 2645 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
5b41d924
ES
2646 tag = PAGECACHE_TAG_TOWRITE;
2647 else
2648 tag = PAGECACHE_TAG_DIRTY;
2649
86679820 2650 pagevec_init(&pvec);
4e7ea81d
JK
2651 mpd->map.m_len = 0;
2652 mpd->next_page = index;
4f01b02c 2653 while (index <= end) {
dc7f3e86 2654 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
67fd707f 2655 tag);
8e48dcfb 2656 if (nr_pages == 0)
4e7ea81d 2657 goto out;
8e48dcfb
TT
2658
2659 for (i = 0; i < nr_pages; i++) {
2660 struct page *page = pvec.pages[i];
2661
aeac589a
ML
2662 /*
2663 * Accumulated enough dirty pages? This doesn't apply
2664 * to WB_SYNC_ALL mode. For integrity sync we have to
2665 * keep going because someone may be concurrently
2666 * dirtying pages, and we might have synced a lot of
2667 * newly appeared dirty pages, but have not synced all
2668 * of the old dirty pages.
2669 */
2670 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2671 goto out;
2672
4e7ea81d
JK
2673 /* If we can't merge this page, we are done. */
2674 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2675 goto out;
78aaced3 2676
8e48dcfb 2677 lock_page(page);
8e48dcfb 2678 /*
4e7ea81d
JK
2679 * If the page is no longer dirty, or its mapping no
2680 * longer corresponds to inode we are writing (which
2681 * means it has been truncated or invalidated), or the
2682 * page is already under writeback and we are not doing
2683 * a data integrity writeback, skip the page
8e48dcfb 2684 */
4f01b02c
TT
2685 if (!PageDirty(page) ||
2686 (PageWriteback(page) &&
4e7ea81d 2687 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
4f01b02c 2688 unlikely(page->mapping != mapping)) {
8e48dcfb
TT
2689 unlock_page(page);
2690 continue;
2691 }
2692
7cb1a535 2693 wait_on_page_writeback(page);
8e48dcfb 2694 BUG_ON(PageWriteback(page));
8e48dcfb 2695
4e7ea81d 2696 if (mpd->map.m_len == 0)
8eb9e5ce 2697 mpd->first_page = page->index;
8eb9e5ce 2698 mpd->next_page = page->index + 1;
f8bec370 2699 /* Add all dirty buffers to mpd */
4e7ea81d 2700 lblk = ((ext4_lblk_t)page->index) <<
09cbfeaf 2701 (PAGE_SHIFT - blkbits);
f8bec370 2702 head = page_buffers(page);
5f1132b2
JK
2703 err = mpage_process_page_bufs(mpd, head, head, lblk);
2704 if (err <= 0)
4e7ea81d 2705 goto out;
5f1132b2 2706 err = 0;
aeac589a 2707 left--;
8e48dcfb
TT
2708 }
2709 pagevec_release(&pvec);
2710 cond_resched();
2711 }
4f01b02c 2712 return 0;
8eb9e5ce
TT
2713out:
2714 pagevec_release(&pvec);
4e7ea81d 2715 return err;
8e48dcfb
TT
2716}
2717
20970ba6
TT
2718static int ext4_writepages(struct address_space *mapping,
2719 struct writeback_control *wbc)
64769240 2720{
4e7ea81d
JK
2721 pgoff_t writeback_index = 0;
2722 long nr_to_write = wbc->nr_to_write;
22208ded 2723 int range_whole = 0;
4e7ea81d 2724 int cycled = 1;
61628a3f 2725 handle_t *handle = NULL;
df22291f 2726 struct mpage_da_data mpd;
5e745b04 2727 struct inode *inode = mapping->host;
6b523df4 2728 int needed_blocks, rsv_blocks = 0, ret = 0;
5e745b04 2729 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
4e7ea81d 2730 bool done;
1bce63d1 2731 struct blk_plug plug;
cb530541 2732 bool give_up_on_write = false;
61628a3f 2733
0db1ff22
TT
2734 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2735 return -EIO;
2736
c8585c6f 2737 percpu_down_read(&sbi->s_journal_flag_rwsem);
20970ba6 2738 trace_ext4_writepages(inode, wbc);
ba80b101 2739
61628a3f
MC
2740 /*
2741 * No pages to write? This is mainly a kludge to avoid starting
2742 * a transaction for special inodes like journal inode on last iput()
2743 * because that could violate lock ordering on umount
2744 */
a1d6cc56 2745 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
bbf023c7 2746 goto out_writepages;
2a21e37e 2747
20970ba6 2748 if (ext4_should_journal_data(inode)) {
043d20d1 2749 ret = generic_writepages(mapping, wbc);
bbf023c7 2750 goto out_writepages;
20970ba6
TT
2751 }
2752
2a21e37e
TT
2753 /*
2754 * If the filesystem has aborted, it is read-only, so return
2755 * right away instead of dumping stack traces later on that
2756 * will obscure the real source of the problem. We test
1751e8a6 2757 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2a21e37e 2758 * the latter could be true if the filesystem is mounted
20970ba6 2759 * read-only, and in that case, ext4_writepages should
2a21e37e
TT
2760 * *never* be called, so if that ever happens, we would want
2761 * the stack trace.
2762 */
0db1ff22
TT
2763 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2764 sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
bbf023c7
ML
2765 ret = -EROFS;
2766 goto out_writepages;
2767 }
2a21e37e 2768
4e7ea81d
JK
2769 /*
2770 * If we have inline data and arrive here, it means that
2771 * we will soon create the block for the 1st page, so
2772 * we'd better clear the inline data here.
2773 */
2774 if (ext4_has_inline_data(inode)) {
2775 /* Just inode will be modified... */
2776 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2777 if (IS_ERR(handle)) {
2778 ret = PTR_ERR(handle);
2779 goto out_writepages;
2780 }
2781 BUG_ON(ext4_test_inode_state(inode,
2782 EXT4_STATE_MAY_INLINE_DATA));
2783 ext4_destroy_inline_data(handle, inode);
2784 ext4_journal_stop(handle);
2785 }
2786
4e343231 2787 if (ext4_should_dioread_nolock(inode)) {
2788 /*
2789 * We may need to convert up to one extent per block in
2790 * the page and we may dirty the inode.
2791 */
2792 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2793 PAGE_SIZE >> inode->i_blkbits);
2794 }
2795
22208ded
AK
2796 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2797 range_whole = 1;
61628a3f 2798
2acf2c26 2799 if (wbc->range_cyclic) {
4e7ea81d
JK
2800 writeback_index = mapping->writeback_index;
2801 if (writeback_index)
2acf2c26 2802 cycled = 0;
4e7ea81d
JK
2803 mpd.first_page = writeback_index;
2804 mpd.last_page = -1;
5b41d924 2805 } else {
09cbfeaf
KS
2806 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2807 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
5b41d924 2808 }
a1d6cc56 2809
4e7ea81d
JK
2810 mpd.inode = inode;
2811 mpd.wbc = wbc;
2812 ext4_io_submit_init(&mpd.io_submit, wbc);
2acf2c26 2813retry:
6e6938b6 2814 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
4e7ea81d
JK
2815 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2816 done = false;
1bce63d1 2817 blk_start_plug(&plug);
dddbd6ac
JK
2818
2819 /*
2820 * First writeback pages that don't need mapping - we can avoid
2821 * starting a transaction unnecessarily and also avoid being blocked
2822 * in the block layer on device congestion while having transaction
2823 * started.
2824 */
2825 mpd.do_map = 0;
2826 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2827 if (!mpd.io_submit.io_end) {
2828 ret = -ENOMEM;
2829 goto unplug;
2830 }
2831 ret = mpage_prepare_extent_to_map(&mpd);
a297b2fc
XW
2832 /* Unlock pages we didn't use */
2833 mpage_release_unused_pages(&mpd, false);
dddbd6ac
JK
2834 /* Submit prepared bio */
2835 ext4_io_submit(&mpd.io_submit);
2836 ext4_put_io_end_defer(mpd.io_submit.io_end);
2837 mpd.io_submit.io_end = NULL;
dddbd6ac
JK
2838 if (ret < 0)
2839 goto unplug;
2840
4e7ea81d
JK
2841 while (!done && mpd.first_page <= mpd.last_page) {
2842 /* For each extent of pages we use new io_end */
2843 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2844 if (!mpd.io_submit.io_end) {
2845 ret = -ENOMEM;
2846 break;
2847 }
a1d6cc56
AK
2848
2849 /*
4e7ea81d
JK
2850 * We have two constraints: We find one extent to map and we
2851 * must always write out whole page (makes a difference when
2852 * blocksize < pagesize) so that we don't block on IO when we
2853 * try to write out the rest of the page. Journalled mode is
2854 * not supported by delalloc.
a1d6cc56
AK
2855 */
2856 BUG_ON(ext4_should_journal_data(inode));
525f4ed8 2857 needed_blocks = ext4_da_writepages_trans_blocks(inode);
a1d6cc56 2858
4e7ea81d 2859 /* start a new transaction */
6b523df4
JK
2860 handle = ext4_journal_start_with_reserve(inode,
2861 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
61628a3f
MC
2862 if (IS_ERR(handle)) {
2863 ret = PTR_ERR(handle);
1693918e 2864 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
fbe845dd 2865 "%ld pages, ino %lu; err %d", __func__,
a1d6cc56 2866 wbc->nr_to_write, inode->i_ino, ret);
4e7ea81d
JK
2867 /* Release allocated io_end */
2868 ext4_put_io_end(mpd.io_submit.io_end);
dddbd6ac 2869 mpd.io_submit.io_end = NULL;
4e7ea81d 2870 break;
61628a3f 2871 }
dddbd6ac 2872 mpd.do_map = 1;
f63e6005 2873
4e7ea81d
JK
2874 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2875 ret = mpage_prepare_extent_to_map(&mpd);
2876 if (!ret) {
2877 if (mpd.map.m_len)
cb530541
TT
2878 ret = mpage_map_and_submit_extent(handle, &mpd,
2879 &give_up_on_write);
4e7ea81d
JK
2880 else {
2881 /*
2882 * We scanned the whole range (or exhausted
2883 * nr_to_write), submitted what was mapped and
2884 * didn't find anything needing mapping. We are
2885 * done.
2886 */
2887 done = true;
2888 }
f63e6005 2889 }
646caa9c
JK
2890 /*
2891 * Caution: If the handle is synchronous,
2892 * ext4_journal_stop() can wait for transaction commit
2893 * to finish which may depend on writeback of pages to
2894 * complete or on page lock to be released. In that
2895 * case, we have to wait until after after we have
2896 * submitted all the IO, released page locks we hold,
2897 * and dropped io_end reference (for extent conversion
2898 * to be able to complete) before stopping the handle.
2899 */
2900 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2901 ext4_journal_stop(handle);
2902 handle = NULL;
dddbd6ac 2903 mpd.do_map = 0;
646caa9c 2904 }
4e7ea81d 2905 /* Unlock pages we didn't use */
cb530541 2906 mpage_release_unused_pages(&mpd, give_up_on_write);
a297b2fc
XW
2907 /* Submit prepared bio */
2908 ext4_io_submit(&mpd.io_submit);
2909
646caa9c
JK
2910 /*
2911 * Drop our io_end reference we got from init. We have
2912 * to be careful and use deferred io_end finishing if
2913 * we are still holding the transaction as we can
2914 * release the last reference to io_end which may end
2915 * up doing unwritten extent conversion.
2916 */
2917 if (handle) {
2918 ext4_put_io_end_defer(mpd.io_submit.io_end);
2919 ext4_journal_stop(handle);
2920 } else
2921 ext4_put_io_end(mpd.io_submit.io_end);
dddbd6ac 2922 mpd.io_submit.io_end = NULL;
4e7ea81d
JK
2923
2924 if (ret == -ENOSPC && sbi->s_journal) {
2925 /*
2926 * Commit the transaction which would
22208ded
AK
2927 * free blocks released in the transaction
2928 * and try again
2929 */
df22291f 2930 jbd2_journal_force_commit_nested(sbi->s_journal);
22208ded 2931 ret = 0;
4e7ea81d
JK
2932 continue;
2933 }
2934 /* Fatal error - ENOMEM, EIO... */
2935 if (ret)
61628a3f 2936 break;
a1d6cc56 2937 }
dddbd6ac 2938unplug:
1bce63d1 2939 blk_finish_plug(&plug);
9c12a831 2940 if (!ret && !cycled && wbc->nr_to_write > 0) {
2acf2c26 2941 cycled = 1;
4e7ea81d
JK
2942 mpd.last_page = writeback_index - 1;
2943 mpd.first_page = 0;
2acf2c26
AK
2944 goto retry;
2945 }
22208ded
AK
2946
2947 /* Update index */
22208ded
AK
2948 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2949 /*
4e7ea81d 2950 * Set the writeback_index so that range_cyclic
22208ded
AK
2951 * mode will write it back later
2952 */
4e7ea81d 2953 mapping->writeback_index = mpd.first_page;
a1d6cc56 2954
61628a3f 2955out_writepages:
20970ba6
TT
2956 trace_ext4_writepages_result(inode, wbc, ret,
2957 nr_to_write - wbc->nr_to_write);
c8585c6f 2958 percpu_up_read(&sbi->s_journal_flag_rwsem);
61628a3f 2959 return ret;
64769240
AT
2960}
2961
5f0663bb
DW
2962static int ext4_dax_writepages(struct address_space *mapping,
2963 struct writeback_control *wbc)
2964{
2965 int ret;
2966 long nr_to_write = wbc->nr_to_write;
2967 struct inode *inode = mapping->host;
2968 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2969
2970 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2971 return -EIO;
2972
2973 percpu_down_read(&sbi->s_journal_flag_rwsem);
2974 trace_ext4_writepages(inode, wbc);
2975
2976 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev, wbc);
2977 trace_ext4_writepages_result(inode, wbc, ret,
2978 nr_to_write - wbc->nr_to_write);
2979 percpu_up_read(&sbi->s_journal_flag_rwsem);
2980 return ret;
2981}
2982
79f0be8d
AK
2983static int ext4_nonda_switch(struct super_block *sb)
2984{
5c1ff336 2985 s64 free_clusters, dirty_clusters;
79f0be8d
AK
2986 struct ext4_sb_info *sbi = EXT4_SB(sb);
2987
2988 /*
2989 * switch to non delalloc mode if we are running low
2990 * on free block. The free block accounting via percpu
179f7ebf 2991 * counters can get slightly wrong with percpu_counter_batch getting
79f0be8d
AK
2992 * accumulated on each CPU without updating global counters
2993 * Delalloc need an accurate free block accounting. So switch
2994 * to non delalloc when we are near to error range.
2995 */
5c1ff336
EW
2996 free_clusters =
2997 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2998 dirty_clusters =
2999 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
00d4e736
TT
3000 /*
3001 * Start pushing delalloc when 1/2 of free blocks are dirty.
3002 */
5c1ff336 3003 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
10ee27a0 3004 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
00d4e736 3005
5c1ff336
EW
3006 if (2 * free_clusters < 3 * dirty_clusters ||
3007 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
79f0be8d 3008 /*
c8afb446
ES
3009 * free block count is less than 150% of dirty blocks
3010 * or free blocks is less than watermark
79f0be8d
AK
3011 */
3012 return 1;
3013 }
3014 return 0;
3015}
3016
0ff8947f
ES
3017/* We always reserve for an inode update; the superblock could be there too */
3018static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
3019{
e2b911c5 3020 if (likely(ext4_has_feature_large_file(inode->i_sb)))
0ff8947f
ES
3021 return 1;
3022
3023 if (pos + len <= 0x7fffffffULL)
3024 return 1;
3025
3026 /* We might need to update the superblock to set LARGE_FILE */
3027 return 2;
3028}
3029
64769240 3030static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
de9a55b8
TT
3031 loff_t pos, unsigned len, unsigned flags,
3032 struct page **pagep, void **fsdata)
64769240 3033{
72b8ab9d 3034 int ret, retries = 0;
64769240
AT
3035 struct page *page;
3036 pgoff_t index;
64769240
AT
3037 struct inode *inode = mapping->host;
3038 handle_t *handle;
3039
0db1ff22
TT
3040 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3041 return -EIO;
3042
09cbfeaf 3043 index = pos >> PAGE_SHIFT;
79f0be8d 3044
c93d8f88
EB
3045 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
3046 ext4_verity_in_progress(inode)) {
79f0be8d
AK
3047 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3048 return ext4_write_begin(file, mapping, pos,
3049 len, flags, pagep, fsdata);
3050 }
3051 *fsdata = (void *)0;
9bffad1e 3052 trace_ext4_da_write_begin(inode, pos, len, flags);
9c3569b5
TM
3053
3054 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3055 ret = ext4_da_write_inline_data_begin(mapping, inode,
3056 pos, len, flags,
3057 pagep, fsdata);
3058 if (ret < 0)
47564bfb
TT
3059 return ret;
3060 if (ret == 1)
3061 return 0;
9c3569b5
TM
3062 }
3063
47564bfb
TT
3064 /*
3065 * grab_cache_page_write_begin() can take a long time if the
3066 * system is thrashing due to memory pressure, or if the page
3067 * is being written back. So grab it first before we start
3068 * the transaction handle. This also allows us to allocate
3069 * the page (if needed) without using GFP_NOFS.
3070 */
3071retry_grab:
3072 page = grab_cache_page_write_begin(mapping, index, flags);
3073 if (!page)
3074 return -ENOMEM;
3075 unlock_page(page);
3076
64769240
AT
3077 /*
3078 * With delayed allocation, we don't log the i_disksize update
3079 * if there is delayed block allocation. But we still need
3080 * to journalling the i_disksize update if writes to the end
3081 * of file which has an already mapped buffer.
3082 */
47564bfb 3083retry_journal:
0ff8947f
ES
3084 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3085 ext4_da_write_credits(inode, pos, len));
64769240 3086 if (IS_ERR(handle)) {
09cbfeaf 3087 put_page(page);
47564bfb 3088 return PTR_ERR(handle);
64769240
AT
3089 }
3090
47564bfb
TT
3091 lock_page(page);
3092 if (page->mapping != mapping) {
3093 /* The page got truncated from under us */
3094 unlock_page(page);
09cbfeaf 3095 put_page(page);
d5a0d4f7 3096 ext4_journal_stop(handle);
47564bfb 3097 goto retry_grab;
d5a0d4f7 3098 }
47564bfb 3099 /* In case writeback began while the page was unlocked */
7afe5aa5 3100 wait_for_stable_page(page);
64769240 3101
643fa961 3102#ifdef CONFIG_FS_ENCRYPTION
2058f83a
MH
3103 ret = ext4_block_write_begin(page, pos, len,
3104 ext4_da_get_block_prep);
3105#else
6e1db88d 3106 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2058f83a 3107#endif
64769240
AT
3108 if (ret < 0) {
3109 unlock_page(page);
3110 ext4_journal_stop(handle);
ae4d5372
AK
3111 /*
3112 * block_write_begin may have instantiated a few blocks
3113 * outside i_size. Trim these off again. Don't need
3114 * i_size_read because we hold i_mutex.
3115 */
3116 if (pos + len > inode->i_size)
b9a4207d 3117 ext4_truncate_failed_write(inode);
47564bfb
TT
3118
3119 if (ret == -ENOSPC &&
3120 ext4_should_retry_alloc(inode->i_sb, &retries))
3121 goto retry_journal;
3122
09cbfeaf 3123 put_page(page);
47564bfb 3124 return ret;
64769240
AT
3125 }
3126
47564bfb 3127 *pagep = page;
64769240
AT
3128 return ret;
3129}
3130
632eaeab
MC
3131/*
3132 * Check if we should update i_disksize
3133 * when write to the end of file but not require block allocation
3134 */
3135static int ext4_da_should_update_i_disksize(struct page *page,
de9a55b8 3136 unsigned long offset)
632eaeab
MC
3137{
3138 struct buffer_head *bh;
3139 struct inode *inode = page->mapping->host;
3140 unsigned int idx;
3141 int i;
3142
3143 bh = page_buffers(page);
3144 idx = offset >> inode->i_blkbits;
3145
af5bc92d 3146 for (i = 0; i < idx; i++)
632eaeab
MC
3147 bh = bh->b_this_page;
3148
29fa89d0 3149 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
632eaeab
MC
3150 return 0;
3151 return 1;
3152}
3153
64769240 3154static int ext4_da_write_end(struct file *file,
de9a55b8
TT
3155 struct address_space *mapping,
3156 loff_t pos, unsigned len, unsigned copied,
3157 struct page *page, void *fsdata)
64769240
AT
3158{
3159 struct inode *inode = mapping->host;
3160 int ret = 0, ret2;
3161 handle_t *handle = ext4_journal_current_handle();
3162 loff_t new_i_size;
632eaeab 3163 unsigned long start, end;
79f0be8d
AK
3164 int write_mode = (int)(unsigned long)fsdata;
3165
74d553aa
TT
3166 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3167 return ext4_write_end(file, mapping, pos,
3168 len, copied, page, fsdata);
632eaeab 3169
9bffad1e 3170 trace_ext4_da_write_end(inode, pos, len, copied);
09cbfeaf 3171 start = pos & (PAGE_SIZE - 1);
af5bc92d 3172 end = start + copied - 1;
64769240
AT
3173
3174 /*
3175 * generic_write_end() will run mark_inode_dirty() if i_size
3176 * changes. So let's piggyback the i_disksize mark_inode_dirty
3177 * into that.
3178 */
64769240 3179 new_i_size = pos + copied;
ea51d132 3180 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
9c3569b5
TM
3181 if (ext4_has_inline_data(inode) ||
3182 ext4_da_should_update_i_disksize(page, end)) {
ee124d27 3183 ext4_update_i_disksize(inode, new_i_size);
cf17fea6
AK
3184 /* We need to mark inode dirty even if
3185 * new_i_size is less that inode->i_size
3186 * bu greater than i_disksize.(hint delalloc)
3187 */
3188 ext4_mark_inode_dirty(handle, inode);
64769240 3189 }
632eaeab 3190 }
9c3569b5
TM
3191
3192 if (write_mode != CONVERT_INLINE_DATA &&
3193 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3194 ext4_has_inline_data(inode))
3195 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3196 page);
3197 else
3198 ret2 = generic_write_end(file, mapping, pos, len, copied,
64769240 3199 page, fsdata);
9c3569b5 3200
64769240
AT
3201 copied = ret2;
3202 if (ret2 < 0)
3203 ret = ret2;
3204 ret2 = ext4_journal_stop(handle);
3205 if (!ret)
3206 ret = ret2;
3207
3208 return ret ? ret : copied;
3209}
3210
ccd2506b
TT
3211/*
3212 * Force all delayed allocation blocks to be allocated for a given inode.
3213 */
3214int ext4_alloc_da_blocks(struct inode *inode)
3215{
fb40ba0d
TT
3216 trace_ext4_alloc_da_blocks(inode);
3217
71d4f7d0 3218 if (!EXT4_I(inode)->i_reserved_data_blocks)
ccd2506b
TT
3219 return 0;
3220
3221 /*
3222 * We do something simple for now. The filemap_flush() will
3223 * also start triggering a write of the data blocks, which is
3224 * not strictly speaking necessary (and for users of
3225 * laptop_mode, not even desirable). However, to do otherwise
3226 * would require replicating code paths in:
de9a55b8 3227 *
20970ba6 3228 * ext4_writepages() ->
ccd2506b
TT
3229 * write_cache_pages() ---> (via passed in callback function)
3230 * __mpage_da_writepage() -->
3231 * mpage_add_bh_to_extent()
3232 * mpage_da_map_blocks()
3233 *
3234 * The problem is that write_cache_pages(), located in
3235 * mm/page-writeback.c, marks pages clean in preparation for
3236 * doing I/O, which is not desirable if we're not planning on
3237 * doing I/O at all.
3238 *
3239 * We could call write_cache_pages(), and then redirty all of
380cf090 3240 * the pages by calling redirty_page_for_writepage() but that
ccd2506b
TT
3241 * would be ugly in the extreme. So instead we would need to
3242 * replicate parts of the code in the above functions,
25985edc 3243 * simplifying them because we wouldn't actually intend to
ccd2506b
TT
3244 * write out the pages, but rather only collect contiguous
3245 * logical block extents, call the multi-block allocator, and
3246 * then update the buffer heads with the block allocations.
de9a55b8 3247 *
ccd2506b
TT
3248 * For now, though, we'll cheat by calling filemap_flush(),
3249 * which will map the blocks, and start the I/O, but not
3250 * actually wait for the I/O to complete.
3251 */
3252 return filemap_flush(inode->i_mapping);
3253}
64769240 3254
ac27a0ec
DK
3255/*
3256 * bmap() is special. It gets used by applications such as lilo and by
3257 * the swapper to find the on-disk block of a specific piece of data.
3258 *
3259 * Naturally, this is dangerous if the block concerned is still in the
617ba13b 3260 * journal. If somebody makes a swapfile on an ext4 data-journaling
ac27a0ec
DK
3261 * filesystem and enables swap, then they may get a nasty shock when the
3262 * data getting swapped to that swapfile suddenly gets overwritten by
3263 * the original zero's written out previously to the journal and
3264 * awaiting writeback in the kernel's buffer cache.
3265 *
3266 * So, if we see any bmap calls here on a modified, data-journaled file,
3267 * take extra steps to flush any blocks which might be in the cache.
3268 */
617ba13b 3269static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
ac27a0ec
DK
3270{
3271 struct inode *inode = mapping->host;
3272 journal_t *journal;
3273 int err;
3274
46c7f254
TM
3275 /*
3276 * We can get here for an inline file via the FIBMAP ioctl
3277 */
3278 if (ext4_has_inline_data(inode))
3279 return 0;
3280
64769240
AT
3281 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3282 test_opt(inode->i_sb, DELALLOC)) {
3283 /*
3284 * With delalloc we want to sync the file
3285 * so that we can make sure we allocate
3286 * blocks for file
3287 */
3288 filemap_write_and_wait(mapping);
3289 }
3290
19f5fb7a
TT
3291 if (EXT4_JOURNAL(inode) &&
3292 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
ac27a0ec
DK
3293 /*
3294 * This is a REALLY heavyweight approach, but the use of
3295 * bmap on dirty files is expected to be extremely rare:
3296 * only if we run lilo or swapon on a freshly made file
3297 * do we expect this to happen.
3298 *
3299 * (bmap requires CAP_SYS_RAWIO so this does not
3300 * represent an unprivileged user DOS attack --- we'd be
3301 * in trouble if mortal users could trigger this path at
3302 * will.)
3303 *
617ba13b 3304 * NB. EXT4_STATE_JDATA is not set on files other than
ac27a0ec
DK
3305 * regular files. If somebody wants to bmap a directory
3306 * or symlink and gets confused because the buffer
3307 * hasn't yet been flushed to disk, they deserve
3308 * everything they get.
3309 */
3310
19f5fb7a 3311 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
617ba13b 3312 journal = EXT4_JOURNAL(inode);
dab291af
MC
3313 jbd2_journal_lock_updates(journal);
3314 err = jbd2_journal_flush(journal);
3315 jbd2_journal_unlock_updates(journal);
ac27a0ec
DK
3316
3317 if (err)
3318 return 0;
3319 }
3320
af5bc92d 3321 return generic_block_bmap(mapping, block, ext4_get_block);
ac27a0ec
DK
3322}
3323
617ba13b 3324static int ext4_readpage(struct file *file, struct page *page)
ac27a0ec 3325{
46c7f254
TM
3326 int ret = -EAGAIN;
3327 struct inode *inode = page->mapping->host;
3328
0562e0ba 3329 trace_ext4_readpage(page);
46c7f254
TM
3330
3331 if (ext4_has_inline_data(inode))
3332 ret = ext4_readpage_inline(inode, page);
3333
3334 if (ret == -EAGAIN)
ac22b46a
JA
3335 return ext4_mpage_readpages(page->mapping, NULL, page, 1,
3336 false);
46c7f254
TM
3337
3338 return ret;
ac27a0ec
DK
3339}
3340
3341static int
617ba13b 3342ext4_readpages(struct file *file, struct address_space *mapping,
ac27a0ec
DK
3343 struct list_head *pages, unsigned nr_pages)
3344{
46c7f254
TM
3345 struct inode *inode = mapping->host;
3346
3347 /* If the file has inline data, no need to do readpages. */
3348 if (ext4_has_inline_data(inode))
3349 return 0;
3350
ac22b46a 3351 return ext4_mpage_readpages(mapping, pages, NULL, nr_pages, true);
ac27a0ec
DK
3352}
3353
d47992f8
LC
3354static void ext4_invalidatepage(struct page *page, unsigned int offset,
3355 unsigned int length)
ac27a0ec 3356{
ca99fdd2 3357 trace_ext4_invalidatepage(page, offset, length);
0562e0ba 3358
4520fb3c
JK
3359 /* No journalling happens on data buffers when this function is used */
3360 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3361
ca99fdd2 3362 block_invalidatepage(page, offset, length);
4520fb3c
JK
3363}
3364
53e87268 3365static int __ext4_journalled_invalidatepage(struct page *page,
ca99fdd2
LC
3366 unsigned int offset,
3367 unsigned int length)
4520fb3c
JK
3368{
3369 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3370
ca99fdd2 3371 trace_ext4_journalled_invalidatepage(page, offset, length);
4520fb3c 3372
ac27a0ec
DK
3373 /*
3374 * If it's a full truncate we just forget about the pending dirtying
3375 */
09cbfeaf 3376 if (offset == 0 && length == PAGE_SIZE)
ac27a0ec
DK
3377 ClearPageChecked(page);
3378
ca99fdd2 3379 return jbd2_journal_invalidatepage(journal, page, offset, length);
53e87268
JK
3380}
3381
3382/* Wrapper for aops... */
3383static void ext4_journalled_invalidatepage(struct page *page,
d47992f8
LC
3384 unsigned int offset,
3385 unsigned int length)
53e87268 3386{
ca99fdd2 3387 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
ac27a0ec
DK
3388}
3389
617ba13b 3390static int ext4_releasepage(struct page *page, gfp_t wait)
ac27a0ec 3391{
617ba13b 3392 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
ac27a0ec 3393
0562e0ba
JZ
3394 trace_ext4_releasepage(page);
3395
e1c36595
JK
3396 /* Page has dirty journalled data -> cannot release */
3397 if (PageChecked(page))
ac27a0ec 3398 return 0;
0390131b
FM
3399 if (journal)
3400 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3401 else
3402 return try_to_free_buffers(page);
ac27a0ec
DK
3403}
3404
b8a6176c
JK
3405static bool ext4_inode_datasync_dirty(struct inode *inode)
3406{
3407 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3408
3409 if (journal)
3410 return !jbd2_transaction_committed(journal,
3411 EXT4_I(inode)->i_datasync_tid);
3412 /* Any metadata buffers to write? */
3413 if (!list_empty(&inode->i_mapping->private_list))
3414 return true;
3415 return inode->i_state & I_DIRTY_DATASYNC;
3416}
3417
364443cb
JK
3418static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3419 unsigned flags, struct iomap *iomap)
3420{
5e405595 3421 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
364443cb 3422 unsigned int blkbits = inode->i_blkbits;
bcd8e91f 3423 unsigned long first_block, last_block;
364443cb 3424 struct ext4_map_blocks map;
545052e9 3425 bool delalloc = false;
364443cb
JK
3426 int ret;
3427
bcd8e91f
TT
3428 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3429 return -EINVAL;
3430 first_block = offset >> blkbits;
3431 last_block = min_t(loff_t, (offset + length - 1) >> blkbits,
3432 EXT4_MAX_LOGICAL_BLOCK);
7046ae35
AG
3433
3434 if (flags & IOMAP_REPORT) {
3435 if (ext4_has_inline_data(inode)) {
3436 ret = ext4_inline_data_iomap(inode, iomap);
3437 if (ret != -EAGAIN) {
3438 if (ret == 0 && offset >= iomap->length)
3439 ret = -ENOENT;
3440 return ret;
3441 }
3442 }
3443 } else {
3444 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3445 return -ERANGE;
3446 }
364443cb
JK
3447
3448 map.m_lblk = first_block;
3449 map.m_len = last_block - first_block + 1;
3450
545052e9 3451 if (flags & IOMAP_REPORT) {
776722e8 3452 ret = ext4_map_blocks(NULL, inode, &map, 0);
545052e9
CH
3453 if (ret < 0)
3454 return ret;
3455
3456 if (ret == 0) {
3457 ext4_lblk_t end = map.m_lblk + map.m_len - 1;
3458 struct extent_status es;
3459
ad431025
EW
3460 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3461 map.m_lblk, end, &es);
545052e9
CH
3462
3463 if (!es.es_len || es.es_lblk > end) {
3464 /* entire range is a hole */
3465 } else if (es.es_lblk > map.m_lblk) {
3466 /* range starts with a hole */
3467 map.m_len = es.es_lblk - map.m_lblk;
3468 } else {
3469 ext4_lblk_t offs = 0;
3470
3471 if (es.es_lblk < map.m_lblk)
3472 offs = map.m_lblk - es.es_lblk;
3473 map.m_lblk = es.es_lblk + offs;
3474 map.m_len = es.es_len - offs;
3475 delalloc = true;
3476 }
3477 }
3478 } else if (flags & IOMAP_WRITE) {
776722e8
JK
3479 int dio_credits;
3480 handle_t *handle;
3481 int retries = 0;
3482
3483 /* Trim mapping request to maximum we can map at once for DIO */
3484 if (map.m_len > DIO_MAX_BLOCKS)
3485 map.m_len = DIO_MAX_BLOCKS;
3486 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
3487retry:
3488 /*
3489 * Either we allocate blocks and then we don't get unwritten
3490 * extent so we have reserved enough credits, or the blocks
3491 * are already allocated and unwritten and in that case
3492 * extent conversion fits in the credits as well.
3493 */
3494 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
3495 dio_credits);
3496 if (IS_ERR(handle))
3497 return PTR_ERR(handle);
3498
3499 ret = ext4_map_blocks(handle, inode, &map,
776722e8
JK
3500 EXT4_GET_BLOCKS_CREATE_ZERO);
3501 if (ret < 0) {
3502 ext4_journal_stop(handle);
3503 if (ret == -ENOSPC &&
3504 ext4_should_retry_alloc(inode->i_sb, &retries))
3505 goto retry;
3506 return ret;
3507 }
776722e8
JK
3508
3509 /*
e2ae766c 3510 * If we added blocks beyond i_size, we need to make sure they
776722e8 3511 * will get truncated if we crash before updating i_size in
e2ae766c
JK
3512 * ext4_iomap_end(). For faults we don't need to do that (and
3513 * even cannot because for orphan list operations inode_lock is
3514 * required) - if we happen to instantiate block beyond i_size,
3515 * it is because we race with truncate which has already added
3516 * the inode to the orphan list.
776722e8 3517 */
e2ae766c
JK
3518 if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
3519 (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
776722e8
JK
3520 int err;
3521
3522 err = ext4_orphan_add(handle, inode);
3523 if (err < 0) {
3524 ext4_journal_stop(handle);
3525 return err;
3526 }
3527 }
3528 ext4_journal_stop(handle);
545052e9
CH
3529 } else {
3530 ret = ext4_map_blocks(NULL, inode, &map, 0);
3531 if (ret < 0)
3532 return ret;
776722e8 3533 }
364443cb
JK
3534
3535 iomap->flags = 0;
aaa422c4 3536 if (ext4_inode_datasync_dirty(inode))
b8a6176c 3537 iomap->flags |= IOMAP_F_DIRTY;
5e405595
DW
3538 iomap->bdev = inode->i_sb->s_bdev;
3539 iomap->dax_dev = sbi->s_daxdev;
fe23cb65 3540 iomap->offset = (u64)first_block << blkbits;
545052e9 3541 iomap->length = (u64)map.m_len << blkbits;
364443cb
JK
3542
3543 if (ret == 0) {
545052e9 3544 iomap->type = delalloc ? IOMAP_DELALLOC : IOMAP_HOLE;
19fe5f64 3545 iomap->addr = IOMAP_NULL_ADDR;
364443cb
JK
3546 } else {
3547 if (map.m_flags & EXT4_MAP_MAPPED) {
3548 iomap->type = IOMAP_MAPPED;
3549 } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
3550 iomap->type = IOMAP_UNWRITTEN;
3551 } else {
3552 WARN_ON_ONCE(1);
3553 return -EIO;
3554 }
19fe5f64 3555 iomap->addr = (u64)map.m_pblk << blkbits;
364443cb
JK
3556 }
3557
3558 if (map.m_flags & EXT4_MAP_NEW)
3559 iomap->flags |= IOMAP_F_NEW;
545052e9 3560
364443cb
JK
3561 return 0;
3562}
3563
776722e8
JK
3564static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3565 ssize_t written, unsigned flags, struct iomap *iomap)
3566{
3567 int ret = 0;
3568 handle_t *handle;
3569 int blkbits = inode->i_blkbits;
3570 bool truncate = false;
3571
e2ae766c 3572 if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
776722e8
JK
3573 return 0;
3574
3575 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3576 if (IS_ERR(handle)) {
3577 ret = PTR_ERR(handle);
3578 goto orphan_del;
3579 }
3580 if (ext4_update_inode_size(inode, offset + written))
3581 ext4_mark_inode_dirty(handle, inode);
3582 /*
3583 * We may need to truncate allocated but not written blocks beyond EOF.
3584 */
3585 if (iomap->offset + iomap->length >
3586 ALIGN(inode->i_size, 1 << blkbits)) {
3587 ext4_lblk_t written_blk, end_blk;
3588
3589 written_blk = (offset + written) >> blkbits;
3590 end_blk = (offset + length) >> blkbits;
3591 if (written_blk < end_blk && ext4_can_truncate(inode))
3592 truncate = true;
3593 }
3594 /*
3595 * Remove inode from orphan list if we were extending a inode and
3596 * everything went fine.
3597 */
3598 if (!truncate && inode->i_nlink &&
3599 !list_empty(&EXT4_I(inode)->i_orphan))
3600 ext4_orphan_del(handle, inode);
3601 ext4_journal_stop(handle);
3602 if (truncate) {
3603 ext4_truncate_failed_write(inode);
3604orphan_del:
3605 /*
3606 * If truncate failed early the inode might still be on the
3607 * orphan list; we need to make sure the inode is removed from
3608 * the orphan list in that case.
3609 */
3610 if (inode->i_nlink)
3611 ext4_orphan_del(NULL, inode);
3612 }
3613 return ret;
3614}
3615
8ff6daa1 3616const struct iomap_ops ext4_iomap_ops = {
364443cb 3617 .iomap_begin = ext4_iomap_begin,
776722e8 3618 .iomap_end = ext4_iomap_end,
364443cb
JK
3619};
3620
187372a3 3621static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
7b7a8665 3622 ssize_t size, void *private)
4c0425ff 3623{
109811c2 3624 ext4_io_end_t *io_end = private;
4c0425ff 3625
97a851ed 3626 /* if not async direct IO just return */
7b7a8665 3627 if (!io_end)
187372a3 3628 return 0;
4b70df18 3629
88635ca2 3630 ext_debug("ext4_end_io_dio(): io_end 0x%p "
ace36ad4 3631 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
109811c2 3632 io_end, io_end->inode->i_ino, iocb, offset, size);
8d5d02e6 3633
74c66bcb
JK
3634 /*
3635 * Error during AIO DIO. We cannot convert unwritten extents as the
3636 * data was not written. Just clear the unwritten flag and drop io_end.
3637 */
3638 if (size <= 0) {
3639 ext4_clear_io_unwritten_flag(io_end);
3640 size = 0;
3641 }
4c0425ff
MC
3642 io_end->offset = offset;
3643 io_end->size = size;
7b7a8665 3644 ext4_put_io_end(io_end);
187372a3
CH
3645
3646 return 0;
4c0425ff 3647}
c7064ef1 3648
4c0425ff 3649/*
914f82a3
JK
3650 * Handling of direct IO writes.
3651 *
3652 * For ext4 extent files, ext4 will do direct-io write even to holes,
4c0425ff
MC
3653 * preallocated extents, and those write extend the file, no need to
3654 * fall back to buffered IO.
3655 *
556615dc 3656 * For holes, we fallocate those blocks, mark them as unwritten
69c499d1 3657 * If those blocks were preallocated, we mark sure they are split, but
556615dc 3658 * still keep the range to write as unwritten.
4c0425ff 3659 *
69c499d1 3660 * The unwritten extents will be converted to written when DIO is completed.
8d5d02e6 3661 * For async direct IO, since the IO may still pending when return, we
25985edc 3662 * set up an end_io call back function, which will do the conversion
8d5d02e6 3663 * when async direct IO completed.
4c0425ff
MC
3664 *
3665 * If the O_DIRECT write will extend the file then add this inode to the
3666 * orphan list. So recovery will truncate it back to the original size
3667 * if the machine crashes during the write.
3668 *
3669 */
0e01df10 3670static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
4c0425ff
MC
3671{
3672 struct file *file = iocb->ki_filp;
3673 struct inode *inode = file->f_mapping->host;
45d8ec4d 3674 struct ext4_inode_info *ei = EXT4_I(inode);
4c0425ff 3675 ssize_t ret;
c8b8e32d 3676 loff_t offset = iocb->ki_pos;
a6cbcd4a 3677 size_t count = iov_iter_count(iter);
69c499d1
TT
3678 int overwrite = 0;
3679 get_block_t *get_block_func = NULL;
3680 int dio_flags = 0;
4c0425ff 3681 loff_t final_size = offset + count;
914f82a3
JK
3682 int orphan = 0;
3683 handle_t *handle;
729f52c6 3684
45d8ec4d 3685 if (final_size > inode->i_size || final_size > ei->i_disksize) {
914f82a3
JK
3686 /* Credits for sb + inode write */
3687 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3688 if (IS_ERR(handle)) {
3689 ret = PTR_ERR(handle);
3690 goto out;
3691 }
3692 ret = ext4_orphan_add(handle, inode);
3693 if (ret) {
3694 ext4_journal_stop(handle);
3695 goto out;
3696 }
3697 orphan = 1;
73fdad00 3698 ext4_update_i_disksize(inode, inode->i_size);
914f82a3
JK
3699 ext4_journal_stop(handle);
3700 }
4bd809db 3701
69c499d1 3702 BUG_ON(iocb->private == NULL);
4bd809db 3703
e8340395
JK
3704 /*
3705 * Make all waiters for direct IO properly wait also for extent
3706 * conversion. This also disallows race between truncate() and
3707 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3708 */
914f82a3 3709 inode_dio_begin(inode);
e8340395 3710
69c499d1
TT
3711 /* If we do a overwrite dio, i_mutex locking can be released */
3712 overwrite = *((int *)iocb->private);
4bd809db 3713
2dcba478 3714 if (overwrite)
5955102c 3715 inode_unlock(inode);
8d5d02e6 3716
69c499d1 3717 /*
914f82a3 3718 * For extent mapped files we could direct write to holes and fallocate.
69c499d1 3719 *
109811c2
JK
3720 * Allocated blocks to fill the hole are marked as unwritten to prevent
3721 * parallel buffered read to expose the stale data before DIO complete
3722 * the data IO.
69c499d1 3723 *
109811c2
JK
3724 * As to previously fallocated extents, ext4 get_block will just simply
3725 * mark the buffer mapped but still keep the extents unwritten.
69c499d1 3726 *
109811c2
JK
3727 * For non AIO case, we will convert those unwritten extents to written
3728 * after return back from blockdev_direct_IO. That way we save us from
3729 * allocating io_end structure and also the overhead of offloading
3730 * the extent convertion to a workqueue.
69c499d1
TT
3731 *
3732 * For async DIO, the conversion needs to be deferred when the
3733 * IO is completed. The ext4 end_io callback function will be
3734 * called to take care of the conversion work. Here for async
3735 * case, we allocate an io_end structure to hook to the iocb.
3736 */
3737 iocb->private = NULL;
109811c2 3738 if (overwrite)
705965bd 3739 get_block_func = ext4_dio_get_block_overwrite;
0bd2d5ec 3740 else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
93407472 3741 round_down(offset, i_blocksize(inode)) >= inode->i_size) {
914f82a3
JK
3742 get_block_func = ext4_dio_get_block;
3743 dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
3744 } else if (is_sync_kiocb(iocb)) {
109811c2
JK
3745 get_block_func = ext4_dio_get_block_unwritten_sync;
3746 dio_flags = DIO_LOCKING;
69c499d1 3747 } else {
109811c2 3748 get_block_func = ext4_dio_get_block_unwritten_async;
69c499d1
TT
3749 dio_flags = DIO_LOCKING;
3750 }
0bd2d5ec
JK
3751 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3752 get_block_func, ext4_end_io_dio, NULL,
3753 dio_flags);
69c499d1 3754
97a851ed 3755 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
69c499d1
TT
3756 EXT4_STATE_DIO_UNWRITTEN)) {
3757 int err;
3758 /*
3759 * for non AIO case, since the IO is already
3760 * completed, we could do the conversion right here
3761 */
6b523df4 3762 err = ext4_convert_unwritten_extents(NULL, inode,
69c499d1
TT
3763 offset, ret);
3764 if (err < 0)
3765 ret = err;
3766 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3767 }
4bd809db 3768
914f82a3 3769 inode_dio_end(inode);
69c499d1 3770 /* take i_mutex locking again if we do a ovewrite dio */
2dcba478 3771 if (overwrite)
5955102c 3772 inode_lock(inode);
8d5d02e6 3773
914f82a3
JK
3774 if (ret < 0 && final_size > inode->i_size)
3775 ext4_truncate_failed_write(inode);
3776
3777 /* Handle extending of i_size after direct IO write */
3778 if (orphan) {
3779 int err;
3780
3781 /* Credits for sb + inode write */
3782 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3783 if (IS_ERR(handle)) {
abbc3f93
HS
3784 /*
3785 * We wrote the data but cannot extend
3786 * i_size. Bail out. In async io case, we do
3787 * not return error here because we have
3788 * already submmitted the corresponding
3789 * bio. Returning error here makes the caller
3790 * think that this IO is done and failed
3791 * resulting in race with bio's completion
3792 * handler.
3793 */
3794 if (!ret)
3795 ret = PTR_ERR(handle);
914f82a3
JK
3796 if (inode->i_nlink)
3797 ext4_orphan_del(NULL, inode);
3798
3799 goto out;
3800 }
3801 if (inode->i_nlink)
3802 ext4_orphan_del(handle, inode);
3803 if (ret > 0) {
3804 loff_t end = offset + ret;
45d8ec4d 3805 if (end > inode->i_size || end > ei->i_disksize) {
73fdad00 3806 ext4_update_i_disksize(inode, end);
45d8ec4d
EG
3807 if (end > inode->i_size)
3808 i_size_write(inode, end);
914f82a3
JK
3809 /*
3810 * We're going to return a positive `ret'
3811 * here due to non-zero-length I/O, so there's
3812 * no way of reporting error returns from
3813 * ext4_mark_inode_dirty() to userspace. So
3814 * ignore it.
3815 */
3816 ext4_mark_inode_dirty(handle, inode);
3817 }
3818 }
3819 err = ext4_journal_stop(handle);
3820 if (ret == 0)
3821 ret = err;
3822 }
3823out:
3824 return ret;
3825}
3826
0e01df10 3827static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
914f82a3 3828{
16c54688
JK
3829 struct address_space *mapping = iocb->ki_filp->f_mapping;
3830 struct inode *inode = mapping->host;
0bd2d5ec 3831 size_t count = iov_iter_count(iter);
914f82a3
JK
3832 ssize_t ret;
3833
16c54688
JK
3834 /*
3835 * Shared inode_lock is enough for us - it protects against concurrent
3836 * writes & truncates and since we take care of writing back page cache,
3837 * we are protected against page writeback as well.
3838 */
3839 inode_lock_shared(inode);
0bd2d5ec 3840 ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
e5465795 3841 iocb->ki_pos + count - 1);
0bd2d5ec
JK
3842 if (ret)
3843 goto out_unlock;
3844 ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
3845 iter, ext4_dio_get_block, NULL, NULL, 0);
16c54688
JK
3846out_unlock:
3847 inode_unlock_shared(inode);
69c499d1 3848 return ret;
4c0425ff
MC
3849}
3850
c8b8e32d 3851static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
4c0425ff
MC
3852{
3853 struct file *file = iocb->ki_filp;
3854 struct inode *inode = file->f_mapping->host;
a6cbcd4a 3855 size_t count = iov_iter_count(iter);
c8b8e32d 3856 loff_t offset = iocb->ki_pos;
0562e0ba 3857 ssize_t ret;
4c0425ff 3858
643fa961 3859#ifdef CONFIG_FS_ENCRYPTION
592ddec7 3860 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
2058f83a
MH
3861 return 0;
3862#endif
22cfe4b4
EB
3863 if (fsverity_active(inode))
3864 return 0;
2058f83a 3865
84ebd795
TT
3866 /*
3867 * If we are doing data journalling we don't support O_DIRECT
3868 */
3869 if (ext4_should_journal_data(inode))
3870 return 0;
3871
46c7f254
TM
3872 /* Let buffer I/O handle the inline data case. */
3873 if (ext4_has_inline_data(inode))
3874 return 0;
3875
6f673763 3876 trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
914f82a3 3877 if (iov_iter_rw(iter) == READ)
0e01df10 3878 ret = ext4_direct_IO_read(iocb, iter);
0562e0ba 3879 else
0e01df10 3880 ret = ext4_direct_IO_write(iocb, iter);
6f673763 3881 trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
0562e0ba 3882 return ret;
4c0425ff
MC
3883}
3884
ac27a0ec 3885/*
617ba13b 3886 * Pages can be marked dirty completely asynchronously from ext4's journalling
ac27a0ec
DK
3887 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3888 * much here because ->set_page_dirty is called under VFS locks. The page is
3889 * not necessarily locked.
3890 *
3891 * We cannot just dirty the page and leave attached buffers clean, because the
3892 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3893 * or jbddirty because all the journalling code will explode.
3894 *
3895 * So what we do is to mark the page "pending dirty" and next time writepage
3896 * is called, propagate that into the buffers appropriately.
3897 */
617ba13b 3898static int ext4_journalled_set_page_dirty(struct page *page)
ac27a0ec
DK
3899{
3900 SetPageChecked(page);
3901 return __set_page_dirty_nobuffers(page);
3902}
3903
6dcc693b
JK
3904static int ext4_set_page_dirty(struct page *page)
3905{
3906 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3907 WARN_ON_ONCE(!page_has_buffers(page));
3908 return __set_page_dirty_buffers(page);
3909}
3910
74d553aa 3911static const struct address_space_operations ext4_aops = {
8ab22b9a
HH
3912 .readpage = ext4_readpage,
3913 .readpages = ext4_readpages,
43ce1d23 3914 .writepage = ext4_writepage,
20970ba6 3915 .writepages = ext4_writepages,
8ab22b9a 3916 .write_begin = ext4_write_begin,
74d553aa 3917 .write_end = ext4_write_end,
6dcc693b 3918 .set_page_dirty = ext4_set_page_dirty,
8ab22b9a
HH
3919 .bmap = ext4_bmap,
3920 .invalidatepage = ext4_invalidatepage,
3921 .releasepage = ext4_releasepage,
3922 .direct_IO = ext4_direct_IO,
3923 .migratepage = buffer_migrate_page,
3924 .is_partially_uptodate = block_is_partially_uptodate,
aa261f54 3925 .error_remove_page = generic_error_remove_page,
ac27a0ec
DK
3926};
3927
617ba13b 3928static const struct address_space_operations ext4_journalled_aops = {
8ab22b9a
HH
3929 .readpage = ext4_readpage,
3930 .readpages = ext4_readpages,
43ce1d23 3931 .writepage = ext4_writepage,
20970ba6 3932 .writepages = ext4_writepages,
8ab22b9a
HH
3933 .write_begin = ext4_write_begin,
3934 .write_end = ext4_journalled_write_end,
3935 .set_page_dirty = ext4_journalled_set_page_dirty,
3936 .bmap = ext4_bmap,
4520fb3c 3937 .invalidatepage = ext4_journalled_invalidatepage,
8ab22b9a 3938 .releasepage = ext4_releasepage,
84ebd795 3939 .direct_IO = ext4_direct_IO,
8ab22b9a 3940 .is_partially_uptodate = block_is_partially_uptodate,
aa261f54 3941 .error_remove_page = generic_error_remove_page,
ac27a0ec
DK
3942};
3943
64769240 3944static const struct address_space_operations ext4_da_aops = {
8ab22b9a
HH
3945 .readpage = ext4_readpage,
3946 .readpages = ext4_readpages,
43ce1d23 3947 .writepage = ext4_writepage,
20970ba6 3948 .writepages = ext4_writepages,
8ab22b9a
HH
3949 .write_begin = ext4_da_write_begin,
3950 .write_end = ext4_da_write_end,
6dcc693b 3951 .set_page_dirty = ext4_set_page_dirty,
8ab22b9a 3952 .bmap = ext4_bmap,
8fcc3a58 3953 .invalidatepage = ext4_invalidatepage,
8ab22b9a
HH
3954 .releasepage = ext4_releasepage,
3955 .direct_IO = ext4_direct_IO,
3956 .migratepage = buffer_migrate_page,
3957 .is_partially_uptodate = block_is_partially_uptodate,
aa261f54 3958 .error_remove_page = generic_error_remove_page,
64769240
AT
3959};
3960
5f0663bb
DW
3961static const struct address_space_operations ext4_dax_aops = {
3962 .writepages = ext4_dax_writepages,
3963 .direct_IO = noop_direct_IO,
3964 .set_page_dirty = noop_set_page_dirty,
94dbb631 3965 .bmap = ext4_bmap,
5f0663bb
DW
3966 .invalidatepage = noop_invalidatepage,
3967};
3968
617ba13b 3969void ext4_set_aops(struct inode *inode)
ac27a0ec 3970{
3d2b1582
LC
3971 switch (ext4_inode_journal_mode(inode)) {
3972 case EXT4_INODE_ORDERED_DATA_MODE:
3d2b1582 3973 case EXT4_INODE_WRITEBACK_DATA_MODE:
3d2b1582
LC
3974 break;
3975 case EXT4_INODE_JOURNAL_DATA_MODE:
617ba13b 3976 inode->i_mapping->a_ops = &ext4_journalled_aops;
74d553aa 3977 return;
3d2b1582
LC
3978 default:
3979 BUG();
3980 }
5f0663bb
DW
3981 if (IS_DAX(inode))
3982 inode->i_mapping->a_ops = &ext4_dax_aops;
3983 else if (test_opt(inode->i_sb, DELALLOC))
74d553aa
TT
3984 inode->i_mapping->a_ops = &ext4_da_aops;
3985 else
3986 inode->i_mapping->a_ops = &ext4_aops;
ac27a0ec
DK
3987}
3988
923ae0ff 3989static int __ext4_block_zero_page_range(handle_t *handle,
d863dc36
LC
3990 struct address_space *mapping, loff_t from, loff_t length)
3991{
09cbfeaf
KS
3992 ext4_fsblk_t index = from >> PAGE_SHIFT;
3993 unsigned offset = from & (PAGE_SIZE-1);
923ae0ff 3994 unsigned blocksize, pos;
d863dc36
LC
3995 ext4_lblk_t iblock;
3996 struct inode *inode = mapping->host;
3997 struct buffer_head *bh;
3998 struct page *page;
3999 int err = 0;
4000
09cbfeaf 4001 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
c62d2555 4002 mapping_gfp_constraint(mapping, ~__GFP_FS));
d863dc36
LC
4003 if (!page)
4004 return -ENOMEM;
4005
4006 blocksize = inode->i_sb->s_blocksize;
d863dc36 4007
09cbfeaf 4008 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
d863dc36
LC
4009
4010 if (!page_has_buffers(page))
4011 create_empty_buffers(page, blocksize, 0);
4012
4013 /* Find the buffer that contains "offset" */
4014 bh = page_buffers(page);
4015 pos = blocksize;
4016 while (offset >= pos) {
4017 bh = bh->b_this_page;
4018 iblock++;
4019 pos += blocksize;
4020 }
d863dc36
LC
4021 if (buffer_freed(bh)) {
4022 BUFFER_TRACE(bh, "freed: skip");
4023 goto unlock;
4024 }
d863dc36
LC
4025 if (!buffer_mapped(bh)) {
4026 BUFFER_TRACE(bh, "unmapped");
4027 ext4_get_block(inode, iblock, bh, 0);
4028 /* unmapped? It's a hole - nothing to do */
4029 if (!buffer_mapped(bh)) {
4030 BUFFER_TRACE(bh, "still unmapped");
4031 goto unlock;
4032 }
4033 }
4034
4035 /* Ok, it's mapped. Make sure it's up-to-date */
4036 if (PageUptodate(page))
4037 set_buffer_uptodate(bh);
4038
4039 if (!buffer_uptodate(bh)) {
4040 err = -EIO;
dfec8a14 4041 ll_rw_block(REQ_OP_READ, 0, 1, &bh);
d863dc36
LC
4042 wait_on_buffer(bh);
4043 /* Uhhuh. Read error. Complain and punt. */
4044 if (!buffer_uptodate(bh))
4045 goto unlock;
592ddec7 4046 if (S_ISREG(inode->i_mode) && IS_ENCRYPTED(inode)) {
c9c7429c 4047 /* We expect the key to be set. */
a7550b30 4048 BUG_ON(!fscrypt_has_encryption_key(inode));
aa8bc1ac 4049 WARN_ON_ONCE(fscrypt_decrypt_pagecache_blocks(
ec39a368 4050 page, blocksize, bh_offset(bh)));
c9c7429c 4051 }
d863dc36 4052 }
d863dc36
LC
4053 if (ext4_should_journal_data(inode)) {
4054 BUFFER_TRACE(bh, "get write access");
4055 err = ext4_journal_get_write_access(handle, bh);
4056 if (err)
4057 goto unlock;
4058 }
d863dc36 4059 zero_user(page, offset, length);
d863dc36
LC
4060 BUFFER_TRACE(bh, "zeroed end of block");
4061
d863dc36
LC
4062 if (ext4_should_journal_data(inode)) {
4063 err = ext4_handle_dirty_metadata(handle, inode, bh);
0713ed0c 4064 } else {
353eefd3 4065 err = 0;
d863dc36 4066 mark_buffer_dirty(bh);
3957ef53 4067 if (ext4_should_order_data(inode))
73131fbb
RZ
4068 err = ext4_jbd2_inode_add_write(handle, inode, from,
4069 length);
0713ed0c 4070 }
d863dc36
LC
4071
4072unlock:
4073 unlock_page(page);
09cbfeaf 4074 put_page(page);
d863dc36
LC
4075 return err;
4076}
4077
923ae0ff
RZ
4078/*
4079 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
4080 * starting from file offset 'from'. The range to be zero'd must
4081 * be contained with in one block. If the specified range exceeds
4082 * the end of the block it will be shortened to end of the block
4083 * that cooresponds to 'from'
4084 */
4085static int ext4_block_zero_page_range(handle_t *handle,
4086 struct address_space *mapping, loff_t from, loff_t length)
4087{
4088 struct inode *inode = mapping->host;
09cbfeaf 4089 unsigned offset = from & (PAGE_SIZE-1);
923ae0ff
RZ
4090 unsigned blocksize = inode->i_sb->s_blocksize;
4091 unsigned max = blocksize - (offset & (blocksize - 1));
4092
4093 /*
4094 * correct length if it does not fall between
4095 * 'from' and the end of the block
4096 */
4097 if (length > max || length < 0)
4098 length = max;
4099
47e69351
JK
4100 if (IS_DAX(inode)) {
4101 return iomap_zero_range(inode, from, length, NULL,
4102 &ext4_iomap_ops);
4103 }
923ae0ff
RZ
4104 return __ext4_block_zero_page_range(handle, mapping, from, length);
4105}
4106
94350ab5
MW
4107/*
4108 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4109 * up to the end of the block which corresponds to `from'.
4110 * This required during truncate. We need to physically zero the tail end
4111 * of that block so it doesn't yield old data if the file is later grown.
4112 */
c197855e 4113static int ext4_block_truncate_page(handle_t *handle,
94350ab5
MW
4114 struct address_space *mapping, loff_t from)
4115{
09cbfeaf 4116 unsigned offset = from & (PAGE_SIZE-1);
94350ab5
MW
4117 unsigned length;
4118 unsigned blocksize;
4119 struct inode *inode = mapping->host;
4120
0d06863f 4121 /* If we are processing an encrypted inode during orphan list handling */
592ddec7 4122 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
0d06863f
TT
4123 return 0;
4124
94350ab5
MW
4125 blocksize = inode->i_sb->s_blocksize;
4126 length = blocksize - (offset & (blocksize - 1));
4127
4128 return ext4_block_zero_page_range(handle, mapping, from, length);
4129}
4130
a87dd18c
LC
4131int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
4132 loff_t lstart, loff_t length)
4133{
4134 struct super_block *sb = inode->i_sb;
4135 struct address_space *mapping = inode->i_mapping;
e1be3a92 4136 unsigned partial_start, partial_end;
a87dd18c
LC
4137 ext4_fsblk_t start, end;
4138 loff_t byte_end = (lstart + length - 1);
4139 int err = 0;
4140
e1be3a92
LC
4141 partial_start = lstart & (sb->s_blocksize - 1);
4142 partial_end = byte_end & (sb->s_blocksize - 1);
4143
a87dd18c
LC
4144 start = lstart >> sb->s_blocksize_bits;
4145 end = byte_end >> sb->s_blocksize_bits;
4146
4147 /* Handle partial zero within the single block */
e1be3a92
LC
4148 if (start == end &&
4149 (partial_start || (partial_end != sb->s_blocksize - 1))) {
a87dd18c
LC
4150 err = ext4_block_zero_page_range(handle, mapping,
4151 lstart, length);
4152 return err;
4153 }
4154 /* Handle partial zero out on the start of the range */
e1be3a92 4155 if (partial_start) {
a87dd18c
LC
4156 err = ext4_block_zero_page_range(handle, mapping,
4157 lstart, sb->s_blocksize);
4158 if (err)
4159 return err;
4160 }
4161 /* Handle partial zero out on the end of the range */
e1be3a92 4162 if (partial_end != sb->s_blocksize - 1)
a87dd18c 4163 err = ext4_block_zero_page_range(handle, mapping,
e1be3a92
LC
4164 byte_end - partial_end,
4165 partial_end + 1);
a87dd18c
LC
4166 return err;
4167}
4168
91ef4caf
DG
4169int ext4_can_truncate(struct inode *inode)
4170{
91ef4caf
DG
4171 if (S_ISREG(inode->i_mode))
4172 return 1;
4173 if (S_ISDIR(inode->i_mode))
4174 return 1;
4175 if (S_ISLNK(inode->i_mode))
4176 return !ext4_inode_is_fast_symlink(inode);
4177 return 0;
4178}
4179
01127848
JK
4180/*
4181 * We have to make sure i_disksize gets properly updated before we truncate
4182 * page cache due to hole punching or zero range. Otherwise i_disksize update
4183 * can get lost as it may have been postponed to submission of writeback but
4184 * that will never happen after we truncate page cache.
4185 */
4186int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
4187 loff_t len)
4188{
4189 handle_t *handle;
4190 loff_t size = i_size_read(inode);
4191
5955102c 4192 WARN_ON(!inode_is_locked(inode));
01127848
JK
4193 if (offset > size || offset + len < size)
4194 return 0;
4195
4196 if (EXT4_I(inode)->i_disksize >= size)
4197 return 0;
4198
4199 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4200 if (IS_ERR(handle))
4201 return PTR_ERR(handle);
4202 ext4_update_i_disksize(inode, size);
4203 ext4_mark_inode_dirty(handle, inode);
4204 ext4_journal_stop(handle);
4205
4206 return 0;
4207}
4208
b1f38217 4209static void ext4_wait_dax_page(struct ext4_inode_info *ei)
430657b6 4210{
430657b6
RZ
4211 up_write(&ei->i_mmap_sem);
4212 schedule();
4213 down_write(&ei->i_mmap_sem);
4214}
4215
4216int ext4_break_layouts(struct inode *inode)
4217{
4218 struct ext4_inode_info *ei = EXT4_I(inode);
4219 struct page *page;
430657b6
RZ
4220 int error;
4221
4222 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
4223 return -EINVAL;
4224
4225 do {
430657b6
RZ
4226 page = dax_layout_busy_page(inode->i_mapping);
4227 if (!page)
4228 return 0;
4229
4230 error = ___wait_var_event(&page->_refcount,
4231 atomic_read(&page->_refcount) == 1,
4232 TASK_INTERRUPTIBLE, 0, 0,
b1f38217
RZ
4233 ext4_wait_dax_page(ei));
4234 } while (error == 0);
430657b6
RZ
4235
4236 return error;
4237}
4238
a4bb6b64 4239/*
cca32b7e 4240 * ext4_punch_hole: punches a hole in a file by releasing the blocks
a4bb6b64
AH
4241 * associated with the given offset and length
4242 *
4243 * @inode: File inode
4244 * @offset: The offset where the hole will begin
4245 * @len: The length of the hole
4246 *
4907cb7b 4247 * Returns: 0 on success or negative on failure
a4bb6b64
AH
4248 */
4249
aeb2817a 4250int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
a4bb6b64 4251{
26a4c0c6
TT
4252 struct super_block *sb = inode->i_sb;
4253 ext4_lblk_t first_block, stop_block;
4254 struct address_space *mapping = inode->i_mapping;
a87dd18c 4255 loff_t first_block_offset, last_block_offset;
26a4c0c6
TT
4256 handle_t *handle;
4257 unsigned int credits;
4258 int ret = 0;
4259
a4bb6b64 4260 if (!S_ISREG(inode->i_mode))
73355192 4261 return -EOPNOTSUPP;
a4bb6b64 4262
b8a86845 4263 trace_ext4_punch_hole(inode, offset, length, 0);
aaddea81 4264
c1e8220b
TT
4265 ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4266 if (ext4_has_inline_data(inode)) {
4267 down_write(&EXT4_I(inode)->i_mmap_sem);
4268 ret = ext4_convert_inline_data(inode);
4269 up_write(&EXT4_I(inode)->i_mmap_sem);
4270 if (ret)
4271 return ret;
4272 }
4273
26a4c0c6
TT
4274 /*
4275 * Write out all dirty pages to avoid race conditions
4276 * Then release them.
4277 */
cca32b7e 4278 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
26a4c0c6
TT
4279 ret = filemap_write_and_wait_range(mapping, offset,
4280 offset + length - 1);
4281 if (ret)
4282 return ret;
4283 }
4284
5955102c 4285 inode_lock(inode);
9ef06cec 4286
26a4c0c6
TT
4287 /* No need to punch hole beyond i_size */
4288 if (offset >= inode->i_size)
4289 goto out_mutex;
4290
4291 /*
4292 * If the hole extends beyond i_size, set the hole
4293 * to end after the page that contains i_size
4294 */
4295 if (offset + length > inode->i_size) {
4296 length = inode->i_size +
09cbfeaf 4297 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
26a4c0c6
TT
4298 offset;
4299 }
4300
a361293f
JK
4301 if (offset & (sb->s_blocksize - 1) ||
4302 (offset + length) & (sb->s_blocksize - 1)) {
4303 /*
4304 * Attach jinode to inode for jbd2 if we do any zeroing of
4305 * partial block
4306 */
4307 ret = ext4_inode_attach_jinode(inode);
4308 if (ret < 0)
4309 goto out_mutex;
4310
4311 }
4312
ea3d7209 4313 /* Wait all existing dio workers, newcomers will block on i_mutex */
ea3d7209
JK
4314 inode_dio_wait(inode);
4315
4316 /*
4317 * Prevent page faults from reinstantiating pages we have released from
4318 * page cache.
4319 */
4320 down_write(&EXT4_I(inode)->i_mmap_sem);
430657b6
RZ
4321
4322 ret = ext4_break_layouts(inode);
4323 if (ret)
4324 goto out_dio;
4325
a87dd18c
LC
4326 first_block_offset = round_up(offset, sb->s_blocksize);
4327 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
26a4c0c6 4328
a87dd18c 4329 /* Now release the pages and zero block aligned part of pages*/
01127848
JK
4330 if (last_block_offset > first_block_offset) {
4331 ret = ext4_update_disksize_before_punch(inode, offset, length);
4332 if (ret)
4333 goto out_dio;
a87dd18c
LC
4334 truncate_pagecache_range(inode, first_block_offset,
4335 last_block_offset);
01127848 4336 }
26a4c0c6
TT
4337
4338 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4339 credits = ext4_writepage_trans_blocks(inode);
4340 else
4341 credits = ext4_blocks_for_truncate(inode);
4342 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4343 if (IS_ERR(handle)) {
4344 ret = PTR_ERR(handle);
4345 ext4_std_error(sb, ret);
4346 goto out_dio;
4347 }
4348
a87dd18c
LC
4349 ret = ext4_zero_partial_blocks(handle, inode, offset,
4350 length);
4351 if (ret)
4352 goto out_stop;
26a4c0c6
TT
4353
4354 first_block = (offset + sb->s_blocksize - 1) >>
4355 EXT4_BLOCK_SIZE_BITS(sb);
4356 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4357
eee597ac
LC
4358 /* If there are blocks to remove, do it */
4359 if (stop_block > first_block) {
26a4c0c6 4360
eee597ac
LC
4361 down_write(&EXT4_I(inode)->i_data_sem);
4362 ext4_discard_preallocations(inode);
26a4c0c6 4363
eee597ac
LC
4364 ret = ext4_es_remove_extent(inode, first_block,
4365 stop_block - first_block);
4366 if (ret) {
4367 up_write(&EXT4_I(inode)->i_data_sem);
4368 goto out_stop;
4369 }
26a4c0c6 4370
eee597ac
LC
4371 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4372 ret = ext4_ext_remove_space(inode, first_block,
4373 stop_block - 1);
4374 else
4375 ret = ext4_ind_remove_space(handle, inode, first_block,
4376 stop_block);
26a4c0c6 4377
eee597ac
LC
4378 up_write(&EXT4_I(inode)->i_data_sem);
4379 }
26a4c0c6
TT
4380 if (IS_SYNC(inode))
4381 ext4_handle_sync(handle);
e251f9bc 4382
eeca7ea1 4383 inode->i_mtime = inode->i_ctime = current_time(inode);
26a4c0c6 4384 ext4_mark_inode_dirty(handle, inode);
67a7d5f5
JK
4385 if (ret >= 0)
4386 ext4_update_inode_fsync_trans(handle, inode, 1);
26a4c0c6
TT
4387out_stop:
4388 ext4_journal_stop(handle);
4389out_dio:
ea3d7209 4390 up_write(&EXT4_I(inode)->i_mmap_sem);
26a4c0c6 4391out_mutex:
5955102c 4392 inode_unlock(inode);
26a4c0c6 4393 return ret;
a4bb6b64
AH
4394}
4395
a361293f
JK
4396int ext4_inode_attach_jinode(struct inode *inode)
4397{
4398 struct ext4_inode_info *ei = EXT4_I(inode);
4399 struct jbd2_inode *jinode;
4400
4401 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4402 return 0;
4403
4404 jinode = jbd2_alloc_inode(GFP_KERNEL);
4405 spin_lock(&inode->i_lock);
4406 if (!ei->jinode) {
4407 if (!jinode) {
4408 spin_unlock(&inode->i_lock);
4409 return -ENOMEM;
4410 }
4411 ei->jinode = jinode;
4412 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4413 jinode = NULL;
4414 }
4415 spin_unlock(&inode->i_lock);
4416 if (unlikely(jinode != NULL))
4417 jbd2_free_inode(jinode);
4418 return 0;
4419}
4420
ac27a0ec 4421/*
617ba13b 4422 * ext4_truncate()
ac27a0ec 4423 *
617ba13b
MC
4424 * We block out ext4_get_block() block instantiations across the entire
4425 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
ac27a0ec
DK
4426 * simultaneously on behalf of the same inode.
4427 *
42b2aa86 4428 * As we work through the truncate and commit bits of it to the journal there
ac27a0ec
DK
4429 * is one core, guiding principle: the file's tree must always be consistent on
4430 * disk. We must be able to restart the truncate after a crash.
4431 *
4432 * The file's tree may be transiently inconsistent in memory (although it
4433 * probably isn't), but whenever we close off and commit a journal transaction,
4434 * the contents of (the filesystem + the journal) must be consistent and
4435 * restartable. It's pretty simple, really: bottom up, right to left (although
4436 * left-to-right works OK too).
4437 *
4438 * Note that at recovery time, journal replay occurs *before* the restart of
4439 * truncate against the orphan inode list.
4440 *
4441 * The committed inode has the new, desired i_size (which is the same as
617ba13b 4442 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
ac27a0ec 4443 * that this inode's truncate did not complete and it will again call
617ba13b
MC
4444 * ext4_truncate() to have another go. So there will be instantiated blocks
4445 * to the right of the truncation point in a crashed ext4 filesystem. But
ac27a0ec 4446 * that's fine - as long as they are linked from the inode, the post-crash
617ba13b 4447 * ext4_truncate() run will find them and release them.
ac27a0ec 4448 */
2c98eb5e 4449int ext4_truncate(struct inode *inode)
ac27a0ec 4450{
819c4920
TT
4451 struct ext4_inode_info *ei = EXT4_I(inode);
4452 unsigned int credits;
2c98eb5e 4453 int err = 0;
819c4920
TT
4454 handle_t *handle;
4455 struct address_space *mapping = inode->i_mapping;
819c4920 4456
19b5ef61
TT
4457 /*
4458 * There is a possibility that we're either freeing the inode
e04027e8 4459 * or it's a completely new inode. In those cases we might not
19b5ef61
TT
4460 * have i_mutex locked because it's not necessary.
4461 */
4462 if (!(inode->i_state & (I_NEW|I_FREEING)))
5955102c 4463 WARN_ON(!inode_is_locked(inode));
0562e0ba
JZ
4464 trace_ext4_truncate_enter(inode);
4465
91ef4caf 4466 if (!ext4_can_truncate(inode))
2c98eb5e 4467 return 0;
ac27a0ec 4468
12e9b892 4469 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
c8d46e41 4470
5534fb5b 4471 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
19f5fb7a 4472 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
7d8f9f7d 4473
aef1c851
TM
4474 if (ext4_has_inline_data(inode)) {
4475 int has_inline = 1;
4476
01daf945
TT
4477 err = ext4_inline_data_truncate(inode, &has_inline);
4478 if (err)
4479 return err;
aef1c851 4480 if (has_inline)
2c98eb5e 4481 return 0;
aef1c851
TM
4482 }
4483
a361293f
JK
4484 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4485 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4486 if (ext4_inode_attach_jinode(inode) < 0)
2c98eb5e 4487 return 0;
a361293f
JK
4488 }
4489
819c4920
TT
4490 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4491 credits = ext4_writepage_trans_blocks(inode);
4492 else
4493 credits = ext4_blocks_for_truncate(inode);
4494
4495 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
2c98eb5e
TT
4496 if (IS_ERR(handle))
4497 return PTR_ERR(handle);
819c4920 4498
eb3544c6
LC
4499 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4500 ext4_block_truncate_page(handle, mapping, inode->i_size);
819c4920
TT
4501
4502 /*
4503 * We add the inode to the orphan list, so that if this
4504 * truncate spans multiple transactions, and we crash, we will
4505 * resume the truncate when the filesystem recovers. It also
4506 * marks the inode dirty, to catch the new size.
4507 *
4508 * Implication: the file must always be in a sane, consistent
4509 * truncatable state while each transaction commits.
4510 */
2c98eb5e
TT
4511 err = ext4_orphan_add(handle, inode);
4512 if (err)
819c4920
TT
4513 goto out_stop;
4514
4515 down_write(&EXT4_I(inode)->i_data_sem);
4516
4517 ext4_discard_preallocations(inode);
4518
ff9893dc 4519 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
d0abb36d 4520 err = ext4_ext_truncate(handle, inode);
ff9893dc 4521 else
819c4920
TT
4522 ext4_ind_truncate(handle, inode);
4523
4524 up_write(&ei->i_data_sem);
d0abb36d
TT
4525 if (err)
4526 goto out_stop;
819c4920
TT
4527
4528 if (IS_SYNC(inode))
4529 ext4_handle_sync(handle);
4530
4531out_stop:
4532 /*
4533 * If this was a simple ftruncate() and the file will remain alive,
4534 * then we need to clear up the orphan record which we created above.
4535 * However, if this was a real unlink then we were called by
58d86a50 4536 * ext4_evict_inode(), and we allow that function to clean up the
819c4920
TT
4537 * orphan info for us.
4538 */
4539 if (inode->i_nlink)
4540 ext4_orphan_del(handle, inode);
4541
eeca7ea1 4542 inode->i_mtime = inode->i_ctime = current_time(inode);
819c4920
TT
4543 ext4_mark_inode_dirty(handle, inode);
4544 ext4_journal_stop(handle);
ac27a0ec 4545
0562e0ba 4546 trace_ext4_truncate_exit(inode);
2c98eb5e 4547 return err;
ac27a0ec
DK
4548}
4549
ac27a0ec 4550/*
617ba13b 4551 * ext4_get_inode_loc returns with an extra refcount against the inode's
ac27a0ec
DK
4552 * underlying buffer_head on success. If 'in_mem' is true, we have all
4553 * data in memory that is needed to recreate the on-disk version of this
4554 * inode.
4555 */
617ba13b
MC
4556static int __ext4_get_inode_loc(struct inode *inode,
4557 struct ext4_iloc *iloc, int in_mem)
ac27a0ec 4558{
240799cd
TT
4559 struct ext4_group_desc *gdp;
4560 struct buffer_head *bh;
4561 struct super_block *sb = inode->i_sb;
4562 ext4_fsblk_t block;
02f03c42 4563 struct blk_plug plug;
240799cd
TT
4564 int inodes_per_block, inode_offset;
4565
3a06d778 4566 iloc->bh = NULL;
c37e9e01
TT
4567 if (inode->i_ino < EXT4_ROOT_INO ||
4568 inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
6a797d27 4569 return -EFSCORRUPTED;
ac27a0ec 4570
240799cd
TT
4571 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4572 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4573 if (!gdp)
ac27a0ec
DK
4574 return -EIO;
4575
240799cd
TT
4576 /*
4577 * Figure out the offset within the block group inode table
4578 */
00d09882 4579 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
240799cd
TT
4580 inode_offset = ((inode->i_ino - 1) %
4581 EXT4_INODES_PER_GROUP(sb));
4582 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4583 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4584
4585 bh = sb_getblk(sb, block);
aebf0243 4586 if (unlikely(!bh))
860d21e2 4587 return -ENOMEM;
ac27a0ec
DK
4588 if (!buffer_uptodate(bh)) {
4589 lock_buffer(bh);
9c83a923
HK
4590
4591 /*
4592 * If the buffer has the write error flag, we have failed
4593 * to write out another inode in the same block. In this
4594 * case, we don't have to read the block because we may
4595 * read the old inode data successfully.
4596 */
4597 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4598 set_buffer_uptodate(bh);
4599
ac27a0ec
DK
4600 if (buffer_uptodate(bh)) {
4601 /* someone brought it uptodate while we waited */
4602 unlock_buffer(bh);
4603 goto has_buffer;
4604 }
4605
4606 /*
4607 * If we have all information of the inode in memory and this
4608 * is the only valid inode in the block, we need not read the
4609 * block.
4610 */
4611 if (in_mem) {
4612 struct buffer_head *bitmap_bh;
240799cd 4613 int i, start;
ac27a0ec 4614
240799cd 4615 start = inode_offset & ~(inodes_per_block - 1);
ac27a0ec 4616
240799cd
TT
4617 /* Is the inode bitmap in cache? */
4618 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
aebf0243 4619 if (unlikely(!bitmap_bh))
ac27a0ec
DK
4620 goto make_io;
4621
4622 /*
4623 * If the inode bitmap isn't in cache then the
4624 * optimisation may end up performing two reads instead
4625 * of one, so skip it.
4626 */
4627 if (!buffer_uptodate(bitmap_bh)) {
4628 brelse(bitmap_bh);
4629 goto make_io;
4630 }
240799cd 4631 for (i = start; i < start + inodes_per_block; i++) {
ac27a0ec
DK
4632 if (i == inode_offset)
4633 continue;
617ba13b 4634 if (ext4_test_bit(i, bitmap_bh->b_data))
ac27a0ec
DK
4635 break;
4636 }
4637 brelse(bitmap_bh);
240799cd 4638 if (i == start + inodes_per_block) {
ac27a0ec
DK
4639 /* all other inodes are free, so skip I/O */
4640 memset(bh->b_data, 0, bh->b_size);
4641 set_buffer_uptodate(bh);
4642 unlock_buffer(bh);
4643 goto has_buffer;
4644 }
4645 }
4646
4647make_io:
240799cd
TT
4648 /*
4649 * If we need to do any I/O, try to pre-readahead extra
4650 * blocks from the inode table.
4651 */
02f03c42 4652 blk_start_plug(&plug);
240799cd
TT
4653 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4654 ext4_fsblk_t b, end, table;
4655 unsigned num;
0d606e2c 4656 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
240799cd
TT
4657
4658 table = ext4_inode_table(sb, gdp);
b713a5ec 4659 /* s_inode_readahead_blks is always a power of 2 */
0d606e2c 4660 b = block & ~((ext4_fsblk_t) ra_blks - 1);
240799cd
TT
4661 if (table > b)
4662 b = table;
0d606e2c 4663 end = b + ra_blks;
240799cd 4664 num = EXT4_INODES_PER_GROUP(sb);
feb0ab32 4665 if (ext4_has_group_desc_csum(sb))
560671a0 4666 num -= ext4_itable_unused_count(sb, gdp);
240799cd
TT
4667 table += num / inodes_per_block;
4668 if (end > table)
4669 end = table;
4670 while (b <= end)
4671 sb_breadahead(sb, b++);
4672 }
4673
ac27a0ec
DK
4674 /*
4675 * There are other valid inodes in the buffer, this inode
4676 * has in-inode xattrs, or we don't have this inode in memory.
4677 * Read the block from disk.
4678 */
0562e0ba 4679 trace_ext4_load_inode(inode);
ac27a0ec
DK
4680 get_bh(bh);
4681 bh->b_end_io = end_buffer_read_sync;
2a222ca9 4682 submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
02f03c42 4683 blk_finish_plug(&plug);
ac27a0ec
DK
4684 wait_on_buffer(bh);
4685 if (!buffer_uptodate(bh)) {
c398eda0
TT
4686 EXT4_ERROR_INODE_BLOCK(inode, block,
4687 "unable to read itable block");
ac27a0ec
DK
4688 brelse(bh);
4689 return -EIO;
4690 }
4691 }
4692has_buffer:
4693 iloc->bh = bh;
4694 return 0;
4695}
4696
617ba13b 4697int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
ac27a0ec
DK
4698{
4699 /* We have all inode data except xattrs in memory here. */
617ba13b 4700 return __ext4_get_inode_loc(inode, iloc,
19f5fb7a 4701 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
ac27a0ec
DK
4702}
4703
6642586b
RZ
4704static bool ext4_should_use_dax(struct inode *inode)
4705{
4706 if (!test_opt(inode->i_sb, DAX))
4707 return false;
4708 if (!S_ISREG(inode->i_mode))
4709 return false;
4710 if (ext4_should_journal_data(inode))
4711 return false;
4712 if (ext4_has_inline_data(inode))
4713 return false;
592ddec7 4714 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
6642586b 4715 return false;
c93d8f88
EB
4716 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4717 return false;
6642586b
RZ
4718 return true;
4719}
4720
617ba13b 4721void ext4_set_inode_flags(struct inode *inode)
ac27a0ec 4722{
617ba13b 4723 unsigned int flags = EXT4_I(inode)->i_flags;
00a1a053 4724 unsigned int new_fl = 0;
ac27a0ec 4725
617ba13b 4726 if (flags & EXT4_SYNC_FL)
00a1a053 4727 new_fl |= S_SYNC;
617ba13b 4728 if (flags & EXT4_APPEND_FL)
00a1a053 4729 new_fl |= S_APPEND;
617ba13b 4730 if (flags & EXT4_IMMUTABLE_FL)
00a1a053 4731 new_fl |= S_IMMUTABLE;
617ba13b 4732 if (flags & EXT4_NOATIME_FL)
00a1a053 4733 new_fl |= S_NOATIME;
617ba13b 4734 if (flags & EXT4_DIRSYNC_FL)
00a1a053 4735 new_fl |= S_DIRSYNC;
6642586b 4736 if (ext4_should_use_dax(inode))
923ae0ff 4737 new_fl |= S_DAX;
2ee6a576
EB
4738 if (flags & EXT4_ENCRYPT_FL)
4739 new_fl |= S_ENCRYPTED;
b886ee3e
GKB
4740 if (flags & EXT4_CASEFOLD_FL)
4741 new_fl |= S_CASEFOLD;
c93d8f88
EB
4742 if (flags & EXT4_VERITY_FL)
4743 new_fl |= S_VERITY;
5f16f322 4744 inode_set_flags(inode, new_fl,
2ee6a576 4745 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
c93d8f88 4746 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
ac27a0ec
DK
4747}
4748
0fc1b451 4749static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
de9a55b8 4750 struct ext4_inode_info *ei)
0fc1b451
AK
4751{
4752 blkcnt_t i_blocks ;
8180a562
AK
4753 struct inode *inode = &(ei->vfs_inode);
4754 struct super_block *sb = inode->i_sb;
0fc1b451 4755
e2b911c5 4756 if (ext4_has_feature_huge_file(sb)) {
0fc1b451
AK
4757 /* we are using combined 48 bit field */
4758 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4759 le32_to_cpu(raw_inode->i_blocks_lo);
07a03824 4760 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
8180a562
AK
4761 /* i_blocks represent file system block size */
4762 return i_blocks << (inode->i_blkbits - 9);
4763 } else {
4764 return i_blocks;
4765 }
0fc1b451
AK
4766 } else {
4767 return le32_to_cpu(raw_inode->i_blocks_lo);
4768 }
4769}
ff9ddf7e 4770
eb9b5f01 4771static inline int ext4_iget_extra_inode(struct inode *inode,
152a7b0a
TM
4772 struct ext4_inode *raw_inode,
4773 struct ext4_inode_info *ei)
4774{
4775 __le32 *magic = (void *)raw_inode +
4776 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
eb9b5f01 4777
290ab230
EB
4778 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4779 EXT4_INODE_SIZE(inode->i_sb) &&
4780 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
152a7b0a 4781 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
eb9b5f01 4782 return ext4_find_inline_data_nolock(inode);
f19d5870
TM
4783 } else
4784 EXT4_I(inode)->i_inline_off = 0;
eb9b5f01 4785 return 0;
152a7b0a
TM
4786}
4787
040cb378
LX
4788int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4789{
0b7b7779 4790 if (!ext4_has_feature_project(inode->i_sb))
040cb378
LX
4791 return -EOPNOTSUPP;
4792 *projid = EXT4_I(inode)->i_projid;
4793 return 0;
4794}
4795
e254d1af
EG
4796/*
4797 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4798 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4799 * set.
4800 */
4801static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4802{
4803 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4804 inode_set_iversion_raw(inode, val);
4805 else
4806 inode_set_iversion_queried(inode, val);
4807}
4808static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4809{
4810 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4811 return inode_peek_iversion_raw(inode);
4812 else
4813 return inode_peek_iversion(inode);
4814}
4815
8a363970
TT
4816struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4817 ext4_iget_flags flags, const char *function,
4818 unsigned int line)
ac27a0ec 4819{
617ba13b
MC
4820 struct ext4_iloc iloc;
4821 struct ext4_inode *raw_inode;
1d1fe1ee 4822 struct ext4_inode_info *ei;
1d1fe1ee 4823 struct inode *inode;
b436b9be 4824 journal_t *journal = EXT4_SB(sb)->s_journal;
1d1fe1ee 4825 long ret;
7e6e1ef4 4826 loff_t size;
ac27a0ec 4827 int block;
08cefc7a
EB
4828 uid_t i_uid;
4829 gid_t i_gid;
040cb378 4830 projid_t i_projid;
ac27a0ec 4831
191ce178 4832 if ((!(flags & EXT4_IGET_SPECIAL) &&
8a363970
TT
4833 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4834 (ino < EXT4_ROOT_INO) ||
4835 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4836 if (flags & EXT4_IGET_HANDLE)
4837 return ERR_PTR(-ESTALE);
4838 __ext4_error(sb, function, line,
4839 "inode #%lu: comm %s: iget: illegal inode #",
4840 ino, current->comm);
4841 return ERR_PTR(-EFSCORRUPTED);
4842 }
4843
1d1fe1ee
DH
4844 inode = iget_locked(sb, ino);
4845 if (!inode)
4846 return ERR_PTR(-ENOMEM);
4847 if (!(inode->i_state & I_NEW))
4848 return inode;
4849
4850 ei = EXT4_I(inode);
7dc57615 4851 iloc.bh = NULL;
ac27a0ec 4852
1d1fe1ee
DH
4853 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4854 if (ret < 0)
ac27a0ec 4855 goto bad_inode;
617ba13b 4856 raw_inode = ext4_raw_inode(&iloc);
814525f4 4857
8e4b5eae 4858 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
8a363970
TT
4859 ext4_error_inode(inode, function, line, 0,
4860 "iget: root inode unallocated");
8e4b5eae
TT
4861 ret = -EFSCORRUPTED;
4862 goto bad_inode;
4863 }
4864
8a363970
TT
4865 if ((flags & EXT4_IGET_HANDLE) &&
4866 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4867 ret = -ESTALE;
4868 goto bad_inode;
4869 }
4870
814525f4
DW
4871 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4872 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4873 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
2dc8d9e1
EB
4874 EXT4_INODE_SIZE(inode->i_sb) ||
4875 (ei->i_extra_isize & 3)) {
8a363970
TT
4876 ext4_error_inode(inode, function, line, 0,
4877 "iget: bad extra_isize %u "
4878 "(inode size %u)",
2dc8d9e1
EB
4879 ei->i_extra_isize,
4880 EXT4_INODE_SIZE(inode->i_sb));
6a797d27 4881 ret = -EFSCORRUPTED;
814525f4
DW
4882 goto bad_inode;
4883 }
4884 } else
4885 ei->i_extra_isize = 0;
4886
4887 /* Precompute checksum seed for inode metadata */
9aa5d32b 4888 if (ext4_has_metadata_csum(sb)) {
814525f4
DW
4889 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4890 __u32 csum;
4891 __le32 inum = cpu_to_le32(inode->i_ino);
4892 __le32 gen = raw_inode->i_generation;
4893 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4894 sizeof(inum));
4895 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4896 sizeof(gen));
4897 }
4898
4899 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
8a363970
TT
4900 ext4_error_inode(inode, function, line, 0,
4901 "iget: checksum invalid");
6a797d27 4902 ret = -EFSBADCRC;
814525f4
DW
4903 goto bad_inode;
4904 }
4905
ac27a0ec 4906 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
08cefc7a
EB
4907 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4908 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
0b7b7779 4909 if (ext4_has_feature_project(sb) &&
040cb378
LX
4910 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4911 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4912 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4913 else
4914 i_projid = EXT4_DEF_PROJID;
4915
af5bc92d 4916 if (!(test_opt(inode->i_sb, NO_UID32))) {
08cefc7a
EB
4917 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4918 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
ac27a0ec 4919 }
08cefc7a
EB
4920 i_uid_write(inode, i_uid);
4921 i_gid_write(inode, i_gid);
040cb378 4922 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
bfe86848 4923 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
ac27a0ec 4924
353eb83c 4925 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
67cf5b09 4926 ei->i_inline_off = 0;
ac27a0ec
DK
4927 ei->i_dir_start_lookup = 0;
4928 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4929 /* We now have enough fields to check if the inode was active or not.
4930 * This is needed because nfsd might try to access dead inodes
4931 * the test is that same one that e2fsck uses
4932 * NeilBrown 1999oct15
4933 */
4934 if (inode->i_nlink == 0) {
393d1d1d
DTB
4935 if ((inode->i_mode == 0 ||
4936 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4937 ino != EXT4_BOOT_LOADER_INO) {
ac27a0ec 4938 /* this inode is deleted */
1d1fe1ee 4939 ret = -ESTALE;
ac27a0ec
DK
4940 goto bad_inode;
4941 }
4942 /* The only unlinked inodes we let through here have
4943 * valid i_mode and are being read by the orphan
4944 * recovery code: that's fine, we're about to complete
393d1d1d
DTB
4945 * the process of deleting those.
4946 * OR it is the EXT4_BOOT_LOADER_INO which is
4947 * not initialized on a new filesystem. */
ac27a0ec 4948 }
ac27a0ec 4949 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
cce6c9f7 4950 ext4_set_inode_flags(inode);
0fc1b451 4951 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
7973c0c1 4952 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
e2b911c5 4953 if (ext4_has_feature_64bit(sb))
a1ddeb7e
BP
4954 ei->i_file_acl |=
4955 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
e08ac99f 4956 inode->i_size = ext4_isize(sb, raw_inode);
7e6e1ef4 4957 if ((size = i_size_read(inode)) < 0) {
8a363970
TT
4958 ext4_error_inode(inode, function, line, 0,
4959 "iget: bad i_size value: %lld", size);
7e6e1ef4
DW
4960 ret = -EFSCORRUPTED;
4961 goto bad_inode;
4962 }
ac27a0ec 4963 ei->i_disksize = inode->i_size;
a9e7f447
DM
4964#ifdef CONFIG_QUOTA
4965 ei->i_reserved_quota = 0;
4966#endif
ac27a0ec
DK
4967 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4968 ei->i_block_group = iloc.block_group;
a4912123 4969 ei->i_last_alloc_group = ~0;
ac27a0ec
DK
4970 /*
4971 * NOTE! The in-memory inode i_data array is in little-endian order
4972 * even on big-endian machines: we do NOT byteswap the block numbers!
4973 */
617ba13b 4974 for (block = 0; block < EXT4_N_BLOCKS; block++)
ac27a0ec
DK
4975 ei->i_data[block] = raw_inode->i_block[block];
4976 INIT_LIST_HEAD(&ei->i_orphan);
4977
b436b9be
JK
4978 /*
4979 * Set transaction id's of transactions that have to be committed
4980 * to finish f[data]sync. We set them to currently running transaction
4981 * as we cannot be sure that the inode or some of its metadata isn't
4982 * part of the transaction - the inode could have been reclaimed and
4983 * now it is reread from disk.
4984 */
4985 if (journal) {
4986 transaction_t *transaction;
4987 tid_t tid;
4988
a931da6a 4989 read_lock(&journal->j_state_lock);
b436b9be
JK
4990 if (journal->j_running_transaction)
4991 transaction = journal->j_running_transaction;
4992 else
4993 transaction = journal->j_committing_transaction;
4994 if (transaction)
4995 tid = transaction->t_tid;
4996 else
4997 tid = journal->j_commit_sequence;
a931da6a 4998 read_unlock(&journal->j_state_lock);
b436b9be
JK
4999 ei->i_sync_tid = tid;
5000 ei->i_datasync_tid = tid;
5001 }
5002
0040d987 5003 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
ac27a0ec
DK
5004 if (ei->i_extra_isize == 0) {
5005 /* The extra space is currently unused. Use it. */
2dc8d9e1 5006 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
617ba13b
MC
5007 ei->i_extra_isize = sizeof(struct ext4_inode) -
5008 EXT4_GOOD_OLD_INODE_SIZE;
ac27a0ec 5009 } else {
eb9b5f01
TT
5010 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
5011 if (ret)
5012 goto bad_inode;
ac27a0ec 5013 }
814525f4 5014 }
ac27a0ec 5015
ef7f3835
KS
5016 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5017 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5018 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5019 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5020
ed3654eb 5021 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
ee73f9a5
JL
5022 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
5023
c4f65706
TT
5024 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5025 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
ee73f9a5 5026 ivers |=
c4f65706
TT
5027 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5028 }
e254d1af 5029 ext4_inode_set_iversion_queried(inode, ivers);
25ec56b5
JNC
5030 }
5031
c4b5a614 5032 ret = 0;
485c26ec 5033 if (ei->i_file_acl &&
1032988c 5034 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
8a363970
TT
5035 ext4_error_inode(inode, function, line, 0,
5036 "iget: bad extended attribute block %llu",
24676da4 5037 ei->i_file_acl);
6a797d27 5038 ret = -EFSCORRUPTED;
485c26ec 5039 goto bad_inode;
f19d5870 5040 } else if (!ext4_has_inline_data(inode)) {
bc716523
LS
5041 /* validate the block references in the inode */
5042 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5043 (S_ISLNK(inode->i_mode) &&
5044 !ext4_inode_is_fast_symlink(inode))) {
5045 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
f19d5870 5046 ret = ext4_ext_check_inode(inode);
bc716523
LS
5047 else
5048 ret = ext4_ind_check_inode(inode);
f19d5870 5049 }
fe2c8191 5050 }
567f3e9a 5051 if (ret)
de9a55b8 5052 goto bad_inode;
7a262f7c 5053
ac27a0ec 5054 if (S_ISREG(inode->i_mode)) {
617ba13b 5055 inode->i_op = &ext4_file_inode_operations;
be64f884 5056 inode->i_fop = &ext4_file_operations;
617ba13b 5057 ext4_set_aops(inode);
ac27a0ec 5058 } else if (S_ISDIR(inode->i_mode)) {
617ba13b
MC
5059 inode->i_op = &ext4_dir_inode_operations;
5060 inode->i_fop = &ext4_dir_operations;
ac27a0ec 5061 } else if (S_ISLNK(inode->i_mode)) {
6390d33b
LR
5062 /* VFS does not allow setting these so must be corruption */
5063 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
8a363970
TT
5064 ext4_error_inode(inode, function, line, 0,
5065 "iget: immutable or append flags "
5066 "not allowed on symlinks");
6390d33b
LR
5067 ret = -EFSCORRUPTED;
5068 goto bad_inode;
5069 }
592ddec7 5070 if (IS_ENCRYPTED(inode)) {
a7a67e8a
AV
5071 inode->i_op = &ext4_encrypted_symlink_inode_operations;
5072 ext4_set_aops(inode);
5073 } else if (ext4_inode_is_fast_symlink(inode)) {
75e7566b 5074 inode->i_link = (char *)ei->i_data;
617ba13b 5075 inode->i_op = &ext4_fast_symlink_inode_operations;
e83c1397
DG
5076 nd_terminate_link(ei->i_data, inode->i_size,
5077 sizeof(ei->i_data) - 1);
5078 } else {
617ba13b
MC
5079 inode->i_op = &ext4_symlink_inode_operations;
5080 ext4_set_aops(inode);
ac27a0ec 5081 }
21fc61c7 5082 inode_nohighmem(inode);
563bdd61
TT
5083 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5084 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
617ba13b 5085 inode->i_op = &ext4_special_inode_operations;
ac27a0ec
DK
5086 if (raw_inode->i_block[0])
5087 init_special_inode(inode, inode->i_mode,
5088 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5089 else
5090 init_special_inode(inode, inode->i_mode,
5091 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
393d1d1d
DTB
5092 } else if (ino == EXT4_BOOT_LOADER_INO) {
5093 make_bad_inode(inode);
563bdd61 5094 } else {
6a797d27 5095 ret = -EFSCORRUPTED;
8a363970
TT
5096 ext4_error_inode(inode, function, line, 0,
5097 "iget: bogus i_mode (%o)", inode->i_mode);
563bdd61 5098 goto bad_inode;
ac27a0ec 5099 }
6456ca65
TT
5100 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
5101 ext4_error_inode(inode, function, line, 0,
5102 "casefold flag without casefold feature");
af5bc92d 5103 brelse(iloc.bh);
dec214d0 5104
1d1fe1ee
DH
5105 unlock_new_inode(inode);
5106 return inode;
ac27a0ec
DK
5107
5108bad_inode:
567f3e9a 5109 brelse(iloc.bh);
1d1fe1ee
DH
5110 iget_failed(inode);
5111 return ERR_PTR(ret);
ac27a0ec
DK
5112}
5113
0fc1b451
AK
5114static int ext4_inode_blocks_set(handle_t *handle,
5115 struct ext4_inode *raw_inode,
5116 struct ext4_inode_info *ei)
5117{
5118 struct inode *inode = &(ei->vfs_inode);
5119 u64 i_blocks = inode->i_blocks;
5120 struct super_block *sb = inode->i_sb;
0fc1b451
AK
5121
5122 if (i_blocks <= ~0U) {
5123 /*
4907cb7b 5124 * i_blocks can be represented in a 32 bit variable
0fc1b451
AK
5125 * as multiple of 512 bytes
5126 */
8180a562 5127 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
0fc1b451 5128 raw_inode->i_blocks_high = 0;
84a8dce2 5129 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
f287a1a5
TT
5130 return 0;
5131 }
e2b911c5 5132 if (!ext4_has_feature_huge_file(sb))
f287a1a5
TT
5133 return -EFBIG;
5134
5135 if (i_blocks <= 0xffffffffffffULL) {
0fc1b451
AK
5136 /*
5137 * i_blocks can be represented in a 48 bit variable
5138 * as multiple of 512 bytes
5139 */
8180a562 5140 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
0fc1b451 5141 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
84a8dce2 5142 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
0fc1b451 5143 } else {
84a8dce2 5144 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
8180a562
AK
5145 /* i_block is stored in file system block size */
5146 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5147 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5148 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
0fc1b451 5149 }
f287a1a5 5150 return 0;
0fc1b451
AK
5151}
5152
a26f4992
TT
5153struct other_inode {
5154 unsigned long orig_ino;
5155 struct ext4_inode *raw_inode;
5156};
5157
5158static int other_inode_match(struct inode * inode, unsigned long ino,
5159 void *data)
5160{
5161 struct other_inode *oi = (struct other_inode *) data;
5162
5163 if ((inode->i_ino != ino) ||
5164 (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
0e11f644 5165 I_DIRTY_INODE)) ||
a26f4992
TT
5166 ((inode->i_state & I_DIRTY_TIME) == 0))
5167 return 0;
5168 spin_lock(&inode->i_lock);
5169 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
0e11f644 5170 I_DIRTY_INODE)) == 0) &&
a26f4992
TT
5171 (inode->i_state & I_DIRTY_TIME)) {
5172 struct ext4_inode_info *ei = EXT4_I(inode);
5173
5174 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
5175 spin_unlock(&inode->i_lock);
5176
5177 spin_lock(&ei->i_raw_lock);
5178 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
5179 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
5180 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
5181 ext4_inode_csum_set(inode, oi->raw_inode, ei);
5182 spin_unlock(&ei->i_raw_lock);
5183 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
5184 return -1;
5185 }
5186 spin_unlock(&inode->i_lock);
5187 return -1;
5188}
5189
5190/*
5191 * Opportunistically update the other time fields for other inodes in
5192 * the same inode table block.
5193 */
5194static void ext4_update_other_inodes_time(struct super_block *sb,
5195 unsigned long orig_ino, char *buf)
5196{
5197 struct other_inode oi;
5198 unsigned long ino;
5199 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5200 int inode_size = EXT4_INODE_SIZE(sb);
5201
5202 oi.orig_ino = orig_ino;
0f0ff9a9
TT
5203 /*
5204 * Calculate the first inode in the inode table block. Inode
5205 * numbers are one-based. That is, the first inode in a block
5206 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5207 */
5208 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
a26f4992
TT
5209 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5210 if (ino == orig_ino)
5211 continue;
5212 oi.raw_inode = (struct ext4_inode *) buf;
5213 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
5214 }
5215}
5216
ac27a0ec
DK
5217/*
5218 * Post the struct inode info into an on-disk inode location in the
5219 * buffer-cache. This gobbles the caller's reference to the
5220 * buffer_head in the inode location struct.
5221 *
5222 * The caller must have write access to iloc->bh.
5223 */
617ba13b 5224static int ext4_do_update_inode(handle_t *handle,
ac27a0ec 5225 struct inode *inode,
830156c7 5226 struct ext4_iloc *iloc)
ac27a0ec 5227{
617ba13b
MC
5228 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5229 struct ext4_inode_info *ei = EXT4_I(inode);
ac27a0ec 5230 struct buffer_head *bh = iloc->bh;
202ee5df 5231 struct super_block *sb = inode->i_sb;
ac27a0ec 5232 int err = 0, rc, block;
202ee5df 5233 int need_datasync = 0, set_large_file = 0;
08cefc7a
EB
5234 uid_t i_uid;
5235 gid_t i_gid;
040cb378 5236 projid_t i_projid;
ac27a0ec 5237
202ee5df
TT
5238 spin_lock(&ei->i_raw_lock);
5239
5240 /* For fields not tracked in the in-memory inode,
ac27a0ec 5241 * initialise them to zero for new inodes. */
19f5fb7a 5242 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
617ba13b 5243 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
ac27a0ec
DK
5244
5245 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
08cefc7a
EB
5246 i_uid = i_uid_read(inode);
5247 i_gid = i_gid_read(inode);
040cb378 5248 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
af5bc92d 5249 if (!(test_opt(inode->i_sb, NO_UID32))) {
08cefc7a
EB
5250 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5251 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
ac27a0ec
DK
5252/*
5253 * Fix up interoperability with old kernels. Otherwise, old inodes get
5254 * re-used with the upper 16 bits of the uid/gid intact
5255 */
93e3b4e6
DJ
5256 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5257 raw_inode->i_uid_high = 0;
5258 raw_inode->i_gid_high = 0;
5259 } else {
ac27a0ec 5260 raw_inode->i_uid_high =
08cefc7a 5261 cpu_to_le16(high_16_bits(i_uid));
ac27a0ec 5262 raw_inode->i_gid_high =
08cefc7a 5263 cpu_to_le16(high_16_bits(i_gid));
ac27a0ec
DK
5264 }
5265 } else {
08cefc7a
EB
5266 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5267 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
ac27a0ec
DK
5268 raw_inode->i_uid_high = 0;
5269 raw_inode->i_gid_high = 0;
5270 }
5271 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
ef7f3835
KS
5272
5273 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5274 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5275 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5276 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5277
bce92d56
LX
5278 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5279 if (err) {
202ee5df 5280 spin_unlock(&ei->i_raw_lock);
0fc1b451 5281 goto out_brelse;
202ee5df 5282 }
ac27a0ec 5283 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
353eb83c 5284 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
ed3654eb 5285 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
a1ddeb7e
BP
5286 raw_inode->i_file_acl_high =
5287 cpu_to_le16(ei->i_file_acl >> 32);
7973c0c1 5288 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
e08ac99f 5289 if (ei->i_disksize != ext4_isize(inode->i_sb, raw_inode)) {
b71fc079
JK
5290 ext4_isize_set(raw_inode, ei->i_disksize);
5291 need_datasync = 1;
5292 }
a48380f7 5293 if (ei->i_disksize > 0x7fffffffULL) {
e2b911c5 5294 if (!ext4_has_feature_large_file(sb) ||
a48380f7 5295 EXT4_SB(sb)->s_es->s_rev_level ==
202ee5df
TT
5296 cpu_to_le32(EXT4_GOOD_OLD_REV))
5297 set_large_file = 1;
ac27a0ec
DK
5298 }
5299 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5300 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5301 if (old_valid_dev(inode->i_rdev)) {
5302 raw_inode->i_block[0] =
5303 cpu_to_le32(old_encode_dev(inode->i_rdev));
5304 raw_inode->i_block[1] = 0;
5305 } else {
5306 raw_inode->i_block[0] = 0;
5307 raw_inode->i_block[1] =
5308 cpu_to_le32(new_encode_dev(inode->i_rdev));
5309 raw_inode->i_block[2] = 0;
5310 }
f19d5870 5311 } else if (!ext4_has_inline_data(inode)) {
de9a55b8
TT
5312 for (block = 0; block < EXT4_N_BLOCKS; block++)
5313 raw_inode->i_block[block] = ei->i_data[block];
f19d5870 5314 }
ac27a0ec 5315
ed3654eb 5316 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
e254d1af 5317 u64 ivers = ext4_inode_peek_iversion(inode);
ee73f9a5
JL
5318
5319 raw_inode->i_disk_version = cpu_to_le32(ivers);
c4f65706
TT
5320 if (ei->i_extra_isize) {
5321 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5322 raw_inode->i_version_hi =
ee73f9a5 5323 cpu_to_le32(ivers >> 32);
c4f65706
TT
5324 raw_inode->i_extra_isize =
5325 cpu_to_le16(ei->i_extra_isize);
5326 }
25ec56b5 5327 }
040cb378 5328
0b7b7779 5329 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
040cb378
LX
5330 i_projid != EXT4_DEF_PROJID);
5331
5332 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5333 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5334 raw_inode->i_projid = cpu_to_le32(i_projid);
5335
814525f4 5336 ext4_inode_csum_set(inode, raw_inode, ei);
202ee5df 5337 spin_unlock(&ei->i_raw_lock);
1751e8a6 5338 if (inode->i_sb->s_flags & SB_LAZYTIME)
a26f4992
TT
5339 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5340 bh->b_data);
202ee5df 5341
830156c7 5342 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
73b50c1c 5343 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
830156c7
FM
5344 if (!err)
5345 err = rc;
19f5fb7a 5346 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
202ee5df 5347 if (set_large_file) {
5d601255 5348 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
202ee5df
TT
5349 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5350 if (err)
5351 goto out_brelse;
e2b911c5 5352 ext4_set_feature_large_file(sb);
202ee5df
TT
5353 ext4_handle_sync(handle);
5354 err = ext4_handle_dirty_super(handle, sb);
5355 }
b71fc079 5356 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
ac27a0ec 5357out_brelse:
af5bc92d 5358 brelse(bh);
617ba13b 5359 ext4_std_error(inode->i_sb, err);
ac27a0ec
DK
5360 return err;
5361}
5362
5363/*
617ba13b 5364 * ext4_write_inode()
ac27a0ec
DK
5365 *
5366 * We are called from a few places:
5367 *
87f7e416 5368 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
ac27a0ec 5369 * Here, there will be no transaction running. We wait for any running
4907cb7b 5370 * transaction to commit.
ac27a0ec 5371 *
87f7e416
TT
5372 * - Within flush work (sys_sync(), kupdate and such).
5373 * We wait on commit, if told to.
ac27a0ec 5374 *
87f7e416
TT
5375 * - Within iput_final() -> write_inode_now()
5376 * We wait on commit, if told to.
ac27a0ec
DK
5377 *
5378 * In all cases it is actually safe for us to return without doing anything,
5379 * because the inode has been copied into a raw inode buffer in
87f7e416
TT
5380 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5381 * writeback.
ac27a0ec
DK
5382 *
5383 * Note that we are absolutely dependent upon all inode dirtiers doing the
5384 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5385 * which we are interested.
5386 *
5387 * It would be a bug for them to not do this. The code:
5388 *
5389 * mark_inode_dirty(inode)
5390 * stuff();
5391 * inode->i_size = expr;
5392 *
87f7e416
TT
5393 * is in error because write_inode() could occur while `stuff()' is running,
5394 * and the new i_size will be lost. Plus the inode will no longer be on the
5395 * superblock's dirty inode list.
ac27a0ec 5396 */
a9185b41 5397int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
ac27a0ec 5398{
91ac6f43
FM
5399 int err;
5400
18f2c4fc
TT
5401 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5402 sb_rdonly(inode->i_sb))
ac27a0ec
DK
5403 return 0;
5404
18f2c4fc
TT
5405 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5406 return -EIO;
5407
91ac6f43
FM
5408 if (EXT4_SB(inode->i_sb)->s_journal) {
5409 if (ext4_journal_current_handle()) {
5410 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5411 dump_stack();
5412 return -EIO;
5413 }
ac27a0ec 5414
10542c22
JK
5415 /*
5416 * No need to force transaction in WB_SYNC_NONE mode. Also
5417 * ext4_sync_fs() will force the commit after everything is
5418 * written.
5419 */
5420 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
91ac6f43
FM
5421 return 0;
5422
18f2c4fc
TT
5423 err = jbd2_complete_transaction(EXT4_SB(inode->i_sb)->s_journal,
5424 EXT4_I(inode)->i_sync_tid);
91ac6f43
FM
5425 } else {
5426 struct ext4_iloc iloc;
ac27a0ec 5427
8b472d73 5428 err = __ext4_get_inode_loc(inode, &iloc, 0);
91ac6f43
FM
5429 if (err)
5430 return err;
10542c22
JK
5431 /*
5432 * sync(2) will flush the whole buffer cache. No need to do
5433 * it here separately for each inode.
5434 */
5435 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
830156c7
FM
5436 sync_dirty_buffer(iloc.bh);
5437 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
c398eda0
TT
5438 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5439 "IO error syncing inode");
830156c7
FM
5440 err = -EIO;
5441 }
fd2dd9fb 5442 brelse(iloc.bh);
91ac6f43
FM
5443 }
5444 return err;
ac27a0ec
DK
5445}
5446
53e87268
JK
5447/*
5448 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5449 * buffers that are attached to a page stradding i_size and are undergoing
5450 * commit. In that case we have to wait for commit to finish and try again.
5451 */
5452static void ext4_wait_for_tail_page_commit(struct inode *inode)
5453{
5454 struct page *page;
5455 unsigned offset;
5456 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5457 tid_t commit_tid = 0;
5458 int ret;
5459
09cbfeaf 5460 offset = inode->i_size & (PAGE_SIZE - 1);
53e87268
JK
5461 /*
5462 * All buffers in the last page remain valid? Then there's nothing to
ea1754a0 5463 * do. We do the check mainly to optimize the common PAGE_SIZE ==
53e87268
JK
5464 * blocksize case
5465 */
93407472 5466 if (offset > PAGE_SIZE - i_blocksize(inode))
53e87268
JK
5467 return;
5468 while (1) {
5469 page = find_lock_page(inode->i_mapping,
09cbfeaf 5470 inode->i_size >> PAGE_SHIFT);
53e87268
JK
5471 if (!page)
5472 return;
ca99fdd2 5473 ret = __ext4_journalled_invalidatepage(page, offset,
09cbfeaf 5474 PAGE_SIZE - offset);
53e87268 5475 unlock_page(page);
09cbfeaf 5476 put_page(page);
53e87268
JK
5477 if (ret != -EBUSY)
5478 return;
5479 commit_tid = 0;
5480 read_lock(&journal->j_state_lock);
5481 if (journal->j_committing_transaction)
5482 commit_tid = journal->j_committing_transaction->t_tid;
5483 read_unlock(&journal->j_state_lock);
5484 if (commit_tid)
5485 jbd2_log_wait_commit(journal, commit_tid);
5486 }
5487}
5488
ac27a0ec 5489/*
617ba13b 5490 * ext4_setattr()
ac27a0ec
DK
5491 *
5492 * Called from notify_change.
5493 *
5494 * We want to trap VFS attempts to truncate the file as soon as
5495 * possible. In particular, we want to make sure that when the VFS
5496 * shrinks i_size, we put the inode on the orphan list and modify
5497 * i_disksize immediately, so that during the subsequent flushing of
5498 * dirty pages and freeing of disk blocks, we can guarantee that any
5499 * commit will leave the blocks being flushed in an unused state on
5500 * disk. (On recovery, the inode will get truncated and the blocks will
5501 * be freed, so we have a strong guarantee that no future commit will
5502 * leave these blocks visible to the user.)
5503 *
678aaf48
JK
5504 * Another thing we have to assure is that if we are in ordered mode
5505 * and inode is still attached to the committing transaction, we must
5506 * we start writeout of all the dirty pages which are being truncated.
5507 * This way we are sure that all the data written in the previous
5508 * transaction are already on disk (truncate waits for pages under
5509 * writeback).
5510 *
5511 * Called with inode->i_mutex down.
ac27a0ec 5512 */
617ba13b 5513int ext4_setattr(struct dentry *dentry, struct iattr *attr)
ac27a0ec 5514{
2b0143b5 5515 struct inode *inode = d_inode(dentry);
ac27a0ec 5516 int error, rc = 0;
3d287de3 5517 int orphan = 0;
ac27a0ec
DK
5518 const unsigned int ia_valid = attr->ia_valid;
5519
0db1ff22
TT
5520 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5521 return -EIO;
5522
02b016ca
TT
5523 if (unlikely(IS_IMMUTABLE(inode)))
5524 return -EPERM;
5525
5526 if (unlikely(IS_APPEND(inode) &&
5527 (ia_valid & (ATTR_MODE | ATTR_UID |
5528 ATTR_GID | ATTR_TIMES_SET))))
5529 return -EPERM;
5530
31051c85 5531 error = setattr_prepare(dentry, attr);
ac27a0ec
DK
5532 if (error)
5533 return error;
5534
3ce2b8dd
EB
5535 error = fscrypt_prepare_setattr(dentry, attr);
5536 if (error)
5537 return error;
5538
c93d8f88
EB
5539 error = fsverity_prepare_setattr(dentry, attr);
5540 if (error)
5541 return error;
5542
a7cdadee
JK
5543 if (is_quota_modification(inode, attr)) {
5544 error = dquot_initialize(inode);
5545 if (error)
5546 return error;
5547 }
08cefc7a
EB
5548 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5549 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
ac27a0ec
DK
5550 handle_t *handle;
5551
5552 /* (user+group)*(old+new) structure, inode write (sb,
5553 * inode block, ? - but truncate inode update has it) */
9924a92a
TT
5554 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5555 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5556 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
ac27a0ec
DK
5557 if (IS_ERR(handle)) {
5558 error = PTR_ERR(handle);
5559 goto err_out;
5560 }
7a9ca53a
TE
5561
5562 /* dquot_transfer() calls back ext4_get_inode_usage() which
5563 * counts xattr inode references.
5564 */
5565 down_read(&EXT4_I(inode)->xattr_sem);
b43fa828 5566 error = dquot_transfer(inode, attr);
7a9ca53a
TE
5567 up_read(&EXT4_I(inode)->xattr_sem);
5568
ac27a0ec 5569 if (error) {
617ba13b 5570 ext4_journal_stop(handle);
ac27a0ec
DK
5571 return error;
5572 }
5573 /* Update corresponding info in inode so that everything is in
5574 * one transaction */
5575 if (attr->ia_valid & ATTR_UID)
5576 inode->i_uid = attr->ia_uid;
5577 if (attr->ia_valid & ATTR_GID)
5578 inode->i_gid = attr->ia_gid;
617ba13b
MC
5579 error = ext4_mark_inode_dirty(handle, inode);
5580 ext4_journal_stop(handle);
ac27a0ec
DK
5581 }
5582
3da40c7b 5583 if (attr->ia_valid & ATTR_SIZE) {
5208386c 5584 handle_t *handle;
3da40c7b 5585 loff_t oldsize = inode->i_size;
b9c1c267 5586 int shrink = (attr->ia_size < inode->i_size);
562c72aa 5587
12e9b892 5588 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
e2b46574
ES
5589 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5590
0c095c7f
TT
5591 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5592 return -EFBIG;
e2b46574 5593 }
3da40c7b
JB
5594 if (!S_ISREG(inode->i_mode))
5595 return -EINVAL;
dff6efc3
CH
5596
5597 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5598 inode_inc_iversion(inode);
5599
b9c1c267
JK
5600 if (shrink) {
5601 if (ext4_should_order_data(inode)) {
5602 error = ext4_begin_ordered_truncate(inode,
678aaf48 5603 attr->ia_size);
b9c1c267
JK
5604 if (error)
5605 goto err_out;
5606 }
5607 /*
5608 * Blocks are going to be removed from the inode. Wait
5609 * for dio in flight.
5610 */
5611 inode_dio_wait(inode);
5612 }
5613
5614 down_write(&EXT4_I(inode)->i_mmap_sem);
5615
5616 rc = ext4_break_layouts(inode);
5617 if (rc) {
5618 up_write(&EXT4_I(inode)->i_mmap_sem);
5619 return rc;
3da40c7b 5620 }
b9c1c267 5621
3da40c7b 5622 if (attr->ia_size != inode->i_size) {
5208386c
JK
5623 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5624 if (IS_ERR(handle)) {
5625 error = PTR_ERR(handle);
b9c1c267 5626 goto out_mmap_sem;
5208386c 5627 }
3da40c7b 5628 if (ext4_handle_valid(handle) && shrink) {
5208386c
JK
5629 error = ext4_orphan_add(handle, inode);
5630 orphan = 1;
5631 }
911af577
EG
5632 /*
5633 * Update c/mtime on truncate up, ext4_truncate() will
5634 * update c/mtime in shrink case below
5635 */
5636 if (!shrink) {
eeca7ea1 5637 inode->i_mtime = current_time(inode);
911af577
EG
5638 inode->i_ctime = inode->i_mtime;
5639 }
90e775b7 5640 down_write(&EXT4_I(inode)->i_data_sem);
5208386c
JK
5641 EXT4_I(inode)->i_disksize = attr->ia_size;
5642 rc = ext4_mark_inode_dirty(handle, inode);
5643 if (!error)
5644 error = rc;
90e775b7
JK
5645 /*
5646 * We have to update i_size under i_data_sem together
5647 * with i_disksize to avoid races with writeback code
5648 * running ext4_wb_update_i_disksize().
5649 */
5650 if (!error)
5651 i_size_write(inode, attr->ia_size);
5652 up_write(&EXT4_I(inode)->i_data_sem);
5208386c 5653 ext4_journal_stop(handle);
b9c1c267
JK
5654 if (error)
5655 goto out_mmap_sem;
5656 if (!shrink) {
5657 pagecache_isize_extended(inode, oldsize,
5658 inode->i_size);
5659 } else if (ext4_should_journal_data(inode)) {
5660 ext4_wait_for_tail_page_commit(inode);
678aaf48 5661 }
d6320cbf 5662 }
430657b6 5663
5208386c
JK
5664 /*
5665 * Truncate pagecache after we've waited for commit
5666 * in data=journal mode to make pages freeable.
5667 */
923ae0ff 5668 truncate_pagecache(inode, inode->i_size);
b9c1c267
JK
5669 /*
5670 * Call ext4_truncate() even if i_size didn't change to
5671 * truncate possible preallocated blocks.
5672 */
5673 if (attr->ia_size <= oldsize) {
2c98eb5e
TT
5674 rc = ext4_truncate(inode);
5675 if (rc)
5676 error = rc;
5677 }
b9c1c267 5678out_mmap_sem:
ea3d7209 5679 up_write(&EXT4_I(inode)->i_mmap_sem);
072bd7ea 5680 }
ac27a0ec 5681
2c98eb5e 5682 if (!error) {
1025774c
CH
5683 setattr_copy(inode, attr);
5684 mark_inode_dirty(inode);
5685 }
5686
5687 /*
5688 * If the call to ext4_truncate failed to get a transaction handle at
5689 * all, we need to clean up the in-core orphan list manually.
5690 */
3d287de3 5691 if (orphan && inode->i_nlink)
617ba13b 5692 ext4_orphan_del(NULL, inode);
ac27a0ec 5693
2c98eb5e 5694 if (!error && (ia_valid & ATTR_MODE))
64e178a7 5695 rc = posix_acl_chmod(inode, inode->i_mode);
ac27a0ec
DK
5696
5697err_out:
617ba13b 5698 ext4_std_error(inode->i_sb, error);
ac27a0ec
DK
5699 if (!error)
5700 error = rc;
5701 return error;
5702}
5703
a528d35e
DH
5704int ext4_getattr(const struct path *path, struct kstat *stat,
5705 u32 request_mask, unsigned int query_flags)
3e3398a0 5706{
99652ea5
DH
5707 struct inode *inode = d_inode(path->dentry);
5708 struct ext4_inode *raw_inode;
5709 struct ext4_inode_info *ei = EXT4_I(inode);
5710 unsigned int flags;
5711
5712 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5713 stat->result_mask |= STATX_BTIME;
5714 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5715 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5716 }
5717
5718 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5719 if (flags & EXT4_APPEND_FL)
5720 stat->attributes |= STATX_ATTR_APPEND;
5721 if (flags & EXT4_COMPR_FL)
5722 stat->attributes |= STATX_ATTR_COMPRESSED;
5723 if (flags & EXT4_ENCRYPT_FL)
5724 stat->attributes |= STATX_ATTR_ENCRYPTED;
5725 if (flags & EXT4_IMMUTABLE_FL)
5726 stat->attributes |= STATX_ATTR_IMMUTABLE;
5727 if (flags & EXT4_NODUMP_FL)
5728 stat->attributes |= STATX_ATTR_NODUMP;
3e3398a0 5729
3209f68b
DH
5730 stat->attributes_mask |= (STATX_ATTR_APPEND |
5731 STATX_ATTR_COMPRESSED |
5732 STATX_ATTR_ENCRYPTED |
5733 STATX_ATTR_IMMUTABLE |
5734 STATX_ATTR_NODUMP);
5735
3e3398a0 5736 generic_fillattr(inode, stat);
99652ea5
DH
5737 return 0;
5738}
5739
5740int ext4_file_getattr(const struct path *path, struct kstat *stat,
5741 u32 request_mask, unsigned int query_flags)
5742{
5743 struct inode *inode = d_inode(path->dentry);
5744 u64 delalloc_blocks;
5745
5746 ext4_getattr(path, stat, request_mask, query_flags);
3e3398a0 5747
9206c561
AD
5748 /*
5749 * If there is inline data in the inode, the inode will normally not
5750 * have data blocks allocated (it may have an external xattr block).
5751 * Report at least one sector for such files, so tools like tar, rsync,
d67d64f4 5752 * others don't incorrectly think the file is completely sparse.
9206c561
AD
5753 */
5754 if (unlikely(ext4_has_inline_data(inode)))
5755 stat->blocks += (stat->size + 511) >> 9;
5756
3e3398a0
MC
5757 /*
5758 * We can't update i_blocks if the block allocation is delayed
5759 * otherwise in the case of system crash before the real block
5760 * allocation is done, we will have i_blocks inconsistent with
5761 * on-disk file blocks.
5762 * We always keep i_blocks updated together with real
5763 * allocation. But to not confuse with user, stat
5764 * will return the blocks that include the delayed allocation
5765 * blocks for this file.
5766 */
96607551 5767 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
9206c561
AD
5768 EXT4_I(inode)->i_reserved_data_blocks);
5769 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
3e3398a0
MC
5770 return 0;
5771}
ac27a0ec 5772
fffb2739
JK
5773static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5774 int pextents)
a02908f1 5775{
12e9b892 5776 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
fffb2739
JK
5777 return ext4_ind_trans_blocks(inode, lblocks);
5778 return ext4_ext_index_trans_blocks(inode, pextents);
a02908f1 5779}
ac51d837 5780
ac27a0ec 5781/*
a02908f1
MC
5782 * Account for index blocks, block groups bitmaps and block group
5783 * descriptor blocks if modify datablocks and index blocks
5784 * worse case, the indexs blocks spread over different block groups
ac27a0ec 5785 *
a02908f1 5786 * If datablocks are discontiguous, they are possible to spread over
4907cb7b 5787 * different block groups too. If they are contiguous, with flexbg,
a02908f1 5788 * they could still across block group boundary.
ac27a0ec 5789 *
a02908f1
MC
5790 * Also account for superblock, inode, quota and xattr blocks
5791 */
dec214d0 5792static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
fffb2739 5793 int pextents)
a02908f1 5794{
8df9675f
TT
5795 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5796 int gdpblocks;
a02908f1
MC
5797 int idxblocks;
5798 int ret = 0;
5799
5800 /*
fffb2739
JK
5801 * How many index blocks need to touch to map @lblocks logical blocks
5802 * to @pextents physical extents?
a02908f1 5803 */
fffb2739 5804 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
a02908f1
MC
5805
5806 ret = idxblocks;
5807
5808 /*
5809 * Now let's see how many group bitmaps and group descriptors need
5810 * to account
5811 */
fffb2739 5812 groups = idxblocks + pextents;
a02908f1 5813 gdpblocks = groups;
8df9675f
TT
5814 if (groups > ngroups)
5815 groups = ngroups;
a02908f1
MC
5816 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5817 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5818
5819 /* bitmaps and block group descriptor blocks */
5820 ret += groups + gdpblocks;
5821
5822 /* Blocks for super block, inode, quota and xattr blocks */
5823 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5824
5825 return ret;
5826}
5827
5828/*
25985edc 5829 * Calculate the total number of credits to reserve to fit
f3bd1f3f
MC
5830 * the modification of a single pages into a single transaction,
5831 * which may include multiple chunks of block allocations.
ac27a0ec 5832 *
525f4ed8 5833 * This could be called via ext4_write_begin()
ac27a0ec 5834 *
525f4ed8 5835 * We need to consider the worse case, when
a02908f1 5836 * one new block per extent.
ac27a0ec 5837 */
a86c6181 5838int ext4_writepage_trans_blocks(struct inode *inode)
ac27a0ec 5839{
617ba13b 5840 int bpp = ext4_journal_blocks_per_page(inode);
ac27a0ec
DK
5841 int ret;
5842
fffb2739 5843 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
a86c6181 5844
a02908f1 5845 /* Account for data blocks for journalled mode */
617ba13b 5846 if (ext4_should_journal_data(inode))
a02908f1 5847 ret += bpp;
ac27a0ec
DK
5848 return ret;
5849}
f3bd1f3f
MC
5850
5851/*
5852 * Calculate the journal credits for a chunk of data modification.
5853 *
5854 * This is called from DIO, fallocate or whoever calling
79e83036 5855 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
f3bd1f3f
MC
5856 *
5857 * journal buffers for data blocks are not included here, as DIO
5858 * and fallocate do no need to journal data buffers.
5859 */
5860int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5861{
5862 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5863}
5864
ac27a0ec 5865/*
617ba13b 5866 * The caller must have previously called ext4_reserve_inode_write().
ac27a0ec
DK
5867 * Give this, we know that the caller already has write access to iloc->bh.
5868 */
617ba13b 5869int ext4_mark_iloc_dirty(handle_t *handle,
de9a55b8 5870 struct inode *inode, struct ext4_iloc *iloc)
ac27a0ec
DK
5871{
5872 int err = 0;
5873
a6758309
VA
5874 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5875 put_bh(iloc->bh);
0db1ff22 5876 return -EIO;
a6758309 5877 }
c64db50e 5878 if (IS_I_VERSION(inode))
25ec56b5
JNC
5879 inode_inc_iversion(inode);
5880
ac27a0ec
DK
5881 /* the do_update_inode consumes one bh->b_count */
5882 get_bh(iloc->bh);
5883
dab291af 5884 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
830156c7 5885 err = ext4_do_update_inode(handle, inode, iloc);
ac27a0ec
DK
5886 put_bh(iloc->bh);
5887 return err;
5888}
5889
5890/*
5891 * On success, We end up with an outstanding reference count against
5892 * iloc->bh. This _must_ be cleaned up later.
5893 */
5894
5895int
617ba13b
MC
5896ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5897 struct ext4_iloc *iloc)
ac27a0ec 5898{
0390131b
FM
5899 int err;
5900
0db1ff22
TT
5901 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5902 return -EIO;
5903
0390131b
FM
5904 err = ext4_get_inode_loc(inode, iloc);
5905 if (!err) {
5906 BUFFER_TRACE(iloc->bh, "get_write_access");
5907 err = ext4_journal_get_write_access(handle, iloc->bh);
5908 if (err) {
5909 brelse(iloc->bh);
5910 iloc->bh = NULL;
ac27a0ec
DK
5911 }
5912 }
617ba13b 5913 ext4_std_error(inode->i_sb, err);
ac27a0ec
DK
5914 return err;
5915}
5916
c03b45b8
MX
5917static int __ext4_expand_extra_isize(struct inode *inode,
5918 unsigned int new_extra_isize,
5919 struct ext4_iloc *iloc,
5920 handle_t *handle, int *no_expand)
5921{
5922 struct ext4_inode *raw_inode;
5923 struct ext4_xattr_ibody_header *header;
5924 int error;
5925
5926 raw_inode = ext4_raw_inode(iloc);
5927
5928 header = IHDR(inode, raw_inode);
5929
5930 /* No extended attributes present */
5931 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5932 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5933 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5934 EXT4_I(inode)->i_extra_isize, 0,
5935 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5936 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5937 return 0;
5938 }
5939
5940 /* try to expand with EAs present */
5941 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5942 raw_inode, handle);
5943 if (error) {
5944 /*
5945 * Inode size expansion failed; don't try again
5946 */
5947 *no_expand = 1;
5948 }
5949
5950 return error;
5951}
5952
6dd4ee7c
KS
5953/*
5954 * Expand an inode by new_extra_isize bytes.
5955 * Returns 0 on success or negative error number on failure.
5956 */
cf0a5e81
MX
5957static int ext4_try_to_expand_extra_isize(struct inode *inode,
5958 unsigned int new_extra_isize,
5959 struct ext4_iloc iloc,
5960 handle_t *handle)
6dd4ee7c 5961{
3b10fdc6
MX
5962 int no_expand;
5963 int error;
6dd4ee7c 5964
cf0a5e81
MX
5965 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5966 return -EOVERFLOW;
5967
5968 /*
5969 * In nojournal mode, we can immediately attempt to expand
5970 * the inode. When journaled, we first need to obtain extra
5971 * buffer credits since we may write into the EA block
5972 * with this same handle. If journal_extend fails, then it will
5973 * only result in a minor loss of functionality for that inode.
5974 * If this is felt to be critical, then e2fsck should be run to
5975 * force a large enough s_min_extra_isize.
5976 */
5977 if (ext4_handle_valid(handle) &&
5978 jbd2_journal_extend(handle,
5979 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
5980 return -ENOSPC;
6dd4ee7c 5981
3b10fdc6 5982 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
cf0a5e81 5983 return -EBUSY;
3b10fdc6 5984
c03b45b8
MX
5985 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5986 handle, &no_expand);
5987 ext4_write_unlock_xattr(inode, &no_expand);
6dd4ee7c 5988
c03b45b8
MX
5989 return error;
5990}
6dd4ee7c 5991
c03b45b8
MX
5992int ext4_expand_extra_isize(struct inode *inode,
5993 unsigned int new_extra_isize,
5994 struct ext4_iloc *iloc)
5995{
5996 handle_t *handle;
5997 int no_expand;
5998 int error, rc;
5999
6000 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
6001 brelse(iloc->bh);
6002 return -EOVERFLOW;
6dd4ee7c
KS
6003 }
6004
c03b45b8
MX
6005 handle = ext4_journal_start(inode, EXT4_HT_INODE,
6006 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
6007 if (IS_ERR(handle)) {
6008 error = PTR_ERR(handle);
6009 brelse(iloc->bh);
6010 return error;
6011 }
6012
6013 ext4_write_lock_xattr(inode, &no_expand);
6014
ddccb6db 6015 BUFFER_TRACE(iloc->bh, "get_write_access");
c03b45b8 6016 error = ext4_journal_get_write_access(handle, iloc->bh);
3b10fdc6 6017 if (error) {
c03b45b8
MX
6018 brelse(iloc->bh);
6019 goto out_stop;
3b10fdc6 6020 }
cf0a5e81 6021
c03b45b8
MX
6022 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
6023 handle, &no_expand);
6024
6025 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
6026 if (!error)
6027 error = rc;
6028
6029 ext4_write_unlock_xattr(inode, &no_expand);
6030out_stop:
6031 ext4_journal_stop(handle);
3b10fdc6 6032 return error;
6dd4ee7c
KS
6033}
6034
ac27a0ec
DK
6035/*
6036 * What we do here is to mark the in-core inode as clean with respect to inode
6037 * dirtiness (it may still be data-dirty).
6038 * This means that the in-core inode may be reaped by prune_icache
6039 * without having to perform any I/O. This is a very good thing,
6040 * because *any* task may call prune_icache - even ones which
6041 * have a transaction open against a different journal.
6042 *
6043 * Is this cheating? Not really. Sure, we haven't written the
6044 * inode out, but prune_icache isn't a user-visible syncing function.
6045 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
6046 * we start and wait on commits.
ac27a0ec 6047 */
617ba13b 6048int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
ac27a0ec 6049{
617ba13b 6050 struct ext4_iloc iloc;
6dd4ee7c 6051 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
cf0a5e81 6052 int err;
ac27a0ec
DK
6053
6054 might_sleep();
7ff9c073 6055 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
617ba13b 6056 err = ext4_reserve_inode_write(handle, inode, &iloc);
5e1021f2
EG
6057 if (err)
6058 return err;
cf0a5e81
MX
6059
6060 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6061 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6062 iloc, handle);
6063
5e1021f2 6064 return ext4_mark_iloc_dirty(handle, inode, &iloc);
ac27a0ec
DK
6065}
6066
6067/*
617ba13b 6068 * ext4_dirty_inode() is called from __mark_inode_dirty()
ac27a0ec
DK
6069 *
6070 * We're really interested in the case where a file is being extended.
6071 * i_size has been changed by generic_commit_write() and we thus need
6072 * to include the updated inode in the current transaction.
6073 *
5dd4056d 6074 * Also, dquot_alloc_block() will always dirty the inode when blocks
ac27a0ec
DK
6075 * are allocated to the file.
6076 *
6077 * If the inode is marked synchronous, we don't honour that here - doing
6078 * so would cause a commit on atime updates, which we don't bother doing.
6079 * We handle synchronous inodes at the highest possible level.
0ae45f63
TT
6080 *
6081 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
6082 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
6083 * to copy into the on-disk inode structure are the timestamp files.
ac27a0ec 6084 */
aa385729 6085void ext4_dirty_inode(struct inode *inode, int flags)
ac27a0ec 6086{
ac27a0ec
DK
6087 handle_t *handle;
6088
0ae45f63
TT
6089 if (flags == I_DIRTY_TIME)
6090 return;
9924a92a 6091 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
ac27a0ec
DK
6092 if (IS_ERR(handle))
6093 goto out;
f3dc272f 6094
f3dc272f
CW
6095 ext4_mark_inode_dirty(handle, inode);
6096
617ba13b 6097 ext4_journal_stop(handle);
ac27a0ec
DK
6098out:
6099 return;
6100}
6101
617ba13b 6102int ext4_change_inode_journal_flag(struct inode *inode, int val)
ac27a0ec
DK
6103{
6104 journal_t *journal;
6105 handle_t *handle;
6106 int err;
c8585c6f 6107 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ac27a0ec
DK
6108
6109 /*
6110 * We have to be very careful here: changing a data block's
6111 * journaling status dynamically is dangerous. If we write a
6112 * data block to the journal, change the status and then delete
6113 * that block, we risk forgetting to revoke the old log record
6114 * from the journal and so a subsequent replay can corrupt data.
6115 * So, first we make sure that the journal is empty and that
6116 * nobody is changing anything.
6117 */
6118
617ba13b 6119 journal = EXT4_JOURNAL(inode);
0390131b
FM
6120 if (!journal)
6121 return 0;
d699594d 6122 if (is_journal_aborted(journal))
ac27a0ec
DK
6123 return -EROFS;
6124
17335dcc 6125 /* Wait for all existing dio workers */
17335dcc
DM
6126 inode_dio_wait(inode);
6127
4c546592
DJ
6128 /*
6129 * Before flushing the journal and switching inode's aops, we have
6130 * to flush all dirty data the inode has. There can be outstanding
6131 * delayed allocations, there can be unwritten extents created by
6132 * fallocate or buffered writes in dioread_nolock mode covered by
6133 * dirty data which can be converted only after flushing the dirty
6134 * data (and journalled aops don't know how to handle these cases).
6135 */
6136 if (val) {
6137 down_write(&EXT4_I(inode)->i_mmap_sem);
6138 err = filemap_write_and_wait(inode->i_mapping);
6139 if (err < 0) {
6140 up_write(&EXT4_I(inode)->i_mmap_sem);
4c546592
DJ
6141 return err;
6142 }
6143 }
6144
c8585c6f 6145 percpu_down_write(&sbi->s_journal_flag_rwsem);
dab291af 6146 jbd2_journal_lock_updates(journal);
ac27a0ec
DK
6147
6148 /*
6149 * OK, there are no updates running now, and all cached data is
6150 * synced to disk. We are now in a completely consistent state
6151 * which doesn't have anything in the journal, and we know that
6152 * no filesystem updates are running, so it is safe to modify
6153 * the inode's in-core data-journaling state flag now.
6154 */
6155
6156 if (val)
12e9b892 6157 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5872ddaa 6158 else {
4f879ca6
JK
6159 err = jbd2_journal_flush(journal);
6160 if (err < 0) {
6161 jbd2_journal_unlock_updates(journal);
c8585c6f 6162 percpu_up_write(&sbi->s_journal_flag_rwsem);
4f879ca6
JK
6163 return err;
6164 }
12e9b892 6165 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5872ddaa 6166 }
617ba13b 6167 ext4_set_aops(inode);
ac27a0ec 6168
dab291af 6169 jbd2_journal_unlock_updates(journal);
c8585c6f
DJ
6170 percpu_up_write(&sbi->s_journal_flag_rwsem);
6171
4c546592
DJ
6172 if (val)
6173 up_write(&EXT4_I(inode)->i_mmap_sem);
ac27a0ec
DK
6174
6175 /* Finally we can mark the inode as dirty. */
6176
9924a92a 6177 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
ac27a0ec
DK
6178 if (IS_ERR(handle))
6179 return PTR_ERR(handle);
6180
617ba13b 6181 err = ext4_mark_inode_dirty(handle, inode);
0390131b 6182 ext4_handle_sync(handle);
617ba13b
MC
6183 ext4_journal_stop(handle);
6184 ext4_std_error(inode->i_sb, err);
ac27a0ec
DK
6185
6186 return err;
6187}
2e9ee850
AK
6188
6189static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6190{
6191 return !buffer_mapped(bh);
6192}
6193
401b25aa 6194vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
2e9ee850 6195{
11bac800 6196 struct vm_area_struct *vma = vmf->vma;
c2ec175c 6197 struct page *page = vmf->page;
2e9ee850
AK
6198 loff_t size;
6199 unsigned long len;
401b25aa
SJ
6200 int err;
6201 vm_fault_t ret;
2e9ee850 6202 struct file *file = vma->vm_file;
496ad9aa 6203 struct inode *inode = file_inode(file);
2e9ee850 6204 struct address_space *mapping = inode->i_mapping;
9ea7df53
JK
6205 handle_t *handle;
6206 get_block_t *get_block;
6207 int retries = 0;
2e9ee850 6208
02b016ca
TT
6209 if (unlikely(IS_IMMUTABLE(inode)))
6210 return VM_FAULT_SIGBUS;
6211
8e8ad8a5 6212 sb_start_pagefault(inode->i_sb);
041bbb6d 6213 file_update_time(vma->vm_file);
ea3d7209
JK
6214
6215 down_read(&EXT4_I(inode)->i_mmap_sem);
7b4cc978 6216
401b25aa
SJ
6217 err = ext4_convert_inline_data(inode);
6218 if (err)
7b4cc978
EB
6219 goto out_ret;
6220
9ea7df53
JK
6221 /* Delalloc case is easy... */
6222 if (test_opt(inode->i_sb, DELALLOC) &&
6223 !ext4_should_journal_data(inode) &&
6224 !ext4_nonda_switch(inode->i_sb)) {
6225 do {
401b25aa 6226 err = block_page_mkwrite(vma, vmf,
9ea7df53 6227 ext4_da_get_block_prep);
401b25aa 6228 } while (err == -ENOSPC &&
9ea7df53
JK
6229 ext4_should_retry_alloc(inode->i_sb, &retries));
6230 goto out_ret;
2e9ee850 6231 }
0e499890
DW
6232
6233 lock_page(page);
9ea7df53
JK
6234 size = i_size_read(inode);
6235 /* Page got truncated from under us? */
6236 if (page->mapping != mapping || page_offset(page) > size) {
6237 unlock_page(page);
6238 ret = VM_FAULT_NOPAGE;
6239 goto out;
0e499890 6240 }
2e9ee850 6241
09cbfeaf
KS
6242 if (page->index == size >> PAGE_SHIFT)
6243 len = size & ~PAGE_MASK;
2e9ee850 6244 else
09cbfeaf 6245 len = PAGE_SIZE;
a827eaff 6246 /*
9ea7df53
JK
6247 * Return if we have all the buffers mapped. This avoids the need to do
6248 * journal_start/journal_stop which can block and take a long time
a827eaff 6249 */
2e9ee850 6250 if (page_has_buffers(page)) {
f19d5870
TM
6251 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6252 0, len, NULL,
6253 ext4_bh_unmapped)) {
9ea7df53 6254 /* Wait so that we don't change page under IO */
1d1d1a76 6255 wait_for_stable_page(page);
9ea7df53
JK
6256 ret = VM_FAULT_LOCKED;
6257 goto out;
a827eaff 6258 }
2e9ee850 6259 }
a827eaff 6260 unlock_page(page);
9ea7df53
JK
6261 /* OK, we need to fill the hole... */
6262 if (ext4_should_dioread_nolock(inode))
705965bd 6263 get_block = ext4_get_block_unwritten;
9ea7df53
JK
6264 else
6265 get_block = ext4_get_block;
6266retry_alloc:
9924a92a
TT
6267 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6268 ext4_writepage_trans_blocks(inode));
9ea7df53 6269 if (IS_ERR(handle)) {
c2ec175c 6270 ret = VM_FAULT_SIGBUS;
9ea7df53
JK
6271 goto out;
6272 }
401b25aa
SJ
6273 err = block_page_mkwrite(vma, vmf, get_block);
6274 if (!err && ext4_should_journal_data(inode)) {
f19d5870 6275 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
09cbfeaf 6276 PAGE_SIZE, NULL, do_journal_get_write_access)) {
9ea7df53
JK
6277 unlock_page(page);
6278 ret = VM_FAULT_SIGBUS;
fcbb5515 6279 ext4_journal_stop(handle);
9ea7df53
JK
6280 goto out;
6281 }
6282 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6283 }
6284 ext4_journal_stop(handle);
401b25aa 6285 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
9ea7df53
JK
6286 goto retry_alloc;
6287out_ret:
401b25aa 6288 ret = block_page_mkwrite_return(err);
9ea7df53 6289out:
ea3d7209 6290 up_read(&EXT4_I(inode)->i_mmap_sem);
8e8ad8a5 6291 sb_end_pagefault(inode->i_sb);
2e9ee850
AK
6292 return ret;
6293}
ea3d7209 6294
401b25aa 6295vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
ea3d7209 6296{
11bac800 6297 struct inode *inode = file_inode(vmf->vma->vm_file);
401b25aa 6298 vm_fault_t ret;
ea3d7209
JK
6299
6300 down_read(&EXT4_I(inode)->i_mmap_sem);
401b25aa 6301 ret = filemap_fault(vmf);
ea3d7209
JK
6302 up_read(&EXT4_I(inode)->i_mmap_sem);
6303
401b25aa 6304 return ret;
ea3d7209 6305}