file.c 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018
  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. #include "compression.h"
  44. static struct kmem_cache *btrfs_inode_defrag_cachep;
  45. /*
  46. * when auto defrag is enabled we
  47. * queue up these defrag structs to remember which
  48. * inodes need defragging passes
  49. */
  50. struct inode_defrag {
  51. struct rb_node rb_node;
  52. /* objectid */
  53. u64 ino;
  54. /*
  55. * transid where the defrag was added, we search for
  56. * extents newer than this
  57. */
  58. u64 transid;
  59. /* root objectid */
  60. u64 root;
  61. /* last offset we were able to defrag */
  62. u64 last_offset;
  63. /* if we've wrapped around back to zero once already */
  64. int cycled;
  65. };
  66. static int __compare_inode_defrag(struct inode_defrag *defrag1,
  67. struct inode_defrag *defrag2)
  68. {
  69. if (defrag1->root > defrag2->root)
  70. return 1;
  71. else if (defrag1->root < defrag2->root)
  72. return -1;
  73. else if (defrag1->ino > defrag2->ino)
  74. return 1;
  75. else if (defrag1->ino < defrag2->ino)
  76. return -1;
  77. else
  78. return 0;
  79. }
  80. /* pop a record for an inode into the defrag tree. The lock
  81. * must be held already
  82. *
  83. * If you're inserting a record for an older transid than an
  84. * existing record, the transid already in the tree is lowered
  85. *
  86. * If an existing record is found the defrag item you
  87. * pass in is freed
  88. */
  89. static int __btrfs_add_inode_defrag(struct inode *inode,
  90. struct inode_defrag *defrag)
  91. {
  92. struct btrfs_root *root = BTRFS_I(inode)->root;
  93. struct inode_defrag *entry;
  94. struct rb_node **p;
  95. struct rb_node *parent = NULL;
  96. int ret;
  97. p = &root->fs_info->defrag_inodes.rb_node;
  98. while (*p) {
  99. parent = *p;
  100. entry = rb_entry(parent, struct inode_defrag, rb_node);
  101. ret = __compare_inode_defrag(defrag, entry);
  102. if (ret < 0)
  103. p = &parent->rb_left;
  104. else if (ret > 0)
  105. p = &parent->rb_right;
  106. else {
  107. /* if we're reinserting an entry for
  108. * an old defrag run, make sure to
  109. * lower the transid of our existing record
  110. */
  111. if (defrag->transid < entry->transid)
  112. entry->transid = defrag->transid;
  113. if (defrag->last_offset > entry->last_offset)
  114. entry->last_offset = defrag->last_offset;
  115. return -EEXIST;
  116. }
  117. }
  118. set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  119. rb_link_node(&defrag->rb_node, parent, p);
  120. rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
  121. return 0;
  122. }
  123. static inline int __need_auto_defrag(struct btrfs_root *root)
  124. {
  125. if (!btrfs_test_opt(root, AUTO_DEFRAG))
  126. return 0;
  127. if (btrfs_fs_closing(root->fs_info))
  128. return 0;
  129. return 1;
  130. }
  131. /*
  132. * insert a defrag record for this inode if auto defrag is
  133. * enabled
  134. */
  135. int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
  136. struct inode *inode)
  137. {
  138. struct btrfs_root *root = BTRFS_I(inode)->root;
  139. struct inode_defrag *defrag;
  140. u64 transid;
  141. int ret;
  142. if (!__need_auto_defrag(root))
  143. return 0;
  144. if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
  145. return 0;
  146. if (trans)
  147. transid = trans->transid;
  148. else
  149. transid = BTRFS_I(inode)->root->last_trans;
  150. defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
  151. if (!defrag)
  152. return -ENOMEM;
  153. defrag->ino = btrfs_ino(inode);
  154. defrag->transid = transid;
  155. defrag->root = root->root_key.objectid;
  156. spin_lock(&root->fs_info->defrag_inodes_lock);
  157. if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
  158. /*
  159. * If we set IN_DEFRAG flag and evict the inode from memory,
  160. * and then re-read this inode, this new inode doesn't have
  161. * IN_DEFRAG flag. At the case, we may find the existed defrag.
  162. */
  163. ret = __btrfs_add_inode_defrag(inode, defrag);
  164. if (ret)
  165. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  166. } else {
  167. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  168. }
  169. spin_unlock(&root->fs_info->defrag_inodes_lock);
  170. return 0;
  171. }
  172. /*
  173. * Requeue the defrag object. If there is a defrag object that points to
  174. * the same inode in the tree, we will merge them together (by
  175. * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
  176. */
  177. static void btrfs_requeue_inode_defrag(struct inode *inode,
  178. struct inode_defrag *defrag)
  179. {
  180. struct btrfs_root *root = BTRFS_I(inode)->root;
  181. int ret;
  182. if (!__need_auto_defrag(root))
  183. goto out;
  184. /*
  185. * Here we don't check the IN_DEFRAG flag, because we need merge
  186. * them together.
  187. */
  188. spin_lock(&root->fs_info->defrag_inodes_lock);
  189. ret = __btrfs_add_inode_defrag(inode, defrag);
  190. spin_unlock(&root->fs_info->defrag_inodes_lock);
  191. if (ret)
  192. goto out;
  193. return;
  194. out:
  195. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  196. }
  197. /*
  198. * pick the defragable inode that we want, if it doesn't exist, we will get
  199. * the next one.
  200. */
  201. static struct inode_defrag *
  202. btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
  203. {
  204. struct inode_defrag *entry = NULL;
  205. struct inode_defrag tmp;
  206. struct rb_node *p;
  207. struct rb_node *parent = NULL;
  208. int ret;
  209. tmp.ino = ino;
  210. tmp.root = root;
  211. spin_lock(&fs_info->defrag_inodes_lock);
  212. p = fs_info->defrag_inodes.rb_node;
  213. while (p) {
  214. parent = p;
  215. entry = rb_entry(parent, struct inode_defrag, rb_node);
  216. ret = __compare_inode_defrag(&tmp, entry);
  217. if (ret < 0)
  218. p = parent->rb_left;
  219. else if (ret > 0)
  220. p = parent->rb_right;
  221. else
  222. goto out;
  223. }
  224. if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
  225. parent = rb_next(parent);
  226. if (parent)
  227. entry = rb_entry(parent, struct inode_defrag, rb_node);
  228. else
  229. entry = NULL;
  230. }
  231. out:
  232. if (entry)
  233. rb_erase(parent, &fs_info->defrag_inodes);
  234. spin_unlock(&fs_info->defrag_inodes_lock);
  235. return entry;
  236. }
  237. void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
  238. {
  239. struct inode_defrag *defrag;
  240. struct rb_node *node;
  241. spin_lock(&fs_info->defrag_inodes_lock);
  242. node = rb_first(&fs_info->defrag_inodes);
  243. while (node) {
  244. rb_erase(node, &fs_info->defrag_inodes);
  245. defrag = rb_entry(node, struct inode_defrag, rb_node);
  246. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  247. cond_resched_lock(&fs_info->defrag_inodes_lock);
  248. node = rb_first(&fs_info->defrag_inodes);
  249. }
  250. spin_unlock(&fs_info->defrag_inodes_lock);
  251. }
  252. #define BTRFS_DEFRAG_BATCH 1024
  253. static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
  254. struct inode_defrag *defrag)
  255. {
  256. struct btrfs_root *inode_root;
  257. struct inode *inode;
  258. struct btrfs_key key;
  259. struct btrfs_ioctl_defrag_range_args range;
  260. int num_defrag;
  261. int index;
  262. int ret;
  263. /* get the inode */
  264. key.objectid = defrag->root;
  265. key.type = BTRFS_ROOT_ITEM_KEY;
  266. key.offset = (u64)-1;
  267. index = srcu_read_lock(&fs_info->subvol_srcu);
  268. inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
  269. if (IS_ERR(inode_root)) {
  270. ret = PTR_ERR(inode_root);
  271. goto cleanup;
  272. }
  273. key.objectid = defrag->ino;
  274. key.type = BTRFS_INODE_ITEM_KEY;
  275. key.offset = 0;
  276. inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
  277. if (IS_ERR(inode)) {
  278. ret = PTR_ERR(inode);
  279. goto cleanup;
  280. }
  281. srcu_read_unlock(&fs_info->subvol_srcu, index);
  282. /* do a chunk of defrag */
  283. clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  284. memset(&range, 0, sizeof(range));
  285. range.len = (u64)-1;
  286. range.start = defrag->last_offset;
  287. sb_start_write(fs_info->sb);
  288. num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
  289. BTRFS_DEFRAG_BATCH);
  290. sb_end_write(fs_info->sb);
  291. /*
  292. * if we filled the whole defrag batch, there
  293. * must be more work to do. Queue this defrag
  294. * again
  295. */
  296. if (num_defrag == BTRFS_DEFRAG_BATCH) {
  297. defrag->last_offset = range.start;
  298. btrfs_requeue_inode_defrag(inode, defrag);
  299. } else if (defrag->last_offset && !defrag->cycled) {
  300. /*
  301. * we didn't fill our defrag batch, but
  302. * we didn't start at zero. Make sure we loop
  303. * around to the start of the file.
  304. */
  305. defrag->last_offset = 0;
  306. defrag->cycled = 1;
  307. btrfs_requeue_inode_defrag(inode, defrag);
  308. } else {
  309. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  310. }
  311. iput(inode);
  312. return 0;
  313. cleanup:
  314. srcu_read_unlock(&fs_info->subvol_srcu, index);
  315. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  316. return ret;
  317. }
  318. /*
  319. * run through the list of inodes in the FS that need
  320. * defragging
  321. */
  322. int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
  323. {
  324. struct inode_defrag *defrag;
  325. u64 first_ino = 0;
  326. u64 root_objectid = 0;
  327. atomic_inc(&fs_info->defrag_running);
  328. while (1) {
  329. /* Pause the auto defragger. */
  330. if (test_bit(BTRFS_FS_STATE_REMOUNTING,
  331. &fs_info->fs_state))
  332. break;
  333. if (!__need_auto_defrag(fs_info->tree_root))
  334. break;
  335. /* find an inode to defrag */
  336. defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
  337. first_ino);
  338. if (!defrag) {
  339. if (root_objectid || first_ino) {
  340. root_objectid = 0;
  341. first_ino = 0;
  342. continue;
  343. } else {
  344. break;
  345. }
  346. }
  347. first_ino = defrag->ino + 1;
  348. root_objectid = defrag->root;
  349. __btrfs_run_defrag_inode(fs_info, defrag);
  350. }
  351. atomic_dec(&fs_info->defrag_running);
  352. /*
  353. * during unmount, we use the transaction_wait queue to
  354. * wait for the defragger to stop
  355. */
  356. wake_up(&fs_info->transaction_wait);
  357. return 0;
  358. }
  359. /* simple helper to fault in pages and copy. This should go away
  360. * and be replaced with calls into generic code.
  361. */
  362. static noinline int btrfs_copy_from_user(loff_t pos, 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_SIZE - 1);
  370. while (write_bytes > 0) {
  371. size_t count = min_t(size_t,
  372. PAGE_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_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. put_page(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 = round_up(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. break;
  683. if (WARN_ON_ONCE(key.objectid < ino) ||
  684. key.type < BTRFS_EXTENT_DATA_KEY) {
  685. ASSERT(del_nr == 0);
  686. path->slots[0]++;
  687. goto next_slot;
  688. }
  689. if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
  690. break;
  691. fi = btrfs_item_ptr(leaf, path->slots[0],
  692. struct btrfs_file_extent_item);
  693. extent_type = btrfs_file_extent_type(leaf, fi);
  694. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  695. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  696. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  697. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  698. extent_offset = btrfs_file_extent_offset(leaf, fi);
  699. extent_end = key.offset +
  700. btrfs_file_extent_num_bytes(leaf, fi);
  701. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  702. extent_end = key.offset +
  703. btrfs_file_extent_inline_len(leaf,
  704. path->slots[0], fi);
  705. } else {
  706. /* can't happen */
  707. BUG();
  708. }
  709. /*
  710. * Don't skip extent items representing 0 byte lengths. They
  711. * used to be created (bug) if while punching holes we hit
  712. * -ENOSPC condition. So if we find one here, just ensure we
  713. * delete it, otherwise we would insert a new file extent item
  714. * with the same key (offset) as that 0 bytes length file
  715. * extent item in the call to setup_items_for_insert() later
  716. * in this function.
  717. */
  718. if (extent_end == key.offset && extent_end >= search_start)
  719. goto delete_extent_item;
  720. if (extent_end <= search_start) {
  721. path->slots[0]++;
  722. goto next_slot;
  723. }
  724. found = 1;
  725. search_start = max(key.offset, start);
  726. if (recow || !modify_tree) {
  727. modify_tree = -1;
  728. btrfs_release_path(path);
  729. continue;
  730. }
  731. /*
  732. * | - range to drop - |
  733. * | -------- extent -------- |
  734. */
  735. if (start > key.offset && end < extent_end) {
  736. BUG_ON(del_nr > 0);
  737. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  738. ret = -EOPNOTSUPP;
  739. break;
  740. }
  741. memcpy(&new_key, &key, sizeof(new_key));
  742. new_key.offset = start;
  743. ret = btrfs_duplicate_item(trans, root, path,
  744. &new_key);
  745. if (ret == -EAGAIN) {
  746. btrfs_release_path(path);
  747. continue;
  748. }
  749. if (ret < 0)
  750. break;
  751. leaf = path->nodes[0];
  752. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  753. struct btrfs_file_extent_item);
  754. btrfs_set_file_extent_num_bytes(leaf, fi,
  755. start - key.offset);
  756. fi = btrfs_item_ptr(leaf, path->slots[0],
  757. struct btrfs_file_extent_item);
  758. extent_offset += start - key.offset;
  759. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  760. btrfs_set_file_extent_num_bytes(leaf, fi,
  761. extent_end - start);
  762. btrfs_mark_buffer_dirty(leaf);
  763. if (update_refs && disk_bytenr > 0) {
  764. ret = btrfs_inc_extent_ref(trans, root,
  765. disk_bytenr, num_bytes, 0,
  766. root->root_key.objectid,
  767. new_key.objectid,
  768. start - extent_offset);
  769. BUG_ON(ret); /* -ENOMEM */
  770. }
  771. key.offset = start;
  772. }
  773. /*
  774. * | ---- range to drop ----- |
  775. * | -------- extent -------- |
  776. */
  777. if (start <= key.offset && end < extent_end) {
  778. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  779. ret = -EOPNOTSUPP;
  780. break;
  781. }
  782. memcpy(&new_key, &key, sizeof(new_key));
  783. new_key.offset = end;
  784. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  785. extent_offset += end - key.offset;
  786. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  787. btrfs_set_file_extent_num_bytes(leaf, fi,
  788. extent_end - end);
  789. btrfs_mark_buffer_dirty(leaf);
  790. if (update_refs && disk_bytenr > 0)
  791. inode_sub_bytes(inode, end - key.offset);
  792. break;
  793. }
  794. search_start = extent_end;
  795. /*
  796. * | ---- range to drop ----- |
  797. * | -------- extent -------- |
  798. */
  799. if (start > key.offset && end >= extent_end) {
  800. BUG_ON(del_nr > 0);
  801. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  802. ret = -EOPNOTSUPP;
  803. break;
  804. }
  805. btrfs_set_file_extent_num_bytes(leaf, fi,
  806. start - key.offset);
  807. btrfs_mark_buffer_dirty(leaf);
  808. if (update_refs && disk_bytenr > 0)
  809. inode_sub_bytes(inode, extent_end - start);
  810. if (end == extent_end)
  811. break;
  812. path->slots[0]++;
  813. goto next_slot;
  814. }
  815. /*
  816. * | ---- range to drop ----- |
  817. * | ------ extent ------ |
  818. */
  819. if (start <= key.offset && end >= extent_end) {
  820. delete_extent_item:
  821. if (del_nr == 0) {
  822. del_slot = path->slots[0];
  823. del_nr = 1;
  824. } else {
  825. BUG_ON(del_slot + del_nr != path->slots[0]);
  826. del_nr++;
  827. }
  828. if (update_refs &&
  829. extent_type == BTRFS_FILE_EXTENT_INLINE) {
  830. inode_sub_bytes(inode,
  831. extent_end - key.offset);
  832. extent_end = ALIGN(extent_end,
  833. root->sectorsize);
  834. } else if (update_refs && disk_bytenr > 0) {
  835. ret = btrfs_free_extent(trans, root,
  836. disk_bytenr, num_bytes, 0,
  837. root->root_key.objectid,
  838. key.objectid, key.offset -
  839. extent_offset);
  840. BUG_ON(ret); /* -ENOMEM */
  841. inode_sub_bytes(inode,
  842. extent_end - key.offset);
  843. }
  844. if (end == extent_end)
  845. break;
  846. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  847. path->slots[0]++;
  848. goto next_slot;
  849. }
  850. ret = btrfs_del_items(trans, root, path, del_slot,
  851. del_nr);
  852. if (ret) {
  853. btrfs_abort_transaction(trans, root, ret);
  854. break;
  855. }
  856. del_nr = 0;
  857. del_slot = 0;
  858. btrfs_release_path(path);
  859. continue;
  860. }
  861. BUG_ON(1);
  862. }
  863. if (!ret && del_nr > 0) {
  864. /*
  865. * Set path->slots[0] to first slot, so that after the delete
  866. * if items are move off from our leaf to its immediate left or
  867. * right neighbor leafs, we end up with a correct and adjusted
  868. * path->slots[0] for our insertion (if replace_extent != 0).
  869. */
  870. path->slots[0] = del_slot;
  871. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  872. if (ret)
  873. btrfs_abort_transaction(trans, root, ret);
  874. }
  875. leaf = path->nodes[0];
  876. /*
  877. * If btrfs_del_items() was called, it might have deleted a leaf, in
  878. * which case it unlocked our path, so check path->locks[0] matches a
  879. * write lock.
  880. */
  881. if (!ret && replace_extent && leafs_visited == 1 &&
  882. (path->locks[0] == BTRFS_WRITE_LOCK_BLOCKING ||
  883. path->locks[0] == BTRFS_WRITE_LOCK) &&
  884. btrfs_leaf_free_space(root, leaf) >=
  885. sizeof(struct btrfs_item) + extent_item_size) {
  886. key.objectid = ino;
  887. key.type = BTRFS_EXTENT_DATA_KEY;
  888. key.offset = start;
  889. if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
  890. struct btrfs_key slot_key;
  891. btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
  892. if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
  893. path->slots[0]++;
  894. }
  895. setup_items_for_insert(root, path, &key,
  896. &extent_item_size,
  897. extent_item_size,
  898. sizeof(struct btrfs_item) +
  899. extent_item_size, 1);
  900. *key_inserted = 1;
  901. }
  902. if (!replace_extent || !(*key_inserted))
  903. btrfs_release_path(path);
  904. if (drop_end)
  905. *drop_end = found ? min(end, extent_end) : end;
  906. return ret;
  907. }
  908. int btrfs_drop_extents(struct btrfs_trans_handle *trans,
  909. struct btrfs_root *root, struct inode *inode, u64 start,
  910. u64 end, int drop_cache)
  911. {
  912. struct btrfs_path *path;
  913. int ret;
  914. path = btrfs_alloc_path();
  915. if (!path)
  916. return -ENOMEM;
  917. ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
  918. drop_cache, 0, 0, NULL);
  919. btrfs_free_path(path);
  920. return ret;
  921. }
  922. static int extent_mergeable(struct extent_buffer *leaf, int slot,
  923. u64 objectid, u64 bytenr, u64 orig_offset,
  924. u64 *start, u64 *end)
  925. {
  926. struct btrfs_file_extent_item *fi;
  927. struct btrfs_key key;
  928. u64 extent_end;
  929. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  930. return 0;
  931. btrfs_item_key_to_cpu(leaf, &key, slot);
  932. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  933. return 0;
  934. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  935. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  936. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  937. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  938. btrfs_file_extent_compression(leaf, fi) ||
  939. btrfs_file_extent_encryption(leaf, fi) ||
  940. btrfs_file_extent_other_encoding(leaf, fi))
  941. return 0;
  942. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  943. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  944. return 0;
  945. *start = key.offset;
  946. *end = extent_end;
  947. return 1;
  948. }
  949. /*
  950. * Mark extent in the range start - end as written.
  951. *
  952. * This changes extent type from 'pre-allocated' to 'regular'. If only
  953. * part of extent is marked as written, the extent will be split into
  954. * two or three.
  955. */
  956. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  957. struct inode *inode, u64 start, u64 end)
  958. {
  959. struct btrfs_root *root = BTRFS_I(inode)->root;
  960. struct extent_buffer *leaf;
  961. struct btrfs_path *path;
  962. struct btrfs_file_extent_item *fi;
  963. struct btrfs_key key;
  964. struct btrfs_key new_key;
  965. u64 bytenr;
  966. u64 num_bytes;
  967. u64 extent_end;
  968. u64 orig_offset;
  969. u64 other_start;
  970. u64 other_end;
  971. u64 split;
  972. int del_nr = 0;
  973. int del_slot = 0;
  974. int recow;
  975. int ret;
  976. u64 ino = btrfs_ino(inode);
  977. path = btrfs_alloc_path();
  978. if (!path)
  979. return -ENOMEM;
  980. again:
  981. recow = 0;
  982. split = start;
  983. key.objectid = ino;
  984. key.type = BTRFS_EXTENT_DATA_KEY;
  985. key.offset = split;
  986. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  987. if (ret < 0)
  988. goto out;
  989. if (ret > 0 && path->slots[0] > 0)
  990. path->slots[0]--;
  991. leaf = path->nodes[0];
  992. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  993. BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
  994. fi = btrfs_item_ptr(leaf, path->slots[0],
  995. struct btrfs_file_extent_item);
  996. BUG_ON(btrfs_file_extent_type(leaf, fi) !=
  997. BTRFS_FILE_EXTENT_PREALLOC);
  998. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  999. BUG_ON(key.offset > start || extent_end < end);
  1000. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1001. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  1002. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  1003. memcpy(&new_key, &key, sizeof(new_key));
  1004. if (start == key.offset && end < extent_end) {
  1005. other_start = 0;
  1006. other_end = start;
  1007. if (extent_mergeable(leaf, path->slots[0] - 1,
  1008. ino, bytenr, orig_offset,
  1009. &other_start, &other_end)) {
  1010. new_key.offset = end;
  1011. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  1012. fi = btrfs_item_ptr(leaf, path->slots[0],
  1013. struct btrfs_file_extent_item);
  1014. btrfs_set_file_extent_generation(leaf, fi,
  1015. trans->transid);
  1016. btrfs_set_file_extent_num_bytes(leaf, fi,
  1017. extent_end - end);
  1018. btrfs_set_file_extent_offset(leaf, fi,
  1019. end - orig_offset);
  1020. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1021. struct btrfs_file_extent_item);
  1022. btrfs_set_file_extent_generation(leaf, fi,
  1023. trans->transid);
  1024. btrfs_set_file_extent_num_bytes(leaf, fi,
  1025. end - other_start);
  1026. btrfs_mark_buffer_dirty(leaf);
  1027. goto out;
  1028. }
  1029. }
  1030. if (start > key.offset && end == extent_end) {
  1031. other_start = end;
  1032. other_end = 0;
  1033. if (extent_mergeable(leaf, path->slots[0] + 1,
  1034. ino, bytenr, orig_offset,
  1035. &other_start, &other_end)) {
  1036. fi = btrfs_item_ptr(leaf, path->slots[0],
  1037. struct btrfs_file_extent_item);
  1038. btrfs_set_file_extent_num_bytes(leaf, fi,
  1039. start - key.offset);
  1040. btrfs_set_file_extent_generation(leaf, fi,
  1041. trans->transid);
  1042. path->slots[0]++;
  1043. new_key.offset = start;
  1044. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  1045. fi = btrfs_item_ptr(leaf, path->slots[0],
  1046. struct btrfs_file_extent_item);
  1047. btrfs_set_file_extent_generation(leaf, fi,
  1048. trans->transid);
  1049. btrfs_set_file_extent_num_bytes(leaf, fi,
  1050. other_end - start);
  1051. btrfs_set_file_extent_offset(leaf, fi,
  1052. start - orig_offset);
  1053. btrfs_mark_buffer_dirty(leaf);
  1054. goto out;
  1055. }
  1056. }
  1057. while (start > key.offset || end < extent_end) {
  1058. if (key.offset == start)
  1059. split = end;
  1060. new_key.offset = split;
  1061. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  1062. if (ret == -EAGAIN) {
  1063. btrfs_release_path(path);
  1064. goto again;
  1065. }
  1066. if (ret < 0) {
  1067. btrfs_abort_transaction(trans, root, ret);
  1068. goto out;
  1069. }
  1070. leaf = path->nodes[0];
  1071. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1072. struct btrfs_file_extent_item);
  1073. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1074. btrfs_set_file_extent_num_bytes(leaf, fi,
  1075. split - key.offset);
  1076. fi = btrfs_item_ptr(leaf, path->slots[0],
  1077. struct btrfs_file_extent_item);
  1078. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1079. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  1080. btrfs_set_file_extent_num_bytes(leaf, fi,
  1081. extent_end - split);
  1082. btrfs_mark_buffer_dirty(leaf);
  1083. ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
  1084. root->root_key.objectid,
  1085. ino, orig_offset);
  1086. BUG_ON(ret); /* -ENOMEM */
  1087. if (split == start) {
  1088. key.offset = start;
  1089. } else {
  1090. BUG_ON(start != key.offset);
  1091. path->slots[0]--;
  1092. extent_end = end;
  1093. }
  1094. recow = 1;
  1095. }
  1096. other_start = end;
  1097. other_end = 0;
  1098. if (extent_mergeable(leaf, path->slots[0] + 1,
  1099. ino, bytenr, orig_offset,
  1100. &other_start, &other_end)) {
  1101. if (recow) {
  1102. btrfs_release_path(path);
  1103. goto again;
  1104. }
  1105. extent_end = other_end;
  1106. del_slot = path->slots[0] + 1;
  1107. del_nr++;
  1108. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1109. 0, root->root_key.objectid,
  1110. ino, orig_offset);
  1111. BUG_ON(ret); /* -ENOMEM */
  1112. }
  1113. other_start = 0;
  1114. other_end = start;
  1115. if (extent_mergeable(leaf, path->slots[0] - 1,
  1116. ino, bytenr, orig_offset,
  1117. &other_start, &other_end)) {
  1118. if (recow) {
  1119. btrfs_release_path(path);
  1120. goto again;
  1121. }
  1122. key.offset = other_start;
  1123. del_slot = path->slots[0];
  1124. del_nr++;
  1125. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1126. 0, root->root_key.objectid,
  1127. ino, orig_offset);
  1128. BUG_ON(ret); /* -ENOMEM */
  1129. }
  1130. if (del_nr == 0) {
  1131. fi = btrfs_item_ptr(leaf, path->slots[0],
  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_mark_buffer_dirty(leaf);
  1137. } else {
  1138. fi = btrfs_item_ptr(leaf, del_slot - 1,
  1139. struct btrfs_file_extent_item);
  1140. btrfs_set_file_extent_type(leaf, fi,
  1141. BTRFS_FILE_EXTENT_REG);
  1142. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1143. btrfs_set_file_extent_num_bytes(leaf, fi,
  1144. extent_end - key.offset);
  1145. btrfs_mark_buffer_dirty(leaf);
  1146. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  1147. if (ret < 0) {
  1148. btrfs_abort_transaction(trans, root, ret);
  1149. goto out;
  1150. }
  1151. }
  1152. out:
  1153. btrfs_free_path(path);
  1154. return 0;
  1155. }
  1156. /*
  1157. * on error we return an unlocked page and the error value
  1158. * on success we return a locked page and 0
  1159. */
  1160. static int prepare_uptodate_page(struct inode *inode,
  1161. struct page *page, u64 pos,
  1162. bool force_uptodate)
  1163. {
  1164. int ret = 0;
  1165. if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
  1166. !PageUptodate(page)) {
  1167. ret = btrfs_readpage(NULL, page);
  1168. if (ret)
  1169. return ret;
  1170. lock_page(page);
  1171. if (!PageUptodate(page)) {
  1172. unlock_page(page);
  1173. return -EIO;
  1174. }
  1175. if (page->mapping != inode->i_mapping) {
  1176. unlock_page(page);
  1177. return -EAGAIN;
  1178. }
  1179. }
  1180. return 0;
  1181. }
  1182. /*
  1183. * this just gets pages into the page cache and locks them down.
  1184. */
  1185. static noinline int prepare_pages(struct inode *inode, struct page **pages,
  1186. size_t num_pages, loff_t pos,
  1187. size_t write_bytes, bool force_uptodate)
  1188. {
  1189. int i;
  1190. unsigned long index = pos >> PAGE_SHIFT;
  1191. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  1192. int err = 0;
  1193. int faili;
  1194. for (i = 0; i < num_pages; i++) {
  1195. again:
  1196. pages[i] = find_or_create_page(inode->i_mapping, index + i,
  1197. mask | __GFP_WRITE);
  1198. if (!pages[i]) {
  1199. faili = i - 1;
  1200. err = -ENOMEM;
  1201. goto fail;
  1202. }
  1203. if (i == 0)
  1204. err = prepare_uptodate_page(inode, pages[i], pos,
  1205. force_uptodate);
  1206. if (!err && i == num_pages - 1)
  1207. err = prepare_uptodate_page(inode, pages[i],
  1208. pos + write_bytes, false);
  1209. if (err) {
  1210. put_page(pages[i]);
  1211. if (err == -EAGAIN) {
  1212. err = 0;
  1213. goto again;
  1214. }
  1215. faili = i - 1;
  1216. goto fail;
  1217. }
  1218. wait_on_page_writeback(pages[i]);
  1219. }
  1220. return 0;
  1221. fail:
  1222. while (faili >= 0) {
  1223. unlock_page(pages[faili]);
  1224. put_page(pages[faili]);
  1225. faili--;
  1226. }
  1227. return err;
  1228. }
  1229. /*
  1230. * This function locks the extent and properly waits for data=ordered extents
  1231. * to finish before allowing the pages to be modified if need.
  1232. *
  1233. * The return value:
  1234. * 1 - the extent is locked
  1235. * 0 - the extent is not locked, and everything is OK
  1236. * -EAGAIN - need re-prepare the pages
  1237. * the other < 0 number - Something wrong happens
  1238. */
  1239. static noinline int
  1240. lock_and_cleanup_extent_if_need(struct inode *inode, struct page **pages,
  1241. size_t num_pages, loff_t pos,
  1242. size_t write_bytes,
  1243. u64 *lockstart, u64 *lockend,
  1244. struct extent_state **cached_state)
  1245. {
  1246. struct btrfs_root *root = BTRFS_I(inode)->root;
  1247. u64 start_pos;
  1248. u64 last_pos;
  1249. int i;
  1250. int ret = 0;
  1251. start_pos = round_down(pos, root->sectorsize);
  1252. last_pos = start_pos
  1253. + round_up(pos + write_bytes - start_pos, root->sectorsize) - 1;
  1254. if (start_pos < inode->i_size) {
  1255. struct btrfs_ordered_extent *ordered;
  1256. lock_extent_bits(&BTRFS_I(inode)->io_tree,
  1257. start_pos, last_pos, cached_state);
  1258. ordered = btrfs_lookup_ordered_range(inode, start_pos,
  1259. last_pos - start_pos + 1);
  1260. if (ordered &&
  1261. ordered->file_offset + ordered->len > start_pos &&
  1262. ordered->file_offset <= last_pos) {
  1263. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1264. start_pos, last_pos,
  1265. cached_state, GFP_NOFS);
  1266. for (i = 0; i < num_pages; i++) {
  1267. unlock_page(pages[i]);
  1268. put_page(pages[i]);
  1269. }
  1270. btrfs_start_ordered_extent(inode, ordered, 1);
  1271. btrfs_put_ordered_extent(ordered);
  1272. return -EAGAIN;
  1273. }
  1274. if (ordered)
  1275. btrfs_put_ordered_extent(ordered);
  1276. clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
  1277. last_pos, EXTENT_DIRTY | EXTENT_DELALLOC |
  1278. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  1279. 0, 0, cached_state, GFP_NOFS);
  1280. *lockstart = start_pos;
  1281. *lockend = last_pos;
  1282. ret = 1;
  1283. }
  1284. for (i = 0; i < num_pages; i++) {
  1285. if (clear_page_dirty_for_io(pages[i]))
  1286. account_page_redirty(pages[i]);
  1287. set_page_extent_mapped(pages[i]);
  1288. WARN_ON(!PageLocked(pages[i]));
  1289. }
  1290. return ret;
  1291. }
  1292. static noinline int check_can_nocow(struct inode *inode, loff_t pos,
  1293. size_t *write_bytes)
  1294. {
  1295. struct btrfs_root *root = BTRFS_I(inode)->root;
  1296. struct btrfs_ordered_extent *ordered;
  1297. u64 lockstart, lockend;
  1298. u64 num_bytes;
  1299. int ret;
  1300. ret = btrfs_start_write_no_snapshoting(root);
  1301. if (!ret)
  1302. return -ENOSPC;
  1303. lockstart = round_down(pos, root->sectorsize);
  1304. lockend = round_up(pos + *write_bytes, root->sectorsize) - 1;
  1305. while (1) {
  1306. lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1307. ordered = btrfs_lookup_ordered_range(inode, lockstart,
  1308. lockend - lockstart + 1);
  1309. if (!ordered) {
  1310. break;
  1311. }
  1312. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1313. btrfs_start_ordered_extent(inode, ordered, 1);
  1314. btrfs_put_ordered_extent(ordered);
  1315. }
  1316. num_bytes = lockend - lockstart + 1;
  1317. ret = can_nocow_extent(inode, lockstart, &num_bytes, NULL, NULL, NULL);
  1318. if (ret <= 0) {
  1319. ret = 0;
  1320. btrfs_end_write_no_snapshoting(root);
  1321. } else {
  1322. *write_bytes = min_t(size_t, *write_bytes ,
  1323. num_bytes - pos + lockstart);
  1324. }
  1325. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1326. return ret;
  1327. }
  1328. static noinline ssize_t __btrfs_buffered_write(struct file *file,
  1329. struct iov_iter *i,
  1330. loff_t pos)
  1331. {
  1332. struct inode *inode = file_inode(file);
  1333. struct btrfs_root *root = BTRFS_I(inode)->root;
  1334. struct page **pages = NULL;
  1335. struct extent_state *cached_state = NULL;
  1336. u64 release_bytes = 0;
  1337. u64 lockstart;
  1338. u64 lockend;
  1339. size_t num_written = 0;
  1340. int nrptrs;
  1341. int ret = 0;
  1342. bool only_release_metadata = false;
  1343. bool force_page_uptodate = false;
  1344. bool need_unlock;
  1345. nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
  1346. PAGE_SIZE / (sizeof(struct page *)));
  1347. nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
  1348. nrptrs = max(nrptrs, 8);
  1349. pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
  1350. if (!pages)
  1351. return -ENOMEM;
  1352. while (iov_iter_count(i) > 0) {
  1353. size_t offset = pos & (PAGE_SIZE - 1);
  1354. size_t sector_offset;
  1355. size_t write_bytes = min(iov_iter_count(i),
  1356. nrptrs * (size_t)PAGE_SIZE -
  1357. offset);
  1358. size_t num_pages = DIV_ROUND_UP(write_bytes + offset,
  1359. PAGE_SIZE);
  1360. size_t reserve_bytes;
  1361. size_t dirty_pages;
  1362. size_t copied;
  1363. size_t dirty_sectors;
  1364. size_t num_sectors;
  1365. WARN_ON(num_pages > nrptrs);
  1366. /*
  1367. * Fault pages before locking them in prepare_pages
  1368. * to avoid recursive lock
  1369. */
  1370. if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
  1371. ret = -EFAULT;
  1372. break;
  1373. }
  1374. sector_offset = pos & (root->sectorsize - 1);
  1375. reserve_bytes = round_up(write_bytes + sector_offset,
  1376. root->sectorsize);
  1377. ret = btrfs_check_data_free_space(inode, pos, write_bytes);
  1378. if (ret < 0) {
  1379. if ((BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
  1380. BTRFS_INODE_PREALLOC)) &&
  1381. check_can_nocow(inode, pos, &write_bytes) > 0) {
  1382. /*
  1383. * For nodata cow case, no need to reserve
  1384. * data space.
  1385. */
  1386. only_release_metadata = true;
  1387. /*
  1388. * our prealloc extent may be smaller than
  1389. * write_bytes, so scale down.
  1390. */
  1391. num_pages = DIV_ROUND_UP(write_bytes + offset,
  1392. PAGE_SIZE);
  1393. reserve_bytes = round_up(write_bytes +
  1394. sector_offset,
  1395. root->sectorsize);
  1396. } else {
  1397. break;
  1398. }
  1399. }
  1400. ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes);
  1401. if (ret) {
  1402. if (!only_release_metadata)
  1403. btrfs_free_reserved_data_space(inode, pos,
  1404. write_bytes);
  1405. else
  1406. btrfs_end_write_no_snapshoting(root);
  1407. break;
  1408. }
  1409. release_bytes = reserve_bytes;
  1410. need_unlock = false;
  1411. again:
  1412. /*
  1413. * This is going to setup the pages array with the number of
  1414. * pages we want, so we don't really need to worry about the
  1415. * contents of pages from loop to loop
  1416. */
  1417. ret = prepare_pages(inode, pages, num_pages,
  1418. pos, write_bytes,
  1419. force_page_uptodate);
  1420. if (ret)
  1421. break;
  1422. ret = lock_and_cleanup_extent_if_need(inode, pages, num_pages,
  1423. pos, write_bytes, &lockstart,
  1424. &lockend, &cached_state);
  1425. if (ret < 0) {
  1426. if (ret == -EAGAIN)
  1427. goto again;
  1428. break;
  1429. } else if (ret > 0) {
  1430. need_unlock = true;
  1431. ret = 0;
  1432. }
  1433. copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
  1434. num_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info,
  1435. reserve_bytes);
  1436. dirty_sectors = round_up(copied + sector_offset,
  1437. root->sectorsize);
  1438. dirty_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info,
  1439. dirty_sectors);
  1440. /*
  1441. * if we have trouble faulting in the pages, fall
  1442. * back to one page at a time
  1443. */
  1444. if (copied < write_bytes)
  1445. nrptrs = 1;
  1446. if (copied == 0) {
  1447. force_page_uptodate = true;
  1448. dirty_sectors = 0;
  1449. dirty_pages = 0;
  1450. } else {
  1451. force_page_uptodate = false;
  1452. dirty_pages = DIV_ROUND_UP(copied + offset,
  1453. PAGE_SIZE);
  1454. }
  1455. /*
  1456. * If we had a short copy we need to release the excess delaloc
  1457. * bytes we reserved. We need to increment outstanding_extents
  1458. * because btrfs_delalloc_release_space and
  1459. * btrfs_delalloc_release_metadata will decrement it, but
  1460. * we still have an outstanding extent for the chunk we actually
  1461. * managed to copy.
  1462. */
  1463. if (num_sectors > dirty_sectors) {
  1464. /* release everything except the sectors we dirtied */
  1465. release_bytes -= dirty_sectors <<
  1466. root->fs_info->sb->s_blocksize_bits;
  1467. if (copied > 0) {
  1468. spin_lock(&BTRFS_I(inode)->lock);
  1469. BTRFS_I(inode)->outstanding_extents++;
  1470. spin_unlock(&BTRFS_I(inode)->lock);
  1471. }
  1472. if (only_release_metadata) {
  1473. btrfs_delalloc_release_metadata(inode,
  1474. release_bytes);
  1475. } else {
  1476. u64 __pos;
  1477. __pos = round_down(pos, root->sectorsize) +
  1478. (dirty_pages << PAGE_SHIFT);
  1479. btrfs_delalloc_release_space(inode, __pos,
  1480. release_bytes);
  1481. }
  1482. }
  1483. release_bytes = round_up(copied + sector_offset,
  1484. root->sectorsize);
  1485. if (copied > 0)
  1486. ret = btrfs_dirty_pages(root, inode, pages,
  1487. dirty_pages, pos, copied,
  1488. NULL);
  1489. if (need_unlock)
  1490. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1491. lockstart, lockend, &cached_state,
  1492. GFP_NOFS);
  1493. if (ret) {
  1494. btrfs_drop_pages(pages, num_pages);
  1495. break;
  1496. }
  1497. release_bytes = 0;
  1498. if (only_release_metadata)
  1499. btrfs_end_write_no_snapshoting(root);
  1500. if (only_release_metadata && copied > 0) {
  1501. lockstart = round_down(pos, root->sectorsize);
  1502. lockend = round_up(pos + copied, root->sectorsize) - 1;
  1503. set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  1504. lockend, EXTENT_NORESERVE, NULL,
  1505. NULL, GFP_NOFS);
  1506. only_release_metadata = false;
  1507. }
  1508. btrfs_drop_pages(pages, num_pages);
  1509. cond_resched();
  1510. balance_dirty_pages_ratelimited(inode->i_mapping);
  1511. if (dirty_pages < (root->nodesize >> PAGE_SHIFT) + 1)
  1512. btrfs_btree_balance_dirty(root);
  1513. pos += copied;
  1514. num_written += copied;
  1515. }
  1516. kfree(pages);
  1517. if (release_bytes) {
  1518. if (only_release_metadata) {
  1519. btrfs_end_write_no_snapshoting(root);
  1520. btrfs_delalloc_release_metadata(inode, release_bytes);
  1521. } else {
  1522. btrfs_delalloc_release_space(inode,
  1523. round_down(pos, root->sectorsize),
  1524. release_bytes);
  1525. }
  1526. }
  1527. return num_written ? num_written : ret;
  1528. }
  1529. static ssize_t __btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
  1530. {
  1531. struct file *file = iocb->ki_filp;
  1532. struct inode *inode = file_inode(file);
  1533. loff_t pos = iocb->ki_pos;
  1534. ssize_t written;
  1535. ssize_t written_buffered;
  1536. loff_t endbyte;
  1537. int err;
  1538. written = generic_file_direct_write(iocb, from);
  1539. if (written < 0 || !iov_iter_count(from))
  1540. return written;
  1541. pos += written;
  1542. written_buffered = __btrfs_buffered_write(file, from, pos);
  1543. if (written_buffered < 0) {
  1544. err = written_buffered;
  1545. goto out;
  1546. }
  1547. /*
  1548. * Ensure all data is persisted. We want the next direct IO read to be
  1549. * able to read what was just written.
  1550. */
  1551. endbyte = pos + written_buffered - 1;
  1552. err = btrfs_fdatawrite_range(inode, pos, endbyte);
  1553. if (err)
  1554. goto out;
  1555. err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
  1556. if (err)
  1557. goto out;
  1558. written += written_buffered;
  1559. iocb->ki_pos = pos + written_buffered;
  1560. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
  1561. endbyte >> PAGE_SHIFT);
  1562. out:
  1563. return written ? written : err;
  1564. }
  1565. static void update_time_for_write(struct inode *inode)
  1566. {
  1567. struct timespec now;
  1568. if (IS_NOCMTIME(inode))
  1569. return;
  1570. now = current_fs_time(inode->i_sb);
  1571. if (!timespec_equal(&inode->i_mtime, &now))
  1572. inode->i_mtime = now;
  1573. if (!timespec_equal(&inode->i_ctime, &now))
  1574. inode->i_ctime = now;
  1575. if (IS_I_VERSION(inode))
  1576. inode_inc_iversion(inode);
  1577. }
  1578. static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
  1579. struct iov_iter *from)
  1580. {
  1581. struct file *file = iocb->ki_filp;
  1582. struct inode *inode = file_inode(file);
  1583. struct btrfs_root *root = BTRFS_I(inode)->root;
  1584. u64 start_pos;
  1585. u64 end_pos;
  1586. ssize_t num_written = 0;
  1587. bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
  1588. ssize_t err;
  1589. loff_t pos;
  1590. size_t count;
  1591. loff_t oldsize;
  1592. int clean_page = 0;
  1593. inode_lock(inode);
  1594. err = generic_write_checks(iocb, from);
  1595. if (err <= 0) {
  1596. inode_unlock(inode);
  1597. return err;
  1598. }
  1599. current->backing_dev_info = inode_to_bdi(inode);
  1600. err = file_remove_privs(file);
  1601. if (err) {
  1602. inode_unlock(inode);
  1603. goto out;
  1604. }
  1605. /*
  1606. * If BTRFS flips readonly due to some impossible error
  1607. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1608. * although we have opened a file as writable, we have
  1609. * to stop this write operation to ensure FS consistency.
  1610. */
  1611. if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
  1612. inode_unlock(inode);
  1613. err = -EROFS;
  1614. goto out;
  1615. }
  1616. /*
  1617. * We reserve space for updating the inode when we reserve space for the
  1618. * extent we are going to write, so we will enospc out there. We don't
  1619. * need to start yet another transaction to update the inode as we will
  1620. * update the inode when we finish writing whatever data we write.
  1621. */
  1622. update_time_for_write(inode);
  1623. pos = iocb->ki_pos;
  1624. count = iov_iter_count(from);
  1625. start_pos = round_down(pos, root->sectorsize);
  1626. oldsize = i_size_read(inode);
  1627. if (start_pos > oldsize) {
  1628. /* Expand hole size to cover write data, preventing empty gap */
  1629. end_pos = round_up(pos + count, root->sectorsize);
  1630. err = btrfs_cont_expand(inode, oldsize, end_pos);
  1631. if (err) {
  1632. inode_unlock(inode);
  1633. goto out;
  1634. }
  1635. if (start_pos > round_up(oldsize, root->sectorsize))
  1636. clean_page = 1;
  1637. }
  1638. if (sync)
  1639. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1640. if (iocb->ki_flags & IOCB_DIRECT) {
  1641. num_written = __btrfs_direct_write(iocb, from);
  1642. } else {
  1643. num_written = __btrfs_buffered_write(file, from, pos);
  1644. if (num_written > 0)
  1645. iocb->ki_pos = pos + num_written;
  1646. if (clean_page)
  1647. pagecache_isize_extended(inode, oldsize,
  1648. i_size_read(inode));
  1649. }
  1650. inode_unlock(inode);
  1651. /*
  1652. * We also have to set last_sub_trans to the current log transid,
  1653. * otherwise subsequent syncs to a file that's been synced in this
  1654. * transaction will appear to have already occurred.
  1655. */
  1656. spin_lock(&BTRFS_I(inode)->lock);
  1657. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1658. spin_unlock(&BTRFS_I(inode)->lock);
  1659. if (num_written > 0)
  1660. num_written = generic_write_sync(iocb, num_written);
  1661. if (sync)
  1662. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1663. out:
  1664. current->backing_dev_info = NULL;
  1665. return num_written ? num_written : err;
  1666. }
  1667. int btrfs_release_file(struct inode *inode, struct file *filp)
  1668. {
  1669. if (filp->private_data)
  1670. btrfs_ioctl_trans_end(filp);
  1671. /*
  1672. * ordered_data_close is set by settattr when we are about to truncate
  1673. * a file from a non-zero size to a zero size. This tries to
  1674. * flush down new bytes that may have been written if the
  1675. * application were using truncate to replace a file in place.
  1676. */
  1677. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1678. &BTRFS_I(inode)->runtime_flags))
  1679. filemap_flush(inode->i_mapping);
  1680. return 0;
  1681. }
  1682. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1683. {
  1684. int ret;
  1685. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1686. ret = btrfs_fdatawrite_range(inode, start, end);
  1687. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1688. return ret;
  1689. }
  1690. /*
  1691. * fsync call for both files and directories. This logs the inode into
  1692. * the tree log instead of forcing full commits whenever possible.
  1693. *
  1694. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1695. * in the metadata btree are up to date for copying to the log.
  1696. *
  1697. * It drops the inode mutex before doing the tree log commit. This is an
  1698. * important optimization for directories because holding the mutex prevents
  1699. * new operations on the dir while we write to disk.
  1700. */
  1701. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1702. {
  1703. struct dentry *dentry = file_dentry(file);
  1704. struct inode *inode = d_inode(dentry);
  1705. struct btrfs_root *root = BTRFS_I(inode)->root;
  1706. struct btrfs_trans_handle *trans;
  1707. struct btrfs_log_ctx ctx;
  1708. int ret = 0;
  1709. bool full_sync = 0;
  1710. u64 len;
  1711. /*
  1712. * The range length can be represented by u64, we have to do the typecasts
  1713. * to avoid signed overflow if it's [0, LLONG_MAX] eg. from fsync()
  1714. */
  1715. len = (u64)end - (u64)start + 1;
  1716. trace_btrfs_sync_file(file, datasync);
  1717. /*
  1718. * We write the dirty pages in the range and wait until they complete
  1719. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1720. * multi-task, and make the performance up. See
  1721. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1722. */
  1723. ret = start_ordered_ops(inode, start, end);
  1724. if (ret)
  1725. return ret;
  1726. inode_lock(inode);
  1727. atomic_inc(&root->log_batch);
  1728. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1729. &BTRFS_I(inode)->runtime_flags);
  1730. /*
  1731. * We might have have had more pages made dirty after calling
  1732. * start_ordered_ops and before acquiring the inode's i_mutex.
  1733. */
  1734. if (full_sync) {
  1735. /*
  1736. * For a full sync, we need to make sure any ordered operations
  1737. * start and finish before we start logging the inode, so that
  1738. * all extents are persisted and the respective file extent
  1739. * items are in the fs/subvol btree.
  1740. */
  1741. ret = btrfs_wait_ordered_range(inode, start, len);
  1742. } else {
  1743. /*
  1744. * Start any new ordered operations before starting to log the
  1745. * inode. We will wait for them to finish in btrfs_sync_log().
  1746. *
  1747. * Right before acquiring the inode's mutex, we might have new
  1748. * writes dirtying pages, which won't immediately start the
  1749. * respective ordered operations - that is done through the
  1750. * fill_delalloc callbacks invoked from the writepage and
  1751. * writepages address space operations. So make sure we start
  1752. * all ordered operations before starting to log our inode. Not
  1753. * doing this means that while logging the inode, writeback
  1754. * could start and invoke writepage/writepages, which would call
  1755. * the fill_delalloc callbacks (cow_file_range,
  1756. * submit_compressed_extents). These callbacks add first an
  1757. * extent map to the modified list of extents and then create
  1758. * the respective ordered operation, which means in
  1759. * tree-log.c:btrfs_log_inode() we might capture all existing
  1760. * ordered operations (with btrfs_get_logged_extents()) before
  1761. * the fill_delalloc callback adds its ordered operation, and by
  1762. * the time we visit the modified list of extent maps (with
  1763. * btrfs_log_changed_extents()), we see and process the extent
  1764. * map they created. We then use the extent map to construct a
  1765. * file extent item for logging without waiting for the
  1766. * respective ordered operation to finish - this file extent
  1767. * item points to a disk location that might not have yet been
  1768. * written to, containing random data - so after a crash a log
  1769. * replay will make our inode have file extent items that point
  1770. * to disk locations containing invalid data, as we returned
  1771. * success to userspace without waiting for the respective
  1772. * ordered operation to finish, because it wasn't captured by
  1773. * btrfs_get_logged_extents().
  1774. */
  1775. ret = start_ordered_ops(inode, start, end);
  1776. }
  1777. if (ret) {
  1778. inode_unlock(inode);
  1779. goto out;
  1780. }
  1781. atomic_inc(&root->log_batch);
  1782. /*
  1783. * If the last transaction that changed this file was before the current
  1784. * transaction and we have the full sync flag set in our inode, we can
  1785. * bail out now without any syncing.
  1786. *
  1787. * Note that we can't bail out if the full sync flag isn't set. This is
  1788. * because when the full sync flag is set we start all ordered extents
  1789. * and wait for them to fully complete - when they complete they update
  1790. * the inode's last_trans field through:
  1791. *
  1792. * btrfs_finish_ordered_io() ->
  1793. * btrfs_update_inode_fallback() ->
  1794. * btrfs_update_inode() ->
  1795. * btrfs_set_inode_last_trans()
  1796. *
  1797. * So we are sure that last_trans is up to date and can do this check to
  1798. * bail out safely. For the fast path, when the full sync flag is not
  1799. * set in our inode, we can not do it because we start only our ordered
  1800. * extents and don't wait for them to complete (that is when
  1801. * btrfs_finish_ordered_io runs), so here at this point their last_trans
  1802. * value might be less than or equals to fs_info->last_trans_committed,
  1803. * and setting a speculative last_trans for an inode when a buffered
  1804. * write is made (such as fs_info->generation + 1 for example) would not
  1805. * be reliable since after setting the value and before fsync is called
  1806. * any number of transactions can start and commit (transaction kthread
  1807. * commits the current transaction periodically), and a transaction
  1808. * commit does not start nor waits for ordered extents to complete.
  1809. */
  1810. smp_mb();
  1811. if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
  1812. (full_sync && BTRFS_I(inode)->last_trans <=
  1813. root->fs_info->last_trans_committed) ||
  1814. (!btrfs_have_ordered_extents_in_range(inode, start, len) &&
  1815. BTRFS_I(inode)->last_trans
  1816. <= root->fs_info->last_trans_committed)) {
  1817. /*
  1818. * We've had everything committed since the last time we were
  1819. * modified so clear this flag in case it was set for whatever
  1820. * reason, it's no longer relevant.
  1821. */
  1822. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1823. &BTRFS_I(inode)->runtime_flags);
  1824. /*
  1825. * An ordered extent might have started before and completed
  1826. * already with io errors, in which case the inode was not
  1827. * updated and we end up here. So check the inode's mapping
  1828. * flags for any errors that might have happened while doing
  1829. * writeback of file data.
  1830. */
  1831. ret = btrfs_inode_check_errors(inode);
  1832. inode_unlock(inode);
  1833. goto out;
  1834. }
  1835. /*
  1836. * ok we haven't committed the transaction yet, lets do a commit
  1837. */
  1838. if (file->private_data)
  1839. btrfs_ioctl_trans_end(file);
  1840. /*
  1841. * We use start here because we will need to wait on the IO to complete
  1842. * in btrfs_sync_log, which could require joining a transaction (for
  1843. * example checking cross references in the nocow path). If we use join
  1844. * here we could get into a situation where we're waiting on IO to
  1845. * happen that is blocked on a transaction trying to commit. With start
  1846. * we inc the extwriter counter, so we wait for all extwriters to exit
  1847. * before we start blocking join'ers. This comment is to keep somebody
  1848. * from thinking they are super smart and changing this to
  1849. * btrfs_join_transaction *cough*Josef*cough*.
  1850. */
  1851. trans = btrfs_start_transaction(root, 0);
  1852. if (IS_ERR(trans)) {
  1853. ret = PTR_ERR(trans);
  1854. inode_unlock(inode);
  1855. goto out;
  1856. }
  1857. trans->sync = true;
  1858. btrfs_init_log_ctx(&ctx);
  1859. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1860. if (ret < 0) {
  1861. /* Fallthrough and commit/free transaction. */
  1862. ret = 1;
  1863. }
  1864. /* we've logged all the items and now have a consistent
  1865. * version of the file in the log. It is possible that
  1866. * someone will come in and modify the file, but that's
  1867. * fine because the log is consistent on disk, and we
  1868. * have references to all of the file's extents
  1869. *
  1870. * It is possible that someone will come in and log the
  1871. * file again, but that will end up using the synchronization
  1872. * inside btrfs_sync_log to keep things safe.
  1873. */
  1874. inode_unlock(inode);
  1875. /*
  1876. * If any of the ordered extents had an error, just return it to user
  1877. * space, so that the application knows some writes didn't succeed and
  1878. * can take proper action (retry for e.g.). Blindly committing the
  1879. * transaction in this case, would fool userspace that everything was
  1880. * successful. And we also want to make sure our log doesn't contain
  1881. * file extent items pointing to extents that weren't fully written to -
  1882. * just like in the non fast fsync path, where we check for the ordered
  1883. * operation's error flag before writing to the log tree and return -EIO
  1884. * if any of them had this flag set (btrfs_wait_ordered_range) -
  1885. * therefore we need to check for errors in the ordered operations,
  1886. * which are indicated by ctx.io_err.
  1887. */
  1888. if (ctx.io_err) {
  1889. btrfs_end_transaction(trans, root);
  1890. ret = ctx.io_err;
  1891. goto out;
  1892. }
  1893. if (ret != BTRFS_NO_LOG_SYNC) {
  1894. if (!ret) {
  1895. ret = btrfs_sync_log(trans, root, &ctx);
  1896. if (!ret) {
  1897. ret = btrfs_end_transaction(trans, root);
  1898. goto out;
  1899. }
  1900. }
  1901. if (!full_sync) {
  1902. ret = btrfs_wait_ordered_range(inode, start, len);
  1903. if (ret) {
  1904. btrfs_end_transaction(trans, root);
  1905. goto out;
  1906. }
  1907. }
  1908. ret = btrfs_commit_transaction(trans, root);
  1909. } else {
  1910. ret = btrfs_end_transaction(trans, root);
  1911. }
  1912. out:
  1913. return ret > 0 ? -EIO : ret;
  1914. }
  1915. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1916. .fault = filemap_fault,
  1917. .map_pages = filemap_map_pages,
  1918. .page_mkwrite = btrfs_page_mkwrite,
  1919. };
  1920. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1921. {
  1922. struct address_space *mapping = filp->f_mapping;
  1923. if (!mapping->a_ops->readpage)
  1924. return -ENOEXEC;
  1925. file_accessed(filp);
  1926. vma->vm_ops = &btrfs_file_vm_ops;
  1927. return 0;
  1928. }
  1929. static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
  1930. int slot, u64 start, u64 end)
  1931. {
  1932. struct btrfs_file_extent_item *fi;
  1933. struct btrfs_key key;
  1934. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1935. return 0;
  1936. btrfs_item_key_to_cpu(leaf, &key, slot);
  1937. if (key.objectid != btrfs_ino(inode) ||
  1938. key.type != BTRFS_EXTENT_DATA_KEY)
  1939. return 0;
  1940. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1941. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1942. return 0;
  1943. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1944. return 0;
  1945. if (key.offset == end)
  1946. return 1;
  1947. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1948. return 1;
  1949. return 0;
  1950. }
  1951. static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
  1952. struct btrfs_path *path, u64 offset, u64 end)
  1953. {
  1954. struct btrfs_root *root = BTRFS_I(inode)->root;
  1955. struct extent_buffer *leaf;
  1956. struct btrfs_file_extent_item *fi;
  1957. struct extent_map *hole_em;
  1958. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  1959. struct btrfs_key key;
  1960. int ret;
  1961. if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
  1962. goto out;
  1963. key.objectid = btrfs_ino(inode);
  1964. key.type = BTRFS_EXTENT_DATA_KEY;
  1965. key.offset = offset;
  1966. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1967. if (ret < 0)
  1968. return ret;
  1969. BUG_ON(!ret);
  1970. leaf = path->nodes[0];
  1971. if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
  1972. u64 num_bytes;
  1973. path->slots[0]--;
  1974. fi = btrfs_item_ptr(leaf, path->slots[0],
  1975. struct btrfs_file_extent_item);
  1976. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1977. end - offset;
  1978. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1979. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1980. btrfs_set_file_extent_offset(leaf, fi, 0);
  1981. btrfs_mark_buffer_dirty(leaf);
  1982. goto out;
  1983. }
  1984. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1985. u64 num_bytes;
  1986. key.offset = offset;
  1987. btrfs_set_item_key_safe(root->fs_info, path, &key);
  1988. fi = btrfs_item_ptr(leaf, path->slots[0],
  1989. struct btrfs_file_extent_item);
  1990. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1991. offset;
  1992. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1993. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1994. btrfs_set_file_extent_offset(leaf, fi, 0);
  1995. btrfs_mark_buffer_dirty(leaf);
  1996. goto out;
  1997. }
  1998. btrfs_release_path(path);
  1999. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
  2000. 0, 0, end - offset, 0, end - offset,
  2001. 0, 0, 0);
  2002. if (ret)
  2003. return ret;
  2004. out:
  2005. btrfs_release_path(path);
  2006. hole_em = alloc_extent_map();
  2007. if (!hole_em) {
  2008. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2009. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2010. &BTRFS_I(inode)->runtime_flags);
  2011. } else {
  2012. hole_em->start = offset;
  2013. hole_em->len = end - offset;
  2014. hole_em->ram_bytes = hole_em->len;
  2015. hole_em->orig_start = offset;
  2016. hole_em->block_start = EXTENT_MAP_HOLE;
  2017. hole_em->block_len = 0;
  2018. hole_em->orig_block_len = 0;
  2019. hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
  2020. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  2021. hole_em->generation = trans->transid;
  2022. do {
  2023. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2024. write_lock(&em_tree->lock);
  2025. ret = add_extent_mapping(em_tree, hole_em, 1);
  2026. write_unlock(&em_tree->lock);
  2027. } while (ret == -EEXIST);
  2028. free_extent_map(hole_em);
  2029. if (ret)
  2030. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2031. &BTRFS_I(inode)->runtime_flags);
  2032. }
  2033. return 0;
  2034. }
  2035. /*
  2036. * Find a hole extent on given inode and change start/len to the end of hole
  2037. * extent.(hole/vacuum extent whose em->start <= start &&
  2038. * em->start + em->len > start)
  2039. * When a hole extent is found, return 1 and modify start/len.
  2040. */
  2041. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  2042. {
  2043. struct extent_map *em;
  2044. int ret = 0;
  2045. em = btrfs_get_extent(inode, NULL, 0, *start, *len, 0);
  2046. if (IS_ERR_OR_NULL(em)) {
  2047. if (!em)
  2048. ret = -ENOMEM;
  2049. else
  2050. ret = PTR_ERR(em);
  2051. return ret;
  2052. }
  2053. /* Hole or vacuum extent(only exists in no-hole mode) */
  2054. if (em->block_start == EXTENT_MAP_HOLE) {
  2055. ret = 1;
  2056. *len = em->start + em->len > *start + *len ?
  2057. 0 : *start + *len - em->start - em->len;
  2058. *start = em->start + em->len;
  2059. }
  2060. free_extent_map(em);
  2061. return ret;
  2062. }
  2063. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2064. {
  2065. struct btrfs_root *root = BTRFS_I(inode)->root;
  2066. struct extent_state *cached_state = NULL;
  2067. struct btrfs_path *path;
  2068. struct btrfs_block_rsv *rsv;
  2069. struct btrfs_trans_handle *trans;
  2070. u64 lockstart;
  2071. u64 lockend;
  2072. u64 tail_start;
  2073. u64 tail_len;
  2074. u64 orig_start = offset;
  2075. u64 cur_offset;
  2076. u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
  2077. u64 drop_end;
  2078. int ret = 0;
  2079. int err = 0;
  2080. unsigned int rsv_count;
  2081. bool same_block;
  2082. bool no_holes = btrfs_fs_incompat(root->fs_info, NO_HOLES);
  2083. u64 ino_size;
  2084. bool truncated_block = false;
  2085. bool updated_inode = false;
  2086. ret = btrfs_wait_ordered_range(inode, offset, len);
  2087. if (ret)
  2088. return ret;
  2089. inode_lock(inode);
  2090. ino_size = round_up(inode->i_size, root->sectorsize);
  2091. ret = find_first_non_hole(inode, &offset, &len);
  2092. if (ret < 0)
  2093. goto out_only_mutex;
  2094. if (ret && !len) {
  2095. /* Already in a large hole */
  2096. ret = 0;
  2097. goto out_only_mutex;
  2098. }
  2099. lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
  2100. lockend = round_down(offset + len,
  2101. BTRFS_I(inode)->root->sectorsize) - 1;
  2102. same_block = (BTRFS_BYTES_TO_BLKS(root->fs_info, offset))
  2103. == (BTRFS_BYTES_TO_BLKS(root->fs_info, offset + len - 1));
  2104. /*
  2105. * We needn't truncate any block which is beyond the end of the file
  2106. * because we are sure there is no data there.
  2107. */
  2108. /*
  2109. * Only do this if we are in the same block and we aren't doing the
  2110. * entire block.
  2111. */
  2112. if (same_block && len < root->sectorsize) {
  2113. if (offset < ino_size) {
  2114. truncated_block = true;
  2115. ret = btrfs_truncate_block(inode, offset, len, 0);
  2116. } else {
  2117. ret = 0;
  2118. }
  2119. goto out_only_mutex;
  2120. }
  2121. /* zero back part of the first block */
  2122. if (offset < ino_size) {
  2123. truncated_block = true;
  2124. ret = btrfs_truncate_block(inode, offset, 0, 0);
  2125. if (ret) {
  2126. inode_unlock(inode);
  2127. return ret;
  2128. }
  2129. }
  2130. /* Check the aligned pages after the first unaligned page,
  2131. * if offset != orig_start, which means the first unaligned page
  2132. * including several following pages are already in holes,
  2133. * the extra check can be skipped */
  2134. if (offset == orig_start) {
  2135. /* after truncate page, check hole again */
  2136. len = offset + len - lockstart;
  2137. offset = lockstart;
  2138. ret = find_first_non_hole(inode, &offset, &len);
  2139. if (ret < 0)
  2140. goto out_only_mutex;
  2141. if (ret && !len) {
  2142. ret = 0;
  2143. goto out_only_mutex;
  2144. }
  2145. lockstart = offset;
  2146. }
  2147. /* Check the tail unaligned part is in a hole */
  2148. tail_start = lockend + 1;
  2149. tail_len = offset + len - tail_start;
  2150. if (tail_len) {
  2151. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2152. if (unlikely(ret < 0))
  2153. goto out_only_mutex;
  2154. if (!ret) {
  2155. /* zero the front end of the last page */
  2156. if (tail_start + tail_len < ino_size) {
  2157. truncated_block = true;
  2158. ret = btrfs_truncate_block(inode,
  2159. tail_start + tail_len,
  2160. 0, 1);
  2161. if (ret)
  2162. goto out_only_mutex;
  2163. }
  2164. }
  2165. }
  2166. if (lockend < lockstart) {
  2167. ret = 0;
  2168. goto out_only_mutex;
  2169. }
  2170. while (1) {
  2171. struct btrfs_ordered_extent *ordered;
  2172. truncate_pagecache_range(inode, lockstart, lockend);
  2173. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2174. &cached_state);
  2175. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2176. /*
  2177. * We need to make sure we have no ordered extents in this range
  2178. * and nobody raced in and read a page in this range, if we did
  2179. * we need to try again.
  2180. */
  2181. if ((!ordered ||
  2182. (ordered->file_offset + ordered->len <= lockstart ||
  2183. ordered->file_offset > lockend)) &&
  2184. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2185. if (ordered)
  2186. btrfs_put_ordered_extent(ordered);
  2187. break;
  2188. }
  2189. if (ordered)
  2190. btrfs_put_ordered_extent(ordered);
  2191. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2192. lockend, &cached_state, GFP_NOFS);
  2193. ret = btrfs_wait_ordered_range(inode, lockstart,
  2194. lockend - lockstart + 1);
  2195. if (ret) {
  2196. inode_unlock(inode);
  2197. return ret;
  2198. }
  2199. }
  2200. path = btrfs_alloc_path();
  2201. if (!path) {
  2202. ret = -ENOMEM;
  2203. goto out;
  2204. }
  2205. rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
  2206. if (!rsv) {
  2207. ret = -ENOMEM;
  2208. goto out_free;
  2209. }
  2210. rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
  2211. rsv->failfast = 1;
  2212. /*
  2213. * 1 - update the inode
  2214. * 1 - removing the extents in the range
  2215. * 1 - adding the hole extent if no_holes isn't set
  2216. */
  2217. rsv_count = no_holes ? 2 : 3;
  2218. trans = btrfs_start_transaction(root, rsv_count);
  2219. if (IS_ERR(trans)) {
  2220. err = PTR_ERR(trans);
  2221. goto out_free;
  2222. }
  2223. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
  2224. min_size, 0);
  2225. BUG_ON(ret);
  2226. trans->block_rsv = rsv;
  2227. cur_offset = lockstart;
  2228. len = lockend - cur_offset;
  2229. while (cur_offset < lockend) {
  2230. ret = __btrfs_drop_extents(trans, root, inode, path,
  2231. cur_offset, lockend + 1,
  2232. &drop_end, 1, 0, 0, NULL);
  2233. if (ret != -ENOSPC)
  2234. break;
  2235. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2236. if (cur_offset < ino_size) {
  2237. ret = fill_holes(trans, inode, path, cur_offset,
  2238. drop_end);
  2239. if (ret) {
  2240. err = ret;
  2241. break;
  2242. }
  2243. }
  2244. cur_offset = drop_end;
  2245. ret = btrfs_update_inode(trans, root, inode);
  2246. if (ret) {
  2247. err = ret;
  2248. break;
  2249. }
  2250. btrfs_end_transaction(trans, root);
  2251. btrfs_btree_balance_dirty(root);
  2252. trans = btrfs_start_transaction(root, rsv_count);
  2253. if (IS_ERR(trans)) {
  2254. ret = PTR_ERR(trans);
  2255. trans = NULL;
  2256. break;
  2257. }
  2258. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
  2259. rsv, min_size, 0);
  2260. BUG_ON(ret); /* shouldn't happen */
  2261. trans->block_rsv = rsv;
  2262. ret = find_first_non_hole(inode, &cur_offset, &len);
  2263. if (unlikely(ret < 0))
  2264. break;
  2265. if (ret && !len) {
  2266. ret = 0;
  2267. break;
  2268. }
  2269. }
  2270. if (ret) {
  2271. err = ret;
  2272. goto out_trans;
  2273. }
  2274. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2275. /*
  2276. * If we are using the NO_HOLES feature we might have had already an
  2277. * hole that overlaps a part of the region [lockstart, lockend] and
  2278. * ends at (or beyond) lockend. Since we have no file extent items to
  2279. * represent holes, drop_end can be less than lockend and so we must
  2280. * make sure we have an extent map representing the existing hole (the
  2281. * call to __btrfs_drop_extents() might have dropped the existing extent
  2282. * map representing the existing hole), otherwise the fast fsync path
  2283. * will not record the existence of the hole region
  2284. * [existing_hole_start, lockend].
  2285. */
  2286. if (drop_end <= lockend)
  2287. drop_end = lockend + 1;
  2288. /*
  2289. * Don't insert file hole extent item if it's for a range beyond eof
  2290. * (because it's useless) or if it represents a 0 bytes range (when
  2291. * cur_offset == drop_end).
  2292. */
  2293. if (cur_offset < ino_size && cur_offset < drop_end) {
  2294. ret = fill_holes(trans, inode, path, cur_offset, drop_end);
  2295. if (ret) {
  2296. err = ret;
  2297. goto out_trans;
  2298. }
  2299. }
  2300. out_trans:
  2301. if (!trans)
  2302. goto out_free;
  2303. inode_inc_iversion(inode);
  2304. inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb);
  2305. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2306. ret = btrfs_update_inode(trans, root, inode);
  2307. updated_inode = true;
  2308. btrfs_end_transaction(trans, root);
  2309. btrfs_btree_balance_dirty(root);
  2310. out_free:
  2311. btrfs_free_path(path);
  2312. btrfs_free_block_rsv(root, rsv);
  2313. out:
  2314. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2315. &cached_state, GFP_NOFS);
  2316. out_only_mutex:
  2317. if (!updated_inode && truncated_block && !ret && !err) {
  2318. /*
  2319. * If we only end up zeroing part of a page, we still need to
  2320. * update the inode item, so that all the time fields are
  2321. * updated as well as the necessary btrfs inode in memory fields
  2322. * for detecting, at fsync time, if the inode isn't yet in the
  2323. * log tree or it's there but not up to date.
  2324. */
  2325. trans = btrfs_start_transaction(root, 1);
  2326. if (IS_ERR(trans)) {
  2327. err = PTR_ERR(trans);
  2328. } else {
  2329. err = btrfs_update_inode(trans, root, inode);
  2330. ret = btrfs_end_transaction(trans, root);
  2331. }
  2332. }
  2333. inode_unlock(inode);
  2334. if (ret && !err)
  2335. err = ret;
  2336. return err;
  2337. }
  2338. /* Helper structure to record which range is already reserved */
  2339. struct falloc_range {
  2340. struct list_head list;
  2341. u64 start;
  2342. u64 len;
  2343. };
  2344. /*
  2345. * Helper function to add falloc range
  2346. *
  2347. * Caller should have locked the larger range of extent containing
  2348. * [start, len)
  2349. */
  2350. static int add_falloc_range(struct list_head *head, u64 start, u64 len)
  2351. {
  2352. struct falloc_range *prev = NULL;
  2353. struct falloc_range *range = NULL;
  2354. if (list_empty(head))
  2355. goto insert;
  2356. /*
  2357. * As fallocate iterate by bytenr order, we only need to check
  2358. * the last range.
  2359. */
  2360. prev = list_entry(head->prev, struct falloc_range, list);
  2361. if (prev->start + prev->len == start) {
  2362. prev->len += len;
  2363. return 0;
  2364. }
  2365. insert:
  2366. range = kmalloc(sizeof(*range), GFP_KERNEL);
  2367. if (!range)
  2368. return -ENOMEM;
  2369. range->start = start;
  2370. range->len = len;
  2371. list_add_tail(&range->list, head);
  2372. return 0;
  2373. }
  2374. static long btrfs_fallocate(struct file *file, int mode,
  2375. loff_t offset, loff_t len)
  2376. {
  2377. struct inode *inode = file_inode(file);
  2378. struct extent_state *cached_state = NULL;
  2379. struct falloc_range *range;
  2380. struct falloc_range *tmp;
  2381. struct list_head reserve_list;
  2382. u64 cur_offset;
  2383. u64 last_byte;
  2384. u64 alloc_start;
  2385. u64 alloc_end;
  2386. u64 alloc_hint = 0;
  2387. u64 locked_end;
  2388. u64 actual_end = 0;
  2389. struct extent_map *em;
  2390. int blocksize = BTRFS_I(inode)->root->sectorsize;
  2391. int ret;
  2392. alloc_start = round_down(offset, blocksize);
  2393. alloc_end = round_up(offset + len, blocksize);
  2394. /* Make sure we aren't being give some crap mode */
  2395. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2396. return -EOPNOTSUPP;
  2397. if (mode & FALLOC_FL_PUNCH_HOLE)
  2398. return btrfs_punch_hole(inode, offset, len);
  2399. /*
  2400. * Only trigger disk allocation, don't trigger qgroup reserve
  2401. *
  2402. * For qgroup space, it will be checked later.
  2403. */
  2404. ret = btrfs_alloc_data_chunk_ondemand(inode, alloc_end - alloc_start);
  2405. if (ret < 0)
  2406. return ret;
  2407. inode_lock(inode);
  2408. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
  2409. ret = inode_newsize_ok(inode, offset + len);
  2410. if (ret)
  2411. goto out;
  2412. }
  2413. /*
  2414. * TODO: Move these two operations after we have checked
  2415. * accurate reserved space, or fallocate can still fail but
  2416. * with page truncated or size expanded.
  2417. *
  2418. * But that's a minor problem and won't do much harm BTW.
  2419. */
  2420. if (alloc_start > inode->i_size) {
  2421. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2422. alloc_start);
  2423. if (ret)
  2424. goto out;
  2425. } else if (offset + len > inode->i_size) {
  2426. /*
  2427. * If we are fallocating from the end of the file onward we
  2428. * need to zero out the end of the block if i_size lands in the
  2429. * middle of a block.
  2430. */
  2431. ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
  2432. if (ret)
  2433. goto out;
  2434. }
  2435. /*
  2436. * wait for ordered IO before we have any locks. We'll loop again
  2437. * below with the locks held.
  2438. */
  2439. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2440. alloc_end - alloc_start);
  2441. if (ret)
  2442. goto out;
  2443. locked_end = alloc_end - 1;
  2444. while (1) {
  2445. struct btrfs_ordered_extent *ordered;
  2446. /* the extent lock is ordered inside the running
  2447. * transaction
  2448. */
  2449. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2450. locked_end, &cached_state);
  2451. ordered = btrfs_lookup_first_ordered_extent(inode,
  2452. alloc_end - 1);
  2453. if (ordered &&
  2454. ordered->file_offset + ordered->len > alloc_start &&
  2455. ordered->file_offset < alloc_end) {
  2456. btrfs_put_ordered_extent(ordered);
  2457. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2458. alloc_start, locked_end,
  2459. &cached_state, GFP_KERNEL);
  2460. /*
  2461. * we can't wait on the range with the transaction
  2462. * running or with the extent lock held
  2463. */
  2464. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2465. alloc_end - alloc_start);
  2466. if (ret)
  2467. goto out;
  2468. } else {
  2469. if (ordered)
  2470. btrfs_put_ordered_extent(ordered);
  2471. break;
  2472. }
  2473. }
  2474. /* First, check if we exceed the qgroup limit */
  2475. INIT_LIST_HEAD(&reserve_list);
  2476. cur_offset = alloc_start;
  2477. while (1) {
  2478. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  2479. alloc_end - cur_offset, 0);
  2480. if (IS_ERR_OR_NULL(em)) {
  2481. if (!em)
  2482. ret = -ENOMEM;
  2483. else
  2484. ret = PTR_ERR(em);
  2485. break;
  2486. }
  2487. last_byte = min(extent_map_end(em), alloc_end);
  2488. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2489. last_byte = ALIGN(last_byte, blocksize);
  2490. if (em->block_start == EXTENT_MAP_HOLE ||
  2491. (cur_offset >= inode->i_size &&
  2492. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2493. ret = add_falloc_range(&reserve_list, cur_offset,
  2494. last_byte - cur_offset);
  2495. if (ret < 0) {
  2496. free_extent_map(em);
  2497. break;
  2498. }
  2499. ret = btrfs_qgroup_reserve_data(inode, cur_offset,
  2500. last_byte - cur_offset);
  2501. if (ret < 0)
  2502. break;
  2503. }
  2504. free_extent_map(em);
  2505. cur_offset = last_byte;
  2506. if (cur_offset >= alloc_end)
  2507. break;
  2508. }
  2509. /*
  2510. * If ret is still 0, means we're OK to fallocate.
  2511. * Or just cleanup the list and exit.
  2512. */
  2513. list_for_each_entry_safe(range, tmp, &reserve_list, list) {
  2514. if (!ret)
  2515. ret = btrfs_prealloc_file_range(inode, mode,
  2516. range->start,
  2517. range->len, 1 << inode->i_blkbits,
  2518. offset + len, &alloc_hint);
  2519. list_del(&range->list);
  2520. kfree(range);
  2521. }
  2522. if (ret < 0)
  2523. goto out_unlock;
  2524. if (actual_end > inode->i_size &&
  2525. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2526. struct btrfs_trans_handle *trans;
  2527. struct btrfs_root *root = BTRFS_I(inode)->root;
  2528. /*
  2529. * We didn't need to allocate any more space, but we
  2530. * still extended the size of the file so we need to
  2531. * update i_size and the inode item.
  2532. */
  2533. trans = btrfs_start_transaction(root, 1);
  2534. if (IS_ERR(trans)) {
  2535. ret = PTR_ERR(trans);
  2536. } else {
  2537. inode->i_ctime = current_fs_time(inode->i_sb);
  2538. i_size_write(inode, actual_end);
  2539. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2540. ret = btrfs_update_inode(trans, root, inode);
  2541. if (ret)
  2542. btrfs_end_transaction(trans, root);
  2543. else
  2544. ret = btrfs_end_transaction(trans, root);
  2545. }
  2546. }
  2547. out_unlock:
  2548. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2549. &cached_state, GFP_KERNEL);
  2550. out:
  2551. /*
  2552. * As we waited the extent range, the data_rsv_map must be empty
  2553. * in the range, as written data range will be released from it.
  2554. * And for prealloacted extent, it will also be released when
  2555. * its metadata is written.
  2556. * So this is completely used as cleanup.
  2557. */
  2558. btrfs_qgroup_free_data(inode, alloc_start, alloc_end - alloc_start);
  2559. inode_unlock(inode);
  2560. /* Let go of our reservation. */
  2561. btrfs_free_reserved_data_space(inode, alloc_start,
  2562. alloc_end - alloc_start);
  2563. return ret;
  2564. }
  2565. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2566. {
  2567. struct btrfs_root *root = BTRFS_I(inode)->root;
  2568. struct extent_map *em = NULL;
  2569. struct extent_state *cached_state = NULL;
  2570. u64 lockstart;
  2571. u64 lockend;
  2572. u64 start;
  2573. u64 len;
  2574. int ret = 0;
  2575. if (inode->i_size == 0)
  2576. return -ENXIO;
  2577. /*
  2578. * *offset can be negative, in this case we start finding DATA/HOLE from
  2579. * the very start of the file.
  2580. */
  2581. start = max_t(loff_t, 0, *offset);
  2582. lockstart = round_down(start, root->sectorsize);
  2583. lockend = round_up(i_size_read(inode), root->sectorsize);
  2584. if (lockend <= lockstart)
  2585. lockend = lockstart + root->sectorsize;
  2586. lockend--;
  2587. len = lockend - lockstart + 1;
  2588. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2589. &cached_state);
  2590. while (start < inode->i_size) {
  2591. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  2592. if (IS_ERR(em)) {
  2593. ret = PTR_ERR(em);
  2594. em = NULL;
  2595. break;
  2596. }
  2597. if (whence == SEEK_HOLE &&
  2598. (em->block_start == EXTENT_MAP_HOLE ||
  2599. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2600. break;
  2601. else if (whence == SEEK_DATA &&
  2602. (em->block_start != EXTENT_MAP_HOLE &&
  2603. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2604. break;
  2605. start = em->start + em->len;
  2606. free_extent_map(em);
  2607. em = NULL;
  2608. cond_resched();
  2609. }
  2610. free_extent_map(em);
  2611. if (!ret) {
  2612. if (whence == SEEK_DATA && start >= inode->i_size)
  2613. ret = -ENXIO;
  2614. else
  2615. *offset = min_t(loff_t, start, inode->i_size);
  2616. }
  2617. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2618. &cached_state, GFP_NOFS);
  2619. return ret;
  2620. }
  2621. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2622. {
  2623. struct inode *inode = file->f_mapping->host;
  2624. int ret;
  2625. inode_lock(inode);
  2626. switch (whence) {
  2627. case SEEK_END:
  2628. case SEEK_CUR:
  2629. offset = generic_file_llseek(file, offset, whence);
  2630. goto out;
  2631. case SEEK_DATA:
  2632. case SEEK_HOLE:
  2633. if (offset >= i_size_read(inode)) {
  2634. inode_unlock(inode);
  2635. return -ENXIO;
  2636. }
  2637. ret = find_desired_extent(inode, &offset, whence);
  2638. if (ret) {
  2639. inode_unlock(inode);
  2640. return ret;
  2641. }
  2642. }
  2643. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2644. out:
  2645. inode_unlock(inode);
  2646. return offset;
  2647. }
  2648. const struct file_operations btrfs_file_operations = {
  2649. .llseek = btrfs_file_llseek,
  2650. .read_iter = generic_file_read_iter,
  2651. .splice_read = generic_file_splice_read,
  2652. .write_iter = btrfs_file_write_iter,
  2653. .mmap = btrfs_file_mmap,
  2654. .open = generic_file_open,
  2655. .release = btrfs_release_file,
  2656. .fsync = btrfs_sync_file,
  2657. .fallocate = btrfs_fallocate,
  2658. .unlocked_ioctl = btrfs_ioctl,
  2659. #ifdef CONFIG_COMPAT
  2660. .compat_ioctl = btrfs_compat_ioctl,
  2661. #endif
  2662. .copy_file_range = btrfs_copy_file_range,
  2663. .clone_file_range = btrfs_clone_file_range,
  2664. .dedupe_file_range = btrfs_dedupe_file_range,
  2665. };
  2666. void btrfs_auto_defrag_exit(void)
  2667. {
  2668. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2669. }
  2670. int btrfs_auto_defrag_init(void)
  2671. {
  2672. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2673. sizeof(struct inode_defrag), 0,
  2674. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
  2675. NULL);
  2676. if (!btrfs_inode_defrag_cachep)
  2677. return -ENOMEM;
  2678. return 0;
  2679. }
  2680. int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
  2681. {
  2682. int ret;
  2683. /*
  2684. * So with compression we will find and lock a dirty page and clear the
  2685. * first one as dirty, setup an async extent, and immediately return
  2686. * with the entire range locked but with nobody actually marked with
  2687. * writeback. So we can't just filemap_write_and_wait_range() and
  2688. * expect it to work since it will just kick off a thread to do the
  2689. * actual work. So we need to call filemap_fdatawrite_range _again_
  2690. * since it will wait on the page lock, which won't be unlocked until
  2691. * after the pages have been marked as writeback and so we're good to go
  2692. * from there. We have to do this otherwise we'll miss the ordered
  2693. * extents and that results in badness. Please Josef, do not think you
  2694. * know better and pull this out at some point in the future, it is
  2695. * right and you are wrong.
  2696. */
  2697. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2698. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  2699. &BTRFS_I(inode)->runtime_flags))
  2700. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2701. return ret;
  2702. }