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