file.c 54 KB

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