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