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