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