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