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