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