/kern_oII/fs/ext4/inode.c

http://omnia2droid.googlecode.com/ · C · 5311 lines · 3084 code · 516 blank · 1711 comment · 687 complexity · 3d0bd10e47eb9df9ca13e63b4c381ce5 MD5 · raw file

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