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