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