file.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  1. /*
  2. * Copyright (C) 2007 Oracle. All rights reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public
  6. * License v2 as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public
  14. * License along with this program; if not, write to the
  15. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16. * Boston, MA 021110-1307, USA.
  17. */
  18. #include <linux/fs.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/highmem.h>
  21. #include <linux/time.h>
  22. #include <linux/init.h>
  23. #include <linux/string.h>
  24. #include <linux/backing-dev.h>
  25. #include <linux/mpage.h>
  26. #include <linux/falloc.h>
  27. #include <linux/swap.h>
  28. #include <linux/writeback.h>
  29. #include <linux/statfs.h>
  30. #include <linux/compat.h>
  31. #include <linux/slab.h>
  32. #include "ctree.h"
  33. #include "disk-io.h"
  34. #include "transaction.h"
  35. #include "btrfs_inode.h"
  36. #include "ioctl.h"
  37. #include "print-tree.h"
  38. #include "tree-log.h"
  39. #include "locking.h"
  40. #include "compat.h"
  41. /*
  42. * when auto defrag is enabled we
  43. * queue up these defrag structs to remember which
  44. * inodes need defragging passes
  45. */
  46. struct inode_defrag {
  47. struct rb_node rb_node;
  48. /* objectid */
  49. u64 ino;
  50. /*
  51. * transid where the defrag was added, we search for
  52. * extents newer than this
  53. */
  54. u64 transid;
  55. /* root objectid */
  56. u64 root;
  57. /* last offset we were able to defrag */
  58. u64 last_offset;
  59. /* if we've wrapped around back to zero once already */
  60. int cycled;
  61. };
  62. /* pop a record for an inode into the defrag tree. The lock
  63. * must be held already
  64. *
  65. * If you're inserting a record for an older transid than an
  66. * existing record, the transid already in the tree is lowered
  67. *
  68. * If an existing record is found the defrag item you
  69. * pass in is freed
  70. */
  71. static void __btrfs_add_inode_defrag(struct inode *inode,
  72. struct inode_defrag *defrag)
  73. {
  74. struct btrfs_root *root = BTRFS_I(inode)->root;
  75. struct inode_defrag *entry;
  76. struct rb_node **p;
  77. struct rb_node *parent = NULL;
  78. p = &root->fs_info->defrag_inodes.rb_node;
  79. while (*p) {
  80. parent = *p;
  81. entry = rb_entry(parent, struct inode_defrag, rb_node);
  82. if (defrag->ino < entry->ino)
  83. p = &parent->rb_left;
  84. else if (defrag->ino > entry->ino)
  85. p = &parent->rb_right;
  86. else {
  87. /* if we're reinserting an entry for
  88. * an old defrag run, make sure to
  89. * lower the transid of our existing record
  90. */
  91. if (defrag->transid < entry->transid)
  92. entry->transid = defrag->transid;
  93. if (defrag->last_offset > entry->last_offset)
  94. entry->last_offset = defrag->last_offset;
  95. goto exists;
  96. }
  97. }
  98. BTRFS_I(inode)->in_defrag = 1;
  99. rb_link_node(&defrag->rb_node, parent, p);
  100. rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
  101. return;
  102. exists:
  103. kfree(defrag);
  104. return;
  105. }
  106. /*
  107. * insert a defrag record for this inode if auto defrag is
  108. * enabled
  109. */
  110. int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
  111. struct inode *inode)
  112. {
  113. struct btrfs_root *root = BTRFS_I(inode)->root;
  114. struct inode_defrag *defrag;
  115. u64 transid;
  116. if (!btrfs_test_opt(root, AUTO_DEFRAG))
  117. return 0;
  118. if (btrfs_fs_closing(root->fs_info))
  119. return 0;
  120. if (BTRFS_I(inode)->in_defrag)
  121. return 0;
  122. if (trans)
  123. transid = trans->transid;
  124. else
  125. transid = BTRFS_I(inode)->root->last_trans;
  126. defrag = kzalloc(sizeof(*defrag), GFP_NOFS);
  127. if (!defrag)
  128. return -ENOMEM;
  129. defrag->ino = btrfs_ino(inode);
  130. defrag->transid = transid;
  131. defrag->root = root->root_key.objectid;
  132. spin_lock(&root->fs_info->defrag_inodes_lock);
  133. if (!BTRFS_I(inode)->in_defrag)
  134. __btrfs_add_inode_defrag(inode, defrag);
  135. else
  136. kfree(defrag);
  137. spin_unlock(&root->fs_info->defrag_inodes_lock);
  138. return 0;
  139. }
  140. /*
  141. * must be called with the defrag_inodes lock held
  142. */
  143. struct inode_defrag *btrfs_find_defrag_inode(struct btrfs_fs_info *info, u64 ino,
  144. struct rb_node **next)
  145. {
  146. struct inode_defrag *entry = NULL;
  147. struct rb_node *p;
  148. struct rb_node *parent = NULL;
  149. p = info->defrag_inodes.rb_node;
  150. while (p) {
  151. parent = p;
  152. entry = rb_entry(parent, struct inode_defrag, rb_node);
  153. if (ino < entry->ino)
  154. p = parent->rb_left;
  155. else if (ino > entry->ino)
  156. p = parent->rb_right;
  157. else
  158. return entry;
  159. }
  160. if (next) {
  161. while (parent && ino > entry->ino) {
  162. parent = rb_next(parent);
  163. entry = rb_entry(parent, struct inode_defrag, rb_node);
  164. }
  165. *next = parent;
  166. }
  167. return NULL;
  168. }
  169. /*
  170. * run through the list of inodes in the FS that need
  171. * defragging
  172. */
  173. int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
  174. {
  175. struct inode_defrag *defrag;
  176. struct btrfs_root *inode_root;
  177. struct inode *inode;
  178. struct rb_node *n;
  179. struct btrfs_key key;
  180. struct btrfs_ioctl_defrag_range_args range;
  181. u64 first_ino = 0;
  182. int num_defrag;
  183. int defrag_batch = 1024;
  184. memset(&range, 0, sizeof(range));
  185. range.len = (u64)-1;
  186. atomic_inc(&fs_info->defrag_running);
  187. spin_lock(&fs_info->defrag_inodes_lock);
  188. while(1) {
  189. n = NULL;
  190. /* find an inode to defrag */
  191. defrag = btrfs_find_defrag_inode(fs_info, first_ino, &n);
  192. if (!defrag) {
  193. if (n)
  194. defrag = rb_entry(n, struct inode_defrag, rb_node);
  195. else if (first_ino) {
  196. first_ino = 0;
  197. continue;
  198. } else {
  199. break;
  200. }
  201. }
  202. /* remove it from the rbtree */
  203. first_ino = defrag->ino + 1;
  204. rb_erase(&defrag->rb_node, &fs_info->defrag_inodes);
  205. if (btrfs_fs_closing(fs_info))
  206. goto next_free;
  207. spin_unlock(&fs_info->defrag_inodes_lock);
  208. /* get the inode */
  209. key.objectid = defrag->root;
  210. btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
  211. key.offset = (u64)-1;
  212. inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
  213. if (IS_ERR(inode_root))
  214. goto next;
  215. key.objectid = defrag->ino;
  216. btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
  217. key.offset = 0;
  218. inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
  219. if (IS_ERR(inode))
  220. goto next;
  221. /* do a chunk of defrag */
  222. BTRFS_I(inode)->in_defrag = 0;
  223. range.start = defrag->last_offset;
  224. num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
  225. defrag_batch);
  226. /*
  227. * if we filled the whole defrag batch, there
  228. * must be more work to do. Queue this defrag
  229. * again
  230. */
  231. if (num_defrag == defrag_batch) {
  232. defrag->last_offset = range.start;
  233. __btrfs_add_inode_defrag(inode, defrag);
  234. /*
  235. * we don't want to kfree defrag, we added it back to
  236. * the rbtree
  237. */
  238. defrag = NULL;
  239. } else if (defrag->last_offset && !defrag->cycled) {
  240. /*
  241. * we didn't fill our defrag batch, but
  242. * we didn't start at zero. Make sure we loop
  243. * around to the start of the file.
  244. */
  245. defrag->last_offset = 0;
  246. defrag->cycled = 1;
  247. __btrfs_add_inode_defrag(inode, defrag);
  248. defrag = NULL;
  249. }
  250. iput(inode);
  251. next:
  252. spin_lock(&fs_info->defrag_inodes_lock);
  253. next_free:
  254. kfree(defrag);
  255. }
  256. spin_unlock(&fs_info->defrag_inodes_lock);
  257. atomic_dec(&fs_info->defrag_running);
  258. /*
  259. * during unmount, we use the transaction_wait queue to
  260. * wait for the defragger to stop
  261. */
  262. wake_up(&fs_info->transaction_wait);
  263. return 0;
  264. }
  265. /* simple helper to fault in pages and copy. This should go away
  266. * and be replaced with calls into generic code.
  267. */
  268. static noinline int btrfs_copy_from_user(loff_t pos, int num_pages,
  269. size_t write_bytes,
  270. struct page **prepared_pages,
  271. struct iov_iter *i)
  272. {
  273. size_t copied = 0;
  274. size_t total_copied = 0;
  275. int pg = 0;
  276. int offset = pos & (PAGE_CACHE_SIZE - 1);
  277. while (write_bytes > 0) {
  278. size_t count = min_t(size_t,
  279. PAGE_CACHE_SIZE - offset, write_bytes);
  280. struct page *page = prepared_pages[pg];
  281. /*
  282. * Copy data from userspace to the current page
  283. *
  284. * Disable pagefault to avoid recursive lock since
  285. * the pages are already locked
  286. */
  287. pagefault_disable();
  288. copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
  289. pagefault_enable();
  290. /* Flush processor's dcache for this page */
  291. flush_dcache_page(page);
  292. /*
  293. * if we get a partial write, we can end up with
  294. * partially up to date pages. These add
  295. * a lot of complexity, so make sure they don't
  296. * happen by forcing this copy to be retried.
  297. *
  298. * The rest of the btrfs_file_write code will fall
  299. * back to page at a time copies after we return 0.
  300. */
  301. if (!PageUptodate(page) && copied < count)
  302. copied = 0;
  303. iov_iter_advance(i, copied);
  304. write_bytes -= copied;
  305. total_copied += copied;
  306. /* Return to btrfs_file_aio_write to fault page */
  307. if (unlikely(copied == 0))
  308. break;
  309. if (unlikely(copied < PAGE_CACHE_SIZE - offset)) {
  310. offset += copied;
  311. } else {
  312. pg++;
  313. offset = 0;
  314. }
  315. }
  316. return total_copied;
  317. }
  318. /*
  319. * unlocks pages after btrfs_file_write is done with them
  320. */
  321. void btrfs_drop_pages(struct page **pages, size_t num_pages)
  322. {
  323. size_t i;
  324. for (i = 0; i < num_pages; i++) {
  325. /* page checked is some magic around finding pages that
  326. * have been modified without going through btrfs_set_page_dirty
  327. * clear it here
  328. */
  329. ClearPageChecked(pages[i]);
  330. unlock_page(pages[i]);
  331. mark_page_accessed(pages[i]);
  332. page_cache_release(pages[i]);
  333. }
  334. }
  335. /*
  336. * after copy_from_user, pages need to be dirtied and we need to make
  337. * sure holes are created between the current EOF and the start of
  338. * any next extents (if required).
  339. *
  340. * this also makes the decision about creating an inline extent vs
  341. * doing real data extents, marking pages dirty and delalloc as required.
  342. */
  343. int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
  344. struct page **pages, size_t num_pages,
  345. loff_t pos, size_t write_bytes,
  346. struct extent_state **cached)
  347. {
  348. int err = 0;
  349. int i;
  350. u64 num_bytes;
  351. u64 start_pos;
  352. u64 end_of_last_block;
  353. u64 end_pos = pos + write_bytes;
  354. loff_t isize = i_size_read(inode);
  355. start_pos = pos & ~((u64)root->sectorsize - 1);
  356. num_bytes = (write_bytes + pos - start_pos +
  357. root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
  358. end_of_last_block = start_pos + num_bytes - 1;
  359. err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
  360. cached);
  361. if (err)
  362. return err;
  363. for (i = 0; i < num_pages; i++) {
  364. struct page *p = pages[i];
  365. SetPageUptodate(p);
  366. ClearPageChecked(p);
  367. set_page_dirty(p);
  368. }
  369. /*
  370. * we've only changed i_size in ram, and we haven't updated
  371. * the disk i_size. There is no need to log the inode
  372. * at this time.
  373. */
  374. if (end_pos > isize)
  375. i_size_write(inode, end_pos);
  376. return 0;
  377. }
  378. /*
  379. * this drops all the extents in the cache that intersect the range
  380. * [start, end]. Existing extents are split as required.
  381. */
  382. int btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
  383. int skip_pinned)
  384. {
  385. struct extent_map *em;
  386. struct extent_map *split = NULL;
  387. struct extent_map *split2 = NULL;
  388. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  389. u64 len = end - start + 1;
  390. int ret;
  391. int testend = 1;
  392. unsigned long flags;
  393. int compressed = 0;
  394. WARN_ON(end < start);
  395. if (end == (u64)-1) {
  396. len = (u64)-1;
  397. testend = 0;
  398. }
  399. while (1) {
  400. if (!split)
  401. split = alloc_extent_map();
  402. if (!split2)
  403. split2 = alloc_extent_map();
  404. BUG_ON(!split || !split2); /* -ENOMEM */
  405. write_lock(&em_tree->lock);
  406. em = lookup_extent_mapping(em_tree, start, len);
  407. if (!em) {
  408. write_unlock(&em_tree->lock);
  409. break;
  410. }
  411. flags = em->flags;
  412. if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
  413. if (testend && em->start + em->len >= start + len) {
  414. free_extent_map(em);
  415. write_unlock(&em_tree->lock);
  416. break;
  417. }
  418. start = em->start + em->len;
  419. if (testend)
  420. len = start + len - (em->start + em->len);
  421. free_extent_map(em);
  422. write_unlock(&em_tree->lock);
  423. continue;
  424. }
  425. compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  426. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  427. remove_extent_mapping(em_tree, em);
  428. if (em->block_start < EXTENT_MAP_LAST_BYTE &&
  429. em->start < start) {
  430. split->start = em->start;
  431. split->len = start - em->start;
  432. split->orig_start = em->orig_start;
  433. split->block_start = em->block_start;
  434. if (compressed)
  435. split->block_len = em->block_len;
  436. else
  437. split->block_len = split->len;
  438. split->bdev = em->bdev;
  439. split->flags = flags;
  440. split->compress_type = em->compress_type;
  441. ret = add_extent_mapping(em_tree, split);
  442. BUG_ON(ret); /* Logic error */
  443. free_extent_map(split);
  444. split = split2;
  445. split2 = NULL;
  446. }
  447. if (em->block_start < EXTENT_MAP_LAST_BYTE &&
  448. testend && em->start + em->len > start + len) {
  449. u64 diff = start + len - em->start;
  450. split->start = start + len;
  451. split->len = em->start + em->len - (start + len);
  452. split->bdev = em->bdev;
  453. split->flags = flags;
  454. split->compress_type = em->compress_type;
  455. if (compressed) {
  456. split->block_len = em->block_len;
  457. split->block_start = em->block_start;
  458. split->orig_start = em->orig_start;
  459. } else {
  460. split->block_len = split->len;
  461. split->block_start = em->block_start + diff;
  462. split->orig_start = split->start;
  463. }
  464. ret = add_extent_mapping(em_tree, split);
  465. BUG_ON(ret); /* Logic error */
  466. free_extent_map(split);
  467. split = NULL;
  468. }
  469. write_unlock(&em_tree->lock);
  470. /* once for us */
  471. free_extent_map(em);
  472. /* once for the tree*/
  473. free_extent_map(em);
  474. }
  475. if (split)
  476. free_extent_map(split);
  477. if (split2)
  478. free_extent_map(split2);
  479. return 0;
  480. }
  481. /*
  482. * this is very complex, but the basic idea is to drop all extents
  483. * in the range start - end. hint_block is filled in with a block number
  484. * that would be a good hint to the block allocator for this file.
  485. *
  486. * If an extent intersects the range but is not entirely inside the range
  487. * it is either truncated or split. Anything entirely inside the range
  488. * is deleted from the tree.
  489. */
  490. int btrfs_drop_extents(struct btrfs_trans_handle *trans, struct inode *inode,
  491. u64 start, u64 end, u64 *hint_byte, int drop_cache)
  492. {
  493. struct btrfs_root *root = BTRFS_I(inode)->root;
  494. struct extent_buffer *leaf;
  495. struct btrfs_file_extent_item *fi;
  496. struct btrfs_path *path;
  497. struct btrfs_key key;
  498. struct btrfs_key new_key;
  499. u64 ino = btrfs_ino(inode);
  500. u64 search_start = start;
  501. u64 disk_bytenr = 0;
  502. u64 num_bytes = 0;
  503. u64 extent_offset = 0;
  504. u64 extent_end = 0;
  505. int del_nr = 0;
  506. int del_slot = 0;
  507. int extent_type;
  508. int recow;
  509. int ret;
  510. if (drop_cache)
  511. btrfs_drop_extent_cache(inode, start, end - 1, 0);
  512. path = btrfs_alloc_path();
  513. if (!path)
  514. return -ENOMEM;
  515. while (1) {
  516. recow = 0;
  517. ret = btrfs_lookup_file_extent(trans, root, path, ino,
  518. search_start, -1);
  519. if (ret < 0)
  520. break;
  521. if (ret > 0 && path->slots[0] > 0 && search_start == start) {
  522. leaf = path->nodes[0];
  523. btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
  524. if (key.objectid == ino &&
  525. key.type == BTRFS_EXTENT_DATA_KEY)
  526. path->slots[0]--;
  527. }
  528. ret = 0;
  529. next_slot:
  530. leaf = path->nodes[0];
  531. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  532. BUG_ON(del_nr > 0);
  533. ret = btrfs_next_leaf(root, path);
  534. if (ret < 0)
  535. break;
  536. if (ret > 0) {
  537. ret = 0;
  538. break;
  539. }
  540. leaf = path->nodes[0];
  541. recow = 1;
  542. }
  543. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  544. if (key.objectid > ino ||
  545. key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
  546. break;
  547. fi = btrfs_item_ptr(leaf, path->slots[0],
  548. struct btrfs_file_extent_item);
  549. extent_type = btrfs_file_extent_type(leaf, fi);
  550. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  551. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  552. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  553. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  554. extent_offset = btrfs_file_extent_offset(leaf, fi);
  555. extent_end = key.offset +
  556. btrfs_file_extent_num_bytes(leaf, fi);
  557. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  558. extent_end = key.offset +
  559. btrfs_file_extent_inline_len(leaf, fi);
  560. } else {
  561. WARN_ON(1);
  562. extent_end = search_start;
  563. }
  564. if (extent_end <= search_start) {
  565. path->slots[0]++;
  566. goto next_slot;
  567. }
  568. search_start = max(key.offset, start);
  569. if (recow) {
  570. btrfs_release_path(path);
  571. continue;
  572. }
  573. /*
  574. * | - range to drop - |
  575. * | -------- extent -------- |
  576. */
  577. if (start > key.offset && end < extent_end) {
  578. BUG_ON(del_nr > 0);
  579. BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
  580. memcpy(&new_key, &key, sizeof(new_key));
  581. new_key.offset = start;
  582. ret = btrfs_duplicate_item(trans, root, path,
  583. &new_key);
  584. if (ret == -EAGAIN) {
  585. btrfs_release_path(path);
  586. continue;
  587. }
  588. if (ret < 0)
  589. break;
  590. leaf = path->nodes[0];
  591. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  592. struct btrfs_file_extent_item);
  593. btrfs_set_file_extent_num_bytes(leaf, fi,
  594. start - key.offset);
  595. fi = btrfs_item_ptr(leaf, path->slots[0],
  596. struct btrfs_file_extent_item);
  597. extent_offset += start - key.offset;
  598. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  599. btrfs_set_file_extent_num_bytes(leaf, fi,
  600. extent_end - start);
  601. btrfs_mark_buffer_dirty(leaf);
  602. if (disk_bytenr > 0) {
  603. ret = btrfs_inc_extent_ref(trans, root,
  604. disk_bytenr, num_bytes, 0,
  605. root->root_key.objectid,
  606. new_key.objectid,
  607. start - extent_offset, 0);
  608. BUG_ON(ret); /* -ENOMEM */
  609. *hint_byte = disk_bytenr;
  610. }
  611. key.offset = start;
  612. }
  613. /*
  614. * | ---- range to drop ----- |
  615. * | -------- extent -------- |
  616. */
  617. if (start <= key.offset && end < extent_end) {
  618. BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
  619. memcpy(&new_key, &key, sizeof(new_key));
  620. new_key.offset = end;
  621. btrfs_set_item_key_safe(trans, root, path, &new_key);
  622. extent_offset += end - key.offset;
  623. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  624. btrfs_set_file_extent_num_bytes(leaf, fi,
  625. extent_end - end);
  626. btrfs_mark_buffer_dirty(leaf);
  627. if (disk_bytenr > 0) {
  628. inode_sub_bytes(inode, end - key.offset);
  629. *hint_byte = disk_bytenr;
  630. }
  631. break;
  632. }
  633. search_start = extent_end;
  634. /*
  635. * | ---- range to drop ----- |
  636. * | -------- extent -------- |
  637. */
  638. if (start > key.offset && end >= extent_end) {
  639. BUG_ON(del_nr > 0);
  640. BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
  641. btrfs_set_file_extent_num_bytes(leaf, fi,
  642. start - key.offset);
  643. btrfs_mark_buffer_dirty(leaf);
  644. if (disk_bytenr > 0) {
  645. inode_sub_bytes(inode, extent_end - start);
  646. *hint_byte = disk_bytenr;
  647. }
  648. if (end == extent_end)
  649. break;
  650. path->slots[0]++;
  651. goto next_slot;
  652. }
  653. /*
  654. * | ---- range to drop ----- |
  655. * | ------ extent ------ |
  656. */
  657. if (start <= key.offset && end >= extent_end) {
  658. if (del_nr == 0) {
  659. del_slot = path->slots[0];
  660. del_nr = 1;
  661. } else {
  662. BUG_ON(del_slot + del_nr != path->slots[0]);
  663. del_nr++;
  664. }
  665. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  666. inode_sub_bytes(inode,
  667. extent_end - key.offset);
  668. extent_end = ALIGN(extent_end,
  669. root->sectorsize);
  670. } else if (disk_bytenr > 0) {
  671. ret = btrfs_free_extent(trans, root,
  672. disk_bytenr, num_bytes, 0,
  673. root->root_key.objectid,
  674. key.objectid, key.offset -
  675. extent_offset, 0);
  676. BUG_ON(ret); /* -ENOMEM */
  677. inode_sub_bytes(inode,
  678. extent_end - key.offset);
  679. *hint_byte = disk_bytenr;
  680. }
  681. if (end == extent_end)
  682. break;
  683. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  684. path->slots[0]++;
  685. goto next_slot;
  686. }
  687. ret = btrfs_del_items(trans, root, path, del_slot,
  688. del_nr);
  689. if (ret) {
  690. btrfs_abort_transaction(trans, root, ret);
  691. goto out;
  692. }
  693. del_nr = 0;
  694. del_slot = 0;
  695. btrfs_release_path(path);
  696. continue;
  697. }
  698. BUG_ON(1);
  699. }
  700. if (!ret && del_nr > 0) {
  701. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  702. if (ret)
  703. btrfs_abort_transaction(trans, root, ret);
  704. }
  705. out:
  706. btrfs_free_path(path);
  707. return ret;
  708. }
  709. static int extent_mergeable(struct extent_buffer *leaf, int slot,
  710. u64 objectid, u64 bytenr, u64 orig_offset,
  711. u64 *start, u64 *end)
  712. {
  713. struct btrfs_file_extent_item *fi;
  714. struct btrfs_key key;
  715. u64 extent_end;
  716. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  717. return 0;
  718. btrfs_item_key_to_cpu(leaf, &key, slot);
  719. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  720. return 0;
  721. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  722. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  723. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  724. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  725. btrfs_file_extent_compression(leaf, fi) ||
  726. btrfs_file_extent_encryption(leaf, fi) ||
  727. btrfs_file_extent_other_encoding(leaf, fi))
  728. return 0;
  729. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  730. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  731. return 0;
  732. *start = key.offset;
  733. *end = extent_end;
  734. return 1;
  735. }
  736. /*
  737. * Mark extent in the range start - end as written.
  738. *
  739. * This changes extent type from 'pre-allocated' to 'regular'. If only
  740. * part of extent is marked as written, the extent will be split into
  741. * two or three.
  742. */
  743. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  744. struct inode *inode, u64 start, u64 end)
  745. {
  746. struct btrfs_root *root = BTRFS_I(inode)->root;
  747. struct extent_buffer *leaf;
  748. struct btrfs_path *path;
  749. struct btrfs_file_extent_item *fi;
  750. struct btrfs_key key;
  751. struct btrfs_key new_key;
  752. u64 bytenr;
  753. u64 num_bytes;
  754. u64 extent_end;
  755. u64 orig_offset;
  756. u64 other_start;
  757. u64 other_end;
  758. u64 split;
  759. int del_nr = 0;
  760. int del_slot = 0;
  761. int recow;
  762. int ret;
  763. u64 ino = btrfs_ino(inode);
  764. btrfs_drop_extent_cache(inode, start, end - 1, 0);
  765. path = btrfs_alloc_path();
  766. if (!path)
  767. return -ENOMEM;
  768. again:
  769. recow = 0;
  770. split = start;
  771. key.objectid = ino;
  772. key.type = BTRFS_EXTENT_DATA_KEY;
  773. key.offset = split;
  774. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  775. if (ret < 0)
  776. goto out;
  777. if (ret > 0 && path->slots[0] > 0)
  778. path->slots[0]--;
  779. leaf = path->nodes[0];
  780. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  781. BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
  782. fi = btrfs_item_ptr(leaf, path->slots[0],
  783. struct btrfs_file_extent_item);
  784. BUG_ON(btrfs_file_extent_type(leaf, fi) !=
  785. BTRFS_FILE_EXTENT_PREALLOC);
  786. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  787. BUG_ON(key.offset > start || extent_end < end);
  788. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  789. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  790. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  791. memcpy(&new_key, &key, sizeof(new_key));
  792. if (start == key.offset && end < extent_end) {
  793. other_start = 0;
  794. other_end = start;
  795. if (extent_mergeable(leaf, path->slots[0] - 1,
  796. ino, bytenr, orig_offset,
  797. &other_start, &other_end)) {
  798. new_key.offset = end;
  799. btrfs_set_item_key_safe(trans, root, path, &new_key);
  800. fi = btrfs_item_ptr(leaf, path->slots[0],
  801. struct btrfs_file_extent_item);
  802. btrfs_set_file_extent_num_bytes(leaf, fi,
  803. extent_end - end);
  804. btrfs_set_file_extent_offset(leaf, fi,
  805. end - orig_offset);
  806. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  807. struct btrfs_file_extent_item);
  808. btrfs_set_file_extent_num_bytes(leaf, fi,
  809. end - other_start);
  810. btrfs_mark_buffer_dirty(leaf);
  811. goto out;
  812. }
  813. }
  814. if (start > key.offset && end == extent_end) {
  815. other_start = end;
  816. other_end = 0;
  817. if (extent_mergeable(leaf, path->slots[0] + 1,
  818. ino, bytenr, orig_offset,
  819. &other_start, &other_end)) {
  820. fi = btrfs_item_ptr(leaf, path->slots[0],
  821. struct btrfs_file_extent_item);
  822. btrfs_set_file_extent_num_bytes(leaf, fi,
  823. start - key.offset);
  824. path->slots[0]++;
  825. new_key.offset = start;
  826. btrfs_set_item_key_safe(trans, root, path, &new_key);
  827. fi = btrfs_item_ptr(leaf, path->slots[0],
  828. struct btrfs_file_extent_item);
  829. btrfs_set_file_extent_num_bytes(leaf, fi,
  830. other_end - start);
  831. btrfs_set_file_extent_offset(leaf, fi,
  832. start - orig_offset);
  833. btrfs_mark_buffer_dirty(leaf);
  834. goto out;
  835. }
  836. }
  837. while (start > key.offset || end < extent_end) {
  838. if (key.offset == start)
  839. split = end;
  840. new_key.offset = split;
  841. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  842. if (ret == -EAGAIN) {
  843. btrfs_release_path(path);
  844. goto again;
  845. }
  846. if (ret < 0) {
  847. btrfs_abort_transaction(trans, root, ret);
  848. goto out;
  849. }
  850. leaf = path->nodes[0];
  851. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  852. struct btrfs_file_extent_item);
  853. btrfs_set_file_extent_num_bytes(leaf, fi,
  854. split - key.offset);
  855. fi = btrfs_item_ptr(leaf, path->slots[0],
  856. struct btrfs_file_extent_item);
  857. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  858. btrfs_set_file_extent_num_bytes(leaf, fi,
  859. extent_end - split);
  860. btrfs_mark_buffer_dirty(leaf);
  861. ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
  862. root->root_key.objectid,
  863. ino, orig_offset, 0);
  864. BUG_ON(ret); /* -ENOMEM */
  865. if (split == start) {
  866. key.offset = start;
  867. } else {
  868. BUG_ON(start != key.offset);
  869. path->slots[0]--;
  870. extent_end = end;
  871. }
  872. recow = 1;
  873. }
  874. other_start = end;
  875. other_end = 0;
  876. if (extent_mergeable(leaf, path->slots[0] + 1,
  877. ino, bytenr, orig_offset,
  878. &other_start, &other_end)) {
  879. if (recow) {
  880. btrfs_release_path(path);
  881. goto again;
  882. }
  883. extent_end = other_end;
  884. del_slot = path->slots[0] + 1;
  885. del_nr++;
  886. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  887. 0, root->root_key.objectid,
  888. ino, orig_offset, 0);
  889. BUG_ON(ret); /* -ENOMEM */
  890. }
  891. other_start = 0;
  892. other_end = start;
  893. if (extent_mergeable(leaf, path->slots[0] - 1,
  894. ino, bytenr, orig_offset,
  895. &other_start, &other_end)) {
  896. if (recow) {
  897. btrfs_release_path(path);
  898. goto again;
  899. }
  900. key.offset = other_start;
  901. del_slot = path->slots[0];
  902. del_nr++;
  903. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  904. 0, root->root_key.objectid,
  905. ino, orig_offset, 0);
  906. BUG_ON(ret); /* -ENOMEM */
  907. }
  908. if (del_nr == 0) {
  909. fi = btrfs_item_ptr(leaf, path->slots[0],
  910. struct btrfs_file_extent_item);
  911. btrfs_set_file_extent_type(leaf, fi,
  912. BTRFS_FILE_EXTENT_REG);
  913. btrfs_mark_buffer_dirty(leaf);
  914. } else {
  915. fi = btrfs_item_ptr(leaf, del_slot - 1,
  916. struct btrfs_file_extent_item);
  917. btrfs_set_file_extent_type(leaf, fi,
  918. BTRFS_FILE_EXTENT_REG);
  919. btrfs_set_file_extent_num_bytes(leaf, fi,
  920. extent_end - key.offset);
  921. btrfs_mark_buffer_dirty(leaf);
  922. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  923. if (ret < 0) {
  924. btrfs_abort_transaction(trans, root, ret);
  925. goto out;
  926. }
  927. }
  928. out:
  929. btrfs_free_path(path);
  930. return 0;
  931. }
  932. /*
  933. * on error we return an unlocked page and the error value
  934. * on success we return a locked page and 0
  935. */
  936. static int prepare_uptodate_page(struct page *page, u64 pos,
  937. bool force_uptodate)
  938. {
  939. int ret = 0;
  940. if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
  941. !PageUptodate(page)) {
  942. ret = btrfs_readpage(NULL, page);
  943. if (ret)
  944. return ret;
  945. lock_page(page);
  946. if (!PageUptodate(page)) {
  947. unlock_page(page);
  948. return -EIO;
  949. }
  950. }
  951. return 0;
  952. }
  953. /*
  954. * this gets pages into the page cache and locks them down, it also properly
  955. * waits for data=ordered extents to finish before allowing the pages to be
  956. * modified.
  957. */
  958. static noinline int prepare_pages(struct btrfs_root *root, struct file *file,
  959. struct page **pages, size_t num_pages,
  960. loff_t pos, unsigned long first_index,
  961. size_t write_bytes, bool force_uptodate)
  962. {
  963. struct extent_state *cached_state = NULL;
  964. int i;
  965. unsigned long index = pos >> PAGE_CACHE_SHIFT;
  966. struct inode *inode = fdentry(file)->d_inode;
  967. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  968. int err = 0;
  969. int faili = 0;
  970. u64 start_pos;
  971. u64 last_pos;
  972. start_pos = pos & ~((u64)root->sectorsize - 1);
  973. last_pos = ((u64)index + num_pages) << PAGE_CACHE_SHIFT;
  974. again:
  975. for (i = 0; i < num_pages; i++) {
  976. pages[i] = find_or_create_page(inode->i_mapping, index + i,
  977. mask | __GFP_WRITE);
  978. if (!pages[i]) {
  979. faili = i - 1;
  980. err = -ENOMEM;
  981. goto fail;
  982. }
  983. if (i == 0)
  984. err = prepare_uptodate_page(pages[i], pos,
  985. force_uptodate);
  986. if (i == num_pages - 1)
  987. err = prepare_uptodate_page(pages[i],
  988. pos + write_bytes, false);
  989. if (err) {
  990. page_cache_release(pages[i]);
  991. faili = i - 1;
  992. goto fail;
  993. }
  994. wait_on_page_writeback(pages[i]);
  995. }
  996. err = 0;
  997. if (start_pos < inode->i_size) {
  998. struct btrfs_ordered_extent *ordered;
  999. lock_extent_bits(&BTRFS_I(inode)->io_tree,
  1000. start_pos, last_pos - 1, 0, &cached_state);
  1001. ordered = btrfs_lookup_first_ordered_extent(inode,
  1002. last_pos - 1);
  1003. if (ordered &&
  1004. ordered->file_offset + ordered->len > start_pos &&
  1005. ordered->file_offset < last_pos) {
  1006. btrfs_put_ordered_extent(ordered);
  1007. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1008. start_pos, last_pos - 1,
  1009. &cached_state, GFP_NOFS);
  1010. for (i = 0; i < num_pages; i++) {
  1011. unlock_page(pages[i]);
  1012. page_cache_release(pages[i]);
  1013. }
  1014. btrfs_wait_ordered_range(inode, start_pos,
  1015. last_pos - start_pos);
  1016. goto again;
  1017. }
  1018. if (ordered)
  1019. btrfs_put_ordered_extent(ordered);
  1020. clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
  1021. last_pos - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
  1022. EXTENT_DO_ACCOUNTING, 0, 0, &cached_state,
  1023. GFP_NOFS);
  1024. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1025. start_pos, last_pos - 1, &cached_state,
  1026. GFP_NOFS);
  1027. }
  1028. for (i = 0; i < num_pages; i++) {
  1029. if (clear_page_dirty_for_io(pages[i]))
  1030. account_page_redirty(pages[i]);
  1031. set_page_extent_mapped(pages[i]);
  1032. WARN_ON(!PageLocked(pages[i]));
  1033. }
  1034. return 0;
  1035. fail:
  1036. while (faili >= 0) {
  1037. unlock_page(pages[faili]);
  1038. page_cache_release(pages[faili]);
  1039. faili--;
  1040. }
  1041. return err;
  1042. }
  1043. static noinline ssize_t __btrfs_buffered_write(struct file *file,
  1044. struct iov_iter *i,
  1045. loff_t pos)
  1046. {
  1047. struct inode *inode = fdentry(file)->d_inode;
  1048. struct btrfs_root *root = BTRFS_I(inode)->root;
  1049. struct page **pages = NULL;
  1050. unsigned long first_index;
  1051. size_t num_written = 0;
  1052. int nrptrs;
  1053. int ret = 0;
  1054. bool force_page_uptodate = false;
  1055. nrptrs = min((iov_iter_count(i) + PAGE_CACHE_SIZE - 1) /
  1056. PAGE_CACHE_SIZE, PAGE_CACHE_SIZE /
  1057. (sizeof(struct page *)));
  1058. nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
  1059. nrptrs = max(nrptrs, 8);
  1060. pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
  1061. if (!pages)
  1062. return -ENOMEM;
  1063. first_index = pos >> PAGE_CACHE_SHIFT;
  1064. while (iov_iter_count(i) > 0) {
  1065. size_t offset = pos & (PAGE_CACHE_SIZE - 1);
  1066. size_t write_bytes = min(iov_iter_count(i),
  1067. nrptrs * (size_t)PAGE_CACHE_SIZE -
  1068. offset);
  1069. size_t num_pages = (write_bytes + offset +
  1070. PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1071. size_t dirty_pages;
  1072. size_t copied;
  1073. WARN_ON(num_pages > nrptrs);
  1074. /*
  1075. * Fault pages before locking them in prepare_pages
  1076. * to avoid recursive lock
  1077. */
  1078. if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
  1079. ret = -EFAULT;
  1080. break;
  1081. }
  1082. ret = btrfs_delalloc_reserve_space(inode,
  1083. num_pages << PAGE_CACHE_SHIFT);
  1084. if (ret)
  1085. break;
  1086. /*
  1087. * This is going to setup the pages array with the number of
  1088. * pages we want, so we don't really need to worry about the
  1089. * contents of pages from loop to loop
  1090. */
  1091. ret = prepare_pages(root, file, pages, num_pages,
  1092. pos, first_index, write_bytes,
  1093. force_page_uptodate);
  1094. if (ret) {
  1095. btrfs_delalloc_release_space(inode,
  1096. num_pages << PAGE_CACHE_SHIFT);
  1097. break;
  1098. }
  1099. copied = btrfs_copy_from_user(pos, num_pages,
  1100. write_bytes, pages, i);
  1101. /*
  1102. * if we have trouble faulting in the pages, fall
  1103. * back to one page at a time
  1104. */
  1105. if (copied < write_bytes)
  1106. nrptrs = 1;
  1107. if (copied == 0) {
  1108. force_page_uptodate = true;
  1109. dirty_pages = 0;
  1110. } else {
  1111. force_page_uptodate = false;
  1112. dirty_pages = (copied + offset +
  1113. PAGE_CACHE_SIZE - 1) >>
  1114. PAGE_CACHE_SHIFT;
  1115. }
  1116. /*
  1117. * If we had a short copy we need to release the excess delaloc
  1118. * bytes we reserved. We need to increment outstanding_extents
  1119. * because btrfs_delalloc_release_space will decrement it, but
  1120. * we still have an outstanding extent for the chunk we actually
  1121. * managed to copy.
  1122. */
  1123. if (num_pages > dirty_pages) {
  1124. if (copied > 0) {
  1125. spin_lock(&BTRFS_I(inode)->lock);
  1126. BTRFS_I(inode)->outstanding_extents++;
  1127. spin_unlock(&BTRFS_I(inode)->lock);
  1128. }
  1129. btrfs_delalloc_release_space(inode,
  1130. (num_pages - dirty_pages) <<
  1131. PAGE_CACHE_SHIFT);
  1132. }
  1133. if (copied > 0) {
  1134. ret = btrfs_dirty_pages(root, inode, pages,
  1135. dirty_pages, pos, copied,
  1136. NULL);
  1137. if (ret) {
  1138. btrfs_delalloc_release_space(inode,
  1139. dirty_pages << PAGE_CACHE_SHIFT);
  1140. btrfs_drop_pages(pages, num_pages);
  1141. break;
  1142. }
  1143. }
  1144. btrfs_drop_pages(pages, num_pages);
  1145. cond_resched();
  1146. balance_dirty_pages_ratelimited_nr(inode->i_mapping,
  1147. dirty_pages);
  1148. if (dirty_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
  1149. btrfs_btree_balance_dirty(root, 1);
  1150. pos += copied;
  1151. num_written += copied;
  1152. }
  1153. kfree(pages);
  1154. return num_written ? num_written : ret;
  1155. }
  1156. static ssize_t __btrfs_direct_write(struct kiocb *iocb,
  1157. const struct iovec *iov,
  1158. unsigned long nr_segs, loff_t pos,
  1159. loff_t *ppos, size_t count, size_t ocount)
  1160. {
  1161. struct file *file = iocb->ki_filp;
  1162. struct inode *inode = fdentry(file)->d_inode;
  1163. struct iov_iter i;
  1164. ssize_t written;
  1165. ssize_t written_buffered;
  1166. loff_t endbyte;
  1167. int err;
  1168. written = generic_file_direct_write(iocb, iov, &nr_segs, pos, ppos,
  1169. count, ocount);
  1170. /*
  1171. * the generic O_DIRECT will update in-memory i_size after the
  1172. * DIOs are done. But our endio handlers that update the on
  1173. * disk i_size never update past the in memory i_size. So we
  1174. * need one more update here to catch any additions to the
  1175. * file
  1176. */
  1177. if (inode->i_size != BTRFS_I(inode)->disk_i_size) {
  1178. btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
  1179. mark_inode_dirty(inode);
  1180. }
  1181. if (written < 0 || written == count)
  1182. return written;
  1183. pos += written;
  1184. count -= written;
  1185. iov_iter_init(&i, iov, nr_segs, count, written);
  1186. written_buffered = __btrfs_buffered_write(file, &i, pos);
  1187. if (written_buffered < 0) {
  1188. err = written_buffered;
  1189. goto out;
  1190. }
  1191. endbyte = pos + written_buffered - 1;
  1192. err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
  1193. if (err)
  1194. goto out;
  1195. written += written_buffered;
  1196. *ppos = pos + written_buffered;
  1197. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
  1198. endbyte >> PAGE_CACHE_SHIFT);
  1199. out:
  1200. return written ? written : err;
  1201. }
  1202. static ssize_t btrfs_file_aio_write(struct kiocb *iocb,
  1203. const struct iovec *iov,
  1204. unsigned long nr_segs, loff_t pos)
  1205. {
  1206. struct file *file = iocb->ki_filp;
  1207. struct inode *inode = fdentry(file)->d_inode;
  1208. struct btrfs_root *root = BTRFS_I(inode)->root;
  1209. loff_t *ppos = &iocb->ki_pos;
  1210. u64 start_pos;
  1211. ssize_t num_written = 0;
  1212. ssize_t err = 0;
  1213. size_t count, ocount;
  1214. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  1215. mutex_lock(&inode->i_mutex);
  1216. err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
  1217. if (err) {
  1218. mutex_unlock(&inode->i_mutex);
  1219. goto out;
  1220. }
  1221. count = ocount;
  1222. current->backing_dev_info = inode->i_mapping->backing_dev_info;
  1223. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  1224. if (err) {
  1225. mutex_unlock(&inode->i_mutex);
  1226. goto out;
  1227. }
  1228. if (count == 0) {
  1229. mutex_unlock(&inode->i_mutex);
  1230. goto out;
  1231. }
  1232. err = file_remove_suid(file);
  1233. if (err) {
  1234. mutex_unlock(&inode->i_mutex);
  1235. goto out;
  1236. }
  1237. /*
  1238. * If BTRFS flips readonly due to some impossible error
  1239. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1240. * although we have opened a file as writable, we have
  1241. * to stop this write operation to ensure FS consistency.
  1242. */
  1243. if (root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) {
  1244. mutex_unlock(&inode->i_mutex);
  1245. err = -EROFS;
  1246. goto out;
  1247. }
  1248. err = btrfs_update_time(file);
  1249. if (err) {
  1250. mutex_unlock(&inode->i_mutex);
  1251. goto out;
  1252. }
  1253. BTRFS_I(inode)->sequence++;
  1254. start_pos = round_down(pos, root->sectorsize);
  1255. if (start_pos > i_size_read(inode)) {
  1256. err = btrfs_cont_expand(inode, i_size_read(inode), start_pos);
  1257. if (err) {
  1258. mutex_unlock(&inode->i_mutex);
  1259. goto out;
  1260. }
  1261. }
  1262. if (unlikely(file->f_flags & O_DIRECT)) {
  1263. num_written = __btrfs_direct_write(iocb, iov, nr_segs,
  1264. pos, ppos, count, ocount);
  1265. } else {
  1266. struct iov_iter i;
  1267. iov_iter_init(&i, iov, nr_segs, count, num_written);
  1268. num_written = __btrfs_buffered_write(file, &i, pos);
  1269. if (num_written > 0)
  1270. *ppos = pos + num_written;
  1271. }
  1272. mutex_unlock(&inode->i_mutex);
  1273. /*
  1274. * we want to make sure fsync finds this change
  1275. * but we haven't joined a transaction running right now.
  1276. *
  1277. * Later on, someone is sure to update the inode and get the
  1278. * real transid recorded.
  1279. *
  1280. * We set last_trans now to the fs_info generation + 1,
  1281. * this will either be one more than the running transaction
  1282. * or the generation used for the next transaction if there isn't
  1283. * one running right now.
  1284. */
  1285. BTRFS_I(inode)->last_trans = root->fs_info->generation + 1;
  1286. if (num_written > 0 || num_written == -EIOCBQUEUED) {
  1287. err = generic_write_sync(file, pos, num_written);
  1288. if (err < 0 && num_written > 0)
  1289. num_written = err;
  1290. }
  1291. out:
  1292. current->backing_dev_info = NULL;
  1293. return num_written ? num_written : err;
  1294. }
  1295. int btrfs_release_file(struct inode *inode, struct file *filp)
  1296. {
  1297. /*
  1298. * ordered_data_close is set by settattr when we are about to truncate
  1299. * a file from a non-zero size to a zero size. This tries to
  1300. * flush down new bytes that may have been written if the
  1301. * application were using truncate to replace a file in place.
  1302. */
  1303. if (BTRFS_I(inode)->ordered_data_close) {
  1304. BTRFS_I(inode)->ordered_data_close = 0;
  1305. btrfs_add_ordered_operation(NULL, BTRFS_I(inode)->root, inode);
  1306. if (inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
  1307. filemap_flush(inode->i_mapping);
  1308. }
  1309. if (filp->private_data)
  1310. btrfs_ioctl_trans_end(filp);
  1311. return 0;
  1312. }
  1313. /*
  1314. * fsync call for both files and directories. This logs the inode into
  1315. * the tree log instead of forcing full commits whenever possible.
  1316. *
  1317. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1318. * in the metadata btree are up to date for copying to the log.
  1319. *
  1320. * It drops the inode mutex before doing the tree log commit. This is an
  1321. * important optimization for directories because holding the mutex prevents
  1322. * new operations on the dir while we write to disk.
  1323. */
  1324. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1325. {
  1326. struct dentry *dentry = file->f_path.dentry;
  1327. struct inode *inode = dentry->d_inode;
  1328. struct btrfs_root *root = BTRFS_I(inode)->root;
  1329. int ret = 0;
  1330. struct btrfs_trans_handle *trans;
  1331. trace_btrfs_sync_file(file, datasync);
  1332. ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
  1333. if (ret)
  1334. return ret;
  1335. mutex_lock(&inode->i_mutex);
  1336. /* we wait first, since the writeback may change the inode */
  1337. root->log_batch++;
  1338. btrfs_wait_ordered_range(inode, 0, (u64)-1);
  1339. root->log_batch++;
  1340. /*
  1341. * check the transaction that last modified this inode
  1342. * and see if its already been committed
  1343. */
  1344. if (!BTRFS_I(inode)->last_trans) {
  1345. mutex_unlock(&inode->i_mutex);
  1346. goto out;
  1347. }
  1348. /*
  1349. * if the last transaction that changed this file was before
  1350. * the current transaction, we can bail out now without any
  1351. * syncing
  1352. */
  1353. smp_mb();
  1354. if (BTRFS_I(inode)->last_trans <=
  1355. root->fs_info->last_trans_committed) {
  1356. BTRFS_I(inode)->last_trans = 0;
  1357. mutex_unlock(&inode->i_mutex);
  1358. goto out;
  1359. }
  1360. /*
  1361. * ok we haven't committed the transaction yet, lets do a commit
  1362. */
  1363. if (file->private_data)
  1364. btrfs_ioctl_trans_end(file);
  1365. trans = btrfs_start_transaction(root, 0);
  1366. if (IS_ERR(trans)) {
  1367. ret = PTR_ERR(trans);
  1368. mutex_unlock(&inode->i_mutex);
  1369. goto out;
  1370. }
  1371. ret = btrfs_log_dentry_safe(trans, root, dentry);
  1372. if (ret < 0) {
  1373. mutex_unlock(&inode->i_mutex);
  1374. goto out;
  1375. }
  1376. /* we've logged all the items and now have a consistent
  1377. * version of the file in the log. It is possible that
  1378. * someone will come in and modify the file, but that's
  1379. * fine because the log is consistent on disk, and we
  1380. * have references to all of the file's extents
  1381. *
  1382. * It is possible that someone will come in and log the
  1383. * file again, but that will end up using the synchronization
  1384. * inside btrfs_sync_log to keep things safe.
  1385. */
  1386. mutex_unlock(&inode->i_mutex);
  1387. if (ret != BTRFS_NO_LOG_SYNC) {
  1388. if (ret > 0) {
  1389. ret = btrfs_commit_transaction(trans, root);
  1390. } else {
  1391. ret = btrfs_sync_log(trans, root);
  1392. if (ret == 0)
  1393. ret = btrfs_end_transaction(trans, root);
  1394. else
  1395. ret = btrfs_commit_transaction(trans, root);
  1396. }
  1397. } else {
  1398. ret = btrfs_end_transaction(trans, root);
  1399. }
  1400. out:
  1401. return ret > 0 ? -EIO : ret;
  1402. }
  1403. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1404. .fault = filemap_fault,
  1405. .page_mkwrite = btrfs_page_mkwrite,
  1406. };
  1407. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1408. {
  1409. struct address_space *mapping = filp->f_mapping;
  1410. if (!mapping->a_ops->readpage)
  1411. return -ENOEXEC;
  1412. file_accessed(filp);
  1413. vma->vm_ops = &btrfs_file_vm_ops;
  1414. vma->vm_flags |= VM_CAN_NONLINEAR;
  1415. return 0;
  1416. }
  1417. static long btrfs_fallocate(struct file *file, int mode,
  1418. loff_t offset, loff_t len)
  1419. {
  1420. struct inode *inode = file->f_path.dentry->d_inode;
  1421. struct extent_state *cached_state = NULL;
  1422. u64 cur_offset;
  1423. u64 last_byte;
  1424. u64 alloc_start;
  1425. u64 alloc_end;
  1426. u64 alloc_hint = 0;
  1427. u64 locked_end;
  1428. u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
  1429. struct extent_map *em;
  1430. int ret;
  1431. alloc_start = offset & ~mask;
  1432. alloc_end = (offset + len + mask) & ~mask;
  1433. /* We only support the FALLOC_FL_KEEP_SIZE mode */
  1434. if (mode & ~FALLOC_FL_KEEP_SIZE)
  1435. return -EOPNOTSUPP;
  1436. /*
  1437. * Make sure we have enough space before we do the
  1438. * allocation.
  1439. */
  1440. ret = btrfs_check_data_free_space(inode, len);
  1441. if (ret)
  1442. return ret;
  1443. /*
  1444. * wait for ordered IO before we have any locks. We'll loop again
  1445. * below with the locks held.
  1446. */
  1447. btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
  1448. mutex_lock(&inode->i_mutex);
  1449. ret = inode_newsize_ok(inode, alloc_end);
  1450. if (ret)
  1451. goto out;
  1452. if (alloc_start > inode->i_size) {
  1453. ret = btrfs_cont_expand(inode, i_size_read(inode),
  1454. alloc_start);
  1455. if (ret)
  1456. goto out;
  1457. }
  1458. locked_end = alloc_end - 1;
  1459. while (1) {
  1460. struct btrfs_ordered_extent *ordered;
  1461. /* the extent lock is ordered inside the running
  1462. * transaction
  1463. */
  1464. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  1465. locked_end, 0, &cached_state);
  1466. ordered = btrfs_lookup_first_ordered_extent(inode,
  1467. alloc_end - 1);
  1468. if (ordered &&
  1469. ordered->file_offset + ordered->len > alloc_start &&
  1470. ordered->file_offset < alloc_end) {
  1471. btrfs_put_ordered_extent(ordered);
  1472. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1473. alloc_start, locked_end,
  1474. &cached_state, GFP_NOFS);
  1475. /*
  1476. * we can't wait on the range with the transaction
  1477. * running or with the extent lock held
  1478. */
  1479. btrfs_wait_ordered_range(inode, alloc_start,
  1480. alloc_end - alloc_start);
  1481. } else {
  1482. if (ordered)
  1483. btrfs_put_ordered_extent(ordered);
  1484. break;
  1485. }
  1486. }
  1487. cur_offset = alloc_start;
  1488. while (1) {
  1489. u64 actual_end;
  1490. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  1491. alloc_end - cur_offset, 0);
  1492. if (IS_ERR_OR_NULL(em)) {
  1493. if (!em)
  1494. ret = -ENOMEM;
  1495. else
  1496. ret = PTR_ERR(em);
  1497. break;
  1498. }
  1499. last_byte = min(extent_map_end(em), alloc_end);
  1500. actual_end = min_t(u64, extent_map_end(em), offset + len);
  1501. last_byte = (last_byte + mask) & ~mask;
  1502. if (em->block_start == EXTENT_MAP_HOLE ||
  1503. (cur_offset >= inode->i_size &&
  1504. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  1505. ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
  1506. last_byte - cur_offset,
  1507. 1 << inode->i_blkbits,
  1508. offset + len,
  1509. &alloc_hint);
  1510. if (ret < 0) {
  1511. free_extent_map(em);
  1512. break;
  1513. }
  1514. } else if (actual_end > inode->i_size &&
  1515. !(mode & FALLOC_FL_KEEP_SIZE)) {
  1516. /*
  1517. * We didn't need to allocate any more space, but we
  1518. * still extended the size of the file so we need to
  1519. * update i_size.
  1520. */
  1521. inode->i_ctime = CURRENT_TIME;
  1522. i_size_write(inode, actual_end);
  1523. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  1524. }
  1525. free_extent_map(em);
  1526. cur_offset = last_byte;
  1527. if (cur_offset >= alloc_end) {
  1528. ret = 0;
  1529. break;
  1530. }
  1531. }
  1532. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  1533. &cached_state, GFP_NOFS);
  1534. out:
  1535. mutex_unlock(&inode->i_mutex);
  1536. /* Let go of our reservation. */
  1537. btrfs_free_reserved_data_space(inode, len);
  1538. return ret;
  1539. }
  1540. static int find_desired_extent(struct inode *inode, loff_t *offset, int origin)
  1541. {
  1542. struct btrfs_root *root = BTRFS_I(inode)->root;
  1543. struct extent_map *em;
  1544. struct extent_state *cached_state = NULL;
  1545. u64 lockstart = *offset;
  1546. u64 lockend = i_size_read(inode);
  1547. u64 start = *offset;
  1548. u64 orig_start = *offset;
  1549. u64 len = i_size_read(inode);
  1550. u64 last_end = 0;
  1551. int ret = 0;
  1552. lockend = max_t(u64, root->sectorsize, lockend);
  1553. if (lockend <= lockstart)
  1554. lockend = lockstart + root->sectorsize;
  1555. len = lockend - lockstart + 1;
  1556. len = max_t(u64, len, root->sectorsize);
  1557. if (inode->i_size == 0)
  1558. return -ENXIO;
  1559. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
  1560. &cached_state);
  1561. /*
  1562. * Delalloc is such a pain. If we have a hole and we have pending
  1563. * delalloc for a portion of the hole we will get back a hole that
  1564. * exists for the entire range since it hasn't been actually written
  1565. * yet. So to take care of this case we need to look for an extent just
  1566. * before the position we want in case there is outstanding delalloc
  1567. * going on here.
  1568. */
  1569. if (origin == SEEK_HOLE && start != 0) {
  1570. if (start <= root->sectorsize)
  1571. em = btrfs_get_extent_fiemap(inode, NULL, 0, 0,
  1572. root->sectorsize, 0);
  1573. else
  1574. em = btrfs_get_extent_fiemap(inode, NULL, 0,
  1575. start - root->sectorsize,
  1576. root->sectorsize, 0);
  1577. if (IS_ERR(em)) {
  1578. ret = PTR_ERR(em);
  1579. goto out;
  1580. }
  1581. last_end = em->start + em->len;
  1582. if (em->block_start == EXTENT_MAP_DELALLOC)
  1583. last_end = min_t(u64, last_end, inode->i_size);
  1584. free_extent_map(em);
  1585. }
  1586. while (1) {
  1587. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  1588. if (IS_ERR(em)) {
  1589. ret = PTR_ERR(em);
  1590. break;
  1591. }
  1592. if (em->block_start == EXTENT_MAP_HOLE) {
  1593. if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
  1594. if (last_end <= orig_start) {
  1595. free_extent_map(em);
  1596. ret = -ENXIO;
  1597. break;
  1598. }
  1599. }
  1600. if (origin == SEEK_HOLE) {
  1601. *offset = start;
  1602. free_extent_map(em);
  1603. break;
  1604. }
  1605. } else {
  1606. if (origin == SEEK_DATA) {
  1607. if (em->block_start == EXTENT_MAP_DELALLOC) {
  1608. if (start >= inode->i_size) {
  1609. free_extent_map(em);
  1610. ret = -ENXIO;
  1611. break;
  1612. }
  1613. }
  1614. *offset = start;
  1615. free_extent_map(em);
  1616. break;
  1617. }
  1618. }
  1619. start = em->start + em->len;
  1620. last_end = em->start + em->len;
  1621. if (em->block_start == EXTENT_MAP_DELALLOC)
  1622. last_end = min_t(u64, last_end, inode->i_size);
  1623. if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
  1624. free_extent_map(em);
  1625. ret = -ENXIO;
  1626. break;
  1627. }
  1628. free_extent_map(em);
  1629. cond_resched();
  1630. }
  1631. if (!ret)
  1632. *offset = min(*offset, inode->i_size);
  1633. out:
  1634. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  1635. &cached_state, GFP_NOFS);
  1636. return ret;
  1637. }
  1638. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int origin)
  1639. {
  1640. struct inode *inode = file->f_mapping->host;
  1641. int ret;
  1642. mutex_lock(&inode->i_mutex);
  1643. switch (origin) {
  1644. case SEEK_END:
  1645. case SEEK_CUR:
  1646. offset = generic_file_llseek(file, offset, origin);
  1647. goto out;
  1648. case SEEK_DATA:
  1649. case SEEK_HOLE:
  1650. if (offset >= i_size_read(inode)) {
  1651. mutex_unlock(&inode->i_mutex);
  1652. return -ENXIO;
  1653. }
  1654. ret = find_desired_extent(inode, &offset, origin);
  1655. if (ret) {
  1656. mutex_unlock(&inode->i_mutex);
  1657. return ret;
  1658. }
  1659. }
  1660. if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET)) {
  1661. offset = -EINVAL;
  1662. goto out;
  1663. }
  1664. if (offset > inode->i_sb->s_maxbytes) {
  1665. offset = -EINVAL;
  1666. goto out;
  1667. }
  1668. /* Special lock needed here? */
  1669. if (offset != file->f_pos) {
  1670. file->f_pos = offset;
  1671. file->f_version = 0;
  1672. }
  1673. out:
  1674. mutex_unlock(&inode->i_mutex);
  1675. return offset;
  1676. }
  1677. const struct file_operations btrfs_file_operations = {
  1678. .llseek = btrfs_file_llseek,
  1679. .read = do_sync_read,
  1680. .write = do_sync_write,
  1681. .aio_read = generic_file_aio_read,
  1682. .splice_read = generic_file_splice_read,
  1683. .aio_write = btrfs_file_aio_write,
  1684. .mmap = btrfs_file_mmap,
  1685. .open = generic_file_open,
  1686. .release = btrfs_release_file,
  1687. .fsync = btrfs_sync_file,
  1688. .fallocate = btrfs_fallocate,
  1689. .unlocked_ioctl = btrfs_ioctl,
  1690. #ifdef CONFIG_COMPAT
  1691. .compat_ioctl = btrfs_ioctl,
  1692. #endif
  1693. };