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