file.c 76 KB

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