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