file.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. /*
  2. * Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
  3. */
  4. #include <linux/time.h>
  5. #include <linux/reiserfs_fs.h>
  6. #include <linux/reiserfs_acl.h>
  7. #include <linux/reiserfs_xattr.h>
  8. #include <asm/uaccess.h>
  9. #include <linux/pagemap.h>
  10. #include <linux/swap.h>
  11. #include <linux/writeback.h>
  12. #include <linux/blkdev.h>
  13. #include <linux/buffer_head.h>
  14. #include <linux/quotaops.h>
  15. /*
  16. ** We pack the tails of files on file close, not at the time they are written.
  17. ** This implies an unnecessary copy of the tail and an unnecessary indirect item
  18. ** insertion/balancing, for files that are written in one write.
  19. ** It avoids unnecessary tail packings (balances) for files that are written in
  20. ** multiple writes and are small enough to have tails.
  21. **
  22. ** file_release is called by the VFS layer when the file is closed. If
  23. ** this is the last open file descriptor, and the file
  24. ** small enough to have a tail, and the tail is currently in an
  25. ** unformatted node, the tail is converted back into a direct item.
  26. **
  27. ** We use reiserfs_truncate_file to pack the tail, since it already has
  28. ** all the conditions coded.
  29. */
  30. static int reiserfs_file_release(struct inode *inode, struct file *filp)
  31. {
  32. struct reiserfs_transaction_handle th;
  33. int err;
  34. int jbegin_failure = 0;
  35. BUG_ON(!S_ISREG(inode->i_mode));
  36. /* fast out for when nothing needs to be done */
  37. if ((atomic_read(&inode->i_count) > 1 ||
  38. !(REISERFS_I(inode)->i_flags & i_pack_on_close_mask) ||
  39. !tail_has_to_be_packed(inode)) &&
  40. REISERFS_I(inode)->i_prealloc_count <= 0) {
  41. return 0;
  42. }
  43. mutex_lock(&inode->i_mutex);
  44. mutex_lock(&(REISERFS_I(inode)->i_mmap));
  45. if (REISERFS_I(inode)->i_flags & i_ever_mapped)
  46. REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
  47. reiserfs_write_lock(inode->i_sb);
  48. /* freeing preallocation only involves relogging blocks that
  49. * are already in the current transaction. preallocation gets
  50. * freed at the end of each transaction, so it is impossible for
  51. * us to log any additional blocks (including quota blocks)
  52. */
  53. err = journal_begin(&th, inode->i_sb, 1);
  54. if (err) {
  55. /* uh oh, we can't allow the inode to go away while there
  56. * is still preallocation blocks pending. Try to join the
  57. * aborted transaction
  58. */
  59. jbegin_failure = err;
  60. err = journal_join_abort(&th, inode->i_sb, 1);
  61. if (err) {
  62. /* hmpf, our choices here aren't good. We can pin the inode
  63. * which will disallow unmount from every happening, we can
  64. * do nothing, which will corrupt random memory on unmount,
  65. * or we can forcibly remove the file from the preallocation
  66. * list, which will leak blocks on disk. Lets pin the inode
  67. * and let the admin know what is going on.
  68. */
  69. igrab(inode);
  70. reiserfs_warning(inode->i_sb,
  71. "pinning inode %lu because the "
  72. "preallocation can't be freed",
  73. inode->i_ino);
  74. goto out;
  75. }
  76. }
  77. reiserfs_update_inode_transaction(inode);
  78. #ifdef REISERFS_PREALLOCATE
  79. reiserfs_discard_prealloc(&th, inode);
  80. #endif
  81. err = journal_end(&th, inode->i_sb, 1);
  82. /* copy back the error code from journal_begin */
  83. if (!err)
  84. err = jbegin_failure;
  85. if (!err && atomic_read(&inode->i_count) <= 1 &&
  86. (REISERFS_I(inode)->i_flags & i_pack_on_close_mask) &&
  87. tail_has_to_be_packed(inode)) {
  88. /* if regular file is released by last holder and it has been
  89. appended (we append by unformatted node only) or its direct
  90. item(s) had to be converted, then it may have to be
  91. indirect2direct converted */
  92. err = reiserfs_truncate_file(inode, 0);
  93. }
  94. out:
  95. mutex_unlock(&(REISERFS_I(inode)->i_mmap));
  96. mutex_unlock(&inode->i_mutex);
  97. reiserfs_write_unlock(inode->i_sb);
  98. return err;
  99. }
  100. static int reiserfs_file_mmap(struct file *file, struct vm_area_struct *vma)
  101. {
  102. struct inode *inode;
  103. inode = file->f_path.dentry->d_inode;
  104. mutex_lock(&(REISERFS_I(inode)->i_mmap));
  105. REISERFS_I(inode)->i_flags |= i_ever_mapped;
  106. mutex_unlock(&(REISERFS_I(inode)->i_mmap));
  107. return generic_file_mmap(file, vma);
  108. }
  109. static void reiserfs_vfs_truncate_file(struct inode *inode)
  110. {
  111. reiserfs_truncate_file(inode, 1);
  112. }
  113. /* Sync a reiserfs file. */
  114. /*
  115. * FIXME: sync_mapping_buffers() never has anything to sync. Can
  116. * be removed...
  117. */
  118. static int reiserfs_sync_file(struct file *p_s_filp,
  119. struct dentry *p_s_dentry, int datasync)
  120. {
  121. struct inode *p_s_inode = p_s_dentry->d_inode;
  122. int n_err;
  123. int barrier_done;
  124. BUG_ON(!S_ISREG(p_s_inode->i_mode));
  125. n_err = sync_mapping_buffers(p_s_inode->i_mapping);
  126. reiserfs_write_lock(p_s_inode->i_sb);
  127. barrier_done = reiserfs_commit_for_inode(p_s_inode);
  128. reiserfs_write_unlock(p_s_inode->i_sb);
  129. if (barrier_done != 1 && reiserfs_barrier_flush(p_s_inode->i_sb))
  130. blkdev_issue_flush(p_s_inode->i_sb->s_bdev, NULL);
  131. if (barrier_done < 0)
  132. return barrier_done;
  133. return (n_err < 0) ? -EIO : 0;
  134. }
  135. /* I really do not want to play with memory shortage right now, so
  136. to simplify the code, we are not going to write more than this much pages at
  137. a time. This still should considerably improve performance compared to 4k
  138. at a time case. This is 32 pages of 4k size. */
  139. #define REISERFS_WRITE_PAGES_AT_A_TIME (128 * 1024) / PAGE_CACHE_SIZE
  140. /* Allocates blocks for a file to fulfil write request.
  141. Maps all unmapped but prepared pages from the list.
  142. Updates metadata with newly allocated blocknumbers as needed */
  143. static int reiserfs_allocate_blocks_for_region(struct reiserfs_transaction_handle *th, struct inode *inode, /* Inode we work with */
  144. loff_t pos, /* Writing position */
  145. int num_pages, /* number of pages write going
  146. to touch */
  147. int write_bytes, /* amount of bytes to write */
  148. struct page **prepared_pages, /* array of
  149. prepared pages
  150. */
  151. int blocks_to_allocate /* Amount of blocks we
  152. need to allocate to
  153. fit the data into file
  154. */
  155. )
  156. {
  157. struct cpu_key key; // cpu key of item that we are going to deal with
  158. struct item_head *ih; // pointer to item head that we are going to deal with
  159. struct buffer_head *bh; // Buffer head that contains items that we are going to deal with
  160. __le32 *item; // pointer to item we are going to deal with
  161. INITIALIZE_PATH(path); // path to item, that we are going to deal with.
  162. b_blocknr_t *allocated_blocks; // Pointer to a place where allocated blocknumbers would be stored.
  163. reiserfs_blocknr_hint_t hint; // hint structure for block allocator.
  164. size_t res; // return value of various functions that we call.
  165. int curr_block; // current block used to keep track of unmapped blocks.
  166. int i; // loop counter
  167. int itempos; // position in item
  168. unsigned int from = (pos & (PAGE_CACHE_SIZE - 1)); // writing position in
  169. // first page
  170. unsigned int to = ((pos + write_bytes - 1) & (PAGE_CACHE_SIZE - 1)) + 1; /* last modified byte offset in last page */
  171. __u64 hole_size; // amount of blocks for a file hole, if it needed to be created.
  172. int modifying_this_item = 0; // Flag for items traversal code to keep track
  173. // of the fact that we already prepared
  174. // current block for journal
  175. int will_prealloc = 0;
  176. RFALSE(!blocks_to_allocate,
  177. "green-9004: tried to allocate zero blocks?");
  178. /* only preallocate if this is a small write */
  179. if (REISERFS_I(inode)->i_prealloc_count ||
  180. (!(write_bytes & (inode->i_sb->s_blocksize - 1)) &&
  181. blocks_to_allocate <
  182. REISERFS_SB(inode->i_sb)->s_alloc_options.preallocsize))
  183. will_prealloc =
  184. REISERFS_SB(inode->i_sb)->s_alloc_options.preallocsize;
  185. allocated_blocks = kmalloc((blocks_to_allocate + will_prealloc) *
  186. sizeof(b_blocknr_t), GFP_NOFS);
  187. if (!allocated_blocks)
  188. return -ENOMEM;
  189. /* First we compose a key to point at the writing position, we want to do
  190. that outside of any locking region. */
  191. make_cpu_key(&key, inode, pos + 1, TYPE_ANY, 3 /*key length */ );
  192. /* If we came here, it means we absolutely need to open a transaction,
  193. since we need to allocate some blocks */
  194. reiserfs_write_lock(inode->i_sb); // Journaling stuff and we need that.
  195. res = journal_begin(th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 3 + 1 + 2 * REISERFS_QUOTA_TRANS_BLOCKS(inode->i_sb)); // Wish I know if this number enough
  196. if (res)
  197. goto error_exit;
  198. reiserfs_update_inode_transaction(inode);
  199. /* Look for the in-tree position of our write, need path for block allocator */
  200. res = search_for_position_by_key(inode->i_sb, &key, &path);
  201. if (res == IO_ERROR) {
  202. res = -EIO;
  203. goto error_exit;
  204. }
  205. /* Allocate blocks */
  206. /* First fill in "hint" structure for block allocator */
  207. hint.th = th; // transaction handle.
  208. hint.path = &path; // Path, so that block allocator can determine packing locality or whatever it needs to determine.
  209. hint.inode = inode; // Inode is needed by block allocator too.
  210. hint.search_start = 0; // We have no hint on where to search free blocks for block allocator.
  211. hint.key = key.on_disk_key; // on disk key of file.
  212. hint.block = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9); // Number of disk blocks this file occupies already.
  213. hint.formatted_node = 0; // We are allocating blocks for unformatted node.
  214. hint.preallocate = will_prealloc;
  215. /* Call block allocator to allocate blocks */
  216. res =
  217. reiserfs_allocate_blocknrs(&hint, allocated_blocks,
  218. blocks_to_allocate, blocks_to_allocate);
  219. if (res != CARRY_ON) {
  220. if (res == NO_DISK_SPACE) {
  221. /* We flush the transaction in case of no space. This way some
  222. blocks might become free */
  223. SB_JOURNAL(inode->i_sb)->j_must_wait = 1;
  224. res = restart_transaction(th, inode, &path);
  225. if (res)
  226. goto error_exit;
  227. /* We might have scheduled, so search again */
  228. res =
  229. search_for_position_by_key(inode->i_sb, &key,
  230. &path);
  231. if (res == IO_ERROR) {
  232. res = -EIO;
  233. goto error_exit;
  234. }
  235. /* update changed info for hint structure. */
  236. res =
  237. reiserfs_allocate_blocknrs(&hint, allocated_blocks,
  238. blocks_to_allocate,
  239. blocks_to_allocate);
  240. if (res != CARRY_ON) {
  241. res = res == QUOTA_EXCEEDED ? -EDQUOT : -ENOSPC;
  242. pathrelse(&path);
  243. goto error_exit;
  244. }
  245. } else {
  246. res = res == QUOTA_EXCEEDED ? -EDQUOT : -ENOSPC;
  247. pathrelse(&path);
  248. goto error_exit;
  249. }
  250. }
  251. #ifdef __BIG_ENDIAN
  252. // Too bad, I have not found any way to convert a given region from
  253. // cpu format to little endian format
  254. {
  255. int i;
  256. for (i = 0; i < blocks_to_allocate; i++)
  257. allocated_blocks[i] = cpu_to_le32(allocated_blocks[i]);
  258. }
  259. #endif
  260. /* Blocks allocating well might have scheduled and tree might have changed,
  261. let's search the tree again */
  262. /* find where in the tree our write should go */
  263. res = search_for_position_by_key(inode->i_sb, &key, &path);
  264. if (res == IO_ERROR) {
  265. res = -EIO;
  266. goto error_exit_free_blocks;
  267. }
  268. bh = get_last_bh(&path); // Get a bufferhead for last element in path.
  269. ih = get_ih(&path); // Get a pointer to last item head in path.
  270. item = get_item(&path); // Get a pointer to last item in path
  271. /* Let's see what we have found */
  272. if (res != POSITION_FOUND) { /* position not found, this means that we
  273. might need to append file with holes
  274. first */
  275. // Since we are writing past the file's end, we need to find out if
  276. // there is a hole that needs to be inserted before our writing
  277. // position, and how many blocks it is going to cover (we need to
  278. // populate pointers to file blocks representing the hole with zeros)
  279. {
  280. int item_offset = 1;
  281. /*
  282. * if ih is stat data, its offset is 0 and we don't want to
  283. * add 1 to pos in the hole_size calculation
  284. */
  285. if (is_statdata_le_ih(ih))
  286. item_offset = 0;
  287. hole_size = (pos + item_offset -
  288. (le_key_k_offset
  289. (get_inode_item_key_version(inode),
  290. &(ih->ih_key)) + op_bytes_number(ih,
  291. inode->
  292. i_sb->
  293. s_blocksize)))
  294. >> inode->i_sb->s_blocksize_bits;
  295. }
  296. if (hole_size > 0) {
  297. int to_paste = min_t(__u64, hole_size, MAX_ITEM_LEN(inode->i_sb->s_blocksize) / UNFM_P_SIZE); // How much data to insert first time.
  298. /* area filled with zeroes, to supply as list of zero blocknumbers
  299. We allocate it outside of loop just in case loop would spin for
  300. several iterations. */
  301. char *zeros = kzalloc(to_paste * UNFM_P_SIZE, GFP_ATOMIC); // We cannot insert more than MAX_ITEM_LEN bytes anyway.
  302. if (!zeros) {
  303. res = -ENOMEM;
  304. goto error_exit_free_blocks;
  305. }
  306. do {
  307. to_paste =
  308. min_t(__u64, hole_size,
  309. MAX_ITEM_LEN(inode->i_sb->
  310. s_blocksize) /
  311. UNFM_P_SIZE);
  312. if (is_indirect_le_ih(ih)) {
  313. /* Ok, there is existing indirect item already. Need to append it */
  314. /* Calculate position past inserted item */
  315. make_cpu_key(&key, inode,
  316. le_key_k_offset
  317. (get_inode_item_key_version
  318. (inode),
  319. &(ih->ih_key)) +
  320. op_bytes_number(ih,
  321. inode->
  322. i_sb->
  323. s_blocksize),
  324. TYPE_INDIRECT, 3);
  325. res =
  326. reiserfs_paste_into_item(th, &path,
  327. &key,
  328. inode,
  329. (char *)
  330. zeros,
  331. UNFM_P_SIZE
  332. *
  333. to_paste);
  334. if (res) {
  335. kfree(zeros);
  336. goto error_exit_free_blocks;
  337. }
  338. } else if (is_statdata_le_ih(ih)) {
  339. /* No existing item, create it */
  340. /* item head for new item */
  341. struct item_head ins_ih;
  342. /* create a key for our new item */
  343. make_cpu_key(&key, inode, 1,
  344. TYPE_INDIRECT, 3);
  345. /* Create new item head for our new item */
  346. make_le_item_head(&ins_ih, &key,
  347. key.version, 1,
  348. TYPE_INDIRECT,
  349. to_paste *
  350. UNFM_P_SIZE,
  351. 0 /* free space */ );
  352. /* Find where such item should live in the tree */
  353. res =
  354. search_item(inode->i_sb, &key,
  355. &path);
  356. if (res != ITEM_NOT_FOUND) {
  357. /* item should not exist, otherwise we have error */
  358. if (res != -ENOSPC) {
  359. reiserfs_warning(inode->
  360. i_sb,
  361. "green-9008: search_by_key (%K) returned %d",
  362. &key,
  363. res);
  364. }
  365. res = -EIO;
  366. kfree(zeros);
  367. goto error_exit_free_blocks;
  368. }
  369. res =
  370. reiserfs_insert_item(th, &path,
  371. &key, &ins_ih,
  372. inode,
  373. (char *)zeros);
  374. } else {
  375. reiserfs_panic(inode->i_sb,
  376. "green-9011: Unexpected key type %K\n",
  377. &key);
  378. }
  379. if (res) {
  380. kfree(zeros);
  381. goto error_exit_free_blocks;
  382. }
  383. /* Now we want to check if transaction is too full, and if it is
  384. we restart it. This will also free the path. */
  385. if (journal_transaction_should_end
  386. (th, th->t_blocks_allocated)) {
  387. inode->i_size = cpu_key_k_offset(&key) +
  388. (to_paste << inode->i_blkbits);
  389. res =
  390. restart_transaction(th, inode,
  391. &path);
  392. if (res) {
  393. pathrelse(&path);
  394. kfree(zeros);
  395. goto error_exit;
  396. }
  397. }
  398. /* Well, need to recalculate path and stuff */
  399. set_cpu_key_k_offset(&key,
  400. cpu_key_k_offset(&key) +
  401. (to_paste << inode->
  402. i_blkbits));
  403. res =
  404. search_for_position_by_key(inode->i_sb,
  405. &key, &path);
  406. if (res == IO_ERROR) {
  407. res = -EIO;
  408. kfree(zeros);
  409. goto error_exit_free_blocks;
  410. }
  411. bh = get_last_bh(&path);
  412. ih = get_ih(&path);
  413. item = get_item(&path);
  414. hole_size -= to_paste;
  415. } while (hole_size);
  416. kfree(zeros);
  417. }
  418. }
  419. // Go through existing indirect items first
  420. // replace all zeroes with blocknumbers from list
  421. // Note that if no corresponding item was found, by previous search,
  422. // it means there are no existing in-tree representation for file area
  423. // we are going to overwrite, so there is nothing to scan through for holes.
  424. for (curr_block = 0, itempos = path.pos_in_item;
  425. curr_block < blocks_to_allocate && res == POSITION_FOUND;) {
  426. retry:
  427. if (itempos >= ih_item_len(ih) / UNFM_P_SIZE) {
  428. /* We run out of data in this indirect item, let's look for another
  429. one. */
  430. /* First if we are already modifying current item, log it */
  431. if (modifying_this_item) {
  432. journal_mark_dirty(th, inode->i_sb, bh);
  433. modifying_this_item = 0;
  434. }
  435. /* Then set the key to look for a new indirect item (offset of old
  436. item is added to old item length */
  437. set_cpu_key_k_offset(&key,
  438. le_key_k_offset
  439. (get_inode_item_key_version(inode),
  440. &(ih->ih_key)) +
  441. op_bytes_number(ih,
  442. inode->i_sb->
  443. s_blocksize));
  444. /* Search ofor position of new key in the tree. */
  445. res =
  446. search_for_position_by_key(inode->i_sb, &key,
  447. &path);
  448. if (res == IO_ERROR) {
  449. res = -EIO;
  450. goto error_exit_free_blocks;
  451. }
  452. bh = get_last_bh(&path);
  453. ih = get_ih(&path);
  454. item = get_item(&path);
  455. itempos = path.pos_in_item;
  456. continue; // loop to check all kinds of conditions and so on.
  457. }
  458. /* Ok, we have correct position in item now, so let's see if it is
  459. representing file hole (blocknumber is zero) and fill it if needed */
  460. if (!item[itempos]) {
  461. /* Ok, a hole. Now we need to check if we already prepared this
  462. block to be journaled */
  463. while (!modifying_this_item) { // loop until succeed
  464. /* Well, this item is not journaled yet, so we must prepare
  465. it for journal first, before we can change it */
  466. struct item_head tmp_ih; // We copy item head of found item,
  467. // here to detect if fs changed under
  468. // us while we were preparing for
  469. // journal.
  470. int fs_gen; // We store fs generation here to find if someone
  471. // changes fs under our feet
  472. copy_item_head(&tmp_ih, ih); // Remember itemhead
  473. fs_gen = get_generation(inode->i_sb); // remember fs generation
  474. reiserfs_prepare_for_journal(inode->i_sb, bh, 1); // Prepare a buffer within which indirect item is stored for changing.
  475. if (fs_changed(fs_gen, inode->i_sb)
  476. && item_moved(&tmp_ih, &path)) {
  477. // Sigh, fs was changed under us, we need to look for new
  478. // location of item we are working with
  479. /* unmark prepaerd area as journaled and search for it's
  480. new position */
  481. reiserfs_restore_prepared_buffer(inode->
  482. i_sb,
  483. bh);
  484. res =
  485. search_for_position_by_key(inode->
  486. i_sb,
  487. &key,
  488. &path);
  489. if (res == IO_ERROR) {
  490. res = -EIO;
  491. goto error_exit_free_blocks;
  492. }
  493. bh = get_last_bh(&path);
  494. ih = get_ih(&path);
  495. item = get_item(&path);
  496. itempos = path.pos_in_item;
  497. goto retry;
  498. }
  499. modifying_this_item = 1;
  500. }
  501. item[itempos] = allocated_blocks[curr_block]; // Assign new block
  502. curr_block++;
  503. }
  504. itempos++;
  505. }
  506. if (modifying_this_item) { // We need to log last-accessed block, if it
  507. // was modified, but not logged yet.
  508. journal_mark_dirty(th, inode->i_sb, bh);
  509. }
  510. if (curr_block < blocks_to_allocate) {
  511. // Oh, well need to append to indirect item, or to create indirect item
  512. // if there weren't any
  513. if (is_indirect_le_ih(ih)) {
  514. // Existing indirect item - append. First calculate key for append
  515. // position. We do not need to recalculate path as it should
  516. // already point to correct place.
  517. make_cpu_key(&key, inode,
  518. le_key_k_offset(get_inode_item_key_version
  519. (inode),
  520. &(ih->ih_key)) +
  521. op_bytes_number(ih,
  522. inode->i_sb->s_blocksize),
  523. TYPE_INDIRECT, 3);
  524. res =
  525. reiserfs_paste_into_item(th, &path, &key, inode,
  526. (char *)(allocated_blocks +
  527. curr_block),
  528. UNFM_P_SIZE *
  529. (blocks_to_allocate -
  530. curr_block));
  531. if (res) {
  532. goto error_exit_free_blocks;
  533. }
  534. } else if (is_statdata_le_ih(ih)) {
  535. // Last found item was statdata. That means we need to create indirect item.
  536. struct item_head ins_ih; /* itemhead for new item */
  537. /* create a key for our new item */
  538. make_cpu_key(&key, inode, 1, TYPE_INDIRECT, 3); // Position one,
  539. // because that's
  540. // where first
  541. // indirect item
  542. // begins
  543. /* Create new item head for our new item */
  544. make_le_item_head(&ins_ih, &key, key.version, 1,
  545. TYPE_INDIRECT,
  546. (blocks_to_allocate -
  547. curr_block) * UNFM_P_SIZE,
  548. 0 /* free space */ );
  549. /* Find where such item should live in the tree */
  550. res = search_item(inode->i_sb, &key, &path);
  551. if (res != ITEM_NOT_FOUND) {
  552. /* Well, if we have found such item already, or some error
  553. occured, we need to warn user and return error */
  554. if (res != -ENOSPC) {
  555. reiserfs_warning(inode->i_sb,
  556. "green-9009: search_by_key (%K) "
  557. "returned %d", &key,
  558. res);
  559. }
  560. res = -EIO;
  561. goto error_exit_free_blocks;
  562. }
  563. /* Insert item into the tree with the data as its body */
  564. res =
  565. reiserfs_insert_item(th, &path, &key, &ins_ih,
  566. inode,
  567. (char *)(allocated_blocks +
  568. curr_block));
  569. } else {
  570. reiserfs_panic(inode->i_sb,
  571. "green-9010: unexpected item type for key %K\n",
  572. &key);
  573. }
  574. }
  575. // the caller is responsible for closing the transaction
  576. // unless we return an error, they are also responsible for logging
  577. // the inode.
  578. //
  579. pathrelse(&path);
  580. /*
  581. * cleanup prellocation from previous writes
  582. * if this is a partial block write
  583. */
  584. if (write_bytes & (inode->i_sb->s_blocksize - 1))
  585. reiserfs_discard_prealloc(th, inode);
  586. reiserfs_write_unlock(inode->i_sb);
  587. // go through all the pages/buffers and map the buffers to newly allocated
  588. // blocks (so that system knows where to write these pages later).
  589. curr_block = 0;
  590. for (i = 0; i < num_pages; i++) {
  591. struct page *page = prepared_pages[i]; //current page
  592. struct buffer_head *head = page_buffers(page); // first buffer for a page
  593. int block_start, block_end; // in-page offsets for buffers.
  594. if (!page_buffers(page))
  595. reiserfs_panic(inode->i_sb,
  596. "green-9005: No buffers for prepared page???");
  597. /* For each buffer in page */
  598. for (bh = head, block_start = 0; bh != head || !block_start;
  599. block_start = block_end, bh = bh->b_this_page) {
  600. if (!bh)
  601. reiserfs_panic(inode->i_sb,
  602. "green-9006: Allocated but absent buffer for a page?");
  603. block_end = block_start + inode->i_sb->s_blocksize;
  604. if (i == 0 && block_end <= from)
  605. /* if this buffer is before requested data to map, skip it */
  606. continue;
  607. if (i == num_pages - 1 && block_start >= to)
  608. /* If this buffer is after requested data to map, abort
  609. processing of current page */
  610. break;
  611. if (!buffer_mapped(bh)) { // Ok, unmapped buffer, need to map it
  612. map_bh(bh, inode->i_sb,
  613. le32_to_cpu(allocated_blocks
  614. [curr_block]));
  615. curr_block++;
  616. set_buffer_new(bh);
  617. }
  618. }
  619. }
  620. RFALSE(curr_block > blocks_to_allocate,
  621. "green-9007: Used too many blocks? weird");
  622. kfree(allocated_blocks);
  623. return 0;
  624. // Need to deal with transaction here.
  625. error_exit_free_blocks:
  626. pathrelse(&path);
  627. // free blocks
  628. for (i = 0; i < blocks_to_allocate; i++)
  629. reiserfs_free_block(th, inode, le32_to_cpu(allocated_blocks[i]),
  630. 1);
  631. error_exit:
  632. if (th->t_trans_id) {
  633. int err;
  634. // update any changes we made to blk count
  635. mark_inode_dirty(inode);
  636. err =
  637. journal_end(th, inode->i_sb,
  638. JOURNAL_PER_BALANCE_CNT * 3 + 1 +
  639. 2 * REISERFS_QUOTA_TRANS_BLOCKS(inode->i_sb));
  640. if (err)
  641. res = err;
  642. }
  643. reiserfs_write_unlock(inode->i_sb);
  644. kfree(allocated_blocks);
  645. return res;
  646. }
  647. /* Unlock pages prepared by reiserfs_prepare_file_region_for_write */
  648. static void reiserfs_unprepare_pages(struct page **prepared_pages, /* list of locked pages */
  649. size_t num_pages /* amount of pages */ )
  650. {
  651. int i; // loop counter
  652. for (i = 0; i < num_pages; i++) {
  653. struct page *page = prepared_pages[i];
  654. try_to_free_buffers(page);
  655. unlock_page(page);
  656. page_cache_release(page);
  657. }
  658. }
  659. /* This function will copy data from userspace to specified pages within
  660. supplied byte range */
  661. static int reiserfs_copy_from_user_to_file_region(loff_t pos, /* In-file position */
  662. int num_pages, /* Number of pages affected */
  663. int write_bytes, /* Amount of bytes to write */
  664. struct page **prepared_pages, /* pointer to
  665. array to
  666. prepared pages
  667. */
  668. const char __user * buf /* Pointer to user-supplied
  669. data */
  670. )
  671. {
  672. long page_fault = 0; // status of copy_from_user.
  673. int i; // loop counter.
  674. int offset; // offset in page
  675. for (i = 0, offset = (pos & (PAGE_CACHE_SIZE - 1)); i < num_pages;
  676. i++, offset = 0) {
  677. size_t count = min_t(size_t, PAGE_CACHE_SIZE - offset, write_bytes); // How much of bytes to write to this page
  678. struct page *page = prepared_pages[i]; // Current page we process.
  679. fault_in_pages_readable(buf, count);
  680. /* Copy data from userspace to the current page */
  681. kmap(page);
  682. page_fault = __copy_from_user(page_address(page) + offset, buf, count); // Copy the data.
  683. /* Flush processor's dcache for this page */
  684. flush_dcache_page(page);
  685. kunmap(page);
  686. buf += count;
  687. write_bytes -= count;
  688. if (page_fault)
  689. break; // Was there a fault? abort.
  690. }
  691. return page_fault ? -EFAULT : 0;
  692. }
  693. /* taken fs/buffer.c:__block_commit_write */
  694. int reiserfs_commit_page(struct inode *inode, struct page *page,
  695. unsigned from, unsigned to)
  696. {
  697. unsigned block_start, block_end;
  698. int partial = 0;
  699. unsigned blocksize;
  700. struct buffer_head *bh, *head;
  701. unsigned long i_size_index = inode->i_size >> PAGE_CACHE_SHIFT;
  702. int new;
  703. int logit = reiserfs_file_data_log(inode);
  704. struct super_block *s = inode->i_sb;
  705. int bh_per_page = PAGE_CACHE_SIZE / s->s_blocksize;
  706. struct reiserfs_transaction_handle th;
  707. int ret = 0;
  708. th.t_trans_id = 0;
  709. blocksize = 1 << inode->i_blkbits;
  710. if (logit) {
  711. reiserfs_write_lock(s);
  712. ret = journal_begin(&th, s, bh_per_page + 1);
  713. if (ret)
  714. goto drop_write_lock;
  715. reiserfs_update_inode_transaction(inode);
  716. }
  717. for (bh = head = page_buffers(page), block_start = 0;
  718. bh != head || !block_start;
  719. block_start = block_end, bh = bh->b_this_page) {
  720. new = buffer_new(bh);
  721. clear_buffer_new(bh);
  722. block_end = block_start + blocksize;
  723. if (block_end <= from || block_start >= to) {
  724. if (!buffer_uptodate(bh))
  725. partial = 1;
  726. } else {
  727. set_buffer_uptodate(bh);
  728. if (logit) {
  729. reiserfs_prepare_for_journal(s, bh, 1);
  730. journal_mark_dirty(&th, s, bh);
  731. } else if (!buffer_dirty(bh)) {
  732. mark_buffer_dirty(bh);
  733. /* do data=ordered on any page past the end
  734. * of file and any buffer marked BH_New.
  735. */
  736. if (reiserfs_data_ordered(inode->i_sb) &&
  737. (new || page->index >= i_size_index)) {
  738. reiserfs_add_ordered_list(inode, bh);
  739. }
  740. }
  741. }
  742. }
  743. if (logit) {
  744. ret = journal_end(&th, s, bh_per_page + 1);
  745. drop_write_lock:
  746. reiserfs_write_unlock(s);
  747. }
  748. /*
  749. * If this is a partial write which happened to make all buffers
  750. * uptodate then we can optimize away a bogus readpage() for
  751. * the next read(). Here we 'discover' whether the page went
  752. * uptodate as a result of this (potentially partial) write.
  753. */
  754. if (!partial)
  755. SetPageUptodate(page);
  756. return ret;
  757. }
  758. /* Submit pages for write. This was separated from actual file copying
  759. because we might want to allocate block numbers in-between.
  760. This function assumes that caller will adjust file size to correct value. */
  761. static int reiserfs_submit_file_region_for_write(struct reiserfs_transaction_handle *th, struct inode *inode, loff_t pos, /* Writing position offset */
  762. size_t num_pages, /* Number of pages to write */
  763. size_t write_bytes, /* number of bytes to write */
  764. struct page **prepared_pages /* list of pages */
  765. )
  766. {
  767. int status; // return status of block_commit_write.
  768. int retval = 0; // Return value we are going to return.
  769. int i; // loop counter
  770. int offset; // Writing offset in page.
  771. int orig_write_bytes = write_bytes;
  772. int sd_update = 0;
  773. for (i = 0, offset = (pos & (PAGE_CACHE_SIZE - 1)); i < num_pages;
  774. i++, offset = 0) {
  775. int count = min_t(int, PAGE_CACHE_SIZE - offset, write_bytes); // How much of bytes to write to this page
  776. struct page *page = prepared_pages[i]; // Current page we process.
  777. status =
  778. reiserfs_commit_page(inode, page, offset, offset + count);
  779. if (status)
  780. retval = status; // To not overcomplicate matters We are going to
  781. // submit all the pages even if there was error.
  782. // we only remember error status to report it on
  783. // exit.
  784. write_bytes -= count;
  785. }
  786. /* now that we've gotten all the ordered buffers marked dirty,
  787. * we can safely update i_size and close any running transaction
  788. */
  789. if (pos + orig_write_bytes > inode->i_size) {
  790. inode->i_size = pos + orig_write_bytes; // Set new size
  791. /* If the file have grown so much that tail packing is no
  792. * longer possible, reset "need to pack" flag */
  793. if ((have_large_tails(inode->i_sb) &&
  794. inode->i_size > i_block_size(inode) * 4) ||
  795. (have_small_tails(inode->i_sb) &&
  796. inode->i_size > i_block_size(inode)))
  797. REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
  798. else if ((have_large_tails(inode->i_sb) &&
  799. inode->i_size < i_block_size(inode) * 4) ||
  800. (have_small_tails(inode->i_sb) &&
  801. inode->i_size < i_block_size(inode)))
  802. REISERFS_I(inode)->i_flags |= i_pack_on_close_mask;
  803. if (th->t_trans_id) {
  804. reiserfs_write_lock(inode->i_sb);
  805. // this sets the proper flags for O_SYNC to trigger a commit
  806. mark_inode_dirty(inode);
  807. reiserfs_write_unlock(inode->i_sb);
  808. } else {
  809. reiserfs_write_lock(inode->i_sb);
  810. reiserfs_update_inode_transaction(inode);
  811. mark_inode_dirty(inode);
  812. reiserfs_write_unlock(inode->i_sb);
  813. }
  814. sd_update = 1;
  815. }
  816. if (th->t_trans_id) {
  817. reiserfs_write_lock(inode->i_sb);
  818. if (!sd_update)
  819. mark_inode_dirty(inode);
  820. status = journal_end(th, th->t_super, th->t_blocks_allocated);
  821. if (status)
  822. retval = status;
  823. reiserfs_write_unlock(inode->i_sb);
  824. }
  825. th->t_trans_id = 0;
  826. /*
  827. * we have to unlock the pages after updating i_size, otherwise
  828. * we race with writepage
  829. */
  830. for (i = 0; i < num_pages; i++) {
  831. struct page *page = prepared_pages[i];
  832. unlock_page(page);
  833. mark_page_accessed(page);
  834. page_cache_release(page);
  835. }
  836. return retval;
  837. }
  838. /* Look if passed writing region is going to touch file's tail
  839. (if it is present). And if it is, convert the tail to unformatted node */
  840. static int reiserfs_check_for_tail_and_convert(struct inode *inode, /* inode to deal with */
  841. loff_t pos, /* Writing position */
  842. int write_bytes /* amount of bytes to write */
  843. )
  844. {
  845. INITIALIZE_PATH(path); // needed for search_for_position
  846. struct cpu_key key; // Key that would represent last touched writing byte.
  847. struct item_head *ih; // item header of found block;
  848. int res; // Return value of various functions we call.
  849. int cont_expand_offset; // We will put offset for generic_cont_expand here
  850. // This can be int just because tails are created
  851. // only for small files.
  852. /* this embodies a dependency on a particular tail policy */
  853. if (inode->i_size >= inode->i_sb->s_blocksize * 4) {
  854. /* such a big files do not have tails, so we won't bother ourselves
  855. to look for tails, simply return */
  856. return 0;
  857. }
  858. reiserfs_write_lock(inode->i_sb);
  859. /* find the item containing the last byte to be written, or if
  860. * writing past the end of the file then the last item of the
  861. * file (and then we check its type). */
  862. make_cpu_key(&key, inode, pos + write_bytes + 1, TYPE_ANY,
  863. 3 /*key length */ );
  864. res = search_for_position_by_key(inode->i_sb, &key, &path);
  865. if (res == IO_ERROR) {
  866. reiserfs_write_unlock(inode->i_sb);
  867. return -EIO;
  868. }
  869. ih = get_ih(&path);
  870. res = 0;
  871. if (is_direct_le_ih(ih)) {
  872. /* Ok, closest item is file tail (tails are stored in "direct"
  873. * items), so we need to unpack it. */
  874. /* To not overcomplicate matters, we just call generic_cont_expand
  875. which will in turn call other stuff and finally will boil down to
  876. reiserfs_get_block() that would do necessary conversion. */
  877. cont_expand_offset =
  878. le_key_k_offset(get_inode_item_key_version(inode),
  879. &(ih->ih_key));
  880. pathrelse(&path);
  881. res = generic_cont_expand(inode, cont_expand_offset);
  882. } else
  883. pathrelse(&path);
  884. reiserfs_write_unlock(inode->i_sb);
  885. return res;
  886. }
  887. /* This function locks pages starting from @pos for @inode.
  888. @num_pages pages are locked and stored in
  889. @prepared_pages array. Also buffers are allocated for these pages.
  890. First and last page of the region is read if it is overwritten only
  891. partially. If last page did not exist before write (file hole or file
  892. append), it is zeroed, then.
  893. Returns number of unallocated blocks that should be allocated to cover
  894. new file data.*/
  895. static int reiserfs_prepare_file_region_for_write(struct inode *inode
  896. /* Inode of the file */ ,
  897. loff_t pos, /* position in the file */
  898. size_t num_pages, /* number of pages to
  899. prepare */
  900. size_t write_bytes, /* Amount of bytes to be
  901. overwritten from
  902. @pos */
  903. struct page **prepared_pages /* pointer to array
  904. where to store
  905. prepared pages */
  906. )
  907. {
  908. int res = 0; // Return values of different functions we call.
  909. unsigned long index = pos >> PAGE_CACHE_SHIFT; // Offset in file in pages.
  910. int from = (pos & (PAGE_CACHE_SIZE - 1)); // Writing offset in first page
  911. int to = ((pos + write_bytes - 1) & (PAGE_CACHE_SIZE - 1)) + 1;
  912. /* offset of last modified byte in last
  913. page */
  914. struct address_space *mapping = inode->i_mapping; // Pages are mapped here.
  915. int i; // Simple counter
  916. int blocks = 0; /* Return value (blocks that should be allocated) */
  917. struct buffer_head *bh, *head; // Current bufferhead and first bufferhead
  918. // of a page.
  919. unsigned block_start, block_end; // Starting and ending offsets of current
  920. // buffer in the page.
  921. struct buffer_head *wait[2], **wait_bh = wait; // Buffers for page, if
  922. // Page appeared to be not up
  923. // to date. Note how we have
  924. // at most 2 buffers, this is
  925. // because we at most may
  926. // partially overwrite two
  927. // buffers for one page. One at // the beginning of write area
  928. // and one at the end.
  929. // Everything inthe middle gets // overwritten totally.
  930. struct cpu_key key; // cpu key of item that we are going to deal with
  931. struct item_head *ih = NULL; // pointer to item head that we are going to deal with
  932. struct buffer_head *itembuf = NULL; // Buffer head that contains items that we are going to deal with
  933. INITIALIZE_PATH(path); // path to item, that we are going to deal with.
  934. __le32 *item = NULL; // pointer to item we are going to deal with
  935. int item_pos = -1; /* Position in indirect item */
  936. if (num_pages < 1) {
  937. reiserfs_warning(inode->i_sb,
  938. "green-9001: reiserfs_prepare_file_region_for_write "
  939. "called with zero number of pages to process");
  940. return -EFAULT;
  941. }
  942. /* We have 2 loops for pages. In first loop we grab and lock the pages, so
  943. that nobody would touch these until we release the pages. Then
  944. we'd start to deal with mapping buffers to blocks. */
  945. for (i = 0; i < num_pages; i++) {
  946. prepared_pages[i] = grab_cache_page(mapping, index + i); // locks the page
  947. if (!prepared_pages[i]) {
  948. res = -ENOMEM;
  949. goto failed_page_grabbing;
  950. }
  951. if (!page_has_buffers(prepared_pages[i]))
  952. create_empty_buffers(prepared_pages[i],
  953. inode->i_sb->s_blocksize, 0);
  954. }
  955. /* Let's count amount of blocks for a case where all the blocks
  956. overwritten are new (we will substract already allocated blocks later) */
  957. if (num_pages > 2)
  958. /* These are full-overwritten pages so we count all the blocks in
  959. these pages are counted as needed to be allocated */
  960. blocks =
  961. (num_pages - 2) << (PAGE_CACHE_SHIFT - inode->i_blkbits);
  962. /* count blocks needed for first page (possibly partially written) */
  963. blocks += ((PAGE_CACHE_SIZE - from) >> inode->i_blkbits) + !!(from & (inode->i_sb->s_blocksize - 1)); /* roundup */
  964. /* Now we account for last page. If last page == first page (we
  965. overwrite only one page), we substract all the blocks past the
  966. last writing position in a page out of already calculated number
  967. of blocks */
  968. blocks += ((num_pages > 1) << (PAGE_CACHE_SHIFT - inode->i_blkbits)) -
  969. ((PAGE_CACHE_SIZE - to) >> inode->i_blkbits);
  970. /* Note how we do not roundup here since partial blocks still
  971. should be allocated */
  972. /* Now if all the write area lies past the file end, no point in
  973. maping blocks, since there is none, so we just zero out remaining
  974. parts of first and last pages in write area (if needed) */
  975. if ((pos & ~((loff_t) PAGE_CACHE_SIZE - 1)) > inode->i_size) {
  976. if (from != 0) /* First page needs to be partially zeroed */
  977. zero_user_page(prepared_pages[0], 0, from, KM_USER0);
  978. if (to != PAGE_CACHE_SIZE) /* Last page needs to be partially zeroed */
  979. zero_user_page(prepared_pages[num_pages-1], to,
  980. PAGE_CACHE_SIZE - to, KM_USER0);
  981. /* Since all blocks are new - use already calculated value */
  982. return blocks;
  983. }
  984. /* Well, since we write somewhere into the middle of a file, there is
  985. possibility we are writing over some already allocated blocks, so
  986. let's map these blocks and substract number of such blocks out of blocks
  987. we need to allocate (calculated above) */
  988. /* Mask write position to start on blocksize, we do it out of the
  989. loop for performance reasons */
  990. pos &= ~((loff_t) inode->i_sb->s_blocksize - 1);
  991. /* Set cpu key to the starting position in a file (on left block boundary) */
  992. make_cpu_key(&key, inode,
  993. 1 + ((pos) & ~((loff_t) inode->i_sb->s_blocksize - 1)),
  994. TYPE_ANY, 3 /*key length */ );
  995. reiserfs_write_lock(inode->i_sb); // We need that for at least search_by_key()
  996. for (i = 0; i < num_pages; i++) {
  997. head = page_buffers(prepared_pages[i]);
  998. /* For each buffer in the page */
  999. for (bh = head, block_start = 0; bh != head || !block_start;
  1000. block_start = block_end, bh = bh->b_this_page) {
  1001. if (!bh)
  1002. reiserfs_panic(inode->i_sb,
  1003. "green-9002: Allocated but absent buffer for a page?");
  1004. /* Find where this buffer ends */
  1005. block_end = block_start + inode->i_sb->s_blocksize;
  1006. if (i == 0 && block_end <= from)
  1007. /* if this buffer is before requested data to map, skip it */
  1008. continue;
  1009. if (i == num_pages - 1 && block_start >= to) {
  1010. /* If this buffer is after requested data to map, abort
  1011. processing of current page */
  1012. break;
  1013. }
  1014. if (buffer_mapped(bh) && bh->b_blocknr != 0) {
  1015. /* This is optimisation for a case where buffer is mapped
  1016. and have blocknumber assigned. In case significant amount
  1017. of such buffers are present, we may avoid some amount
  1018. of search_by_key calls.
  1019. Probably it would be possible to move parts of this code
  1020. out of BKL, but I afraid that would overcomplicate code
  1021. without any noticeable benefit.
  1022. */
  1023. item_pos++;
  1024. /* Update the key */
  1025. set_cpu_key_k_offset(&key,
  1026. cpu_key_k_offset(&key) +
  1027. inode->i_sb->s_blocksize);
  1028. blocks--; // Decrease the amount of blocks that need to be
  1029. // allocated
  1030. continue; // Go to the next buffer
  1031. }
  1032. if (!itembuf || /* if first iteration */
  1033. item_pos >= ih_item_len(ih) / UNFM_P_SIZE) { /* or if we progressed past the
  1034. current unformatted_item */
  1035. /* Try to find next item */
  1036. res =
  1037. search_for_position_by_key(inode->i_sb,
  1038. &key, &path);
  1039. /* Abort if no more items */
  1040. if (res != POSITION_FOUND) {
  1041. /* make sure later loops don't use this item */
  1042. itembuf = NULL;
  1043. item = NULL;
  1044. break;
  1045. }
  1046. /* Update information about current indirect item */
  1047. itembuf = get_last_bh(&path);
  1048. ih = get_ih(&path);
  1049. item = get_item(&path);
  1050. item_pos = path.pos_in_item;
  1051. RFALSE(!is_indirect_le_ih(ih),
  1052. "green-9003: indirect item expected");
  1053. }
  1054. /* See if there is some block associated with the file
  1055. at that position, map the buffer to this block */
  1056. if (get_block_num(item, item_pos)) {
  1057. map_bh(bh, inode->i_sb,
  1058. get_block_num(item, item_pos));
  1059. blocks--; // Decrease the amount of blocks that need to be
  1060. // allocated
  1061. }
  1062. item_pos++;
  1063. /* Update the key */
  1064. set_cpu_key_k_offset(&key,
  1065. cpu_key_k_offset(&key) +
  1066. inode->i_sb->s_blocksize);
  1067. }
  1068. }
  1069. pathrelse(&path); // Free the path
  1070. reiserfs_write_unlock(inode->i_sb);
  1071. /* Now zero out unmappend buffers for the first and last pages of
  1072. write area or issue read requests if page is mapped. */
  1073. /* First page, see if it is not uptodate */
  1074. if (!PageUptodate(prepared_pages[0])) {
  1075. head = page_buffers(prepared_pages[0]);
  1076. /* For each buffer in page */
  1077. for (bh = head, block_start = 0; bh != head || !block_start;
  1078. block_start = block_end, bh = bh->b_this_page) {
  1079. if (!bh)
  1080. reiserfs_panic(inode->i_sb,
  1081. "green-9002: Allocated but absent buffer for a page?");
  1082. /* Find where this buffer ends */
  1083. block_end = block_start + inode->i_sb->s_blocksize;
  1084. if (block_end <= from)
  1085. /* if this buffer is before requested data to map, skip it */
  1086. continue;
  1087. if (block_start < from) { /* Aha, our partial buffer */
  1088. if (buffer_mapped(bh)) { /* If it is mapped, we need to
  1089. issue READ request for it to
  1090. not loose data */
  1091. ll_rw_block(READ, 1, &bh);
  1092. *wait_bh++ = bh;
  1093. } else { /* Not mapped, zero it */
  1094. zero_user_page(prepared_pages[0],
  1095. block_start,
  1096. from - block_start, KM_USER0);
  1097. set_buffer_uptodate(bh);
  1098. }
  1099. }
  1100. }
  1101. }
  1102. /* Last page, see if it is not uptodate, or if the last page is past the end of the file. */
  1103. if (!PageUptodate(prepared_pages[num_pages - 1]) ||
  1104. ((pos + write_bytes) >> PAGE_CACHE_SHIFT) >
  1105. (inode->i_size >> PAGE_CACHE_SHIFT)) {
  1106. head = page_buffers(prepared_pages[num_pages - 1]);
  1107. /* for each buffer in page */
  1108. for (bh = head, block_start = 0; bh != head || !block_start;
  1109. block_start = block_end, bh = bh->b_this_page) {
  1110. if (!bh)
  1111. reiserfs_panic(inode->i_sb,
  1112. "green-9002: Allocated but absent buffer for a page?");
  1113. /* Find where this buffer ends */
  1114. block_end = block_start + inode->i_sb->s_blocksize;
  1115. if (block_start >= to)
  1116. /* if this buffer is after requested data to map, skip it */
  1117. break;
  1118. if (block_end > to) { /* Aha, our partial buffer */
  1119. if (buffer_mapped(bh)) { /* If it is mapped, we need to
  1120. issue READ request for it to
  1121. not loose data */
  1122. ll_rw_block(READ, 1, &bh);
  1123. *wait_bh++ = bh;
  1124. } else { /* Not mapped, zero it */
  1125. zero_user_page(prepared_pages[num_pages-1],
  1126. to, block_end - to, KM_USER0);
  1127. set_buffer_uptodate(bh);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. /* Wait for read requests we made to happen, if necessary */
  1133. while (wait_bh > wait) {
  1134. wait_on_buffer(*--wait_bh);
  1135. if (!buffer_uptodate(*wait_bh)) {
  1136. res = -EIO;
  1137. goto failed_read;
  1138. }
  1139. }
  1140. return blocks;
  1141. failed_page_grabbing:
  1142. num_pages = i;
  1143. failed_read:
  1144. reiserfs_unprepare_pages(prepared_pages, num_pages);
  1145. return res;
  1146. }
  1147. /* Write @count bytes at position @ppos in a file indicated by @file
  1148. from the buffer @buf.
  1149. generic_file_write() is only appropriate for filesystems that are not seeking to optimize performance and want
  1150. something simple that works. It is not for serious use by general purpose filesystems, excepting the one that it was
  1151. written for (ext2/3). This is for several reasons:
  1152. * It has no understanding of any filesystem specific optimizations.
  1153. * It enters the filesystem repeatedly for each page that is written.
  1154. * It depends on reiserfs_get_block() function which if implemented by reiserfs performs costly search_by_key
  1155. * operation for each page it is supplied with. By contrast reiserfs_file_write() feeds as much as possible at a time
  1156. * to reiserfs which allows for fewer tree traversals.
  1157. * Each indirect pointer insertion takes a lot of cpu, because it involves memory moves inside of blocks.
  1158. * Asking the block allocation code for blocks one at a time is slightly less efficient.
  1159. All of these reasons for not using only generic file write were understood back when reiserfs was first miscoded to
  1160. use it, but we were in a hurry to make code freeze, and so it couldn't be revised then. This new code should make
  1161. things right finally.
  1162. Future Features: providing search_by_key with hints.
  1163. */
  1164. static ssize_t reiserfs_file_write(struct file *file, /* the file we are going to write into */
  1165. const char __user * buf, /* pointer to user supplied data
  1166. (in userspace) */
  1167. size_t count, /* amount of bytes to write */
  1168. loff_t * ppos /* pointer to position in file that we start writing at. Should be updated to
  1169. * new current position before returning. */
  1170. )
  1171. {
  1172. size_t already_written = 0; // Number of bytes already written to the file.
  1173. loff_t pos; // Current position in the file.
  1174. ssize_t res; // return value of various functions that we call.
  1175. int err = 0;
  1176. struct inode *inode = file->f_path.dentry->d_inode; // Inode of the file that we are writing to.
  1177. /* To simplify coding at this time, we store
  1178. locked pages in array for now */
  1179. struct page *prepared_pages[REISERFS_WRITE_PAGES_AT_A_TIME];
  1180. struct reiserfs_transaction_handle th;
  1181. th.t_trans_id = 0;
  1182. /* If a filesystem is converted from 3.5 to 3.6, we'll have v3.5 items
  1183. * lying around (most of the disk, in fact). Despite the filesystem
  1184. * now being a v3.6 format, the old items still can't support large
  1185. * file sizes. Catch this case here, as the rest of the VFS layer is
  1186. * oblivious to the different limitations between old and new items.
  1187. * reiserfs_setattr catches this for truncates. This chunk is lifted
  1188. * from generic_write_checks. */
  1189. if (get_inode_item_key_version (inode) == KEY_FORMAT_3_5 &&
  1190. *ppos + count > MAX_NON_LFS) {
  1191. if (*ppos >= MAX_NON_LFS) {
  1192. return -EFBIG;
  1193. }
  1194. if (count > MAX_NON_LFS - (unsigned long)*ppos)
  1195. count = MAX_NON_LFS - (unsigned long)*ppos;
  1196. }
  1197. if (file->f_flags & O_DIRECT)
  1198. return do_sync_write(file, buf, count, ppos);
  1199. if (unlikely((ssize_t) count < 0))
  1200. return -EINVAL;
  1201. if (unlikely(!access_ok(VERIFY_READ, buf, count)))
  1202. return -EFAULT;
  1203. mutex_lock(&inode->i_mutex); // locks the entire file for just us
  1204. pos = *ppos;
  1205. /* Check if we can write to specified region of file, file
  1206. is not overly big and this kind of stuff. Adjust pos and
  1207. count, if needed */
  1208. res = generic_write_checks(file, &pos, &count, 0);
  1209. if (res)
  1210. goto out;
  1211. if (count == 0)
  1212. goto out;
  1213. res = remove_suid(file->f_path.dentry);
  1214. if (res)
  1215. goto out;
  1216. file_update_time(file);
  1217. // Ok, we are done with all the checks.
  1218. // Now we should start real work
  1219. /* If we are going to write past the file's packed tail or if we are going
  1220. to overwrite part of the tail, we need that tail to be converted into
  1221. unformatted node */
  1222. res = reiserfs_check_for_tail_and_convert(inode, pos, count);
  1223. if (res)
  1224. goto out;
  1225. while (count > 0) {
  1226. /* This is the main loop in which we running until some error occures
  1227. or until we write all of the data. */
  1228. size_t num_pages; /* amount of pages we are going to write this iteration */
  1229. size_t write_bytes; /* amount of bytes to write during this iteration */
  1230. size_t blocks_to_allocate; /* how much blocks we need to allocate for this iteration */
  1231. /* (pos & (PAGE_CACHE_SIZE-1)) is an idiom for offset into a page of pos */
  1232. num_pages = !!((pos + count) & (PAGE_CACHE_SIZE - 1)) + /* round up partial
  1233. pages */
  1234. ((count +
  1235. (pos & (PAGE_CACHE_SIZE - 1))) >> PAGE_CACHE_SHIFT);
  1236. /* convert size to amount of
  1237. pages */
  1238. reiserfs_write_lock(inode->i_sb);
  1239. if (num_pages > REISERFS_WRITE_PAGES_AT_A_TIME
  1240. || num_pages > reiserfs_can_fit_pages(inode->i_sb)) {
  1241. /* If we were asked to write more data than we want to or if there
  1242. is not that much space, then we shorten amount of data to write
  1243. for this iteration. */
  1244. num_pages =
  1245. min_t(size_t, REISERFS_WRITE_PAGES_AT_A_TIME,
  1246. reiserfs_can_fit_pages(inode->i_sb));
  1247. /* Also we should not forget to set size in bytes accordingly */
  1248. write_bytes = (num_pages << PAGE_CACHE_SHIFT) -
  1249. (pos & (PAGE_CACHE_SIZE - 1));
  1250. /* If position is not on the
  1251. start of the page, we need
  1252. to substract the offset
  1253. within page */
  1254. } else
  1255. write_bytes = count;
  1256. /* reserve the blocks to be allocated later, so that later on
  1257. we still have the space to write the blocks to */
  1258. reiserfs_claim_blocks_to_be_allocated(inode->i_sb,
  1259. num_pages <<
  1260. (PAGE_CACHE_SHIFT -
  1261. inode->i_blkbits));
  1262. reiserfs_write_unlock(inode->i_sb);
  1263. if (!num_pages) { /* If we do not have enough space even for a single page... */
  1264. if (pos >
  1265. inode->i_size + inode->i_sb->s_blocksize -
  1266. (pos & (inode->i_sb->s_blocksize - 1))) {
  1267. res = -ENOSPC;
  1268. break; // In case we are writing past the end of the last file block, break.
  1269. }
  1270. // Otherwise we are possibly overwriting the file, so
  1271. // let's set write size to be equal or less than blocksize.
  1272. // This way we get it correctly for file holes.
  1273. // But overwriting files on absolutelly full volumes would not
  1274. // be very efficient. Well, people are not supposed to fill
  1275. // 100% of disk space anyway.
  1276. write_bytes =
  1277. min_t(size_t, count,
  1278. inode->i_sb->s_blocksize -
  1279. (pos & (inode->i_sb->s_blocksize - 1)));
  1280. num_pages = 1;
  1281. // No blocks were claimed before, so do it now.
  1282. reiserfs_claim_blocks_to_be_allocated(inode->i_sb,
  1283. 1 <<
  1284. (PAGE_CACHE_SHIFT
  1285. -
  1286. inode->
  1287. i_blkbits));
  1288. }
  1289. /* Prepare for writing into the region, read in all the
  1290. partially overwritten pages, if needed. And lock the pages,
  1291. so that nobody else can access these until we are done.
  1292. We get number of actual blocks needed as a result. */
  1293. res = reiserfs_prepare_file_region_for_write(inode, pos,
  1294. num_pages,
  1295. write_bytes,
  1296. prepared_pages);
  1297. if (res < 0) {
  1298. reiserfs_release_claimed_blocks(inode->i_sb,
  1299. num_pages <<
  1300. (PAGE_CACHE_SHIFT -
  1301. inode->i_blkbits));
  1302. break;
  1303. }
  1304. blocks_to_allocate = res;
  1305. /* First we correct our estimate of how many blocks we need */
  1306. reiserfs_release_claimed_blocks(inode->i_sb,
  1307. (num_pages <<
  1308. (PAGE_CACHE_SHIFT -
  1309. inode->i_sb->
  1310. s_blocksize_bits)) -
  1311. blocks_to_allocate);
  1312. if (blocks_to_allocate > 0) { /*We only allocate blocks if we need to */
  1313. /* Fill in all the possible holes and append the file if needed */
  1314. res =
  1315. reiserfs_allocate_blocks_for_region(&th, inode, pos,
  1316. num_pages,
  1317. write_bytes,
  1318. prepared_pages,
  1319. blocks_to_allocate);
  1320. }
  1321. /* well, we have allocated the blocks, so it is time to free
  1322. the reservation we made earlier. */
  1323. reiserfs_release_claimed_blocks(inode->i_sb,
  1324. blocks_to_allocate);
  1325. if (res) {
  1326. reiserfs_unprepare_pages(prepared_pages, num_pages);
  1327. break;
  1328. }
  1329. /* NOTE that allocating blocks and filling blocks can be done in reverse order
  1330. and probably we would do that just to get rid of garbage in files after a
  1331. crash */
  1332. /* Copy data from user-supplied buffer to file's pages */
  1333. res =
  1334. reiserfs_copy_from_user_to_file_region(pos, num_pages,
  1335. write_bytes,
  1336. prepared_pages, buf);
  1337. if (res) {
  1338. reiserfs_unprepare_pages(prepared_pages, num_pages);
  1339. break;
  1340. }
  1341. /* Send the pages to disk and unlock them. */
  1342. res =
  1343. reiserfs_submit_file_region_for_write(&th, inode, pos,
  1344. num_pages,
  1345. write_bytes,
  1346. prepared_pages);
  1347. if (res)
  1348. break;
  1349. already_written += write_bytes;
  1350. buf += write_bytes;
  1351. *ppos = pos += write_bytes;
  1352. count -= write_bytes;
  1353. balance_dirty_pages_ratelimited_nr(inode->i_mapping, num_pages);
  1354. }
  1355. /* this is only true on error */
  1356. if (th.t_trans_id) {
  1357. reiserfs_write_lock(inode->i_sb);
  1358. err = journal_end(&th, th.t_super, th.t_blocks_allocated);
  1359. reiserfs_write_unlock(inode->i_sb);
  1360. if (err) {
  1361. res = err;
  1362. goto out;
  1363. }
  1364. }
  1365. if (likely(res >= 0) &&
  1366. (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))))
  1367. res = generic_osync_inode(inode, file->f_mapping,
  1368. OSYNC_METADATA | OSYNC_DATA);
  1369. mutex_unlock(&inode->i_mutex);
  1370. reiserfs_async_progress_wait(inode->i_sb);
  1371. return (already_written != 0) ? already_written : res;
  1372. out:
  1373. mutex_unlock(&inode->i_mutex); // unlock the file on exit.
  1374. return res;
  1375. }
  1376. const struct file_operations reiserfs_file_operations = {
  1377. .read = do_sync_read,
  1378. .write = reiserfs_file_write,
  1379. .ioctl = reiserfs_ioctl,
  1380. #ifdef CONFIG_COMPAT
  1381. .compat_ioctl = reiserfs_compat_ioctl,
  1382. #endif
  1383. .mmap = reiserfs_file_mmap,
  1384. .open = generic_file_open,
  1385. .release = reiserfs_file_release,
  1386. .fsync = reiserfs_sync_file,
  1387. .aio_read = generic_file_aio_read,
  1388. .aio_write = generic_file_aio_write,
  1389. .splice_read = generic_file_splice_read,
  1390. .splice_write = generic_file_splice_write,
  1391. };
  1392. const struct inode_operations reiserfs_file_inode_operations = {
  1393. .truncate = reiserfs_vfs_truncate_file,
  1394. .setattr = reiserfs_setattr,
  1395. .setxattr = reiserfs_setxattr,
  1396. .getxattr = reiserfs_getxattr,
  1397. .listxattr = reiserfs_listxattr,
  1398. .removexattr = reiserfs_removexattr,
  1399. .permission = reiserfs_permission,
  1400. };