file.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812
  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/aio.h>
  27. #include <linux/falloc.h>
  28. #include <linux/swap.h>
  29. #include <linux/writeback.h>
  30. #include <linux/statfs.h>
  31. #include <linux/compat.h>
  32. #include <linux/slab.h>
  33. #include <linux/btrfs.h>
  34. #include "ctree.h"
  35. #include "disk-io.h"
  36. #include "transaction.h"
  37. #include "btrfs_inode.h"
  38. #include "print-tree.h"
  39. #include "tree-log.h"
  40. #include "locking.h"
  41. #include "volumes.h"
  42. #include "qgroup.h"
  43. static struct kmem_cache *btrfs_inode_defrag_cachep;
  44. /*
  45. * when auto defrag is enabled we
  46. * queue up these defrag structs to remember which
  47. * inodes need defragging passes
  48. */
  49. struct inode_defrag {
  50. struct rb_node rb_node;
  51. /* objectid */
  52. u64 ino;
  53. /*
  54. * transid where the defrag was added, we search for
  55. * extents newer than this
  56. */
  57. u64 transid;
  58. /* root objectid */
  59. u64 root;
  60. /* last offset we were able to defrag */
  61. u64 last_offset;
  62. /* if we've wrapped around back to zero once already */
  63. int cycled;
  64. };
  65. static int __compare_inode_defrag(struct inode_defrag *defrag1,
  66. struct inode_defrag *defrag2)
  67. {
  68. if (defrag1->root > defrag2->root)
  69. return 1;
  70. else if (defrag1->root < defrag2->root)
  71. return -1;
  72. else if (defrag1->ino > defrag2->ino)
  73. return 1;
  74. else if (defrag1->ino < defrag2->ino)
  75. return -1;
  76. else
  77. return 0;
  78. }
  79. /* pop a record for an inode into the defrag tree. The lock
  80. * must be held already
  81. *
  82. * If you're inserting a record for an older transid than an
  83. * existing record, the transid already in the tree is lowered
  84. *
  85. * If an existing record is found the defrag item you
  86. * pass in is freed
  87. */
  88. static int __btrfs_add_inode_defrag(struct inode *inode,
  89. struct inode_defrag *defrag)
  90. {
  91. struct btrfs_root *root = BTRFS_I(inode)->root;
  92. struct inode_defrag *entry;
  93. struct rb_node **p;
  94. struct rb_node *parent = NULL;
  95. int ret;
  96. p = &root->fs_info->defrag_inodes.rb_node;
  97. while (*p) {
  98. parent = *p;
  99. entry = rb_entry(parent, struct inode_defrag, rb_node);
  100. ret = __compare_inode_defrag(defrag, entry);
  101. if (ret < 0)
  102. p = &parent->rb_left;
  103. else if (ret > 0)
  104. p = &parent->rb_right;
  105. else {
  106. /* if we're reinserting an entry for
  107. * an old defrag run, make sure to
  108. * lower the transid of our existing record
  109. */
  110. if (defrag->transid < entry->transid)
  111. entry->transid = defrag->transid;
  112. if (defrag->last_offset > entry->last_offset)
  113. entry->last_offset = defrag->last_offset;
  114. return -EEXIST;
  115. }
  116. }
  117. set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  118. rb_link_node(&defrag->rb_node, parent, p);
  119. rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
  120. return 0;
  121. }
  122. static inline int __need_auto_defrag(struct btrfs_root *root)
  123. {
  124. if (!btrfs_test_opt(root, AUTO_DEFRAG))
  125. return 0;
  126. if (btrfs_fs_closing(root->fs_info))
  127. return 0;
  128. return 1;
  129. }
  130. /*
  131. * insert a defrag record for this inode if auto defrag is
  132. * enabled
  133. */
  134. int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
  135. struct inode *inode)
  136. {
  137. struct btrfs_root *root = BTRFS_I(inode)->root;
  138. struct inode_defrag *defrag;
  139. u64 transid;
  140. int ret;
  141. if (!__need_auto_defrag(root))
  142. return 0;
  143. if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
  144. return 0;
  145. if (trans)
  146. transid = trans->transid;
  147. else
  148. transid = BTRFS_I(inode)->root->last_trans;
  149. defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
  150. if (!defrag)
  151. return -ENOMEM;
  152. defrag->ino = btrfs_ino(inode);
  153. defrag->transid = transid;
  154. defrag->root = root->root_key.objectid;
  155. spin_lock(&root->fs_info->defrag_inodes_lock);
  156. if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
  157. /*
  158. * If we set IN_DEFRAG flag and evict the inode from memory,
  159. * and then re-read this inode, this new inode doesn't have
  160. * IN_DEFRAG flag. At the case, we may find the existed defrag.
  161. */
  162. ret = __btrfs_add_inode_defrag(inode, defrag);
  163. if (ret)
  164. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  165. } else {
  166. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  167. }
  168. spin_unlock(&root->fs_info->defrag_inodes_lock);
  169. return 0;
  170. }
  171. /*
  172. * Requeue the defrag object. If there is a defrag object that points to
  173. * the same inode in the tree, we will merge them together (by
  174. * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
  175. */
  176. static void btrfs_requeue_inode_defrag(struct inode *inode,
  177. struct inode_defrag *defrag)
  178. {
  179. struct btrfs_root *root = BTRFS_I(inode)->root;
  180. int ret;
  181. if (!__need_auto_defrag(root))
  182. goto out;
  183. /*
  184. * Here we don't check the IN_DEFRAG flag, because we need merge
  185. * them together.
  186. */
  187. spin_lock(&root->fs_info->defrag_inodes_lock);
  188. ret = __btrfs_add_inode_defrag(inode, defrag);
  189. spin_unlock(&root->fs_info->defrag_inodes_lock);
  190. if (ret)
  191. goto out;
  192. return;
  193. out:
  194. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  195. }
  196. /*
  197. * pick the defragable inode that we want, if it doesn't exist, we will get
  198. * the next one.
  199. */
  200. static struct inode_defrag *
  201. btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
  202. {
  203. struct inode_defrag *entry = NULL;
  204. struct inode_defrag tmp;
  205. struct rb_node *p;
  206. struct rb_node *parent = NULL;
  207. int ret;
  208. tmp.ino = ino;
  209. tmp.root = root;
  210. spin_lock(&fs_info->defrag_inodes_lock);
  211. p = fs_info->defrag_inodes.rb_node;
  212. while (p) {
  213. parent = p;
  214. entry = rb_entry(parent, struct inode_defrag, rb_node);
  215. ret = __compare_inode_defrag(&tmp, entry);
  216. if (ret < 0)
  217. p = parent->rb_left;
  218. else if (ret > 0)
  219. p = parent->rb_right;
  220. else
  221. goto out;
  222. }
  223. if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
  224. parent = rb_next(parent);
  225. if (parent)
  226. entry = rb_entry(parent, struct inode_defrag, rb_node);
  227. else
  228. entry = NULL;
  229. }
  230. out:
  231. if (entry)
  232. rb_erase(parent, &fs_info->defrag_inodes);
  233. spin_unlock(&fs_info->defrag_inodes_lock);
  234. return entry;
  235. }
  236. void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
  237. {
  238. struct inode_defrag *defrag;
  239. struct rb_node *node;
  240. spin_lock(&fs_info->defrag_inodes_lock);
  241. node = rb_first(&fs_info->defrag_inodes);
  242. while (node) {
  243. rb_erase(node, &fs_info->defrag_inodes);
  244. defrag = rb_entry(node, struct inode_defrag, rb_node);
  245. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  246. if (need_resched()) {
  247. spin_unlock(&fs_info->defrag_inodes_lock);
  248. cond_resched();
  249. spin_lock(&fs_info->defrag_inodes_lock);
  250. }
  251. node = rb_first(&fs_info->defrag_inodes);
  252. }
  253. spin_unlock(&fs_info->defrag_inodes_lock);
  254. }
  255. #define BTRFS_DEFRAG_BATCH 1024
  256. static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
  257. struct inode_defrag *defrag)
  258. {
  259. struct btrfs_root *inode_root;
  260. struct inode *inode;
  261. struct btrfs_key key;
  262. struct btrfs_ioctl_defrag_range_args range;
  263. int num_defrag;
  264. int index;
  265. int ret;
  266. /* get the inode */
  267. key.objectid = defrag->root;
  268. key.type = BTRFS_ROOT_ITEM_KEY;
  269. key.offset = (u64)-1;
  270. index = srcu_read_lock(&fs_info->subvol_srcu);
  271. inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
  272. if (IS_ERR(inode_root)) {
  273. ret = PTR_ERR(inode_root);
  274. goto cleanup;
  275. }
  276. key.objectid = defrag->ino;
  277. key.type = BTRFS_INODE_ITEM_KEY;
  278. key.offset = 0;
  279. inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
  280. if (IS_ERR(inode)) {
  281. ret = PTR_ERR(inode);
  282. goto cleanup;
  283. }
  284. srcu_read_unlock(&fs_info->subvol_srcu, index);
  285. /* do a chunk of defrag */
  286. clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  287. memset(&range, 0, sizeof(range));
  288. range.len = (u64)-1;
  289. range.start = defrag->last_offset;
  290. sb_start_write(fs_info->sb);
  291. num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
  292. BTRFS_DEFRAG_BATCH);
  293. sb_end_write(fs_info->sb);
  294. /*
  295. * if we filled the whole defrag batch, there
  296. * must be more work to do. Queue this defrag
  297. * again
  298. */
  299. if (num_defrag == BTRFS_DEFRAG_BATCH) {
  300. defrag->last_offset = range.start;
  301. btrfs_requeue_inode_defrag(inode, defrag);
  302. } else if (defrag->last_offset && !defrag->cycled) {
  303. /*
  304. * we didn't fill our defrag batch, but
  305. * we didn't start at zero. Make sure we loop
  306. * around to the start of the file.
  307. */
  308. defrag->last_offset = 0;
  309. defrag->cycled = 1;
  310. btrfs_requeue_inode_defrag(inode, defrag);
  311. } else {
  312. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  313. }
  314. iput(inode);
  315. return 0;
  316. cleanup:
  317. srcu_read_unlock(&fs_info->subvol_srcu, index);
  318. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  319. return ret;
  320. }
  321. /*
  322. * run through the list of inodes in the FS that need
  323. * defragging
  324. */
  325. int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
  326. {
  327. struct inode_defrag *defrag;
  328. u64 first_ino = 0;
  329. u64 root_objectid = 0;
  330. atomic_inc(&fs_info->defrag_running);
  331. while (1) {
  332. /* Pause the auto defragger. */
  333. if (test_bit(BTRFS_FS_STATE_REMOUNTING,
  334. &fs_info->fs_state))
  335. break;
  336. if (!__need_auto_defrag(fs_info->tree_root))
  337. break;
  338. /* find an inode to defrag */
  339. defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
  340. first_ino);
  341. if (!defrag) {
  342. if (root_objectid || first_ino) {
  343. root_objectid = 0;
  344. first_ino = 0;
  345. continue;
  346. } else {
  347. break;
  348. }
  349. }
  350. first_ino = defrag->ino + 1;
  351. root_objectid = defrag->root;
  352. __btrfs_run_defrag_inode(fs_info, defrag);
  353. }
  354. atomic_dec(&fs_info->defrag_running);
  355. /*
  356. * during unmount, we use the transaction_wait queue to
  357. * wait for the defragger to stop
  358. */
  359. wake_up(&fs_info->transaction_wait);
  360. return 0;
  361. }
  362. /* simple helper to fault in pages and copy. This should go away
  363. * and be replaced with calls into generic code.
  364. */
  365. static noinline int btrfs_copy_from_user(loff_t pos, int num_pages,
  366. size_t write_bytes,
  367. struct page **prepared_pages,
  368. struct iov_iter *i)
  369. {
  370. size_t copied = 0;
  371. size_t total_copied = 0;
  372. int pg = 0;
  373. int offset = pos & (PAGE_CACHE_SIZE - 1);
  374. while (write_bytes > 0) {
  375. size_t count = min_t(size_t,
  376. PAGE_CACHE_SIZE - offset, write_bytes);
  377. struct page *page = prepared_pages[pg];
  378. /*
  379. * Copy data from userspace to the current page
  380. */
  381. copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
  382. /* Flush processor's dcache for this page */
  383. flush_dcache_page(page);
  384. /*
  385. * if we get a partial write, we can end up with
  386. * partially up to date pages. These add
  387. * a lot of complexity, so make sure they don't
  388. * happen by forcing this copy to be retried.
  389. *
  390. * The rest of the btrfs_file_write code will fall
  391. * back to page at a time copies after we return 0.
  392. */
  393. if (!PageUptodate(page) && copied < count)
  394. copied = 0;
  395. iov_iter_advance(i, copied);
  396. write_bytes -= copied;
  397. total_copied += copied;
  398. /* Return to btrfs_file_write_iter to fault page */
  399. if (unlikely(copied == 0))
  400. break;
  401. if (copied < PAGE_CACHE_SIZE - offset) {
  402. offset += copied;
  403. } else {
  404. pg++;
  405. offset = 0;
  406. }
  407. }
  408. return total_copied;
  409. }
  410. /*
  411. * unlocks pages after btrfs_file_write is done with them
  412. */
  413. static void btrfs_drop_pages(struct page **pages, size_t num_pages)
  414. {
  415. size_t i;
  416. for (i = 0; i < num_pages; i++) {
  417. /* page checked is some magic around finding pages that
  418. * have been modified without going through btrfs_set_page_dirty
  419. * clear it here. There should be no need to mark the pages
  420. * accessed as prepare_pages should have marked them accessed
  421. * in prepare_pages via find_or_create_page()
  422. */
  423. ClearPageChecked(pages[i]);
  424. unlock_page(pages[i]);
  425. page_cache_release(pages[i]);
  426. }
  427. }
  428. /*
  429. * after copy_from_user, pages need to be dirtied and we need to make
  430. * sure holes are created between the current EOF and the start of
  431. * any next extents (if required).
  432. *
  433. * this also makes the decision about creating an inline extent vs
  434. * doing real data extents, marking pages dirty and delalloc as required.
  435. */
  436. int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
  437. struct page **pages, size_t num_pages,
  438. loff_t pos, size_t write_bytes,
  439. struct extent_state **cached)
  440. {
  441. int err = 0;
  442. int i;
  443. u64 num_bytes;
  444. u64 start_pos;
  445. u64 end_of_last_block;
  446. u64 end_pos = pos + write_bytes;
  447. loff_t isize = i_size_read(inode);
  448. start_pos = pos & ~((u64)root->sectorsize - 1);
  449. num_bytes = ALIGN(write_bytes + pos - start_pos, root->sectorsize);
  450. end_of_last_block = start_pos + num_bytes - 1;
  451. err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
  452. cached);
  453. if (err)
  454. return err;
  455. for (i = 0; i < num_pages; i++) {
  456. struct page *p = pages[i];
  457. SetPageUptodate(p);
  458. ClearPageChecked(p);
  459. set_page_dirty(p);
  460. }
  461. /*
  462. * we've only changed i_size in ram, and we haven't updated
  463. * the disk i_size. There is no need to log the inode
  464. * at this time.
  465. */
  466. if (end_pos > isize)
  467. i_size_write(inode, end_pos);
  468. return 0;
  469. }
  470. /*
  471. * this drops all the extents in the cache that intersect the range
  472. * [start, end]. Existing extents are split as required.
  473. */
  474. void btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
  475. int skip_pinned)
  476. {
  477. struct extent_map *em;
  478. struct extent_map *split = NULL;
  479. struct extent_map *split2 = NULL;
  480. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  481. u64 len = end - start + 1;
  482. u64 gen;
  483. int ret;
  484. int testend = 1;
  485. unsigned long flags;
  486. int compressed = 0;
  487. bool modified;
  488. WARN_ON(end < start);
  489. if (end == (u64)-1) {
  490. len = (u64)-1;
  491. testend = 0;
  492. }
  493. while (1) {
  494. int no_splits = 0;
  495. modified = false;
  496. if (!split)
  497. split = alloc_extent_map();
  498. if (!split2)
  499. split2 = alloc_extent_map();
  500. if (!split || !split2)
  501. no_splits = 1;
  502. write_lock(&em_tree->lock);
  503. em = lookup_extent_mapping(em_tree, start, len);
  504. if (!em) {
  505. write_unlock(&em_tree->lock);
  506. break;
  507. }
  508. flags = em->flags;
  509. gen = em->generation;
  510. if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
  511. if (testend && em->start + em->len >= start + len) {
  512. free_extent_map(em);
  513. write_unlock(&em_tree->lock);
  514. break;
  515. }
  516. start = em->start + em->len;
  517. if (testend)
  518. len = start + len - (em->start + em->len);
  519. free_extent_map(em);
  520. write_unlock(&em_tree->lock);
  521. continue;
  522. }
  523. compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  524. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  525. clear_bit(EXTENT_FLAG_LOGGING, &flags);
  526. modified = !list_empty(&em->list);
  527. if (no_splits)
  528. goto next;
  529. if (em->start < start) {
  530. split->start = em->start;
  531. split->len = start - em->start;
  532. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  533. split->orig_start = em->orig_start;
  534. split->block_start = em->block_start;
  535. if (compressed)
  536. split->block_len = em->block_len;
  537. else
  538. split->block_len = split->len;
  539. split->orig_block_len = max(split->block_len,
  540. em->orig_block_len);
  541. split->ram_bytes = em->ram_bytes;
  542. } else {
  543. split->orig_start = split->start;
  544. split->block_len = 0;
  545. split->block_start = em->block_start;
  546. split->orig_block_len = 0;
  547. split->ram_bytes = split->len;
  548. }
  549. split->generation = gen;
  550. split->bdev = em->bdev;
  551. split->flags = flags;
  552. split->compress_type = em->compress_type;
  553. replace_extent_mapping(em_tree, em, split, modified);
  554. free_extent_map(split);
  555. split = split2;
  556. split2 = NULL;
  557. }
  558. if (testend && em->start + em->len > start + len) {
  559. u64 diff = start + len - em->start;
  560. split->start = start + len;
  561. split->len = em->start + em->len - (start + len);
  562. split->bdev = em->bdev;
  563. split->flags = flags;
  564. split->compress_type = em->compress_type;
  565. split->generation = gen;
  566. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  567. split->orig_block_len = max(em->block_len,
  568. em->orig_block_len);
  569. split->ram_bytes = em->ram_bytes;
  570. if (compressed) {
  571. split->block_len = em->block_len;
  572. split->block_start = em->block_start;
  573. split->orig_start = em->orig_start;
  574. } else {
  575. split->block_len = split->len;
  576. split->block_start = em->block_start
  577. + diff;
  578. split->orig_start = em->orig_start;
  579. }
  580. } else {
  581. split->ram_bytes = split->len;
  582. split->orig_start = split->start;
  583. split->block_len = 0;
  584. split->block_start = em->block_start;
  585. split->orig_block_len = 0;
  586. }
  587. if (extent_map_in_tree(em)) {
  588. replace_extent_mapping(em_tree, em, split,
  589. modified);
  590. } else {
  591. ret = add_extent_mapping(em_tree, split,
  592. modified);
  593. ASSERT(ret == 0); /* Logic error */
  594. }
  595. free_extent_map(split);
  596. split = NULL;
  597. }
  598. next:
  599. if (extent_map_in_tree(em))
  600. remove_extent_mapping(em_tree, em);
  601. write_unlock(&em_tree->lock);
  602. /* once for us */
  603. free_extent_map(em);
  604. /* once for the tree*/
  605. free_extent_map(em);
  606. }
  607. if (split)
  608. free_extent_map(split);
  609. if (split2)
  610. free_extent_map(split2);
  611. }
  612. /*
  613. * this is very complex, but the basic idea is to drop all extents
  614. * in the range start - end. hint_block is filled in with a block number
  615. * that would be a good hint to the block allocator for this file.
  616. *
  617. * If an extent intersects the range but is not entirely inside the range
  618. * it is either truncated or split. Anything entirely inside the range
  619. * is deleted from the tree.
  620. */
  621. int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
  622. struct btrfs_root *root, struct inode *inode,
  623. struct btrfs_path *path, u64 start, u64 end,
  624. u64 *drop_end, int drop_cache,
  625. int replace_extent,
  626. u32 extent_item_size,
  627. int *key_inserted)
  628. {
  629. struct extent_buffer *leaf;
  630. struct btrfs_file_extent_item *fi;
  631. struct btrfs_key key;
  632. struct btrfs_key new_key;
  633. u64 ino = btrfs_ino(inode);
  634. u64 search_start = start;
  635. u64 disk_bytenr = 0;
  636. u64 num_bytes = 0;
  637. u64 extent_offset = 0;
  638. u64 extent_end = 0;
  639. int del_nr = 0;
  640. int del_slot = 0;
  641. int extent_type;
  642. int recow;
  643. int ret;
  644. int modify_tree = -1;
  645. int update_refs;
  646. int found = 0;
  647. int leafs_visited = 0;
  648. if (drop_cache)
  649. btrfs_drop_extent_cache(inode, start, end - 1, 0);
  650. if (start >= BTRFS_I(inode)->disk_i_size && !replace_extent)
  651. modify_tree = 0;
  652. update_refs = (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  653. root == root->fs_info->tree_root);
  654. while (1) {
  655. recow = 0;
  656. ret = btrfs_lookup_file_extent(trans, root, path, ino,
  657. search_start, modify_tree);
  658. if (ret < 0)
  659. break;
  660. if (ret > 0 && path->slots[0] > 0 && search_start == start) {
  661. leaf = path->nodes[0];
  662. btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
  663. if (key.objectid == ino &&
  664. key.type == BTRFS_EXTENT_DATA_KEY)
  665. path->slots[0]--;
  666. }
  667. ret = 0;
  668. leafs_visited++;
  669. next_slot:
  670. leaf = path->nodes[0];
  671. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  672. BUG_ON(del_nr > 0);
  673. ret = btrfs_next_leaf(root, path);
  674. if (ret < 0)
  675. break;
  676. if (ret > 0) {
  677. ret = 0;
  678. break;
  679. }
  680. leafs_visited++;
  681. leaf = path->nodes[0];
  682. recow = 1;
  683. }
  684. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  685. if (key.objectid > ino ||
  686. key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
  687. break;
  688. fi = btrfs_item_ptr(leaf, path->slots[0],
  689. struct btrfs_file_extent_item);
  690. extent_type = btrfs_file_extent_type(leaf, fi);
  691. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  692. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  693. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  694. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  695. extent_offset = btrfs_file_extent_offset(leaf, fi);
  696. extent_end = key.offset +
  697. btrfs_file_extent_num_bytes(leaf, fi);
  698. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  699. extent_end = key.offset +
  700. btrfs_file_extent_inline_len(leaf,
  701. path->slots[0], fi);
  702. } else {
  703. WARN_ON(1);
  704. extent_end = search_start;
  705. }
  706. /*
  707. * Don't skip extent items representing 0 byte lengths. They
  708. * used to be created (bug) if while punching holes we hit
  709. * -ENOSPC condition. So if we find one here, just ensure we
  710. * delete it, otherwise we would insert a new file extent item
  711. * with the same key (offset) as that 0 bytes length file
  712. * extent item in the call to setup_items_for_insert() later
  713. * in this function.
  714. */
  715. if (extent_end == key.offset && extent_end >= search_start)
  716. goto delete_extent_item;
  717. if (extent_end <= search_start) {
  718. path->slots[0]++;
  719. goto next_slot;
  720. }
  721. found = 1;
  722. search_start = max(key.offset, start);
  723. if (recow || !modify_tree) {
  724. modify_tree = -1;
  725. btrfs_release_path(path);
  726. continue;
  727. }
  728. /*
  729. * | - range to drop - |
  730. * | -------- extent -------- |
  731. */
  732. if (start > key.offset && end < extent_end) {
  733. BUG_ON(del_nr > 0);
  734. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  735. ret = -EOPNOTSUPP;
  736. break;
  737. }
  738. memcpy(&new_key, &key, sizeof(new_key));
  739. new_key.offset = start;
  740. ret = btrfs_duplicate_item(trans, root, path,
  741. &new_key);
  742. if (ret == -EAGAIN) {
  743. btrfs_release_path(path);
  744. continue;
  745. }
  746. if (ret < 0)
  747. break;
  748. leaf = path->nodes[0];
  749. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  750. struct btrfs_file_extent_item);
  751. btrfs_set_file_extent_num_bytes(leaf, fi,
  752. start - key.offset);
  753. fi = btrfs_item_ptr(leaf, path->slots[0],
  754. struct btrfs_file_extent_item);
  755. extent_offset += start - key.offset;
  756. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  757. btrfs_set_file_extent_num_bytes(leaf, fi,
  758. extent_end - start);
  759. btrfs_mark_buffer_dirty(leaf);
  760. if (update_refs && disk_bytenr > 0) {
  761. ret = btrfs_inc_extent_ref(trans, root,
  762. disk_bytenr, num_bytes, 0,
  763. root->root_key.objectid,
  764. new_key.objectid,
  765. start - extent_offset, 1);
  766. BUG_ON(ret); /* -ENOMEM */
  767. }
  768. key.offset = start;
  769. }
  770. /*
  771. * | ---- range to drop ----- |
  772. * | -------- extent -------- |
  773. */
  774. if (start <= key.offset && end < extent_end) {
  775. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  776. ret = -EOPNOTSUPP;
  777. break;
  778. }
  779. memcpy(&new_key, &key, sizeof(new_key));
  780. new_key.offset = end;
  781. btrfs_set_item_key_safe(root, path, &new_key);
  782. extent_offset += end - key.offset;
  783. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  784. btrfs_set_file_extent_num_bytes(leaf, fi,
  785. extent_end - end);
  786. btrfs_mark_buffer_dirty(leaf);
  787. if (update_refs && disk_bytenr > 0)
  788. inode_sub_bytes(inode, end - key.offset);
  789. break;
  790. }
  791. search_start = extent_end;
  792. /*
  793. * | ---- range to drop ----- |
  794. * | -------- extent -------- |
  795. */
  796. if (start > key.offset && end >= extent_end) {
  797. BUG_ON(del_nr > 0);
  798. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  799. ret = -EOPNOTSUPP;
  800. break;
  801. }
  802. btrfs_set_file_extent_num_bytes(leaf, fi,
  803. start - key.offset);
  804. btrfs_mark_buffer_dirty(leaf);
  805. if (update_refs && disk_bytenr > 0)
  806. inode_sub_bytes(inode, extent_end - start);
  807. if (end == extent_end)
  808. break;
  809. path->slots[0]++;
  810. goto next_slot;
  811. }
  812. /*
  813. * | ---- range to drop ----- |
  814. * | ------ extent ------ |
  815. */
  816. if (start <= key.offset && end >= extent_end) {
  817. delete_extent_item:
  818. if (del_nr == 0) {
  819. del_slot = path->slots[0];
  820. del_nr = 1;
  821. } else {
  822. BUG_ON(del_slot + del_nr != path->slots[0]);
  823. del_nr++;
  824. }
  825. if (update_refs &&
  826. extent_type == BTRFS_FILE_EXTENT_INLINE) {
  827. inode_sub_bytes(inode,
  828. extent_end - key.offset);
  829. extent_end = ALIGN(extent_end,
  830. root->sectorsize);
  831. } else if (update_refs && disk_bytenr > 0) {
  832. ret = btrfs_free_extent(trans, root,
  833. disk_bytenr, num_bytes, 0,
  834. root->root_key.objectid,
  835. key.objectid, key.offset -
  836. extent_offset, 0);
  837. BUG_ON(ret); /* -ENOMEM */
  838. inode_sub_bytes(inode,
  839. extent_end - key.offset);
  840. }
  841. if (end == extent_end)
  842. break;
  843. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  844. path->slots[0]++;
  845. goto next_slot;
  846. }
  847. ret = btrfs_del_items(trans, root, path, del_slot,
  848. del_nr);
  849. if (ret) {
  850. btrfs_abort_transaction(trans, root, ret);
  851. break;
  852. }
  853. del_nr = 0;
  854. del_slot = 0;
  855. btrfs_release_path(path);
  856. continue;
  857. }
  858. BUG_ON(1);
  859. }
  860. if (!ret && del_nr > 0) {
  861. /*
  862. * Set path->slots[0] to first slot, so that after the delete
  863. * if items are move off from our leaf to its immediate left or
  864. * right neighbor leafs, we end up with a correct and adjusted
  865. * path->slots[0] for our insertion (if replace_extent != 0).
  866. */
  867. path->slots[0] = del_slot;
  868. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  869. if (ret)
  870. btrfs_abort_transaction(trans, root, ret);
  871. }
  872. leaf = path->nodes[0];
  873. /*
  874. * If btrfs_del_items() was called, it might have deleted a leaf, in
  875. * which case it unlocked our path, so check path->locks[0] matches a
  876. * write lock.
  877. */
  878. if (!ret && replace_extent && leafs_visited == 1 &&
  879. (path->locks[0] == BTRFS_WRITE_LOCK_BLOCKING ||
  880. path->locks[0] == BTRFS_WRITE_LOCK) &&
  881. btrfs_leaf_free_space(root, leaf) >=
  882. sizeof(struct btrfs_item) + extent_item_size) {
  883. key.objectid = ino;
  884. key.type = BTRFS_EXTENT_DATA_KEY;
  885. key.offset = start;
  886. if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
  887. struct btrfs_key slot_key;
  888. btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
  889. if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
  890. path->slots[0]++;
  891. }
  892. setup_items_for_insert(root, path, &key,
  893. &extent_item_size,
  894. extent_item_size,
  895. sizeof(struct btrfs_item) +
  896. extent_item_size, 1);
  897. *key_inserted = 1;
  898. }
  899. if (!replace_extent || !(*key_inserted))
  900. btrfs_release_path(path);
  901. if (drop_end)
  902. *drop_end = found ? min(end, extent_end) : end;
  903. return ret;
  904. }
  905. int btrfs_drop_extents(struct btrfs_trans_handle *trans,
  906. struct btrfs_root *root, struct inode *inode, u64 start,
  907. u64 end, int drop_cache)
  908. {
  909. struct btrfs_path *path;
  910. int ret;
  911. path = btrfs_alloc_path();
  912. if (!path)
  913. return -ENOMEM;
  914. ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
  915. drop_cache, 0, 0, NULL);
  916. btrfs_free_path(path);
  917. return ret;
  918. }
  919. static int extent_mergeable(struct extent_buffer *leaf, int slot,
  920. u64 objectid, u64 bytenr, u64 orig_offset,
  921. u64 *start, u64 *end)
  922. {
  923. struct btrfs_file_extent_item *fi;
  924. struct btrfs_key key;
  925. u64 extent_end;
  926. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  927. return 0;
  928. btrfs_item_key_to_cpu(leaf, &key, slot);
  929. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  930. return 0;
  931. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  932. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  933. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  934. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  935. btrfs_file_extent_compression(leaf, fi) ||
  936. btrfs_file_extent_encryption(leaf, fi) ||
  937. btrfs_file_extent_other_encoding(leaf, fi))
  938. return 0;
  939. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  940. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  941. return 0;
  942. *start = key.offset;
  943. *end = extent_end;
  944. return 1;
  945. }
  946. /*
  947. * Mark extent in the range start - end as written.
  948. *
  949. * This changes extent type from 'pre-allocated' to 'regular'. If only
  950. * part of extent is marked as written, the extent will be split into
  951. * two or three.
  952. */
  953. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  954. struct inode *inode, u64 start, u64 end)
  955. {
  956. struct btrfs_root *root = BTRFS_I(inode)->root;
  957. struct extent_buffer *leaf;
  958. struct btrfs_path *path;
  959. struct btrfs_file_extent_item *fi;
  960. struct btrfs_key key;
  961. struct btrfs_key new_key;
  962. u64 bytenr;
  963. u64 num_bytes;
  964. u64 extent_end;
  965. u64 orig_offset;
  966. u64 other_start;
  967. u64 other_end;
  968. u64 split;
  969. int del_nr = 0;
  970. int del_slot = 0;
  971. int recow;
  972. int ret;
  973. u64 ino = btrfs_ino(inode);
  974. path = btrfs_alloc_path();
  975. if (!path)
  976. return -ENOMEM;
  977. again:
  978. recow = 0;
  979. split = start;
  980. key.objectid = ino;
  981. key.type = BTRFS_EXTENT_DATA_KEY;
  982. key.offset = split;
  983. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  984. if (ret < 0)
  985. goto out;
  986. if (ret > 0 && path->slots[0] > 0)
  987. path->slots[0]--;
  988. leaf = path->nodes[0];
  989. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  990. BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
  991. fi = btrfs_item_ptr(leaf, path->slots[0],
  992. struct btrfs_file_extent_item);
  993. BUG_ON(btrfs_file_extent_type(leaf, fi) !=
  994. BTRFS_FILE_EXTENT_PREALLOC);
  995. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  996. BUG_ON(key.offset > start || extent_end < end);
  997. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  998. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  999. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  1000. memcpy(&new_key, &key, sizeof(new_key));
  1001. if (start == key.offset && end < extent_end) {
  1002. other_start = 0;
  1003. other_end = start;
  1004. if (extent_mergeable(leaf, path->slots[0] - 1,
  1005. ino, bytenr, orig_offset,
  1006. &other_start, &other_end)) {
  1007. new_key.offset = end;
  1008. btrfs_set_item_key_safe(root, path, &new_key);
  1009. fi = btrfs_item_ptr(leaf, path->slots[0],
  1010. struct btrfs_file_extent_item);
  1011. btrfs_set_file_extent_generation(leaf, fi,
  1012. trans->transid);
  1013. btrfs_set_file_extent_num_bytes(leaf, fi,
  1014. extent_end - end);
  1015. btrfs_set_file_extent_offset(leaf, fi,
  1016. end - orig_offset);
  1017. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1018. struct btrfs_file_extent_item);
  1019. btrfs_set_file_extent_generation(leaf, fi,
  1020. trans->transid);
  1021. btrfs_set_file_extent_num_bytes(leaf, fi,
  1022. end - other_start);
  1023. btrfs_mark_buffer_dirty(leaf);
  1024. goto out;
  1025. }
  1026. }
  1027. if (start > key.offset && end == extent_end) {
  1028. other_start = end;
  1029. other_end = 0;
  1030. if (extent_mergeable(leaf, path->slots[0] + 1,
  1031. ino, bytenr, orig_offset,
  1032. &other_start, &other_end)) {
  1033. fi = btrfs_item_ptr(leaf, path->slots[0],
  1034. struct btrfs_file_extent_item);
  1035. btrfs_set_file_extent_num_bytes(leaf, fi,
  1036. start - key.offset);
  1037. btrfs_set_file_extent_generation(leaf, fi,
  1038. trans->transid);
  1039. path->slots[0]++;
  1040. new_key.offset = start;
  1041. btrfs_set_item_key_safe(root, path, &new_key);
  1042. fi = btrfs_item_ptr(leaf, path->slots[0],
  1043. struct btrfs_file_extent_item);
  1044. btrfs_set_file_extent_generation(leaf, fi,
  1045. trans->transid);
  1046. btrfs_set_file_extent_num_bytes(leaf, fi,
  1047. other_end - start);
  1048. btrfs_set_file_extent_offset(leaf, fi,
  1049. start - orig_offset);
  1050. btrfs_mark_buffer_dirty(leaf);
  1051. goto out;
  1052. }
  1053. }
  1054. while (start > key.offset || end < extent_end) {
  1055. if (key.offset == start)
  1056. split = end;
  1057. new_key.offset = split;
  1058. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  1059. if (ret == -EAGAIN) {
  1060. btrfs_release_path(path);
  1061. goto again;
  1062. }
  1063. if (ret < 0) {
  1064. btrfs_abort_transaction(trans, root, ret);
  1065. goto out;
  1066. }
  1067. leaf = path->nodes[0];
  1068. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1069. struct btrfs_file_extent_item);
  1070. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1071. btrfs_set_file_extent_num_bytes(leaf, fi,
  1072. split - key.offset);
  1073. fi = btrfs_item_ptr(leaf, path->slots[0],
  1074. struct btrfs_file_extent_item);
  1075. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1076. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  1077. btrfs_set_file_extent_num_bytes(leaf, fi,
  1078. extent_end - split);
  1079. btrfs_mark_buffer_dirty(leaf);
  1080. ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
  1081. root->root_key.objectid,
  1082. ino, orig_offset, 1);
  1083. BUG_ON(ret); /* -ENOMEM */
  1084. if (split == start) {
  1085. key.offset = start;
  1086. } else {
  1087. BUG_ON(start != key.offset);
  1088. path->slots[0]--;
  1089. extent_end = end;
  1090. }
  1091. recow = 1;
  1092. }
  1093. other_start = end;
  1094. other_end = 0;
  1095. if (extent_mergeable(leaf, path->slots[0] + 1,
  1096. ino, bytenr, orig_offset,
  1097. &other_start, &other_end)) {
  1098. if (recow) {
  1099. btrfs_release_path(path);
  1100. goto again;
  1101. }
  1102. extent_end = other_end;
  1103. del_slot = path->slots[0] + 1;
  1104. del_nr++;
  1105. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1106. 0, root->root_key.objectid,
  1107. ino, orig_offset, 0);
  1108. BUG_ON(ret); /* -ENOMEM */
  1109. }
  1110. other_start = 0;
  1111. other_end = start;
  1112. if (extent_mergeable(leaf, path->slots[0] - 1,
  1113. ino, bytenr, orig_offset,
  1114. &other_start, &other_end)) {
  1115. if (recow) {
  1116. btrfs_release_path(path);
  1117. goto again;
  1118. }
  1119. key.offset = other_start;
  1120. del_slot = path->slots[0];
  1121. del_nr++;
  1122. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1123. 0, root->root_key.objectid,
  1124. ino, orig_offset, 0);
  1125. BUG_ON(ret); /* -ENOMEM */
  1126. }
  1127. if (del_nr == 0) {
  1128. fi = btrfs_item_ptr(leaf, path->slots[0],
  1129. struct btrfs_file_extent_item);
  1130. btrfs_set_file_extent_type(leaf, fi,
  1131. BTRFS_FILE_EXTENT_REG);
  1132. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1133. btrfs_mark_buffer_dirty(leaf);
  1134. } else {
  1135. fi = btrfs_item_ptr(leaf, del_slot - 1,
  1136. struct btrfs_file_extent_item);
  1137. btrfs_set_file_extent_type(leaf, fi,
  1138. BTRFS_FILE_EXTENT_REG);
  1139. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1140. btrfs_set_file_extent_num_bytes(leaf, fi,
  1141. extent_end - key.offset);
  1142. btrfs_mark_buffer_dirty(leaf);
  1143. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  1144. if (ret < 0) {
  1145. btrfs_abort_transaction(trans, root, ret);
  1146. goto out;
  1147. }
  1148. }
  1149. out:
  1150. btrfs_free_path(path);
  1151. return 0;
  1152. }
  1153. /*
  1154. * on error we return an unlocked page and the error value
  1155. * on success we return a locked page and 0
  1156. */
  1157. static int prepare_uptodate_page(struct page *page, u64 pos,
  1158. bool force_uptodate)
  1159. {
  1160. int ret = 0;
  1161. if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
  1162. !PageUptodate(page)) {
  1163. ret = btrfs_readpage(NULL, page);
  1164. if (ret)
  1165. return ret;
  1166. lock_page(page);
  1167. if (!PageUptodate(page)) {
  1168. unlock_page(page);
  1169. return -EIO;
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. /*
  1175. * this just gets pages into the page cache and locks them down.
  1176. */
  1177. static noinline int prepare_pages(struct inode *inode, struct page **pages,
  1178. size_t num_pages, loff_t pos,
  1179. size_t write_bytes, bool force_uptodate)
  1180. {
  1181. int i;
  1182. unsigned long index = pos >> PAGE_CACHE_SHIFT;
  1183. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  1184. int err = 0;
  1185. int faili;
  1186. for (i = 0; i < num_pages; i++) {
  1187. pages[i] = find_or_create_page(inode->i_mapping, index + i,
  1188. mask | __GFP_WRITE);
  1189. if (!pages[i]) {
  1190. faili = i - 1;
  1191. err = -ENOMEM;
  1192. goto fail;
  1193. }
  1194. if (i == 0)
  1195. err = prepare_uptodate_page(pages[i], pos,
  1196. force_uptodate);
  1197. if (i == num_pages - 1)
  1198. err = prepare_uptodate_page(pages[i],
  1199. pos + write_bytes, false);
  1200. if (err) {
  1201. page_cache_release(pages[i]);
  1202. faili = i - 1;
  1203. goto fail;
  1204. }
  1205. wait_on_page_writeback(pages[i]);
  1206. }
  1207. return 0;
  1208. fail:
  1209. while (faili >= 0) {
  1210. unlock_page(pages[faili]);
  1211. page_cache_release(pages[faili]);
  1212. faili--;
  1213. }
  1214. return err;
  1215. }
  1216. /*
  1217. * This function locks the extent and properly waits for data=ordered extents
  1218. * to finish before allowing the pages to be modified if need.
  1219. *
  1220. * The return value:
  1221. * 1 - the extent is locked
  1222. * 0 - the extent is not locked, and everything is OK
  1223. * -EAGAIN - need re-prepare the pages
  1224. * the other < 0 number - Something wrong happens
  1225. */
  1226. static noinline int
  1227. lock_and_cleanup_extent_if_need(struct inode *inode, struct page **pages,
  1228. size_t num_pages, loff_t pos,
  1229. u64 *lockstart, u64 *lockend,
  1230. struct extent_state **cached_state)
  1231. {
  1232. u64 start_pos;
  1233. u64 last_pos;
  1234. int i;
  1235. int ret = 0;
  1236. start_pos = pos & ~((u64)PAGE_CACHE_SIZE - 1);
  1237. last_pos = start_pos + ((u64)num_pages << PAGE_CACHE_SHIFT) - 1;
  1238. if (start_pos < inode->i_size) {
  1239. struct btrfs_ordered_extent *ordered;
  1240. lock_extent_bits(&BTRFS_I(inode)->io_tree,
  1241. start_pos, last_pos, 0, cached_state);
  1242. ordered = btrfs_lookup_ordered_range(inode, start_pos,
  1243. last_pos - start_pos + 1);
  1244. if (ordered &&
  1245. ordered->file_offset + ordered->len > start_pos &&
  1246. ordered->file_offset <= last_pos) {
  1247. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1248. start_pos, last_pos,
  1249. cached_state, GFP_NOFS);
  1250. for (i = 0; i < num_pages; i++) {
  1251. unlock_page(pages[i]);
  1252. page_cache_release(pages[i]);
  1253. }
  1254. btrfs_start_ordered_extent(inode, ordered, 1);
  1255. btrfs_put_ordered_extent(ordered);
  1256. return -EAGAIN;
  1257. }
  1258. if (ordered)
  1259. btrfs_put_ordered_extent(ordered);
  1260. clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
  1261. last_pos, EXTENT_DIRTY | EXTENT_DELALLOC |
  1262. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  1263. 0, 0, cached_state, GFP_NOFS);
  1264. *lockstart = start_pos;
  1265. *lockend = last_pos;
  1266. ret = 1;
  1267. }
  1268. for (i = 0; i < num_pages; i++) {
  1269. if (clear_page_dirty_for_io(pages[i]))
  1270. account_page_redirty(pages[i]);
  1271. set_page_extent_mapped(pages[i]);
  1272. WARN_ON(!PageLocked(pages[i]));
  1273. }
  1274. return ret;
  1275. }
  1276. static noinline int check_can_nocow(struct inode *inode, loff_t pos,
  1277. size_t *write_bytes)
  1278. {
  1279. struct btrfs_root *root = BTRFS_I(inode)->root;
  1280. struct btrfs_ordered_extent *ordered;
  1281. u64 lockstart, lockend;
  1282. u64 num_bytes;
  1283. int ret;
  1284. ret = btrfs_start_nocow_write(root);
  1285. if (!ret)
  1286. return -ENOSPC;
  1287. lockstart = round_down(pos, root->sectorsize);
  1288. lockend = round_up(pos + *write_bytes, root->sectorsize) - 1;
  1289. while (1) {
  1290. lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1291. ordered = btrfs_lookup_ordered_range(inode, lockstart,
  1292. lockend - lockstart + 1);
  1293. if (!ordered) {
  1294. break;
  1295. }
  1296. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1297. btrfs_start_ordered_extent(inode, ordered, 1);
  1298. btrfs_put_ordered_extent(ordered);
  1299. }
  1300. num_bytes = lockend - lockstart + 1;
  1301. ret = can_nocow_extent(inode, lockstart, &num_bytes, NULL, NULL, NULL);
  1302. if (ret <= 0) {
  1303. ret = 0;
  1304. btrfs_end_nocow_write(root);
  1305. } else {
  1306. *write_bytes = min_t(size_t, *write_bytes ,
  1307. num_bytes - pos + lockstart);
  1308. }
  1309. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1310. return ret;
  1311. }
  1312. static noinline ssize_t __btrfs_buffered_write(struct file *file,
  1313. struct iov_iter *i,
  1314. loff_t pos)
  1315. {
  1316. struct inode *inode = file_inode(file);
  1317. struct btrfs_root *root = BTRFS_I(inode)->root;
  1318. struct page **pages = NULL;
  1319. struct extent_state *cached_state = NULL;
  1320. u64 release_bytes = 0;
  1321. u64 lockstart;
  1322. u64 lockend;
  1323. unsigned long first_index;
  1324. size_t num_written = 0;
  1325. int nrptrs;
  1326. int ret = 0;
  1327. bool only_release_metadata = false;
  1328. bool force_page_uptodate = false;
  1329. bool need_unlock;
  1330. nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_CACHE_SIZE),
  1331. PAGE_CACHE_SIZE / (sizeof(struct page *)));
  1332. nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
  1333. nrptrs = max(nrptrs, 8);
  1334. pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
  1335. if (!pages)
  1336. return -ENOMEM;
  1337. first_index = pos >> PAGE_CACHE_SHIFT;
  1338. while (iov_iter_count(i) > 0) {
  1339. size_t offset = pos & (PAGE_CACHE_SIZE - 1);
  1340. size_t write_bytes = min(iov_iter_count(i),
  1341. nrptrs * (size_t)PAGE_CACHE_SIZE -
  1342. offset);
  1343. size_t num_pages = DIV_ROUND_UP(write_bytes + offset,
  1344. PAGE_CACHE_SIZE);
  1345. size_t reserve_bytes;
  1346. size_t dirty_pages;
  1347. size_t copied;
  1348. WARN_ON(num_pages > nrptrs);
  1349. /*
  1350. * Fault pages before locking them in prepare_pages
  1351. * to avoid recursive lock
  1352. */
  1353. if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
  1354. ret = -EFAULT;
  1355. break;
  1356. }
  1357. reserve_bytes = num_pages << PAGE_CACHE_SHIFT;
  1358. ret = btrfs_check_data_free_space(inode, reserve_bytes);
  1359. if (ret == -ENOSPC &&
  1360. (BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
  1361. BTRFS_INODE_PREALLOC))) {
  1362. ret = check_can_nocow(inode, pos, &write_bytes);
  1363. if (ret > 0) {
  1364. only_release_metadata = true;
  1365. /*
  1366. * our prealloc extent may be smaller than
  1367. * write_bytes, so scale down.
  1368. */
  1369. num_pages = DIV_ROUND_UP(write_bytes + offset,
  1370. PAGE_CACHE_SIZE);
  1371. reserve_bytes = num_pages << PAGE_CACHE_SHIFT;
  1372. ret = 0;
  1373. } else {
  1374. ret = -ENOSPC;
  1375. }
  1376. }
  1377. if (ret)
  1378. break;
  1379. ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes);
  1380. if (ret) {
  1381. if (!only_release_metadata)
  1382. btrfs_free_reserved_data_space(inode,
  1383. reserve_bytes);
  1384. else
  1385. btrfs_end_nocow_write(root);
  1386. break;
  1387. }
  1388. release_bytes = reserve_bytes;
  1389. need_unlock = false;
  1390. again:
  1391. /*
  1392. * This is going to setup the pages array with the number of
  1393. * pages we want, so we don't really need to worry about the
  1394. * contents of pages from loop to loop
  1395. */
  1396. ret = prepare_pages(inode, pages, num_pages,
  1397. pos, write_bytes,
  1398. force_page_uptodate);
  1399. if (ret)
  1400. break;
  1401. ret = lock_and_cleanup_extent_if_need(inode, pages, num_pages,
  1402. pos, &lockstart, &lockend,
  1403. &cached_state);
  1404. if (ret < 0) {
  1405. if (ret == -EAGAIN)
  1406. goto again;
  1407. break;
  1408. } else if (ret > 0) {
  1409. need_unlock = true;
  1410. ret = 0;
  1411. }
  1412. copied = btrfs_copy_from_user(pos, num_pages,
  1413. write_bytes, pages, i);
  1414. /*
  1415. * if we have trouble faulting in the pages, fall
  1416. * back to one page at a time
  1417. */
  1418. if (copied < write_bytes)
  1419. nrptrs = 1;
  1420. if (copied == 0) {
  1421. force_page_uptodate = true;
  1422. dirty_pages = 0;
  1423. } else {
  1424. force_page_uptodate = false;
  1425. dirty_pages = DIV_ROUND_UP(copied + offset,
  1426. PAGE_CACHE_SIZE);
  1427. }
  1428. /*
  1429. * If we had a short copy we need to release the excess delaloc
  1430. * bytes we reserved. We need to increment outstanding_extents
  1431. * because btrfs_delalloc_release_space will decrement it, but
  1432. * we still have an outstanding extent for the chunk we actually
  1433. * managed to copy.
  1434. */
  1435. if (num_pages > dirty_pages) {
  1436. release_bytes = (num_pages - dirty_pages) <<
  1437. PAGE_CACHE_SHIFT;
  1438. if (copied > 0) {
  1439. spin_lock(&BTRFS_I(inode)->lock);
  1440. BTRFS_I(inode)->outstanding_extents++;
  1441. spin_unlock(&BTRFS_I(inode)->lock);
  1442. }
  1443. if (only_release_metadata)
  1444. btrfs_delalloc_release_metadata(inode,
  1445. release_bytes);
  1446. else
  1447. btrfs_delalloc_release_space(inode,
  1448. release_bytes);
  1449. }
  1450. release_bytes = dirty_pages << PAGE_CACHE_SHIFT;
  1451. if (copied > 0)
  1452. ret = btrfs_dirty_pages(root, inode, pages,
  1453. dirty_pages, pos, copied,
  1454. NULL);
  1455. if (need_unlock)
  1456. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1457. lockstart, lockend, &cached_state,
  1458. GFP_NOFS);
  1459. if (ret) {
  1460. btrfs_drop_pages(pages, num_pages);
  1461. break;
  1462. }
  1463. release_bytes = 0;
  1464. if (only_release_metadata)
  1465. btrfs_end_nocow_write(root);
  1466. if (only_release_metadata && copied > 0) {
  1467. u64 lockstart = round_down(pos, root->sectorsize);
  1468. u64 lockend = lockstart +
  1469. (dirty_pages << PAGE_CACHE_SHIFT) - 1;
  1470. set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  1471. lockend, EXTENT_NORESERVE, NULL,
  1472. NULL, GFP_NOFS);
  1473. only_release_metadata = false;
  1474. }
  1475. btrfs_drop_pages(pages, num_pages);
  1476. cond_resched();
  1477. balance_dirty_pages_ratelimited(inode->i_mapping);
  1478. if (dirty_pages < (root->nodesize >> PAGE_CACHE_SHIFT) + 1)
  1479. btrfs_btree_balance_dirty(root);
  1480. pos += copied;
  1481. num_written += copied;
  1482. }
  1483. kfree(pages);
  1484. if (release_bytes) {
  1485. if (only_release_metadata) {
  1486. btrfs_end_nocow_write(root);
  1487. btrfs_delalloc_release_metadata(inode, release_bytes);
  1488. } else {
  1489. btrfs_delalloc_release_space(inode, release_bytes);
  1490. }
  1491. }
  1492. return num_written ? num_written : ret;
  1493. }
  1494. static ssize_t __btrfs_direct_write(struct kiocb *iocb,
  1495. struct iov_iter *from,
  1496. loff_t pos)
  1497. {
  1498. struct file *file = iocb->ki_filp;
  1499. ssize_t written;
  1500. ssize_t written_buffered;
  1501. loff_t endbyte;
  1502. int err;
  1503. written = generic_file_direct_write(iocb, from, pos);
  1504. if (written < 0 || !iov_iter_count(from))
  1505. return written;
  1506. pos += written;
  1507. written_buffered = __btrfs_buffered_write(file, from, pos);
  1508. if (written_buffered < 0) {
  1509. err = written_buffered;
  1510. goto out;
  1511. }
  1512. endbyte = pos + written_buffered - 1;
  1513. err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
  1514. if (err)
  1515. goto out;
  1516. written += written_buffered;
  1517. iocb->ki_pos = pos + written_buffered;
  1518. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
  1519. endbyte >> PAGE_CACHE_SHIFT);
  1520. out:
  1521. return written ? written : err;
  1522. }
  1523. static void update_time_for_write(struct inode *inode)
  1524. {
  1525. struct timespec now;
  1526. if (IS_NOCMTIME(inode))
  1527. return;
  1528. now = current_fs_time(inode->i_sb);
  1529. if (!timespec_equal(&inode->i_mtime, &now))
  1530. inode->i_mtime = now;
  1531. if (!timespec_equal(&inode->i_ctime, &now))
  1532. inode->i_ctime = now;
  1533. if (IS_I_VERSION(inode))
  1534. inode_inc_iversion(inode);
  1535. }
  1536. static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
  1537. struct iov_iter *from)
  1538. {
  1539. struct file *file = iocb->ki_filp;
  1540. struct inode *inode = file_inode(file);
  1541. struct btrfs_root *root = BTRFS_I(inode)->root;
  1542. u64 start_pos;
  1543. u64 end_pos;
  1544. ssize_t num_written = 0;
  1545. ssize_t err = 0;
  1546. size_t count = iov_iter_count(from);
  1547. bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
  1548. loff_t pos = iocb->ki_pos;
  1549. mutex_lock(&inode->i_mutex);
  1550. current->backing_dev_info = inode->i_mapping->backing_dev_info;
  1551. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  1552. if (err) {
  1553. mutex_unlock(&inode->i_mutex);
  1554. goto out;
  1555. }
  1556. if (count == 0) {
  1557. mutex_unlock(&inode->i_mutex);
  1558. goto out;
  1559. }
  1560. iov_iter_truncate(from, count);
  1561. err = file_remove_suid(file);
  1562. if (err) {
  1563. mutex_unlock(&inode->i_mutex);
  1564. goto out;
  1565. }
  1566. /*
  1567. * If BTRFS flips readonly due to some impossible error
  1568. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1569. * although we have opened a file as writable, we have
  1570. * to stop this write operation to ensure FS consistency.
  1571. */
  1572. if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
  1573. mutex_unlock(&inode->i_mutex);
  1574. err = -EROFS;
  1575. goto out;
  1576. }
  1577. /*
  1578. * We reserve space for updating the inode when we reserve space for the
  1579. * extent we are going to write, so we will enospc out there. We don't
  1580. * need to start yet another transaction to update the inode as we will
  1581. * update the inode when we finish writing whatever data we write.
  1582. */
  1583. update_time_for_write(inode);
  1584. start_pos = round_down(pos, root->sectorsize);
  1585. if (start_pos > i_size_read(inode)) {
  1586. /* Expand hole size to cover write data, preventing empty gap */
  1587. end_pos = round_up(pos + count, root->sectorsize);
  1588. err = btrfs_cont_expand(inode, i_size_read(inode), end_pos);
  1589. if (err) {
  1590. mutex_unlock(&inode->i_mutex);
  1591. goto out;
  1592. }
  1593. }
  1594. if (sync)
  1595. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1596. if (file->f_flags & O_DIRECT) {
  1597. num_written = __btrfs_direct_write(iocb, from, pos);
  1598. } else {
  1599. num_written = __btrfs_buffered_write(file, from, pos);
  1600. if (num_written > 0)
  1601. iocb->ki_pos = pos + num_written;
  1602. }
  1603. mutex_unlock(&inode->i_mutex);
  1604. /*
  1605. * we want to make sure fsync finds this change
  1606. * but we haven't joined a transaction running right now.
  1607. *
  1608. * Later on, someone is sure to update the inode and get the
  1609. * real transid recorded.
  1610. *
  1611. * We set last_trans now to the fs_info generation + 1,
  1612. * this will either be one more than the running transaction
  1613. * or the generation used for the next transaction if there isn't
  1614. * one running right now.
  1615. *
  1616. * We also have to set last_sub_trans to the current log transid,
  1617. * otherwise subsequent syncs to a file that's been synced in this
  1618. * transaction will appear to have already occured.
  1619. */
  1620. BTRFS_I(inode)->last_trans = root->fs_info->generation + 1;
  1621. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1622. if (num_written > 0) {
  1623. err = generic_write_sync(file, pos, num_written);
  1624. if (err < 0)
  1625. num_written = err;
  1626. }
  1627. if (sync)
  1628. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1629. out:
  1630. current->backing_dev_info = NULL;
  1631. return num_written ? num_written : err;
  1632. }
  1633. int btrfs_release_file(struct inode *inode, struct file *filp)
  1634. {
  1635. if (filp->private_data)
  1636. btrfs_ioctl_trans_end(filp);
  1637. /*
  1638. * ordered_data_close is set by settattr when we are about to truncate
  1639. * a file from a non-zero size to a zero size. This tries to
  1640. * flush down new bytes that may have been written if the
  1641. * application were using truncate to replace a file in place.
  1642. */
  1643. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1644. &BTRFS_I(inode)->runtime_flags))
  1645. filemap_flush(inode->i_mapping);
  1646. return 0;
  1647. }
  1648. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1649. {
  1650. int ret;
  1651. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1652. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  1653. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  1654. &BTRFS_I(inode)->runtime_flags))
  1655. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  1656. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1657. return ret;
  1658. }
  1659. /*
  1660. * fsync call for both files and directories. This logs the inode into
  1661. * the tree log instead of forcing full commits whenever possible.
  1662. *
  1663. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1664. * in the metadata btree are up to date for copying to the log.
  1665. *
  1666. * It drops the inode mutex before doing the tree log commit. This is an
  1667. * important optimization for directories because holding the mutex prevents
  1668. * new operations on the dir while we write to disk.
  1669. */
  1670. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1671. {
  1672. struct dentry *dentry = file->f_path.dentry;
  1673. struct inode *inode = dentry->d_inode;
  1674. struct btrfs_root *root = BTRFS_I(inode)->root;
  1675. struct btrfs_trans_handle *trans;
  1676. struct btrfs_log_ctx ctx;
  1677. int ret = 0;
  1678. bool full_sync = 0;
  1679. trace_btrfs_sync_file(file, datasync);
  1680. /*
  1681. * We write the dirty pages in the range and wait until they complete
  1682. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1683. * multi-task, and make the performance up. See
  1684. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1685. */
  1686. ret = start_ordered_ops(inode, start, end);
  1687. if (ret)
  1688. return ret;
  1689. mutex_lock(&inode->i_mutex);
  1690. atomic_inc(&root->log_batch);
  1691. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1692. &BTRFS_I(inode)->runtime_flags);
  1693. /*
  1694. * We might have have had more pages made dirty after calling
  1695. * start_ordered_ops and before acquiring the inode's i_mutex.
  1696. */
  1697. if (full_sync) {
  1698. /*
  1699. * For a full sync, we need to make sure any ordered operations
  1700. * start and finish before we start logging the inode, so that
  1701. * all extents are persisted and the respective file extent
  1702. * items are in the fs/subvol btree.
  1703. */
  1704. ret = btrfs_wait_ordered_range(inode, start, end - start + 1);
  1705. } else {
  1706. /*
  1707. * Start any new ordered operations before starting to log the
  1708. * inode. We will wait for them to finish in btrfs_sync_log().
  1709. *
  1710. * Right before acquiring the inode's mutex, we might have new
  1711. * writes dirtying pages, which won't immediately start the
  1712. * respective ordered operations - that is done through the
  1713. * fill_delalloc callbacks invoked from the writepage and
  1714. * writepages address space operations. So make sure we start
  1715. * all ordered operations before starting to log our inode. Not
  1716. * doing this means that while logging the inode, writeback
  1717. * could start and invoke writepage/writepages, which would call
  1718. * the fill_delalloc callbacks (cow_file_range,
  1719. * submit_compressed_extents). These callbacks add first an
  1720. * extent map to the modified list of extents and then create
  1721. * the respective ordered operation, which means in
  1722. * tree-log.c:btrfs_log_inode() we might capture all existing
  1723. * ordered operations (with btrfs_get_logged_extents()) before
  1724. * the fill_delalloc callback adds its ordered operation, and by
  1725. * the time we visit the modified list of extent maps (with
  1726. * btrfs_log_changed_extents()), we see and process the extent
  1727. * map they created. We then use the extent map to construct a
  1728. * file extent item for logging without waiting for the
  1729. * respective ordered operation to finish - this file extent
  1730. * item points to a disk location that might not have yet been
  1731. * written to, containing random data - so after a crash a log
  1732. * replay will make our inode have file extent items that point
  1733. * to disk locations containing invalid data, as we returned
  1734. * success to userspace without waiting for the respective
  1735. * ordered operation to finish, because it wasn't captured by
  1736. * btrfs_get_logged_extents().
  1737. */
  1738. ret = start_ordered_ops(inode, start, end);
  1739. }
  1740. if (ret) {
  1741. mutex_unlock(&inode->i_mutex);
  1742. goto out;
  1743. }
  1744. atomic_inc(&root->log_batch);
  1745. /*
  1746. * check the transaction that last modified this inode
  1747. * and see if its already been committed
  1748. */
  1749. if (!BTRFS_I(inode)->last_trans) {
  1750. mutex_unlock(&inode->i_mutex);
  1751. goto out;
  1752. }
  1753. /*
  1754. * if the last transaction that changed this file was before
  1755. * the current transaction, we can bail out now without any
  1756. * syncing
  1757. */
  1758. smp_mb();
  1759. if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
  1760. BTRFS_I(inode)->last_trans <=
  1761. root->fs_info->last_trans_committed) {
  1762. BTRFS_I(inode)->last_trans = 0;
  1763. /*
  1764. * We'v had everything committed since the last time we were
  1765. * modified so clear this flag in case it was set for whatever
  1766. * reason, it's no longer relevant.
  1767. */
  1768. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1769. &BTRFS_I(inode)->runtime_flags);
  1770. mutex_unlock(&inode->i_mutex);
  1771. goto out;
  1772. }
  1773. /*
  1774. * ok we haven't committed the transaction yet, lets do a commit
  1775. */
  1776. if (file->private_data)
  1777. btrfs_ioctl_trans_end(file);
  1778. /*
  1779. * We use start here because we will need to wait on the IO to complete
  1780. * in btrfs_sync_log, which could require joining a transaction (for
  1781. * example checking cross references in the nocow path). If we use join
  1782. * here we could get into a situation where we're waiting on IO to
  1783. * happen that is blocked on a transaction trying to commit. With start
  1784. * we inc the extwriter counter, so we wait for all extwriters to exit
  1785. * before we start blocking join'ers. This comment is to keep somebody
  1786. * from thinking they are super smart and changing this to
  1787. * btrfs_join_transaction *cough*Josef*cough*.
  1788. */
  1789. trans = btrfs_start_transaction(root, 0);
  1790. if (IS_ERR(trans)) {
  1791. ret = PTR_ERR(trans);
  1792. mutex_unlock(&inode->i_mutex);
  1793. goto out;
  1794. }
  1795. trans->sync = true;
  1796. btrfs_init_log_ctx(&ctx);
  1797. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1798. if (ret < 0) {
  1799. /* Fallthrough and commit/free transaction. */
  1800. ret = 1;
  1801. }
  1802. /* we've logged all the items and now have a consistent
  1803. * version of the file in the log. It is possible that
  1804. * someone will come in and modify the file, but that's
  1805. * fine because the log is consistent on disk, and we
  1806. * have references to all of the file's extents
  1807. *
  1808. * It is possible that someone will come in and log the
  1809. * file again, but that will end up using the synchronization
  1810. * inside btrfs_sync_log to keep things safe.
  1811. */
  1812. mutex_unlock(&inode->i_mutex);
  1813. /*
  1814. * If any of the ordered extents had an error, just return it to user
  1815. * space, so that the application knows some writes didn't succeed and
  1816. * can take proper action (retry for e.g.). Blindly committing the
  1817. * transaction in this case, would fool userspace that everything was
  1818. * successful. And we also want to make sure our log doesn't contain
  1819. * file extent items pointing to extents that weren't fully written to -
  1820. * just like in the non fast fsync path, where we check for the ordered
  1821. * operation's error flag before writing to the log tree and return -EIO
  1822. * if any of them had this flag set (btrfs_wait_ordered_range) -
  1823. * therefore we need to check for errors in the ordered operations,
  1824. * which are indicated by ctx.io_err.
  1825. */
  1826. if (ctx.io_err) {
  1827. btrfs_end_transaction(trans, root);
  1828. ret = ctx.io_err;
  1829. goto out;
  1830. }
  1831. if (ret != BTRFS_NO_LOG_SYNC) {
  1832. if (!ret) {
  1833. ret = btrfs_sync_log(trans, root, &ctx);
  1834. if (!ret) {
  1835. ret = btrfs_end_transaction(trans, root);
  1836. goto out;
  1837. }
  1838. }
  1839. if (!full_sync) {
  1840. ret = btrfs_wait_ordered_range(inode, start,
  1841. end - start + 1);
  1842. if (ret) {
  1843. btrfs_end_transaction(trans, root);
  1844. goto out;
  1845. }
  1846. }
  1847. ret = btrfs_commit_transaction(trans, root);
  1848. } else {
  1849. ret = btrfs_end_transaction(trans, root);
  1850. }
  1851. out:
  1852. return ret > 0 ? -EIO : ret;
  1853. }
  1854. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1855. .fault = filemap_fault,
  1856. .map_pages = filemap_map_pages,
  1857. .page_mkwrite = btrfs_page_mkwrite,
  1858. .remap_pages = generic_file_remap_pages,
  1859. };
  1860. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1861. {
  1862. struct address_space *mapping = filp->f_mapping;
  1863. if (!mapping->a_ops->readpage)
  1864. return -ENOEXEC;
  1865. file_accessed(filp);
  1866. vma->vm_ops = &btrfs_file_vm_ops;
  1867. return 0;
  1868. }
  1869. static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
  1870. int slot, u64 start, u64 end)
  1871. {
  1872. struct btrfs_file_extent_item *fi;
  1873. struct btrfs_key key;
  1874. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1875. return 0;
  1876. btrfs_item_key_to_cpu(leaf, &key, slot);
  1877. if (key.objectid != btrfs_ino(inode) ||
  1878. key.type != BTRFS_EXTENT_DATA_KEY)
  1879. return 0;
  1880. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1881. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1882. return 0;
  1883. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1884. return 0;
  1885. if (key.offset == end)
  1886. return 1;
  1887. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1888. return 1;
  1889. return 0;
  1890. }
  1891. static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
  1892. struct btrfs_path *path, u64 offset, u64 end)
  1893. {
  1894. struct btrfs_root *root = BTRFS_I(inode)->root;
  1895. struct extent_buffer *leaf;
  1896. struct btrfs_file_extent_item *fi;
  1897. struct extent_map *hole_em;
  1898. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  1899. struct btrfs_key key;
  1900. int ret;
  1901. if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
  1902. goto out;
  1903. key.objectid = btrfs_ino(inode);
  1904. key.type = BTRFS_EXTENT_DATA_KEY;
  1905. key.offset = offset;
  1906. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1907. if (ret < 0)
  1908. return ret;
  1909. BUG_ON(!ret);
  1910. leaf = path->nodes[0];
  1911. if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
  1912. u64 num_bytes;
  1913. path->slots[0]--;
  1914. fi = btrfs_item_ptr(leaf, path->slots[0],
  1915. struct btrfs_file_extent_item);
  1916. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1917. end - offset;
  1918. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1919. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1920. btrfs_set_file_extent_offset(leaf, fi, 0);
  1921. btrfs_mark_buffer_dirty(leaf);
  1922. goto out;
  1923. }
  1924. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1925. u64 num_bytes;
  1926. key.offset = offset;
  1927. btrfs_set_item_key_safe(root, path, &key);
  1928. fi = btrfs_item_ptr(leaf, path->slots[0],
  1929. struct btrfs_file_extent_item);
  1930. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1931. offset;
  1932. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1933. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1934. btrfs_set_file_extent_offset(leaf, fi, 0);
  1935. btrfs_mark_buffer_dirty(leaf);
  1936. goto out;
  1937. }
  1938. btrfs_release_path(path);
  1939. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
  1940. 0, 0, end - offset, 0, end - offset,
  1941. 0, 0, 0);
  1942. if (ret)
  1943. return ret;
  1944. out:
  1945. btrfs_release_path(path);
  1946. hole_em = alloc_extent_map();
  1947. if (!hole_em) {
  1948. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  1949. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1950. &BTRFS_I(inode)->runtime_flags);
  1951. } else {
  1952. hole_em->start = offset;
  1953. hole_em->len = end - offset;
  1954. hole_em->ram_bytes = hole_em->len;
  1955. hole_em->orig_start = offset;
  1956. hole_em->block_start = EXTENT_MAP_HOLE;
  1957. hole_em->block_len = 0;
  1958. hole_em->orig_block_len = 0;
  1959. hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
  1960. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  1961. hole_em->generation = trans->transid;
  1962. do {
  1963. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  1964. write_lock(&em_tree->lock);
  1965. ret = add_extent_mapping(em_tree, hole_em, 1);
  1966. write_unlock(&em_tree->lock);
  1967. } while (ret == -EEXIST);
  1968. free_extent_map(hole_em);
  1969. if (ret)
  1970. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1971. &BTRFS_I(inode)->runtime_flags);
  1972. }
  1973. return 0;
  1974. }
  1975. /*
  1976. * Find a hole extent on given inode and change start/len to the end of hole
  1977. * extent.(hole/vacuum extent whose em->start <= start &&
  1978. * em->start + em->len > start)
  1979. * When a hole extent is found, return 1 and modify start/len.
  1980. */
  1981. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  1982. {
  1983. struct extent_map *em;
  1984. int ret = 0;
  1985. em = btrfs_get_extent(inode, NULL, 0, *start, *len, 0);
  1986. if (IS_ERR_OR_NULL(em)) {
  1987. if (!em)
  1988. ret = -ENOMEM;
  1989. else
  1990. ret = PTR_ERR(em);
  1991. return ret;
  1992. }
  1993. /* Hole or vacuum extent(only exists in no-hole mode) */
  1994. if (em->block_start == EXTENT_MAP_HOLE) {
  1995. ret = 1;
  1996. *len = em->start + em->len > *start + *len ?
  1997. 0 : *start + *len - em->start - em->len;
  1998. *start = em->start + em->len;
  1999. }
  2000. free_extent_map(em);
  2001. return ret;
  2002. }
  2003. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2004. {
  2005. struct btrfs_root *root = BTRFS_I(inode)->root;
  2006. struct extent_state *cached_state = NULL;
  2007. struct btrfs_path *path;
  2008. struct btrfs_block_rsv *rsv;
  2009. struct btrfs_trans_handle *trans;
  2010. u64 lockstart;
  2011. u64 lockend;
  2012. u64 tail_start;
  2013. u64 tail_len;
  2014. u64 orig_start = offset;
  2015. u64 cur_offset;
  2016. u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
  2017. u64 drop_end;
  2018. int ret = 0;
  2019. int err = 0;
  2020. int rsv_count;
  2021. bool same_page;
  2022. bool no_holes = btrfs_fs_incompat(root->fs_info, NO_HOLES);
  2023. u64 ino_size;
  2024. ret = btrfs_wait_ordered_range(inode, offset, len);
  2025. if (ret)
  2026. return ret;
  2027. mutex_lock(&inode->i_mutex);
  2028. ino_size = round_up(inode->i_size, PAGE_CACHE_SIZE);
  2029. ret = find_first_non_hole(inode, &offset, &len);
  2030. if (ret < 0)
  2031. goto out_only_mutex;
  2032. if (ret && !len) {
  2033. /* Already in a large hole */
  2034. ret = 0;
  2035. goto out_only_mutex;
  2036. }
  2037. lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
  2038. lockend = round_down(offset + len,
  2039. BTRFS_I(inode)->root->sectorsize) - 1;
  2040. same_page = ((offset >> PAGE_CACHE_SHIFT) ==
  2041. ((offset + len - 1) >> PAGE_CACHE_SHIFT));
  2042. /*
  2043. * We needn't truncate any page which is beyond the end of the file
  2044. * because we are sure there is no data there.
  2045. */
  2046. /*
  2047. * Only do this if we are in the same page and we aren't doing the
  2048. * entire page.
  2049. */
  2050. if (same_page && len < PAGE_CACHE_SIZE) {
  2051. if (offset < ino_size)
  2052. ret = btrfs_truncate_page(inode, offset, len, 0);
  2053. goto out_only_mutex;
  2054. }
  2055. /* zero back part of the first page */
  2056. if (offset < ino_size) {
  2057. ret = btrfs_truncate_page(inode, offset, 0, 0);
  2058. if (ret) {
  2059. mutex_unlock(&inode->i_mutex);
  2060. return ret;
  2061. }
  2062. }
  2063. /* Check the aligned pages after the first unaligned page,
  2064. * if offset != orig_start, which means the first unaligned page
  2065. * including serveral following pages are already in holes,
  2066. * the extra check can be skipped */
  2067. if (offset == orig_start) {
  2068. /* after truncate page, check hole again */
  2069. len = offset + len - lockstart;
  2070. offset = lockstart;
  2071. ret = find_first_non_hole(inode, &offset, &len);
  2072. if (ret < 0)
  2073. goto out_only_mutex;
  2074. if (ret && !len) {
  2075. ret = 0;
  2076. goto out_only_mutex;
  2077. }
  2078. lockstart = offset;
  2079. }
  2080. /* Check the tail unaligned part is in a hole */
  2081. tail_start = lockend + 1;
  2082. tail_len = offset + len - tail_start;
  2083. if (tail_len) {
  2084. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2085. if (unlikely(ret < 0))
  2086. goto out_only_mutex;
  2087. if (!ret) {
  2088. /* zero the front end of the last page */
  2089. if (tail_start + tail_len < ino_size) {
  2090. ret = btrfs_truncate_page(inode,
  2091. tail_start + tail_len, 0, 1);
  2092. if (ret)
  2093. goto out_only_mutex;
  2094. }
  2095. }
  2096. }
  2097. if (lockend < lockstart) {
  2098. mutex_unlock(&inode->i_mutex);
  2099. return 0;
  2100. }
  2101. while (1) {
  2102. struct btrfs_ordered_extent *ordered;
  2103. truncate_pagecache_range(inode, lockstart, lockend);
  2104. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2105. 0, &cached_state);
  2106. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2107. /*
  2108. * We need to make sure we have no ordered extents in this range
  2109. * and nobody raced in and read a page in this range, if we did
  2110. * we need to try again.
  2111. */
  2112. if ((!ordered ||
  2113. (ordered->file_offset + ordered->len <= lockstart ||
  2114. ordered->file_offset > lockend)) &&
  2115. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2116. if (ordered)
  2117. btrfs_put_ordered_extent(ordered);
  2118. break;
  2119. }
  2120. if (ordered)
  2121. btrfs_put_ordered_extent(ordered);
  2122. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2123. lockend, &cached_state, GFP_NOFS);
  2124. ret = btrfs_wait_ordered_range(inode, lockstart,
  2125. lockend - lockstart + 1);
  2126. if (ret) {
  2127. mutex_unlock(&inode->i_mutex);
  2128. return ret;
  2129. }
  2130. }
  2131. path = btrfs_alloc_path();
  2132. if (!path) {
  2133. ret = -ENOMEM;
  2134. goto out;
  2135. }
  2136. rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
  2137. if (!rsv) {
  2138. ret = -ENOMEM;
  2139. goto out_free;
  2140. }
  2141. rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
  2142. rsv->failfast = 1;
  2143. /*
  2144. * 1 - update the inode
  2145. * 1 - removing the extents in the range
  2146. * 1 - adding the hole extent if no_holes isn't set
  2147. */
  2148. rsv_count = no_holes ? 2 : 3;
  2149. trans = btrfs_start_transaction(root, rsv_count);
  2150. if (IS_ERR(trans)) {
  2151. err = PTR_ERR(trans);
  2152. goto out_free;
  2153. }
  2154. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
  2155. min_size);
  2156. BUG_ON(ret);
  2157. trans->block_rsv = rsv;
  2158. cur_offset = lockstart;
  2159. len = lockend - cur_offset;
  2160. while (cur_offset < lockend) {
  2161. ret = __btrfs_drop_extents(trans, root, inode, path,
  2162. cur_offset, lockend + 1,
  2163. &drop_end, 1, 0, 0, NULL);
  2164. if (ret != -ENOSPC)
  2165. break;
  2166. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2167. if (cur_offset < ino_size) {
  2168. ret = fill_holes(trans, inode, path, cur_offset,
  2169. drop_end);
  2170. if (ret) {
  2171. err = ret;
  2172. break;
  2173. }
  2174. }
  2175. cur_offset = drop_end;
  2176. ret = btrfs_update_inode(trans, root, inode);
  2177. if (ret) {
  2178. err = ret;
  2179. break;
  2180. }
  2181. btrfs_end_transaction(trans, root);
  2182. btrfs_btree_balance_dirty(root);
  2183. trans = btrfs_start_transaction(root, rsv_count);
  2184. if (IS_ERR(trans)) {
  2185. ret = PTR_ERR(trans);
  2186. trans = NULL;
  2187. break;
  2188. }
  2189. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
  2190. rsv, min_size);
  2191. BUG_ON(ret); /* shouldn't happen */
  2192. trans->block_rsv = rsv;
  2193. ret = find_first_non_hole(inode, &cur_offset, &len);
  2194. if (unlikely(ret < 0))
  2195. break;
  2196. if (ret && !len) {
  2197. ret = 0;
  2198. break;
  2199. }
  2200. }
  2201. if (ret) {
  2202. err = ret;
  2203. goto out_trans;
  2204. }
  2205. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2206. /*
  2207. * Don't insert file hole extent item if it's for a range beyond eof
  2208. * (because it's useless) or if it represents a 0 bytes range (when
  2209. * cur_offset == drop_end).
  2210. */
  2211. if (cur_offset < ino_size && cur_offset < drop_end) {
  2212. ret = fill_holes(trans, inode, path, cur_offset, drop_end);
  2213. if (ret) {
  2214. err = ret;
  2215. goto out_trans;
  2216. }
  2217. }
  2218. out_trans:
  2219. if (!trans)
  2220. goto out_free;
  2221. inode_inc_iversion(inode);
  2222. inode->i_mtime = inode->i_ctime = CURRENT_TIME;
  2223. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2224. ret = btrfs_update_inode(trans, root, inode);
  2225. btrfs_end_transaction(trans, root);
  2226. btrfs_btree_balance_dirty(root);
  2227. out_free:
  2228. btrfs_free_path(path);
  2229. btrfs_free_block_rsv(root, rsv);
  2230. out:
  2231. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2232. &cached_state, GFP_NOFS);
  2233. out_only_mutex:
  2234. mutex_unlock(&inode->i_mutex);
  2235. if (ret && !err)
  2236. err = ret;
  2237. return err;
  2238. }
  2239. static long btrfs_fallocate(struct file *file, int mode,
  2240. loff_t offset, loff_t len)
  2241. {
  2242. struct inode *inode = file_inode(file);
  2243. struct extent_state *cached_state = NULL;
  2244. struct btrfs_root *root = BTRFS_I(inode)->root;
  2245. u64 cur_offset;
  2246. u64 last_byte;
  2247. u64 alloc_start;
  2248. u64 alloc_end;
  2249. u64 alloc_hint = 0;
  2250. u64 locked_end;
  2251. struct extent_map *em;
  2252. int blocksize = BTRFS_I(inode)->root->sectorsize;
  2253. int ret;
  2254. alloc_start = round_down(offset, blocksize);
  2255. alloc_end = round_up(offset + len, blocksize);
  2256. /* Make sure we aren't being give some crap mode */
  2257. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2258. return -EOPNOTSUPP;
  2259. if (mode & FALLOC_FL_PUNCH_HOLE)
  2260. return btrfs_punch_hole(inode, offset, len);
  2261. /*
  2262. * Make sure we have enough space before we do the
  2263. * allocation.
  2264. */
  2265. ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
  2266. if (ret)
  2267. return ret;
  2268. if (root->fs_info->quota_enabled) {
  2269. ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
  2270. if (ret)
  2271. goto out_reserve_fail;
  2272. }
  2273. mutex_lock(&inode->i_mutex);
  2274. ret = inode_newsize_ok(inode, alloc_end);
  2275. if (ret)
  2276. goto out;
  2277. if (alloc_start > inode->i_size) {
  2278. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2279. alloc_start);
  2280. if (ret)
  2281. goto out;
  2282. } else {
  2283. /*
  2284. * If we are fallocating from the end of the file onward we
  2285. * need to zero out the end of the page if i_size lands in the
  2286. * middle of a page.
  2287. */
  2288. ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
  2289. if (ret)
  2290. goto out;
  2291. }
  2292. /*
  2293. * wait for ordered IO before we have any locks. We'll loop again
  2294. * below with the locks held.
  2295. */
  2296. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2297. alloc_end - alloc_start);
  2298. if (ret)
  2299. goto out;
  2300. locked_end = alloc_end - 1;
  2301. while (1) {
  2302. struct btrfs_ordered_extent *ordered;
  2303. /* the extent lock is ordered inside the running
  2304. * transaction
  2305. */
  2306. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2307. locked_end, 0, &cached_state);
  2308. ordered = btrfs_lookup_first_ordered_extent(inode,
  2309. alloc_end - 1);
  2310. if (ordered &&
  2311. ordered->file_offset + ordered->len > alloc_start &&
  2312. ordered->file_offset < alloc_end) {
  2313. btrfs_put_ordered_extent(ordered);
  2314. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2315. alloc_start, locked_end,
  2316. &cached_state, GFP_NOFS);
  2317. /*
  2318. * we can't wait on the range with the transaction
  2319. * running or with the extent lock held
  2320. */
  2321. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2322. alloc_end - alloc_start);
  2323. if (ret)
  2324. goto out;
  2325. } else {
  2326. if (ordered)
  2327. btrfs_put_ordered_extent(ordered);
  2328. break;
  2329. }
  2330. }
  2331. cur_offset = alloc_start;
  2332. while (1) {
  2333. u64 actual_end;
  2334. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  2335. alloc_end - cur_offset, 0);
  2336. if (IS_ERR_OR_NULL(em)) {
  2337. if (!em)
  2338. ret = -ENOMEM;
  2339. else
  2340. ret = PTR_ERR(em);
  2341. break;
  2342. }
  2343. last_byte = min(extent_map_end(em), alloc_end);
  2344. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2345. last_byte = ALIGN(last_byte, blocksize);
  2346. if (em->block_start == EXTENT_MAP_HOLE ||
  2347. (cur_offset >= inode->i_size &&
  2348. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2349. ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
  2350. last_byte - cur_offset,
  2351. 1 << inode->i_blkbits,
  2352. offset + len,
  2353. &alloc_hint);
  2354. if (ret < 0) {
  2355. free_extent_map(em);
  2356. break;
  2357. }
  2358. } else if (actual_end > inode->i_size &&
  2359. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2360. /*
  2361. * We didn't need to allocate any more space, but we
  2362. * still extended the size of the file so we need to
  2363. * update i_size.
  2364. */
  2365. inode->i_ctime = CURRENT_TIME;
  2366. i_size_write(inode, actual_end);
  2367. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2368. }
  2369. free_extent_map(em);
  2370. cur_offset = last_byte;
  2371. if (cur_offset >= alloc_end) {
  2372. ret = 0;
  2373. break;
  2374. }
  2375. }
  2376. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2377. &cached_state, GFP_NOFS);
  2378. out:
  2379. mutex_unlock(&inode->i_mutex);
  2380. if (root->fs_info->quota_enabled)
  2381. btrfs_qgroup_free(root, alloc_end - alloc_start);
  2382. out_reserve_fail:
  2383. /* Let go of our reservation. */
  2384. btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
  2385. return ret;
  2386. }
  2387. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2388. {
  2389. struct btrfs_root *root = BTRFS_I(inode)->root;
  2390. struct extent_map *em = NULL;
  2391. struct extent_state *cached_state = NULL;
  2392. u64 lockstart;
  2393. u64 lockend;
  2394. u64 start;
  2395. u64 len;
  2396. int ret = 0;
  2397. if (inode->i_size == 0)
  2398. return -ENXIO;
  2399. /*
  2400. * *offset can be negative, in this case we start finding DATA/HOLE from
  2401. * the very start of the file.
  2402. */
  2403. start = max_t(loff_t, 0, *offset);
  2404. lockstart = round_down(start, root->sectorsize);
  2405. lockend = round_up(i_size_read(inode), root->sectorsize);
  2406. if (lockend <= lockstart)
  2407. lockend = lockstart + root->sectorsize;
  2408. lockend--;
  2409. len = lockend - lockstart + 1;
  2410. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
  2411. &cached_state);
  2412. while (start < inode->i_size) {
  2413. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  2414. if (IS_ERR(em)) {
  2415. ret = PTR_ERR(em);
  2416. em = NULL;
  2417. break;
  2418. }
  2419. if (whence == SEEK_HOLE &&
  2420. (em->block_start == EXTENT_MAP_HOLE ||
  2421. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2422. break;
  2423. else if (whence == SEEK_DATA &&
  2424. (em->block_start != EXTENT_MAP_HOLE &&
  2425. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2426. break;
  2427. start = em->start + em->len;
  2428. free_extent_map(em);
  2429. em = NULL;
  2430. cond_resched();
  2431. }
  2432. free_extent_map(em);
  2433. if (!ret) {
  2434. if (whence == SEEK_DATA && start >= inode->i_size)
  2435. ret = -ENXIO;
  2436. else
  2437. *offset = min_t(loff_t, start, inode->i_size);
  2438. }
  2439. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2440. &cached_state, GFP_NOFS);
  2441. return ret;
  2442. }
  2443. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2444. {
  2445. struct inode *inode = file->f_mapping->host;
  2446. int ret;
  2447. mutex_lock(&inode->i_mutex);
  2448. switch (whence) {
  2449. case SEEK_END:
  2450. case SEEK_CUR:
  2451. offset = generic_file_llseek(file, offset, whence);
  2452. goto out;
  2453. case SEEK_DATA:
  2454. case SEEK_HOLE:
  2455. if (offset >= i_size_read(inode)) {
  2456. mutex_unlock(&inode->i_mutex);
  2457. return -ENXIO;
  2458. }
  2459. ret = find_desired_extent(inode, &offset, whence);
  2460. if (ret) {
  2461. mutex_unlock(&inode->i_mutex);
  2462. return ret;
  2463. }
  2464. }
  2465. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2466. out:
  2467. mutex_unlock(&inode->i_mutex);
  2468. return offset;
  2469. }
  2470. const struct file_operations btrfs_file_operations = {
  2471. .llseek = btrfs_file_llseek,
  2472. .read = new_sync_read,
  2473. .write = new_sync_write,
  2474. .read_iter = generic_file_read_iter,
  2475. .splice_read = generic_file_splice_read,
  2476. .write_iter = btrfs_file_write_iter,
  2477. .mmap = btrfs_file_mmap,
  2478. .open = generic_file_open,
  2479. .release = btrfs_release_file,
  2480. .fsync = btrfs_sync_file,
  2481. .fallocate = btrfs_fallocate,
  2482. .unlocked_ioctl = btrfs_ioctl,
  2483. #ifdef CONFIG_COMPAT
  2484. .compat_ioctl = btrfs_ioctl,
  2485. #endif
  2486. };
  2487. void btrfs_auto_defrag_exit(void)
  2488. {
  2489. if (btrfs_inode_defrag_cachep)
  2490. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2491. }
  2492. int btrfs_auto_defrag_init(void)
  2493. {
  2494. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2495. sizeof(struct inode_defrag), 0,
  2496. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
  2497. NULL);
  2498. if (!btrfs_inode_defrag_cachep)
  2499. return -ENOMEM;
  2500. return 0;
  2501. }