indirect.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. /*
  2. * linux/fs/ext4/indirect.c
  3. *
  4. * from
  5. *
  6. * linux/fs/ext4/inode.c
  7. *
  8. * Copyright (C) 1992, 1993, 1994, 1995
  9. * Remy Card (card@masi.ibp.fr)
  10. * Laboratoire MASI - Institut Blaise Pascal
  11. * Universite Pierre et Marie Curie (Paris VI)
  12. *
  13. * from
  14. *
  15. * linux/fs/minix/inode.c
  16. *
  17. * Copyright (C) 1991, 1992 Linus Torvalds
  18. *
  19. * Goal-directed block allocation by Stephen Tweedie
  20. * (sct@redhat.com), 1993, 1998
  21. */
  22. #include "ext4_jbd2.h"
  23. #include "truncate.h"
  24. #include "ext4_extents.h" /* Needed for EXT_MAX_BLOCKS */
  25. #include <trace/events/ext4.h>
  26. typedef struct {
  27. __le32 *p;
  28. __le32 key;
  29. struct buffer_head *bh;
  30. } Indirect;
  31. static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
  32. {
  33. p->key = *(p->p = v);
  34. p->bh = bh;
  35. }
  36. /**
  37. * ext4_block_to_path - parse the block number into array of offsets
  38. * @inode: inode in question (we are only interested in its superblock)
  39. * @i_block: block number to be parsed
  40. * @offsets: array to store the offsets in
  41. * @boundary: set this non-zero if the referred-to block is likely to be
  42. * followed (on disk) by an indirect block.
  43. *
  44. * To store the locations of file's data ext4 uses a data structure common
  45. * for UNIX filesystems - tree of pointers anchored in the inode, with
  46. * data blocks at leaves and indirect blocks in intermediate nodes.
  47. * This function translates the block number into path in that tree -
  48. * return value is the path length and @offsets[n] is the offset of
  49. * pointer to (n+1)th node in the nth one. If @block is out of range
  50. * (negative or too large) warning is printed and zero returned.
  51. *
  52. * Note: function doesn't find node addresses, so no IO is needed. All
  53. * we need to know is the capacity of indirect blocks (taken from the
  54. * inode->i_sb).
  55. */
  56. /*
  57. * Portability note: the last comparison (check that we fit into triple
  58. * indirect block) is spelled differently, because otherwise on an
  59. * architecture with 32-bit longs and 8Kb pages we might get into trouble
  60. * if our filesystem had 8Kb blocks. We might use long long, but that would
  61. * kill us on x86. Oh, well, at least the sign propagation does not matter -
  62. * i_block would have to be negative in the very beginning, so we would not
  63. * get there at all.
  64. */
  65. static int ext4_block_to_path(struct inode *inode,
  66. ext4_lblk_t i_block,
  67. ext4_lblk_t offsets[4], int *boundary)
  68. {
  69. int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  70. int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
  71. const long direct_blocks = EXT4_NDIR_BLOCKS,
  72. indirect_blocks = ptrs,
  73. double_blocks = (1 << (ptrs_bits * 2));
  74. int n = 0;
  75. int final = 0;
  76. if (i_block < direct_blocks) {
  77. offsets[n++] = i_block;
  78. final = direct_blocks;
  79. } else if ((i_block -= direct_blocks) < indirect_blocks) {
  80. offsets[n++] = EXT4_IND_BLOCK;
  81. offsets[n++] = i_block;
  82. final = ptrs;
  83. } else if ((i_block -= indirect_blocks) < double_blocks) {
  84. offsets[n++] = EXT4_DIND_BLOCK;
  85. offsets[n++] = i_block >> ptrs_bits;
  86. offsets[n++] = i_block & (ptrs - 1);
  87. final = ptrs;
  88. } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
  89. offsets[n++] = EXT4_TIND_BLOCK;
  90. offsets[n++] = i_block >> (ptrs_bits * 2);
  91. offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
  92. offsets[n++] = i_block & (ptrs - 1);
  93. final = ptrs;
  94. } else {
  95. ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
  96. i_block + direct_blocks +
  97. indirect_blocks + double_blocks, inode->i_ino);
  98. }
  99. if (boundary)
  100. *boundary = final - 1 - (i_block & (ptrs - 1));
  101. return n;
  102. }
  103. /**
  104. * ext4_get_branch - read the chain of indirect blocks leading to data
  105. * @inode: inode in question
  106. * @depth: depth of the chain (1 - direct pointer, etc.)
  107. * @offsets: offsets of pointers in inode/indirect blocks
  108. * @chain: place to store the result
  109. * @err: here we store the error value
  110. *
  111. * Function fills the array of triples <key, p, bh> and returns %NULL
  112. * if everything went OK or the pointer to the last filled triple
  113. * (incomplete one) otherwise. Upon the return chain[i].key contains
  114. * the number of (i+1)-th block in the chain (as it is stored in memory,
  115. * i.e. little-endian 32-bit), chain[i].p contains the address of that
  116. * number (it points into struct inode for i==0 and into the bh->b_data
  117. * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
  118. * block for i>0 and NULL for i==0. In other words, it holds the block
  119. * numbers of the chain, addresses they were taken from (and where we can
  120. * verify that chain did not change) and buffer_heads hosting these
  121. * numbers.
  122. *
  123. * Function stops when it stumbles upon zero pointer (absent block)
  124. * (pointer to last triple returned, *@err == 0)
  125. * or when it gets an IO error reading an indirect block
  126. * (ditto, *@err == -EIO)
  127. * or when it reads all @depth-1 indirect blocks successfully and finds
  128. * the whole chain, all way to the data (returns %NULL, *err == 0).
  129. *
  130. * Need to be called with
  131. * down_read(&EXT4_I(inode)->i_data_sem)
  132. */
  133. static Indirect *ext4_get_branch(struct inode *inode, int depth,
  134. ext4_lblk_t *offsets,
  135. Indirect chain[4], int *err)
  136. {
  137. struct super_block *sb = inode->i_sb;
  138. Indirect *p = chain;
  139. struct buffer_head *bh;
  140. int ret = -EIO;
  141. *err = 0;
  142. /* i_data is not going away, no lock needed */
  143. add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
  144. if (!p->key)
  145. goto no_block;
  146. while (--depth) {
  147. bh = sb_getblk(sb, le32_to_cpu(p->key));
  148. if (unlikely(!bh)) {
  149. ret = -ENOMEM;
  150. goto failure;
  151. }
  152. if (!bh_uptodate_or_lock(bh)) {
  153. if (bh_submit_read(bh) < 0) {
  154. put_bh(bh);
  155. goto failure;
  156. }
  157. /* validate block references */
  158. if (ext4_check_indirect_blockref(inode, bh)) {
  159. put_bh(bh);
  160. goto failure;
  161. }
  162. }
  163. add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
  164. /* Reader: end */
  165. if (!p->key)
  166. goto no_block;
  167. }
  168. return NULL;
  169. failure:
  170. *err = ret;
  171. no_block:
  172. return p;
  173. }
  174. /**
  175. * ext4_find_near - find a place for allocation with sufficient locality
  176. * @inode: owner
  177. * @ind: descriptor of indirect block.
  178. *
  179. * This function returns the preferred place for block allocation.
  180. * It is used when heuristic for sequential allocation fails.
  181. * Rules are:
  182. * + if there is a block to the left of our position - allocate near it.
  183. * + if pointer will live in indirect block - allocate near that block.
  184. * + if pointer will live in inode - allocate in the same
  185. * cylinder group.
  186. *
  187. * In the latter case we colour the starting block by the callers PID to
  188. * prevent it from clashing with concurrent allocations for a different inode
  189. * in the same block group. The PID is used here so that functionally related
  190. * files will be close-by on-disk.
  191. *
  192. * Caller must make sure that @ind is valid and will stay that way.
  193. */
  194. static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
  195. {
  196. struct ext4_inode_info *ei = EXT4_I(inode);
  197. __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
  198. __le32 *p;
  199. /* Try to find previous block */
  200. for (p = ind->p - 1; p >= start; p--) {
  201. if (*p)
  202. return le32_to_cpu(*p);
  203. }
  204. /* No such thing, so let's try location of indirect block */
  205. if (ind->bh)
  206. return ind->bh->b_blocknr;
  207. /*
  208. * It is going to be referred to from the inode itself? OK, just put it
  209. * into the same cylinder group then.
  210. */
  211. return ext4_inode_to_goal_block(inode);
  212. }
  213. /**
  214. * ext4_find_goal - find a preferred place for allocation.
  215. * @inode: owner
  216. * @block: block we want
  217. * @partial: pointer to the last triple within a chain
  218. *
  219. * Normally this function find the preferred place for block allocation,
  220. * returns it.
  221. * Because this is only used for non-extent files, we limit the block nr
  222. * to 32 bits.
  223. */
  224. static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
  225. Indirect *partial)
  226. {
  227. ext4_fsblk_t goal;
  228. /*
  229. * XXX need to get goal block from mballoc's data structures
  230. */
  231. goal = ext4_find_near(inode, partial);
  232. goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
  233. return goal;
  234. }
  235. /**
  236. * ext4_blks_to_allocate - Look up the block map and count the number
  237. * of direct blocks need to be allocated for the given branch.
  238. *
  239. * @branch: chain of indirect blocks
  240. * @k: number of blocks need for indirect blocks
  241. * @blks: number of data blocks to be mapped.
  242. * @blocks_to_boundary: the offset in the indirect block
  243. *
  244. * return the total number of blocks to be allocate, including the
  245. * direct and indirect blocks.
  246. */
  247. static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
  248. int blocks_to_boundary)
  249. {
  250. unsigned int count = 0;
  251. /*
  252. * Simple case, [t,d]Indirect block(s) has not allocated yet
  253. * then it's clear blocks on that path have not allocated
  254. */
  255. if (k > 0) {
  256. /* right now we don't handle cross boundary allocation */
  257. if (blks < blocks_to_boundary + 1)
  258. count += blks;
  259. else
  260. count += blocks_to_boundary + 1;
  261. return count;
  262. }
  263. count++;
  264. while (count < blks && count <= blocks_to_boundary &&
  265. le32_to_cpu(*(branch[0].p + count)) == 0) {
  266. count++;
  267. }
  268. return count;
  269. }
  270. /**
  271. * ext4_alloc_blocks: multiple allocate blocks needed for a branch
  272. * @handle: handle for this transaction
  273. * @inode: inode which needs allocated blocks
  274. * @iblock: the logical block to start allocated at
  275. * @goal: preferred physical block of allocation
  276. * @indirect_blks: the number of blocks need to allocate for indirect
  277. * blocks
  278. * @blks: number of desired blocks
  279. * @new_blocks: on return it will store the new block numbers for
  280. * the indirect blocks(if needed) and the first direct block,
  281. * @err: on return it will store the error code
  282. *
  283. * This function will return the number of blocks allocated as
  284. * requested by the passed-in parameters.
  285. */
  286. static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
  287. ext4_lblk_t iblock, ext4_fsblk_t goal,
  288. int indirect_blks, int blks,
  289. ext4_fsblk_t new_blocks[4], int *err)
  290. {
  291. struct ext4_allocation_request ar;
  292. int target, i;
  293. unsigned long count = 0, blk_allocated = 0;
  294. int index = 0;
  295. ext4_fsblk_t current_block = 0;
  296. int ret = 0;
  297. /*
  298. * Here we try to allocate the requested multiple blocks at once,
  299. * on a best-effort basis.
  300. * To build a branch, we should allocate blocks for
  301. * the indirect blocks(if not allocated yet), and at least
  302. * the first direct block of this branch. That's the
  303. * minimum number of blocks need to allocate(required)
  304. */
  305. /* first we try to allocate the indirect blocks */
  306. target = indirect_blks;
  307. while (target > 0) {
  308. count = target;
  309. /* allocating blocks for indirect blocks and direct blocks */
  310. current_block = ext4_new_meta_blocks(handle, inode, goal,
  311. 0, &count, err);
  312. if (*err)
  313. goto failed_out;
  314. if (unlikely(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS)) {
  315. EXT4_ERROR_INODE(inode,
  316. "current_block %llu + count %lu > %d!",
  317. current_block, count,
  318. EXT4_MAX_BLOCK_FILE_PHYS);
  319. *err = -EIO;
  320. goto failed_out;
  321. }
  322. target -= count;
  323. /* allocate blocks for indirect blocks */
  324. while (index < indirect_blks && count) {
  325. new_blocks[index++] = current_block++;
  326. count--;
  327. }
  328. if (count > 0) {
  329. /*
  330. * save the new block number
  331. * for the first direct block
  332. */
  333. new_blocks[index] = current_block;
  334. WARN(1, KERN_INFO "%s returned more blocks than "
  335. "requested\n", __func__);
  336. break;
  337. }
  338. }
  339. target = blks - count ;
  340. blk_allocated = count;
  341. if (!target)
  342. goto allocated;
  343. /* Now allocate data blocks */
  344. memset(&ar, 0, sizeof(ar));
  345. ar.inode = inode;
  346. ar.goal = goal;
  347. ar.len = target;
  348. ar.logical = iblock;
  349. if (S_ISREG(inode->i_mode))
  350. /* enable in-core preallocation only for regular files */
  351. ar.flags = EXT4_MB_HINT_DATA;
  352. current_block = ext4_mb_new_blocks(handle, &ar, err);
  353. if (unlikely(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS)) {
  354. EXT4_ERROR_INODE(inode,
  355. "current_block %llu + ar.len %d > %d!",
  356. current_block, ar.len,
  357. EXT4_MAX_BLOCK_FILE_PHYS);
  358. *err = -EIO;
  359. goto failed_out;
  360. }
  361. if (*err && (target == blks)) {
  362. /*
  363. * if the allocation failed and we didn't allocate
  364. * any blocks before
  365. */
  366. goto failed_out;
  367. }
  368. if (!*err) {
  369. if (target == blks) {
  370. /*
  371. * save the new block number
  372. * for the first direct block
  373. */
  374. new_blocks[index] = current_block;
  375. }
  376. blk_allocated += ar.len;
  377. }
  378. allocated:
  379. /* total number of blocks allocated for direct blocks */
  380. ret = blk_allocated;
  381. *err = 0;
  382. return ret;
  383. failed_out:
  384. for (i = 0; i < index; i++)
  385. ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1, 0);
  386. return ret;
  387. }
  388. /**
  389. * ext4_alloc_branch - allocate and set up a chain of blocks.
  390. * @handle: handle for this transaction
  391. * @inode: owner
  392. * @indirect_blks: number of allocated indirect blocks
  393. * @blks: number of allocated direct blocks
  394. * @goal: preferred place for allocation
  395. * @offsets: offsets (in the blocks) to store the pointers to next.
  396. * @branch: place to store the chain in.
  397. *
  398. * This function allocates blocks, zeroes out all but the last one,
  399. * links them into chain and (if we are synchronous) writes them to disk.
  400. * In other words, it prepares a branch that can be spliced onto the
  401. * inode. It stores the information about that chain in the branch[], in
  402. * the same format as ext4_get_branch() would do. We are calling it after
  403. * we had read the existing part of chain and partial points to the last
  404. * triple of that (one with zero ->key). Upon the exit we have the same
  405. * picture as after the successful ext4_get_block(), except that in one
  406. * place chain is disconnected - *branch->p is still zero (we did not
  407. * set the last link), but branch->key contains the number that should
  408. * be placed into *branch->p to fill that gap.
  409. *
  410. * If allocation fails we free all blocks we've allocated (and forget
  411. * their buffer_heads) and return the error value the from failed
  412. * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
  413. * as described above and return 0.
  414. */
  415. static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
  416. ext4_lblk_t iblock, int indirect_blks,
  417. int *blks, ext4_fsblk_t goal,
  418. ext4_lblk_t *offsets, Indirect *branch)
  419. {
  420. int blocksize = inode->i_sb->s_blocksize;
  421. int i, n = 0;
  422. int err = 0;
  423. struct buffer_head *bh;
  424. int num;
  425. ext4_fsblk_t new_blocks[4];
  426. ext4_fsblk_t current_block;
  427. num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
  428. *blks, new_blocks, &err);
  429. if (err)
  430. return err;
  431. branch[0].key = cpu_to_le32(new_blocks[0]);
  432. /*
  433. * metadata blocks and data blocks are allocated.
  434. */
  435. for (n = 1; n <= indirect_blks; n++) {
  436. /*
  437. * Get buffer_head for parent block, zero it out
  438. * and set the pointer to new one, then send
  439. * parent to disk.
  440. */
  441. bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
  442. if (unlikely(!bh)) {
  443. err = -ENOMEM;
  444. goto failed;
  445. }
  446. branch[n].bh = bh;
  447. lock_buffer(bh);
  448. BUFFER_TRACE(bh, "call get_create_access");
  449. err = ext4_journal_get_create_access(handle, bh);
  450. if (err) {
  451. /* Don't brelse(bh) here; it's done in
  452. * ext4_journal_forget() below */
  453. unlock_buffer(bh);
  454. goto failed;
  455. }
  456. memset(bh->b_data, 0, blocksize);
  457. branch[n].p = (__le32 *) bh->b_data + offsets[n];
  458. branch[n].key = cpu_to_le32(new_blocks[n]);
  459. *branch[n].p = branch[n].key;
  460. if (n == indirect_blks) {
  461. current_block = new_blocks[n];
  462. /*
  463. * End of chain, update the last new metablock of
  464. * the chain to point to the new allocated
  465. * data blocks numbers
  466. */
  467. for (i = 1; i < num; i++)
  468. *(branch[n].p + i) = cpu_to_le32(++current_block);
  469. }
  470. BUFFER_TRACE(bh, "marking uptodate");
  471. set_buffer_uptodate(bh);
  472. unlock_buffer(bh);
  473. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  474. err = ext4_handle_dirty_metadata(handle, inode, bh);
  475. if (err)
  476. goto failed;
  477. }
  478. *blks = num;
  479. return err;
  480. failed:
  481. /* Allocation failed, free what we already allocated */
  482. ext4_free_blocks(handle, inode, NULL, new_blocks[0], 1, 0);
  483. for (i = 1; i <= n ; i++) {
  484. /*
  485. * branch[i].bh is newly allocated, so there is no
  486. * need to revoke the block, which is why we don't
  487. * need to set EXT4_FREE_BLOCKS_METADATA.
  488. */
  489. ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1,
  490. EXT4_FREE_BLOCKS_FORGET);
  491. }
  492. for (i = n+1; i < indirect_blks; i++)
  493. ext4_free_blocks(handle, inode, NULL, new_blocks[i], 1, 0);
  494. ext4_free_blocks(handle, inode, NULL, new_blocks[i], num, 0);
  495. return err;
  496. }
  497. /**
  498. * ext4_splice_branch - splice the allocated branch onto inode.
  499. * @handle: handle for this transaction
  500. * @inode: owner
  501. * @block: (logical) number of block we are adding
  502. * @chain: chain of indirect blocks (with a missing link - see
  503. * ext4_alloc_branch)
  504. * @where: location of missing link
  505. * @num: number of indirect blocks we are adding
  506. * @blks: number of direct blocks we are adding
  507. *
  508. * This function fills the missing link and does all housekeeping needed in
  509. * inode (->i_blocks, etc.). In case of success we end up with the full
  510. * chain to new block and return 0.
  511. */
  512. static int ext4_splice_branch(handle_t *handle, struct inode *inode,
  513. ext4_lblk_t block, Indirect *where, int num,
  514. int blks)
  515. {
  516. int i;
  517. int err = 0;
  518. ext4_fsblk_t current_block;
  519. /*
  520. * If we're splicing into a [td]indirect block (as opposed to the
  521. * inode) then we need to get write access to the [td]indirect block
  522. * before the splice.
  523. */
  524. if (where->bh) {
  525. BUFFER_TRACE(where->bh, "get_write_access");
  526. err = ext4_journal_get_write_access(handle, where->bh);
  527. if (err)
  528. goto err_out;
  529. }
  530. /* That's it */
  531. *where->p = where->key;
  532. /*
  533. * Update the host buffer_head or inode to point to more just allocated
  534. * direct blocks blocks
  535. */
  536. if (num == 0 && blks > 1) {
  537. current_block = le32_to_cpu(where->key) + 1;
  538. for (i = 1; i < blks; i++)
  539. *(where->p + i) = cpu_to_le32(current_block++);
  540. }
  541. /* We are done with atomic stuff, now do the rest of housekeeping */
  542. /* had we spliced it onto indirect block? */
  543. if (where->bh) {
  544. /*
  545. * If we spliced it onto an indirect block, we haven't
  546. * altered the inode. Note however that if it is being spliced
  547. * onto an indirect block at the very end of the file (the
  548. * file is growing) then we *will* alter the inode to reflect
  549. * the new i_size. But that is not done here - it is done in
  550. * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
  551. */
  552. jbd_debug(5, "splicing indirect only\n");
  553. BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
  554. err = ext4_handle_dirty_metadata(handle, inode, where->bh);
  555. if (err)
  556. goto err_out;
  557. } else {
  558. /*
  559. * OK, we spliced it into the inode itself on a direct block.
  560. */
  561. ext4_mark_inode_dirty(handle, inode);
  562. jbd_debug(5, "splicing direct\n");
  563. }
  564. return err;
  565. err_out:
  566. for (i = 1; i <= num; i++) {
  567. /*
  568. * branch[i].bh is newly allocated, so there is no
  569. * need to revoke the block, which is why we don't
  570. * need to set EXT4_FREE_BLOCKS_METADATA.
  571. */
  572. ext4_free_blocks(handle, inode, where[i].bh, 0, 1,
  573. EXT4_FREE_BLOCKS_FORGET);
  574. }
  575. ext4_free_blocks(handle, inode, NULL, le32_to_cpu(where[num].key),
  576. blks, 0);
  577. return err;
  578. }
  579. /*
  580. * The ext4_ind_map_blocks() function handles non-extents inodes
  581. * (i.e., using the traditional indirect/double-indirect i_blocks
  582. * scheme) for ext4_map_blocks().
  583. *
  584. * Allocation strategy is simple: if we have to allocate something, we will
  585. * have to go the whole way to leaf. So let's do it before attaching anything
  586. * to tree, set linkage between the newborn blocks, write them if sync is
  587. * required, recheck the path, free and repeat if check fails, otherwise
  588. * set the last missing link (that will protect us from any truncate-generated
  589. * removals - all blocks on the path are immune now) and possibly force the
  590. * write on the parent block.
  591. * That has a nice additional property: no special recovery from the failed
  592. * allocations is needed - we simply release blocks and do not touch anything
  593. * reachable from inode.
  594. *
  595. * `handle' can be NULL if create == 0.
  596. *
  597. * return > 0, # of blocks mapped or allocated.
  598. * return = 0, if plain lookup failed.
  599. * return < 0, error case.
  600. *
  601. * The ext4_ind_get_blocks() function should be called with
  602. * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
  603. * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
  604. * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
  605. * blocks.
  606. */
  607. int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
  608. struct ext4_map_blocks *map,
  609. int flags)
  610. {
  611. int err = -EIO;
  612. ext4_lblk_t offsets[4];
  613. Indirect chain[4];
  614. Indirect *partial;
  615. ext4_fsblk_t goal;
  616. int indirect_blks;
  617. int blocks_to_boundary = 0;
  618. int depth;
  619. int count = 0;
  620. ext4_fsblk_t first_block = 0;
  621. trace_ext4_ind_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
  622. J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
  623. J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
  624. depth = ext4_block_to_path(inode, map->m_lblk, offsets,
  625. &blocks_to_boundary);
  626. if (depth == 0)
  627. goto out;
  628. partial = ext4_get_branch(inode, depth, offsets, chain, &err);
  629. /* Simplest case - block found, no allocation needed */
  630. if (!partial) {
  631. first_block = le32_to_cpu(chain[depth - 1].key);
  632. count++;
  633. /*map more blocks*/
  634. while (count < map->m_len && count <= blocks_to_boundary) {
  635. ext4_fsblk_t blk;
  636. blk = le32_to_cpu(*(chain[depth-1].p + count));
  637. if (blk == first_block + count)
  638. count++;
  639. else
  640. break;
  641. }
  642. goto got_it;
  643. }
  644. /* Next simple case - plain lookup or failed read of indirect block */
  645. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
  646. goto cleanup;
  647. /*
  648. * Okay, we need to do block allocation.
  649. */
  650. if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
  651. EXT4_FEATURE_RO_COMPAT_BIGALLOC)) {
  652. EXT4_ERROR_INODE(inode, "Can't allocate blocks for "
  653. "non-extent mapped inodes with bigalloc");
  654. return -ENOSPC;
  655. }
  656. goal = ext4_find_goal(inode, map->m_lblk, partial);
  657. /* the number of blocks need to allocate for [d,t]indirect blocks */
  658. indirect_blks = (chain + depth) - partial - 1;
  659. /*
  660. * Next look up the indirect map to count the totoal number of
  661. * direct blocks to allocate for this branch.
  662. */
  663. count = ext4_blks_to_allocate(partial, indirect_blks,
  664. map->m_len, blocks_to_boundary);
  665. /*
  666. * Block out ext4_truncate while we alter the tree
  667. */
  668. err = ext4_alloc_branch(handle, inode, map->m_lblk, indirect_blks,
  669. &count, goal,
  670. offsets + (partial - chain), partial);
  671. /*
  672. * The ext4_splice_branch call will free and forget any buffers
  673. * on the new chain if there is a failure, but that risks using
  674. * up transaction credits, especially for bitmaps where the
  675. * credits cannot be returned. Can we handle this somehow? We
  676. * may need to return -EAGAIN upwards in the worst case. --sct
  677. */
  678. if (!err)
  679. err = ext4_splice_branch(handle, inode, map->m_lblk,
  680. partial, indirect_blks, count);
  681. if (err)
  682. goto cleanup;
  683. map->m_flags |= EXT4_MAP_NEW;
  684. ext4_update_inode_fsync_trans(handle, inode, 1);
  685. got_it:
  686. map->m_flags |= EXT4_MAP_MAPPED;
  687. map->m_pblk = le32_to_cpu(chain[depth-1].key);
  688. map->m_len = count;
  689. if (count > blocks_to_boundary)
  690. map->m_flags |= EXT4_MAP_BOUNDARY;
  691. err = count;
  692. /* Clean up and exit */
  693. partial = chain + depth - 1; /* the whole chain */
  694. cleanup:
  695. while (partial > chain) {
  696. BUFFER_TRACE(partial->bh, "call brelse");
  697. brelse(partial->bh);
  698. partial--;
  699. }
  700. out:
  701. trace_ext4_ind_map_blocks_exit(inode, map, err);
  702. return err;
  703. }
  704. /*
  705. * O_DIRECT for ext3 (or indirect map) based files
  706. *
  707. * If the O_DIRECT write will extend the file then add this inode to the
  708. * orphan list. So recovery will truncate it back to the original size
  709. * if the machine crashes during the write.
  710. *
  711. * If the O_DIRECT write is intantiating holes inside i_size and the machine
  712. * crashes then stale disk data _may_ be exposed inside the file. But current
  713. * VFS code falls back into buffered path in that case so we are safe.
  714. */
  715. ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
  716. const struct iovec *iov, loff_t offset,
  717. unsigned long nr_segs)
  718. {
  719. struct file *file = iocb->ki_filp;
  720. struct inode *inode = file->f_mapping->host;
  721. struct ext4_inode_info *ei = EXT4_I(inode);
  722. handle_t *handle;
  723. ssize_t ret;
  724. int orphan = 0;
  725. size_t count = iov_length(iov, nr_segs);
  726. int retries = 0;
  727. if (rw == WRITE) {
  728. loff_t final_size = offset + count;
  729. if (final_size > inode->i_size) {
  730. /* Credits for sb + inode write */
  731. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  732. if (IS_ERR(handle)) {
  733. ret = PTR_ERR(handle);
  734. goto out;
  735. }
  736. ret = ext4_orphan_add(handle, inode);
  737. if (ret) {
  738. ext4_journal_stop(handle);
  739. goto out;
  740. }
  741. orphan = 1;
  742. ei->i_disksize = inode->i_size;
  743. ext4_journal_stop(handle);
  744. }
  745. }
  746. retry:
  747. if (rw == READ && ext4_should_dioread_nolock(inode)) {
  748. if (unlikely(atomic_read(&EXT4_I(inode)->i_unwritten))) {
  749. mutex_lock(&inode->i_mutex);
  750. ext4_flush_unwritten_io(inode);
  751. mutex_unlock(&inode->i_mutex);
  752. }
  753. /*
  754. * Nolock dioread optimization may be dynamically disabled
  755. * via ext4_inode_block_unlocked_dio(). Check inode's state
  756. * while holding extra i_dio_count ref.
  757. */
  758. atomic_inc(&inode->i_dio_count);
  759. smp_mb();
  760. if (unlikely(ext4_test_inode_state(inode,
  761. EXT4_STATE_DIOREAD_LOCK))) {
  762. inode_dio_done(inode);
  763. goto locked;
  764. }
  765. ret = __blockdev_direct_IO(rw, iocb, inode,
  766. inode->i_sb->s_bdev, iov,
  767. offset, nr_segs,
  768. ext4_get_block, NULL, NULL, 0);
  769. inode_dio_done(inode);
  770. } else {
  771. locked:
  772. ret = blockdev_direct_IO(rw, iocb, inode, iov,
  773. offset, nr_segs, ext4_get_block);
  774. if (unlikely((rw & WRITE) && ret < 0)) {
  775. loff_t isize = i_size_read(inode);
  776. loff_t end = offset + iov_length(iov, nr_segs);
  777. if (end > isize)
  778. ext4_truncate_failed_write(inode);
  779. }
  780. }
  781. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  782. goto retry;
  783. if (orphan) {
  784. int err;
  785. /* Credits for sb + inode write */
  786. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  787. if (IS_ERR(handle)) {
  788. /* This is really bad luck. We've written the data
  789. * but cannot extend i_size. Bail out and pretend
  790. * the write failed... */
  791. ret = PTR_ERR(handle);
  792. if (inode->i_nlink)
  793. ext4_orphan_del(NULL, inode);
  794. goto out;
  795. }
  796. if (inode->i_nlink)
  797. ext4_orphan_del(handle, inode);
  798. if (ret > 0) {
  799. loff_t end = offset + ret;
  800. if (end > inode->i_size) {
  801. ei->i_disksize = end;
  802. i_size_write(inode, end);
  803. /*
  804. * We're going to return a positive `ret'
  805. * here due to non-zero-length I/O, so there's
  806. * no way of reporting error returns from
  807. * ext4_mark_inode_dirty() to userspace. So
  808. * ignore it.
  809. */
  810. ext4_mark_inode_dirty(handle, inode);
  811. }
  812. }
  813. err = ext4_journal_stop(handle);
  814. if (ret == 0)
  815. ret = err;
  816. }
  817. out:
  818. return ret;
  819. }
  820. /*
  821. * Calculate the number of metadata blocks need to reserve
  822. * to allocate a new block at @lblocks for non extent file based file
  823. */
  824. int ext4_ind_calc_metadata_amount(struct inode *inode, sector_t lblock)
  825. {
  826. struct ext4_inode_info *ei = EXT4_I(inode);
  827. sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
  828. int blk_bits;
  829. if (lblock < EXT4_NDIR_BLOCKS)
  830. return 0;
  831. lblock -= EXT4_NDIR_BLOCKS;
  832. if (ei->i_da_metadata_calc_len &&
  833. (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
  834. ei->i_da_metadata_calc_len++;
  835. return 0;
  836. }
  837. ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
  838. ei->i_da_metadata_calc_len = 1;
  839. blk_bits = order_base_2(lblock);
  840. return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
  841. }
  842. int ext4_ind_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  843. {
  844. int indirects;
  845. /* if nrblocks are contiguous */
  846. if (chunk) {
  847. /*
  848. * With N contiguous data blocks, we need at most
  849. * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
  850. * 2 dindirect blocks, and 1 tindirect block
  851. */
  852. return DIV_ROUND_UP(nrblocks,
  853. EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
  854. }
  855. /*
  856. * if nrblocks are not contiguous, worse case, each block touch
  857. * a indirect block, and each indirect block touch a double indirect
  858. * block, plus a triple indirect block
  859. */
  860. indirects = nrblocks * 2 + 1;
  861. return indirects;
  862. }
  863. /*
  864. * Truncate transactions can be complex and absolutely huge. So we need to
  865. * be able to restart the transaction at a conventient checkpoint to make
  866. * sure we don't overflow the journal.
  867. *
  868. * start_transaction gets us a new handle for a truncate transaction,
  869. * and extend_transaction tries to extend the existing one a bit. If
  870. * extend fails, we need to propagate the failure up and restart the
  871. * transaction in the top-level truncate loop. --sct
  872. */
  873. static handle_t *start_transaction(struct inode *inode)
  874. {
  875. handle_t *result;
  876. result = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
  877. ext4_blocks_for_truncate(inode));
  878. if (!IS_ERR(result))
  879. return result;
  880. ext4_std_error(inode->i_sb, PTR_ERR(result));
  881. return result;
  882. }
  883. /*
  884. * Try to extend this transaction for the purposes of truncation.
  885. *
  886. * Returns 0 if we managed to create more room. If we can't create more
  887. * room, and the transaction must be restarted we return 1.
  888. */
  889. static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
  890. {
  891. if (!ext4_handle_valid(handle))
  892. return 0;
  893. if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
  894. return 0;
  895. if (!ext4_journal_extend(handle, ext4_blocks_for_truncate(inode)))
  896. return 0;
  897. return 1;
  898. }
  899. /*
  900. * Probably it should be a library function... search for first non-zero word
  901. * or memcmp with zero_page, whatever is better for particular architecture.
  902. * Linus?
  903. */
  904. static inline int all_zeroes(__le32 *p, __le32 *q)
  905. {
  906. while (p < q)
  907. if (*p++)
  908. return 0;
  909. return 1;
  910. }
  911. /**
  912. * ext4_find_shared - find the indirect blocks for partial truncation.
  913. * @inode: inode in question
  914. * @depth: depth of the affected branch
  915. * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
  916. * @chain: place to store the pointers to partial indirect blocks
  917. * @top: place to the (detached) top of branch
  918. *
  919. * This is a helper function used by ext4_truncate().
  920. *
  921. * When we do truncate() we may have to clean the ends of several
  922. * indirect blocks but leave the blocks themselves alive. Block is
  923. * partially truncated if some data below the new i_size is referred
  924. * from it (and it is on the path to the first completely truncated
  925. * data block, indeed). We have to free the top of that path along
  926. * with everything to the right of the path. Since no allocation
  927. * past the truncation point is possible until ext4_truncate()
  928. * finishes, we may safely do the latter, but top of branch may
  929. * require special attention - pageout below the truncation point
  930. * might try to populate it.
  931. *
  932. * We atomically detach the top of branch from the tree, store the
  933. * block number of its root in *@top, pointers to buffer_heads of
  934. * partially truncated blocks - in @chain[].bh and pointers to
  935. * their last elements that should not be removed - in
  936. * @chain[].p. Return value is the pointer to last filled element
  937. * of @chain.
  938. *
  939. * The work left to caller to do the actual freeing of subtrees:
  940. * a) free the subtree starting from *@top
  941. * b) free the subtrees whose roots are stored in
  942. * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
  943. * c) free the subtrees growing from the inode past the @chain[0].
  944. * (no partially truncated stuff there). */
  945. static Indirect *ext4_find_shared(struct inode *inode, int depth,
  946. ext4_lblk_t offsets[4], Indirect chain[4],
  947. __le32 *top)
  948. {
  949. Indirect *partial, *p;
  950. int k, err;
  951. *top = 0;
  952. /* Make k index the deepest non-null offset + 1 */
  953. for (k = depth; k > 1 && !offsets[k-1]; k--)
  954. ;
  955. partial = ext4_get_branch(inode, k, offsets, chain, &err);
  956. /* Writer: pointers */
  957. if (!partial)
  958. partial = chain + k-1;
  959. /*
  960. * If the branch acquired continuation since we've looked at it -
  961. * fine, it should all survive and (new) top doesn't belong to us.
  962. */
  963. if (!partial->key && *partial->p)
  964. /* Writer: end */
  965. goto no_top;
  966. for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
  967. ;
  968. /*
  969. * OK, we've found the last block that must survive. The rest of our
  970. * branch should be detached before unlocking. However, if that rest
  971. * of branch is all ours and does not grow immediately from the inode
  972. * it's easier to cheat and just decrement partial->p.
  973. */
  974. if (p == chain + k - 1 && p > chain) {
  975. p->p--;
  976. } else {
  977. *top = *p->p;
  978. /* Nope, don't do this in ext4. Must leave the tree intact */
  979. #if 0
  980. *p->p = 0;
  981. #endif
  982. }
  983. /* Writer: end */
  984. while (partial > p) {
  985. brelse(partial->bh);
  986. partial--;
  987. }
  988. no_top:
  989. return partial;
  990. }
  991. /*
  992. * Zero a number of block pointers in either an inode or an indirect block.
  993. * If we restart the transaction we must again get write access to the
  994. * indirect block for further modification.
  995. *
  996. * We release `count' blocks on disk, but (last - first) may be greater
  997. * than `count' because there can be holes in there.
  998. *
  999. * Return 0 on success, 1 on invalid block range
  1000. * and < 0 on fatal error.
  1001. */
  1002. static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
  1003. struct buffer_head *bh,
  1004. ext4_fsblk_t block_to_free,
  1005. unsigned long count, __le32 *first,
  1006. __le32 *last)
  1007. {
  1008. __le32 *p;
  1009. int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
  1010. int err;
  1011. if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
  1012. flags |= EXT4_FREE_BLOCKS_METADATA;
  1013. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
  1014. count)) {
  1015. EXT4_ERROR_INODE(inode, "attempt to clear invalid "
  1016. "blocks %llu len %lu",
  1017. (unsigned long long) block_to_free, count);
  1018. return 1;
  1019. }
  1020. if (try_to_extend_transaction(handle, inode)) {
  1021. if (bh) {
  1022. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  1023. err = ext4_handle_dirty_metadata(handle, inode, bh);
  1024. if (unlikely(err))
  1025. goto out_err;
  1026. }
  1027. err = ext4_mark_inode_dirty(handle, inode);
  1028. if (unlikely(err))
  1029. goto out_err;
  1030. err = ext4_truncate_restart_trans(handle, inode,
  1031. ext4_blocks_for_truncate(inode));
  1032. if (unlikely(err))
  1033. goto out_err;
  1034. if (bh) {
  1035. BUFFER_TRACE(bh, "retaking write access");
  1036. err = ext4_journal_get_write_access(handle, bh);
  1037. if (unlikely(err))
  1038. goto out_err;
  1039. }
  1040. }
  1041. for (p = first; p < last; p++)
  1042. *p = 0;
  1043. ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
  1044. return 0;
  1045. out_err:
  1046. ext4_std_error(inode->i_sb, err);
  1047. return err;
  1048. }
  1049. /**
  1050. * ext4_free_data - free a list of data blocks
  1051. * @handle: handle for this transaction
  1052. * @inode: inode we are dealing with
  1053. * @this_bh: indirect buffer_head which contains *@first and *@last
  1054. * @first: array of block numbers
  1055. * @last: points immediately past the end of array
  1056. *
  1057. * We are freeing all blocks referred from that array (numbers are stored as
  1058. * little-endian 32-bit) and updating @inode->i_blocks appropriately.
  1059. *
  1060. * We accumulate contiguous runs of blocks to free. Conveniently, if these
  1061. * blocks are contiguous then releasing them at one time will only affect one
  1062. * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
  1063. * actually use a lot of journal space.
  1064. *
  1065. * @this_bh will be %NULL if @first and @last point into the inode's direct
  1066. * block pointers.
  1067. */
  1068. static void ext4_free_data(handle_t *handle, struct inode *inode,
  1069. struct buffer_head *this_bh,
  1070. __le32 *first, __le32 *last)
  1071. {
  1072. ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
  1073. unsigned long count = 0; /* Number of blocks in the run */
  1074. __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
  1075. corresponding to
  1076. block_to_free */
  1077. ext4_fsblk_t nr; /* Current block # */
  1078. __le32 *p; /* Pointer into inode/ind
  1079. for current block */
  1080. int err = 0;
  1081. if (this_bh) { /* For indirect block */
  1082. BUFFER_TRACE(this_bh, "get_write_access");
  1083. err = ext4_journal_get_write_access(handle, this_bh);
  1084. /* Important: if we can't update the indirect pointers
  1085. * to the blocks, we can't free them. */
  1086. if (err)
  1087. return;
  1088. }
  1089. for (p = first; p < last; p++) {
  1090. nr = le32_to_cpu(*p);
  1091. if (nr) {
  1092. /* accumulate blocks to free if they're contiguous */
  1093. if (count == 0) {
  1094. block_to_free = nr;
  1095. block_to_free_p = p;
  1096. count = 1;
  1097. } else if (nr == block_to_free + count) {
  1098. count++;
  1099. } else {
  1100. err = ext4_clear_blocks(handle, inode, this_bh,
  1101. block_to_free, count,
  1102. block_to_free_p, p);
  1103. if (err)
  1104. break;
  1105. block_to_free = nr;
  1106. block_to_free_p = p;
  1107. count = 1;
  1108. }
  1109. }
  1110. }
  1111. if (!err && count > 0)
  1112. err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
  1113. count, block_to_free_p, p);
  1114. if (err < 0)
  1115. /* fatal error */
  1116. return;
  1117. if (this_bh) {
  1118. BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
  1119. /*
  1120. * The buffer head should have an attached journal head at this
  1121. * point. However, if the data is corrupted and an indirect
  1122. * block pointed to itself, it would have been detached when
  1123. * the block was cleared. Check for this instead of OOPSing.
  1124. */
  1125. if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
  1126. ext4_handle_dirty_metadata(handle, inode, this_bh);
  1127. else
  1128. EXT4_ERROR_INODE(inode,
  1129. "circular indirect block detected at "
  1130. "block %llu",
  1131. (unsigned long long) this_bh->b_blocknr);
  1132. }
  1133. }
  1134. /**
  1135. * ext4_free_branches - free an array of branches
  1136. * @handle: JBD handle for this transaction
  1137. * @inode: inode we are dealing with
  1138. * @parent_bh: the buffer_head which contains *@first and *@last
  1139. * @first: array of block numbers
  1140. * @last: pointer immediately past the end of array
  1141. * @depth: depth of the branches to free
  1142. *
  1143. * We are freeing all blocks referred from these branches (numbers are
  1144. * stored as little-endian 32-bit) and updating @inode->i_blocks
  1145. * appropriately.
  1146. */
  1147. static void ext4_free_branches(handle_t *handle, struct inode *inode,
  1148. struct buffer_head *parent_bh,
  1149. __le32 *first, __le32 *last, int depth)
  1150. {
  1151. ext4_fsblk_t nr;
  1152. __le32 *p;
  1153. if (ext4_handle_is_aborted(handle))
  1154. return;
  1155. if (depth--) {
  1156. struct buffer_head *bh;
  1157. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  1158. p = last;
  1159. while (--p >= first) {
  1160. nr = le32_to_cpu(*p);
  1161. if (!nr)
  1162. continue; /* A hole */
  1163. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
  1164. nr, 1)) {
  1165. EXT4_ERROR_INODE(inode,
  1166. "invalid indirect mapped "
  1167. "block %lu (level %d)",
  1168. (unsigned long) nr, depth);
  1169. break;
  1170. }
  1171. /* Go read the buffer for the next level down */
  1172. bh = sb_bread(inode->i_sb, nr);
  1173. /*
  1174. * A read failure? Report error and clear slot
  1175. * (should be rare).
  1176. */
  1177. if (!bh) {
  1178. EXT4_ERROR_INODE_BLOCK(inode, nr,
  1179. "Read failure");
  1180. continue;
  1181. }
  1182. /* This zaps the entire block. Bottom up. */
  1183. BUFFER_TRACE(bh, "free child branches");
  1184. ext4_free_branches(handle, inode, bh,
  1185. (__le32 *) bh->b_data,
  1186. (__le32 *) bh->b_data + addr_per_block,
  1187. depth);
  1188. brelse(bh);
  1189. /*
  1190. * Everything below this this pointer has been
  1191. * released. Now let this top-of-subtree go.
  1192. *
  1193. * We want the freeing of this indirect block to be
  1194. * atomic in the journal with the updating of the
  1195. * bitmap block which owns it. So make some room in
  1196. * the journal.
  1197. *
  1198. * We zero the parent pointer *after* freeing its
  1199. * pointee in the bitmaps, so if extend_transaction()
  1200. * for some reason fails to put the bitmap changes and
  1201. * the release into the same transaction, recovery
  1202. * will merely complain about releasing a free block,
  1203. * rather than leaking blocks.
  1204. */
  1205. if (ext4_handle_is_aborted(handle))
  1206. return;
  1207. if (try_to_extend_transaction(handle, inode)) {
  1208. ext4_mark_inode_dirty(handle, inode);
  1209. ext4_truncate_restart_trans(handle, inode,
  1210. ext4_blocks_for_truncate(inode));
  1211. }
  1212. /*
  1213. * The forget flag here is critical because if
  1214. * we are journaling (and not doing data
  1215. * journaling), we have to make sure a revoke
  1216. * record is written to prevent the journal
  1217. * replay from overwriting the (former)
  1218. * indirect block if it gets reallocated as a
  1219. * data block. This must happen in the same
  1220. * transaction where the data blocks are
  1221. * actually freed.
  1222. */
  1223. ext4_free_blocks(handle, inode, NULL, nr, 1,
  1224. EXT4_FREE_BLOCKS_METADATA|
  1225. EXT4_FREE_BLOCKS_FORGET);
  1226. if (parent_bh) {
  1227. /*
  1228. * The block which we have just freed is
  1229. * pointed to by an indirect block: journal it
  1230. */
  1231. BUFFER_TRACE(parent_bh, "get_write_access");
  1232. if (!ext4_journal_get_write_access(handle,
  1233. parent_bh)){
  1234. *p = 0;
  1235. BUFFER_TRACE(parent_bh,
  1236. "call ext4_handle_dirty_metadata");
  1237. ext4_handle_dirty_metadata(handle,
  1238. inode,
  1239. parent_bh);
  1240. }
  1241. }
  1242. }
  1243. } else {
  1244. /* We have reached the bottom of the tree. */
  1245. BUFFER_TRACE(parent_bh, "free data blocks");
  1246. ext4_free_data(handle, inode, parent_bh, first, last);
  1247. }
  1248. }
  1249. void ext4_ind_truncate(struct inode *inode)
  1250. {
  1251. handle_t *handle;
  1252. struct ext4_inode_info *ei = EXT4_I(inode);
  1253. __le32 *i_data = ei->i_data;
  1254. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  1255. struct address_space *mapping = inode->i_mapping;
  1256. ext4_lblk_t offsets[4];
  1257. Indirect chain[4];
  1258. Indirect *partial;
  1259. __le32 nr = 0;
  1260. int n = 0;
  1261. ext4_lblk_t last_block, max_block;
  1262. loff_t page_len;
  1263. unsigned blocksize = inode->i_sb->s_blocksize;
  1264. int err;
  1265. handle = start_transaction(inode);
  1266. if (IS_ERR(handle))
  1267. return; /* AKPM: return what? */
  1268. last_block = (inode->i_size + blocksize-1)
  1269. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  1270. max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
  1271. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  1272. if (inode->i_size % PAGE_CACHE_SIZE != 0) {
  1273. page_len = PAGE_CACHE_SIZE -
  1274. (inode->i_size & (PAGE_CACHE_SIZE - 1));
  1275. err = ext4_discard_partial_page_buffers(handle,
  1276. mapping, inode->i_size, page_len, 0);
  1277. if (err)
  1278. goto out_stop;
  1279. }
  1280. if (last_block != max_block) {
  1281. n = ext4_block_to_path(inode, last_block, offsets, NULL);
  1282. if (n == 0)
  1283. goto out_stop; /* error */
  1284. }
  1285. /*
  1286. * OK. This truncate is going to happen. We add the inode to the
  1287. * orphan list, so that if this truncate spans multiple transactions,
  1288. * and we crash, we will resume the truncate when the filesystem
  1289. * recovers. It also marks the inode dirty, to catch the new size.
  1290. *
  1291. * Implication: the file must always be in a sane, consistent
  1292. * truncatable state while each transaction commits.
  1293. */
  1294. if (ext4_orphan_add(handle, inode))
  1295. goto out_stop;
  1296. /*
  1297. * From here we block out all ext4_get_block() callers who want to
  1298. * modify the block allocation tree.
  1299. */
  1300. down_write(&ei->i_data_sem);
  1301. ext4_discard_preallocations(inode);
  1302. ext4_es_remove_extent(inode, last_block, EXT_MAX_BLOCKS - last_block);
  1303. /*
  1304. * The orphan list entry will now protect us from any crash which
  1305. * occurs before the truncate completes, so it is now safe to propagate
  1306. * the new, shorter inode size (held for now in i_size) into the
  1307. * on-disk inode. We do this via i_disksize, which is the value which
  1308. * ext4 *really* writes onto the disk inode.
  1309. */
  1310. ei->i_disksize = inode->i_size;
  1311. if (last_block == max_block) {
  1312. /*
  1313. * It is unnecessary to free any data blocks if last_block is
  1314. * equal to the indirect block limit.
  1315. */
  1316. goto out_unlock;
  1317. } else if (n == 1) { /* direct blocks */
  1318. ext4_free_data(handle, inode, NULL, i_data+offsets[0],
  1319. i_data + EXT4_NDIR_BLOCKS);
  1320. goto do_indirects;
  1321. }
  1322. partial = ext4_find_shared(inode, n, offsets, chain, &nr);
  1323. /* Kill the top of shared branch (not detached) */
  1324. if (nr) {
  1325. if (partial == chain) {
  1326. /* Shared branch grows from the inode */
  1327. ext4_free_branches(handle, inode, NULL,
  1328. &nr, &nr+1, (chain+n-1) - partial);
  1329. *partial->p = 0;
  1330. /*
  1331. * We mark the inode dirty prior to restart,
  1332. * and prior to stop. No need for it here.
  1333. */
  1334. } else {
  1335. /* Shared branch grows from an indirect block */
  1336. BUFFER_TRACE(partial->bh, "get_write_access");
  1337. ext4_free_branches(handle, inode, partial->bh,
  1338. partial->p,
  1339. partial->p+1, (chain+n-1) - partial);
  1340. }
  1341. }
  1342. /* Clear the ends of indirect blocks on the shared branch */
  1343. while (partial > chain) {
  1344. ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
  1345. (__le32*)partial->bh->b_data+addr_per_block,
  1346. (chain+n-1) - partial);
  1347. BUFFER_TRACE(partial->bh, "call brelse");
  1348. brelse(partial->bh);
  1349. partial--;
  1350. }
  1351. do_indirects:
  1352. /* Kill the remaining (whole) subtrees */
  1353. switch (offsets[0]) {
  1354. default:
  1355. nr = i_data[EXT4_IND_BLOCK];
  1356. if (nr) {
  1357. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
  1358. i_data[EXT4_IND_BLOCK] = 0;
  1359. }
  1360. case EXT4_IND_BLOCK:
  1361. nr = i_data[EXT4_DIND_BLOCK];
  1362. if (nr) {
  1363. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
  1364. i_data[EXT4_DIND_BLOCK] = 0;
  1365. }
  1366. case EXT4_DIND_BLOCK:
  1367. nr = i_data[EXT4_TIND_BLOCK];
  1368. if (nr) {
  1369. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
  1370. i_data[EXT4_TIND_BLOCK] = 0;
  1371. }
  1372. case EXT4_TIND_BLOCK:
  1373. ;
  1374. }
  1375. out_unlock:
  1376. up_write(&ei->i_data_sem);
  1377. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  1378. ext4_mark_inode_dirty(handle, inode);
  1379. /*
  1380. * In a multi-transaction truncate, we only make the final transaction
  1381. * synchronous
  1382. */
  1383. if (IS_SYNC(inode))
  1384. ext4_handle_sync(handle);
  1385. out_stop:
  1386. /*
  1387. * If this was a simple ftruncate(), and the file will remain alive
  1388. * then we need to clear up the orphan record which we created above.
  1389. * However, if this was a real unlink then we were called by
  1390. * ext4_delete_inode(), and we allow that function to clean up the
  1391. * orphan info for us.
  1392. */
  1393. if (inode->i_nlink)
  1394. ext4_orphan_del(handle, inode);
  1395. ext4_journal_stop(handle);
  1396. trace_ext4_truncate_exit(inode);
  1397. }
  1398. static int free_hole_blocks(handle_t *handle, struct inode *inode,
  1399. struct buffer_head *parent_bh, __le32 *i_data,
  1400. int level, ext4_lblk_t first,
  1401. ext4_lblk_t count, int max)
  1402. {
  1403. struct buffer_head *bh = NULL;
  1404. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  1405. int ret = 0;
  1406. int i, inc;
  1407. ext4_lblk_t offset;
  1408. __le32 blk;
  1409. inc = 1 << ((EXT4_BLOCK_SIZE_BITS(inode->i_sb) - 2) * level);
  1410. for (i = 0, offset = 0; i < max; i++, i_data++, offset += inc) {
  1411. if (offset >= count + first)
  1412. break;
  1413. if (*i_data == 0 || (offset + inc) <= first)
  1414. continue;
  1415. blk = *i_data;
  1416. if (level > 0) {
  1417. ext4_lblk_t first2;
  1418. bh = sb_bread(inode->i_sb, le32_to_cpu(blk));
  1419. if (!bh) {
  1420. EXT4_ERROR_INODE_BLOCK(inode, le32_to_cpu(blk),
  1421. "Read failure");
  1422. return -EIO;
  1423. }
  1424. first2 = (first > offset) ? first - offset : 0;
  1425. ret = free_hole_blocks(handle, inode, bh,
  1426. (__le32 *)bh->b_data, level - 1,
  1427. first2, count - offset,
  1428. inode->i_sb->s_blocksize >> 2);
  1429. if (ret) {
  1430. brelse(bh);
  1431. goto err;
  1432. }
  1433. }
  1434. if (level == 0 ||
  1435. (bh && all_zeroes((__le32 *)bh->b_data,
  1436. (__le32 *)bh->b_data + addr_per_block))) {
  1437. ext4_free_data(handle, inode, parent_bh, &blk, &blk+1);
  1438. *i_data = 0;
  1439. }
  1440. brelse(bh);
  1441. bh = NULL;
  1442. }
  1443. err:
  1444. return ret;
  1445. }
  1446. static int ext4_free_hole_blocks(handle_t *handle, struct inode *inode,
  1447. ext4_lblk_t first, ext4_lblk_t stop)
  1448. {
  1449. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  1450. int level, ret = 0;
  1451. int num = EXT4_NDIR_BLOCKS;
  1452. ext4_lblk_t count, max = EXT4_NDIR_BLOCKS;
  1453. __le32 *i_data = EXT4_I(inode)->i_data;
  1454. count = stop - first;
  1455. for (level = 0; level < 4; level++, max *= addr_per_block) {
  1456. if (first < max) {
  1457. ret = free_hole_blocks(handle, inode, NULL, i_data,
  1458. level, first, count, num);
  1459. if (ret)
  1460. goto err;
  1461. if (count > max - first)
  1462. count -= max - first;
  1463. else
  1464. break;
  1465. first = 0;
  1466. } else {
  1467. first -= max;
  1468. }
  1469. i_data += num;
  1470. if (level == 0) {
  1471. num = 1;
  1472. max = 1;
  1473. }
  1474. }
  1475. err:
  1476. return ret;
  1477. }
  1478. int ext4_ind_punch_hole(struct file *file, loff_t offset, loff_t length)
  1479. {
  1480. struct inode *inode = file_inode(file);
  1481. struct super_block *sb = inode->i_sb;
  1482. ext4_lblk_t first_block, stop_block;
  1483. struct address_space *mapping = inode->i_mapping;
  1484. handle_t *handle = NULL;
  1485. loff_t first_page, last_page, page_len;
  1486. loff_t first_page_offset, last_page_offset;
  1487. int err = 0;
  1488. /*
  1489. * Write out all dirty pages to avoid race conditions
  1490. * Then release them.
  1491. */
  1492. if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
  1493. err = filemap_write_and_wait_range(mapping,
  1494. offset, offset + length - 1);
  1495. if (err)
  1496. return err;
  1497. }
  1498. mutex_lock(&inode->i_mutex);
  1499. /* It's not possible punch hole on append only file */
  1500. if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
  1501. err = -EPERM;
  1502. goto out_mutex;
  1503. }
  1504. if (IS_SWAPFILE(inode)) {
  1505. err = -ETXTBSY;
  1506. goto out_mutex;
  1507. }
  1508. /* No need to punch hole beyond i_size */
  1509. if (offset >= inode->i_size)
  1510. goto out_mutex;
  1511. /*
  1512. * If the hole extents beyond i_size, set the hole
  1513. * to end after the page that contains i_size
  1514. */
  1515. if (offset + length > inode->i_size) {
  1516. length = inode->i_size +
  1517. PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
  1518. offset;
  1519. }
  1520. first_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1521. last_page = (offset + length) >> PAGE_CACHE_SHIFT;
  1522. first_page_offset = first_page << PAGE_CACHE_SHIFT;
  1523. last_page_offset = last_page << PAGE_CACHE_SHIFT;
  1524. /* Now release the pages */
  1525. if (last_page_offset > first_page_offset) {
  1526. truncate_pagecache_range(inode, first_page_offset,
  1527. last_page_offset - 1);
  1528. }
  1529. /* Wait all existing dio works, newcomers will block on i_mutex */
  1530. inode_dio_wait(inode);
  1531. handle = start_transaction(inode);
  1532. if (IS_ERR(handle))
  1533. goto out_mutex;
  1534. /*
  1535. * Now we need to zero out the non-page-aligned data in the
  1536. * pages at the start and tail of the hole, and unmap the buffer
  1537. * heads for the block aligned regions of the page that were
  1538. * completely zerod.
  1539. */
  1540. if (first_page > last_page) {
  1541. /*
  1542. * If the file space being truncated is contained within a page
  1543. * just zero out and unmap the middle of that page
  1544. */
  1545. err = ext4_discard_partial_page_buffers(handle,
  1546. mapping, offset, length, 0);
  1547. if (err)
  1548. goto out;
  1549. } else {
  1550. /*
  1551. * Zero out and unmap the paritial page that contains
  1552. * the start of the hole
  1553. */
  1554. page_len = first_page_offset - offset;
  1555. if (page_len > 0) {
  1556. err = ext4_discard_partial_page_buffers(handle, mapping,
  1557. offset, page_len, 0);
  1558. if (err)
  1559. goto out;
  1560. }
  1561. /*
  1562. * Zero out and unmap the partial page that contains
  1563. * the end of the hole
  1564. */
  1565. page_len = offset + length - last_page_offset;
  1566. if (page_len > 0) {
  1567. err = ext4_discard_partial_page_buffers(handle, mapping,
  1568. last_page_offset, page_len, 0);
  1569. if (err)
  1570. goto out;
  1571. }
  1572. }
  1573. /*
  1574. * If i_size contained in the last page, we need to
  1575. * unmap and zero the paritial page after i_size
  1576. */
  1577. if (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&
  1578. inode->i_size % PAGE_CACHE_SIZE != 0) {
  1579. page_len = PAGE_CACHE_SIZE -
  1580. (inode->i_size & (PAGE_CACHE_SIZE - 1));
  1581. if (page_len > 0) {
  1582. err = ext4_discard_partial_page_buffers(handle,
  1583. mapping, inode->i_size, page_len, 0);
  1584. if (err)
  1585. goto out;
  1586. }
  1587. }
  1588. first_block = (offset + sb->s_blocksize - 1) >>
  1589. EXT4_BLOCK_SIZE_BITS(sb);
  1590. stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
  1591. if (first_block >= stop_block)
  1592. goto out;
  1593. down_write(&EXT4_I(inode)->i_data_sem);
  1594. ext4_discard_preallocations(inode);
  1595. err = ext4_es_remove_extent(inode, first_block,
  1596. stop_block - first_block);
  1597. err = ext4_free_hole_blocks(handle, inode, first_block, stop_block);
  1598. ext4_discard_preallocations(inode);
  1599. if (IS_SYNC(inode))
  1600. ext4_handle_sync(handle);
  1601. up_write(&EXT4_I(inode)->i_data_sem);
  1602. out:
  1603. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  1604. ext4_mark_inode_dirty(handle, inode);
  1605. ext4_journal_stop(handle);
  1606. out_mutex:
  1607. mutex_unlock(&inode->i_mutex);
  1608. return err;
  1609. }