file.c 53 KB

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