file.c 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183
  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/compat.h>
  30. #include <linux/slab.h>
  31. #include <linux/btrfs.h>
  32. #include <linux/uio.h>
  33. #include "ctree.h"
  34. #include "disk-io.h"
  35. #include "transaction.h"
  36. #include "btrfs_inode.h"
  37. #include "print-tree.h"
  38. #include "tree-log.h"
  39. #include "locking.h"
  40. #include "volumes.h"
  41. #include "qgroup.h"
  42. #include "compression.h"
  43. static struct kmem_cache *btrfs_inode_defrag_cachep;
  44. /*
  45. * when auto defrag is enabled we
  46. * queue up these defrag structs to remember which
  47. * inodes need defragging passes
  48. */
  49. struct inode_defrag {
  50. struct rb_node rb_node;
  51. /* objectid */
  52. u64 ino;
  53. /*
  54. * transid where the defrag was added, we search for
  55. * extents newer than this
  56. */
  57. u64 transid;
  58. /* root objectid */
  59. u64 root;
  60. /* last offset we were able to defrag */
  61. u64 last_offset;
  62. /* if we've wrapped around back to zero once already */
  63. int cycled;
  64. };
  65. static int __compare_inode_defrag(struct inode_defrag *defrag1,
  66. struct inode_defrag *defrag2)
  67. {
  68. if (defrag1->root > defrag2->root)
  69. return 1;
  70. else if (defrag1->root < defrag2->root)
  71. return -1;
  72. else if (defrag1->ino > defrag2->ino)
  73. return 1;
  74. else if (defrag1->ino < defrag2->ino)
  75. return -1;
  76. else
  77. return 0;
  78. }
  79. /* pop a record for an inode into the defrag tree. The lock
  80. * must be held already
  81. *
  82. * If you're inserting a record for an older transid than an
  83. * existing record, the transid already in the tree is lowered
  84. *
  85. * If an existing record is found the defrag item you
  86. * pass in is freed
  87. */
  88. static int __btrfs_add_inode_defrag(struct btrfs_inode *inode,
  89. struct inode_defrag *defrag)
  90. {
  91. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  92. struct inode_defrag *entry;
  93. struct rb_node **p;
  94. struct rb_node *parent = NULL;
  95. int ret;
  96. p = &fs_info->defrag_inodes.rb_node;
  97. while (*p) {
  98. parent = *p;
  99. entry = rb_entry(parent, struct inode_defrag, rb_node);
  100. ret = __compare_inode_defrag(defrag, entry);
  101. if (ret < 0)
  102. p = &parent->rb_left;
  103. else if (ret > 0)
  104. p = &parent->rb_right;
  105. else {
  106. /* if we're reinserting an entry for
  107. * an old defrag run, make sure to
  108. * lower the transid of our existing record
  109. */
  110. if (defrag->transid < entry->transid)
  111. entry->transid = defrag->transid;
  112. if (defrag->last_offset > entry->last_offset)
  113. entry->last_offset = defrag->last_offset;
  114. return -EEXIST;
  115. }
  116. }
  117. set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
  118. rb_link_node(&defrag->rb_node, parent, p);
  119. rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
  120. return 0;
  121. }
  122. static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info)
  123. {
  124. if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
  125. return 0;
  126. if (btrfs_fs_closing(fs_info))
  127. return 0;
  128. return 1;
  129. }
  130. /*
  131. * insert a defrag record for this inode if auto defrag is
  132. * enabled
  133. */
  134. int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
  135. struct btrfs_inode *inode)
  136. {
  137. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  138. struct btrfs_root *root = inode->root;
  139. struct inode_defrag *defrag;
  140. u64 transid;
  141. int ret;
  142. if (!__need_auto_defrag(fs_info))
  143. return 0;
  144. if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
  145. return 0;
  146. if (trans)
  147. transid = trans->transid;
  148. else
  149. transid = 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(&fs_info->defrag_inodes_lock);
  157. if (!test_bit(BTRFS_INODE_IN_DEFRAG, &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(&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 btrfs_inode *inode,
  178. struct inode_defrag *defrag)
  179. {
  180. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  181. int ret;
  182. if (!__need_auto_defrag(fs_info))
  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(&fs_info->defrag_inodes_lock);
  189. ret = __btrfs_add_inode_defrag(inode, defrag);
  190. spin_unlock(&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(BTRFS_I(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(BTRFS_I(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))
  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. static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
  425. const u64 start,
  426. const u64 len,
  427. struct extent_state **cached_state)
  428. {
  429. u64 search_start = start;
  430. const u64 end = start + len - 1;
  431. while (search_start < end) {
  432. const u64 search_len = end - search_start + 1;
  433. struct extent_map *em;
  434. u64 em_len;
  435. int ret = 0;
  436. em = btrfs_get_extent(inode, NULL, 0, search_start,
  437. search_len, 0);
  438. if (IS_ERR(em))
  439. return PTR_ERR(em);
  440. if (em->block_start != EXTENT_MAP_HOLE)
  441. goto next;
  442. em_len = em->len;
  443. if (em->start < search_start)
  444. em_len -= search_start - em->start;
  445. if (em_len > search_len)
  446. em_len = search_len;
  447. ret = set_extent_bit(&inode->io_tree, search_start,
  448. search_start + em_len - 1,
  449. EXTENT_DELALLOC_NEW,
  450. NULL, cached_state, GFP_NOFS);
  451. next:
  452. search_start = extent_map_end(em);
  453. free_extent_map(em);
  454. if (ret)
  455. return ret;
  456. }
  457. return 0;
  458. }
  459. /*
  460. * after copy_from_user, pages need to be dirtied and we need to make
  461. * sure holes are created between the current EOF and the start of
  462. * any next extents (if required).
  463. *
  464. * this also makes the decision about creating an inline extent vs
  465. * doing real data extents, marking pages dirty and delalloc as required.
  466. */
  467. int btrfs_dirty_pages(struct inode *inode, struct page **pages,
  468. size_t num_pages, loff_t pos, size_t write_bytes,
  469. struct extent_state **cached)
  470. {
  471. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  472. int err = 0;
  473. int i;
  474. u64 num_bytes;
  475. u64 start_pos;
  476. u64 end_of_last_block;
  477. u64 end_pos = pos + write_bytes;
  478. loff_t isize = i_size_read(inode);
  479. unsigned int extra_bits = 0;
  480. start_pos = pos & ~((u64) fs_info->sectorsize - 1);
  481. num_bytes = round_up(write_bytes + pos - start_pos,
  482. fs_info->sectorsize);
  483. end_of_last_block = start_pos + num_bytes - 1;
  484. if (!btrfs_is_free_space_inode(BTRFS_I(inode))) {
  485. if (start_pos >= isize &&
  486. !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)) {
  487. /*
  488. * There can't be any extents following eof in this case
  489. * so just set the delalloc new bit for the range
  490. * directly.
  491. */
  492. extra_bits |= EXTENT_DELALLOC_NEW;
  493. } else {
  494. err = btrfs_find_new_delalloc_bytes(BTRFS_I(inode),
  495. start_pos,
  496. num_bytes, cached);
  497. if (err)
  498. return err;
  499. }
  500. }
  501. err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
  502. extra_bits, cached, 0);
  503. if (err)
  504. return err;
  505. for (i = 0; i < num_pages; i++) {
  506. struct page *p = pages[i];
  507. SetPageUptodate(p);
  508. ClearPageChecked(p);
  509. set_page_dirty(p);
  510. }
  511. /*
  512. * we've only changed i_size in ram, and we haven't updated
  513. * the disk i_size. There is no need to log the inode
  514. * at this time.
  515. */
  516. if (end_pos > isize)
  517. i_size_write(inode, end_pos);
  518. return 0;
  519. }
  520. /*
  521. * this drops all the extents in the cache that intersect the range
  522. * [start, end]. Existing extents are split as required.
  523. */
  524. void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end,
  525. int skip_pinned)
  526. {
  527. struct extent_map *em;
  528. struct extent_map *split = NULL;
  529. struct extent_map *split2 = NULL;
  530. struct extent_map_tree *em_tree = &inode->extent_tree;
  531. u64 len = end - start + 1;
  532. u64 gen;
  533. int ret;
  534. int testend = 1;
  535. unsigned long flags;
  536. int compressed = 0;
  537. bool modified;
  538. WARN_ON(end < start);
  539. if (end == (u64)-1) {
  540. len = (u64)-1;
  541. testend = 0;
  542. }
  543. while (1) {
  544. int no_splits = 0;
  545. modified = false;
  546. if (!split)
  547. split = alloc_extent_map();
  548. if (!split2)
  549. split2 = alloc_extent_map();
  550. if (!split || !split2)
  551. no_splits = 1;
  552. write_lock(&em_tree->lock);
  553. em = lookup_extent_mapping(em_tree, start, len);
  554. if (!em) {
  555. write_unlock(&em_tree->lock);
  556. break;
  557. }
  558. flags = em->flags;
  559. gen = em->generation;
  560. if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
  561. if (testend && em->start + em->len >= start + len) {
  562. free_extent_map(em);
  563. write_unlock(&em_tree->lock);
  564. break;
  565. }
  566. start = em->start + em->len;
  567. if (testend)
  568. len = start + len - (em->start + em->len);
  569. free_extent_map(em);
  570. write_unlock(&em_tree->lock);
  571. continue;
  572. }
  573. compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  574. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  575. clear_bit(EXTENT_FLAG_LOGGING, &flags);
  576. modified = !list_empty(&em->list);
  577. if (no_splits)
  578. goto next;
  579. if (em->start < start) {
  580. split->start = em->start;
  581. split->len = start - em->start;
  582. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  583. split->orig_start = em->orig_start;
  584. split->block_start = em->block_start;
  585. if (compressed)
  586. split->block_len = em->block_len;
  587. else
  588. split->block_len = split->len;
  589. split->orig_block_len = max(split->block_len,
  590. em->orig_block_len);
  591. split->ram_bytes = em->ram_bytes;
  592. } else {
  593. split->orig_start = split->start;
  594. split->block_len = 0;
  595. split->block_start = em->block_start;
  596. split->orig_block_len = 0;
  597. split->ram_bytes = split->len;
  598. }
  599. split->generation = gen;
  600. split->bdev = em->bdev;
  601. split->flags = flags;
  602. split->compress_type = em->compress_type;
  603. replace_extent_mapping(em_tree, em, split, modified);
  604. free_extent_map(split);
  605. split = split2;
  606. split2 = NULL;
  607. }
  608. if (testend && em->start + em->len > start + len) {
  609. u64 diff = start + len - em->start;
  610. split->start = start + len;
  611. split->len = em->start + em->len - (start + len);
  612. split->bdev = em->bdev;
  613. split->flags = flags;
  614. split->compress_type = em->compress_type;
  615. split->generation = gen;
  616. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  617. split->orig_block_len = max(em->block_len,
  618. em->orig_block_len);
  619. split->ram_bytes = em->ram_bytes;
  620. if (compressed) {
  621. split->block_len = em->block_len;
  622. split->block_start = em->block_start;
  623. split->orig_start = em->orig_start;
  624. } else {
  625. split->block_len = split->len;
  626. split->block_start = em->block_start
  627. + diff;
  628. split->orig_start = em->orig_start;
  629. }
  630. } else {
  631. split->ram_bytes = split->len;
  632. split->orig_start = split->start;
  633. split->block_len = 0;
  634. split->block_start = em->block_start;
  635. split->orig_block_len = 0;
  636. }
  637. if (extent_map_in_tree(em)) {
  638. replace_extent_mapping(em_tree, em, split,
  639. modified);
  640. } else {
  641. ret = add_extent_mapping(em_tree, split,
  642. modified);
  643. ASSERT(ret == 0); /* Logic error */
  644. }
  645. free_extent_map(split);
  646. split = NULL;
  647. }
  648. next:
  649. if (extent_map_in_tree(em))
  650. remove_extent_mapping(em_tree, em);
  651. write_unlock(&em_tree->lock);
  652. /* once for us */
  653. free_extent_map(em);
  654. /* once for the tree*/
  655. free_extent_map(em);
  656. }
  657. if (split)
  658. free_extent_map(split);
  659. if (split2)
  660. free_extent_map(split2);
  661. }
  662. /*
  663. * this is very complex, but the basic idea is to drop all extents
  664. * in the range start - end. hint_block is filled in with a block number
  665. * that would be a good hint to the block allocator for this file.
  666. *
  667. * If an extent intersects the range but is not entirely inside the range
  668. * it is either truncated or split. Anything entirely inside the range
  669. * is deleted from the tree.
  670. */
  671. int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
  672. struct btrfs_root *root, struct inode *inode,
  673. struct btrfs_path *path, u64 start, u64 end,
  674. u64 *drop_end, int drop_cache,
  675. int replace_extent,
  676. u32 extent_item_size,
  677. int *key_inserted)
  678. {
  679. struct btrfs_fs_info *fs_info = root->fs_info;
  680. struct extent_buffer *leaf;
  681. struct btrfs_file_extent_item *fi;
  682. struct btrfs_key key;
  683. struct btrfs_key new_key;
  684. u64 ino = btrfs_ino(BTRFS_I(inode));
  685. u64 search_start = start;
  686. u64 disk_bytenr = 0;
  687. u64 num_bytes = 0;
  688. u64 extent_offset = 0;
  689. u64 extent_end = 0;
  690. u64 last_end = start;
  691. int del_nr = 0;
  692. int del_slot = 0;
  693. int extent_type;
  694. int recow;
  695. int ret;
  696. int modify_tree = -1;
  697. int update_refs;
  698. int found = 0;
  699. int leafs_visited = 0;
  700. if (drop_cache)
  701. btrfs_drop_extent_cache(BTRFS_I(inode), start, end - 1, 0);
  702. if (start >= BTRFS_I(inode)->disk_i_size && !replace_extent)
  703. modify_tree = 0;
  704. update_refs = (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  705. root == fs_info->tree_root);
  706. while (1) {
  707. recow = 0;
  708. ret = btrfs_lookup_file_extent(trans, root, path, ino,
  709. search_start, modify_tree);
  710. if (ret < 0)
  711. break;
  712. if (ret > 0 && path->slots[0] > 0 && search_start == start) {
  713. leaf = path->nodes[0];
  714. btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
  715. if (key.objectid == ino &&
  716. key.type == BTRFS_EXTENT_DATA_KEY)
  717. path->slots[0]--;
  718. }
  719. ret = 0;
  720. leafs_visited++;
  721. next_slot:
  722. leaf = path->nodes[0];
  723. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  724. BUG_ON(del_nr > 0);
  725. ret = btrfs_next_leaf(root, path);
  726. if (ret < 0)
  727. break;
  728. if (ret > 0) {
  729. ret = 0;
  730. break;
  731. }
  732. leafs_visited++;
  733. leaf = path->nodes[0];
  734. recow = 1;
  735. }
  736. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  737. if (key.objectid > ino)
  738. break;
  739. if (WARN_ON_ONCE(key.objectid < ino) ||
  740. key.type < BTRFS_EXTENT_DATA_KEY) {
  741. ASSERT(del_nr == 0);
  742. path->slots[0]++;
  743. goto next_slot;
  744. }
  745. if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
  746. break;
  747. fi = btrfs_item_ptr(leaf, path->slots[0],
  748. struct btrfs_file_extent_item);
  749. extent_type = btrfs_file_extent_type(leaf, fi);
  750. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  751. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  752. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  753. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  754. extent_offset = btrfs_file_extent_offset(leaf, fi);
  755. extent_end = key.offset +
  756. btrfs_file_extent_num_bytes(leaf, fi);
  757. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  758. extent_end = key.offset +
  759. btrfs_file_extent_inline_len(leaf,
  760. path->slots[0], fi);
  761. } else {
  762. /* can't happen */
  763. BUG();
  764. }
  765. /*
  766. * Don't skip extent items representing 0 byte lengths. They
  767. * used to be created (bug) if while punching holes we hit
  768. * -ENOSPC condition. So if we find one here, just ensure we
  769. * delete it, otherwise we would insert a new file extent item
  770. * with the same key (offset) as that 0 bytes length file
  771. * extent item in the call to setup_items_for_insert() later
  772. * in this function.
  773. */
  774. if (extent_end == key.offset && extent_end >= search_start) {
  775. last_end = extent_end;
  776. goto delete_extent_item;
  777. }
  778. if (extent_end <= search_start) {
  779. path->slots[0]++;
  780. goto next_slot;
  781. }
  782. found = 1;
  783. search_start = max(key.offset, start);
  784. if (recow || !modify_tree) {
  785. modify_tree = -1;
  786. btrfs_release_path(path);
  787. continue;
  788. }
  789. /*
  790. * | - range to drop - |
  791. * | -------- extent -------- |
  792. */
  793. if (start > key.offset && end < extent_end) {
  794. BUG_ON(del_nr > 0);
  795. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  796. ret = -EOPNOTSUPP;
  797. break;
  798. }
  799. memcpy(&new_key, &key, sizeof(new_key));
  800. new_key.offset = start;
  801. ret = btrfs_duplicate_item(trans, root, path,
  802. &new_key);
  803. if (ret == -EAGAIN) {
  804. btrfs_release_path(path);
  805. continue;
  806. }
  807. if (ret < 0)
  808. break;
  809. leaf = path->nodes[0];
  810. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  811. struct btrfs_file_extent_item);
  812. btrfs_set_file_extent_num_bytes(leaf, fi,
  813. start - key.offset);
  814. fi = btrfs_item_ptr(leaf, path->slots[0],
  815. struct btrfs_file_extent_item);
  816. extent_offset += start - key.offset;
  817. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  818. btrfs_set_file_extent_num_bytes(leaf, fi,
  819. extent_end - start);
  820. btrfs_mark_buffer_dirty(leaf);
  821. if (update_refs && disk_bytenr > 0) {
  822. ret = btrfs_inc_extent_ref(trans, root,
  823. disk_bytenr, num_bytes, 0,
  824. root->root_key.objectid,
  825. new_key.objectid,
  826. start - extent_offset);
  827. BUG_ON(ret); /* -ENOMEM */
  828. }
  829. key.offset = start;
  830. }
  831. /*
  832. * From here on out we will have actually dropped something, so
  833. * last_end can be updated.
  834. */
  835. last_end = extent_end;
  836. /*
  837. * | ---- range to drop ----- |
  838. * | -------- extent -------- |
  839. */
  840. if (start <= key.offset && end < extent_end) {
  841. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  842. ret = -EOPNOTSUPP;
  843. break;
  844. }
  845. memcpy(&new_key, &key, sizeof(new_key));
  846. new_key.offset = end;
  847. btrfs_set_item_key_safe(fs_info, path, &new_key);
  848. extent_offset += end - key.offset;
  849. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  850. btrfs_set_file_extent_num_bytes(leaf, fi,
  851. extent_end - end);
  852. btrfs_mark_buffer_dirty(leaf);
  853. if (update_refs && disk_bytenr > 0)
  854. inode_sub_bytes(inode, end - key.offset);
  855. break;
  856. }
  857. search_start = extent_end;
  858. /*
  859. * | ---- range to drop ----- |
  860. * | -------- extent -------- |
  861. */
  862. if (start > key.offset && end >= extent_end) {
  863. BUG_ON(del_nr > 0);
  864. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  865. ret = -EOPNOTSUPP;
  866. break;
  867. }
  868. btrfs_set_file_extent_num_bytes(leaf, fi,
  869. start - key.offset);
  870. btrfs_mark_buffer_dirty(leaf);
  871. if (update_refs && disk_bytenr > 0)
  872. inode_sub_bytes(inode, extent_end - start);
  873. if (end == extent_end)
  874. break;
  875. path->slots[0]++;
  876. goto next_slot;
  877. }
  878. /*
  879. * | ---- range to drop ----- |
  880. * | ------ extent ------ |
  881. */
  882. if (start <= key.offset && end >= extent_end) {
  883. delete_extent_item:
  884. if (del_nr == 0) {
  885. del_slot = path->slots[0];
  886. del_nr = 1;
  887. } else {
  888. BUG_ON(del_slot + del_nr != path->slots[0]);
  889. del_nr++;
  890. }
  891. if (update_refs &&
  892. extent_type == BTRFS_FILE_EXTENT_INLINE) {
  893. inode_sub_bytes(inode,
  894. extent_end - key.offset);
  895. extent_end = ALIGN(extent_end,
  896. fs_info->sectorsize);
  897. } else if (update_refs && disk_bytenr > 0) {
  898. ret = btrfs_free_extent(trans, root,
  899. disk_bytenr, num_bytes, 0,
  900. root->root_key.objectid,
  901. key.objectid, key.offset -
  902. extent_offset);
  903. BUG_ON(ret); /* -ENOMEM */
  904. inode_sub_bytes(inode,
  905. extent_end - key.offset);
  906. }
  907. if (end == extent_end)
  908. break;
  909. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  910. path->slots[0]++;
  911. goto next_slot;
  912. }
  913. ret = btrfs_del_items(trans, root, path, del_slot,
  914. del_nr);
  915. if (ret) {
  916. btrfs_abort_transaction(trans, ret);
  917. break;
  918. }
  919. del_nr = 0;
  920. del_slot = 0;
  921. btrfs_release_path(path);
  922. continue;
  923. }
  924. BUG_ON(1);
  925. }
  926. if (!ret && del_nr > 0) {
  927. /*
  928. * Set path->slots[0] to first slot, so that after the delete
  929. * if items are move off from our leaf to its immediate left or
  930. * right neighbor leafs, we end up with a correct and adjusted
  931. * path->slots[0] for our insertion (if replace_extent != 0).
  932. */
  933. path->slots[0] = del_slot;
  934. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  935. if (ret)
  936. btrfs_abort_transaction(trans, ret);
  937. }
  938. leaf = path->nodes[0];
  939. /*
  940. * If btrfs_del_items() was called, it might have deleted a leaf, in
  941. * which case it unlocked our path, so check path->locks[0] matches a
  942. * write lock.
  943. */
  944. if (!ret && replace_extent && leafs_visited == 1 &&
  945. (path->locks[0] == BTRFS_WRITE_LOCK_BLOCKING ||
  946. path->locks[0] == BTRFS_WRITE_LOCK) &&
  947. btrfs_leaf_free_space(fs_info, leaf) >=
  948. sizeof(struct btrfs_item) + extent_item_size) {
  949. key.objectid = ino;
  950. key.type = BTRFS_EXTENT_DATA_KEY;
  951. key.offset = start;
  952. if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
  953. struct btrfs_key slot_key;
  954. btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
  955. if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
  956. path->slots[0]++;
  957. }
  958. setup_items_for_insert(root, path, &key,
  959. &extent_item_size,
  960. extent_item_size,
  961. sizeof(struct btrfs_item) +
  962. extent_item_size, 1);
  963. *key_inserted = 1;
  964. }
  965. if (!replace_extent || !(*key_inserted))
  966. btrfs_release_path(path);
  967. if (drop_end)
  968. *drop_end = found ? min(end, last_end) : end;
  969. return ret;
  970. }
  971. int btrfs_drop_extents(struct btrfs_trans_handle *trans,
  972. struct btrfs_root *root, struct inode *inode, u64 start,
  973. u64 end, int drop_cache)
  974. {
  975. struct btrfs_path *path;
  976. int ret;
  977. path = btrfs_alloc_path();
  978. if (!path)
  979. return -ENOMEM;
  980. ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
  981. drop_cache, 0, 0, NULL);
  982. btrfs_free_path(path);
  983. return ret;
  984. }
  985. static int extent_mergeable(struct extent_buffer *leaf, int slot,
  986. u64 objectid, u64 bytenr, u64 orig_offset,
  987. u64 *start, u64 *end)
  988. {
  989. struct btrfs_file_extent_item *fi;
  990. struct btrfs_key key;
  991. u64 extent_end;
  992. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  993. return 0;
  994. btrfs_item_key_to_cpu(leaf, &key, slot);
  995. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  996. return 0;
  997. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  998. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  999. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  1000. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  1001. btrfs_file_extent_compression(leaf, fi) ||
  1002. btrfs_file_extent_encryption(leaf, fi) ||
  1003. btrfs_file_extent_other_encoding(leaf, fi))
  1004. return 0;
  1005. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  1006. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  1007. return 0;
  1008. *start = key.offset;
  1009. *end = extent_end;
  1010. return 1;
  1011. }
  1012. /*
  1013. * Mark extent in the range start - end as written.
  1014. *
  1015. * This changes extent type from 'pre-allocated' to 'regular'. If only
  1016. * part of extent is marked as written, the extent will be split into
  1017. * two or three.
  1018. */
  1019. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  1020. struct btrfs_inode *inode, u64 start, u64 end)
  1021. {
  1022. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  1023. struct btrfs_root *root = inode->root;
  1024. struct extent_buffer *leaf;
  1025. struct btrfs_path *path;
  1026. struct btrfs_file_extent_item *fi;
  1027. struct btrfs_key key;
  1028. struct btrfs_key new_key;
  1029. u64 bytenr;
  1030. u64 num_bytes;
  1031. u64 extent_end;
  1032. u64 orig_offset;
  1033. u64 other_start;
  1034. u64 other_end;
  1035. u64 split;
  1036. int del_nr = 0;
  1037. int del_slot = 0;
  1038. int recow;
  1039. int ret;
  1040. u64 ino = btrfs_ino(inode);
  1041. path = btrfs_alloc_path();
  1042. if (!path)
  1043. return -ENOMEM;
  1044. again:
  1045. recow = 0;
  1046. split = start;
  1047. key.objectid = ino;
  1048. key.type = BTRFS_EXTENT_DATA_KEY;
  1049. key.offset = split;
  1050. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1051. if (ret < 0)
  1052. goto out;
  1053. if (ret > 0 && path->slots[0] > 0)
  1054. path->slots[0]--;
  1055. leaf = path->nodes[0];
  1056. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1057. if (key.objectid != ino ||
  1058. key.type != BTRFS_EXTENT_DATA_KEY) {
  1059. ret = -EINVAL;
  1060. btrfs_abort_transaction(trans, ret);
  1061. goto out;
  1062. }
  1063. fi = btrfs_item_ptr(leaf, path->slots[0],
  1064. struct btrfs_file_extent_item);
  1065. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
  1066. ret = -EINVAL;
  1067. btrfs_abort_transaction(trans, ret);
  1068. goto out;
  1069. }
  1070. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  1071. if (key.offset > start || extent_end < end) {
  1072. ret = -EINVAL;
  1073. btrfs_abort_transaction(trans, ret);
  1074. goto out;
  1075. }
  1076. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1077. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  1078. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  1079. memcpy(&new_key, &key, sizeof(new_key));
  1080. if (start == key.offset && end < extent_end) {
  1081. other_start = 0;
  1082. other_end = start;
  1083. if (extent_mergeable(leaf, path->slots[0] - 1,
  1084. ino, bytenr, orig_offset,
  1085. &other_start, &other_end)) {
  1086. new_key.offset = end;
  1087. btrfs_set_item_key_safe(fs_info, path, &new_key);
  1088. fi = btrfs_item_ptr(leaf, path->slots[0],
  1089. struct btrfs_file_extent_item);
  1090. btrfs_set_file_extent_generation(leaf, fi,
  1091. trans->transid);
  1092. btrfs_set_file_extent_num_bytes(leaf, fi,
  1093. extent_end - end);
  1094. btrfs_set_file_extent_offset(leaf, fi,
  1095. end - orig_offset);
  1096. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1097. struct btrfs_file_extent_item);
  1098. btrfs_set_file_extent_generation(leaf, fi,
  1099. trans->transid);
  1100. btrfs_set_file_extent_num_bytes(leaf, fi,
  1101. end - other_start);
  1102. btrfs_mark_buffer_dirty(leaf);
  1103. goto out;
  1104. }
  1105. }
  1106. if (start > key.offset && end == extent_end) {
  1107. other_start = end;
  1108. other_end = 0;
  1109. if (extent_mergeable(leaf, path->slots[0] + 1,
  1110. ino, bytenr, orig_offset,
  1111. &other_start, &other_end)) {
  1112. fi = btrfs_item_ptr(leaf, path->slots[0],
  1113. struct btrfs_file_extent_item);
  1114. btrfs_set_file_extent_num_bytes(leaf, fi,
  1115. start - key.offset);
  1116. btrfs_set_file_extent_generation(leaf, fi,
  1117. trans->transid);
  1118. path->slots[0]++;
  1119. new_key.offset = start;
  1120. btrfs_set_item_key_safe(fs_info, path, &new_key);
  1121. fi = btrfs_item_ptr(leaf, path->slots[0],
  1122. struct btrfs_file_extent_item);
  1123. btrfs_set_file_extent_generation(leaf, fi,
  1124. trans->transid);
  1125. btrfs_set_file_extent_num_bytes(leaf, fi,
  1126. other_end - start);
  1127. btrfs_set_file_extent_offset(leaf, fi,
  1128. start - orig_offset);
  1129. btrfs_mark_buffer_dirty(leaf);
  1130. goto out;
  1131. }
  1132. }
  1133. while (start > key.offset || end < extent_end) {
  1134. if (key.offset == start)
  1135. split = end;
  1136. new_key.offset = split;
  1137. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  1138. if (ret == -EAGAIN) {
  1139. btrfs_release_path(path);
  1140. goto again;
  1141. }
  1142. if (ret < 0) {
  1143. btrfs_abort_transaction(trans, ret);
  1144. goto out;
  1145. }
  1146. leaf = path->nodes[0];
  1147. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1148. struct btrfs_file_extent_item);
  1149. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1150. btrfs_set_file_extent_num_bytes(leaf, fi,
  1151. split - key.offset);
  1152. fi = btrfs_item_ptr(leaf, path->slots[0],
  1153. struct btrfs_file_extent_item);
  1154. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1155. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  1156. btrfs_set_file_extent_num_bytes(leaf, fi,
  1157. extent_end - split);
  1158. btrfs_mark_buffer_dirty(leaf);
  1159. ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes,
  1160. 0, root->root_key.objectid,
  1161. ino, orig_offset);
  1162. if (ret) {
  1163. btrfs_abort_transaction(trans, ret);
  1164. goto out;
  1165. }
  1166. if (split == start) {
  1167. key.offset = start;
  1168. } else {
  1169. if (start != key.offset) {
  1170. ret = -EINVAL;
  1171. btrfs_abort_transaction(trans, ret);
  1172. goto out;
  1173. }
  1174. path->slots[0]--;
  1175. extent_end = end;
  1176. }
  1177. recow = 1;
  1178. }
  1179. other_start = end;
  1180. other_end = 0;
  1181. if (extent_mergeable(leaf, path->slots[0] + 1,
  1182. ino, bytenr, orig_offset,
  1183. &other_start, &other_end)) {
  1184. if (recow) {
  1185. btrfs_release_path(path);
  1186. goto again;
  1187. }
  1188. extent_end = other_end;
  1189. del_slot = path->slots[0] + 1;
  1190. del_nr++;
  1191. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1192. 0, root->root_key.objectid,
  1193. ino, orig_offset);
  1194. if (ret) {
  1195. btrfs_abort_transaction(trans, ret);
  1196. goto out;
  1197. }
  1198. }
  1199. other_start = 0;
  1200. other_end = start;
  1201. if (extent_mergeable(leaf, path->slots[0] - 1,
  1202. ino, bytenr, orig_offset,
  1203. &other_start, &other_end)) {
  1204. if (recow) {
  1205. btrfs_release_path(path);
  1206. goto again;
  1207. }
  1208. key.offset = other_start;
  1209. del_slot = path->slots[0];
  1210. del_nr++;
  1211. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1212. 0, root->root_key.objectid,
  1213. ino, orig_offset);
  1214. if (ret) {
  1215. btrfs_abort_transaction(trans, ret);
  1216. goto out;
  1217. }
  1218. }
  1219. if (del_nr == 0) {
  1220. fi = btrfs_item_ptr(leaf, path->slots[0],
  1221. struct btrfs_file_extent_item);
  1222. btrfs_set_file_extent_type(leaf, fi,
  1223. BTRFS_FILE_EXTENT_REG);
  1224. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1225. btrfs_mark_buffer_dirty(leaf);
  1226. } else {
  1227. fi = btrfs_item_ptr(leaf, del_slot - 1,
  1228. struct btrfs_file_extent_item);
  1229. btrfs_set_file_extent_type(leaf, fi,
  1230. BTRFS_FILE_EXTENT_REG);
  1231. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1232. btrfs_set_file_extent_num_bytes(leaf, fi,
  1233. extent_end - key.offset);
  1234. btrfs_mark_buffer_dirty(leaf);
  1235. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  1236. if (ret < 0) {
  1237. btrfs_abort_transaction(trans, ret);
  1238. goto out;
  1239. }
  1240. }
  1241. out:
  1242. btrfs_free_path(path);
  1243. return 0;
  1244. }
  1245. /*
  1246. * on error we return an unlocked page and the error value
  1247. * on success we return a locked page and 0
  1248. */
  1249. static int prepare_uptodate_page(struct inode *inode,
  1250. struct page *page, u64 pos,
  1251. bool force_uptodate)
  1252. {
  1253. int ret = 0;
  1254. if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
  1255. !PageUptodate(page)) {
  1256. ret = btrfs_readpage(NULL, page);
  1257. if (ret)
  1258. return ret;
  1259. lock_page(page);
  1260. if (!PageUptodate(page)) {
  1261. unlock_page(page);
  1262. return -EIO;
  1263. }
  1264. if (page->mapping != inode->i_mapping) {
  1265. unlock_page(page);
  1266. return -EAGAIN;
  1267. }
  1268. }
  1269. return 0;
  1270. }
  1271. /*
  1272. * this just gets pages into the page cache and locks them down.
  1273. */
  1274. static noinline int prepare_pages(struct inode *inode, struct page **pages,
  1275. size_t num_pages, loff_t pos,
  1276. size_t write_bytes, bool force_uptodate)
  1277. {
  1278. int i;
  1279. unsigned long index = pos >> PAGE_SHIFT;
  1280. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  1281. int err = 0;
  1282. int faili;
  1283. for (i = 0; i < num_pages; i++) {
  1284. again:
  1285. pages[i] = find_or_create_page(inode->i_mapping, index + i,
  1286. mask | __GFP_WRITE);
  1287. if (!pages[i]) {
  1288. faili = i - 1;
  1289. err = -ENOMEM;
  1290. goto fail;
  1291. }
  1292. if (i == 0)
  1293. err = prepare_uptodate_page(inode, pages[i], pos,
  1294. force_uptodate);
  1295. if (!err && i == num_pages - 1)
  1296. err = prepare_uptodate_page(inode, pages[i],
  1297. pos + write_bytes, false);
  1298. if (err) {
  1299. put_page(pages[i]);
  1300. if (err == -EAGAIN) {
  1301. err = 0;
  1302. goto again;
  1303. }
  1304. faili = i - 1;
  1305. goto fail;
  1306. }
  1307. wait_on_page_writeback(pages[i]);
  1308. }
  1309. return 0;
  1310. fail:
  1311. while (faili >= 0) {
  1312. unlock_page(pages[faili]);
  1313. put_page(pages[faili]);
  1314. faili--;
  1315. }
  1316. return err;
  1317. }
  1318. /*
  1319. * This function locks the extent and properly waits for data=ordered extents
  1320. * to finish before allowing the pages to be modified if need.
  1321. *
  1322. * The return value:
  1323. * 1 - the extent is locked
  1324. * 0 - the extent is not locked, and everything is OK
  1325. * -EAGAIN - need re-prepare the pages
  1326. * the other < 0 number - Something wrong happens
  1327. */
  1328. static noinline int
  1329. lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
  1330. size_t num_pages, loff_t pos,
  1331. size_t write_bytes,
  1332. u64 *lockstart, u64 *lockend,
  1333. struct extent_state **cached_state)
  1334. {
  1335. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  1336. u64 start_pos;
  1337. u64 last_pos;
  1338. int i;
  1339. int ret = 0;
  1340. start_pos = round_down(pos, fs_info->sectorsize);
  1341. last_pos = start_pos
  1342. + round_up(pos + write_bytes - start_pos,
  1343. fs_info->sectorsize) - 1;
  1344. if (start_pos < inode->vfs_inode.i_size) {
  1345. struct btrfs_ordered_extent *ordered;
  1346. lock_extent_bits(&inode->io_tree, start_pos, last_pos,
  1347. cached_state);
  1348. ordered = btrfs_lookup_ordered_range(inode, start_pos,
  1349. last_pos - start_pos + 1);
  1350. if (ordered &&
  1351. ordered->file_offset + ordered->len > start_pos &&
  1352. ordered->file_offset <= last_pos) {
  1353. unlock_extent_cached(&inode->io_tree, start_pos,
  1354. last_pos, cached_state, GFP_NOFS);
  1355. for (i = 0; i < num_pages; i++) {
  1356. unlock_page(pages[i]);
  1357. put_page(pages[i]);
  1358. }
  1359. btrfs_start_ordered_extent(&inode->vfs_inode,
  1360. ordered, 1);
  1361. btrfs_put_ordered_extent(ordered);
  1362. return -EAGAIN;
  1363. }
  1364. if (ordered)
  1365. btrfs_put_ordered_extent(ordered);
  1366. clear_extent_bit(&inode->io_tree, start_pos, last_pos,
  1367. EXTENT_DIRTY | EXTENT_DELALLOC |
  1368. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  1369. 0, 0, cached_state, GFP_NOFS);
  1370. *lockstart = start_pos;
  1371. *lockend = last_pos;
  1372. ret = 1;
  1373. }
  1374. for (i = 0; i < num_pages; i++) {
  1375. if (clear_page_dirty_for_io(pages[i]))
  1376. account_page_redirty(pages[i]);
  1377. set_page_extent_mapped(pages[i]);
  1378. WARN_ON(!PageLocked(pages[i]));
  1379. }
  1380. return ret;
  1381. }
  1382. static noinline int check_can_nocow(struct btrfs_inode *inode, loff_t pos,
  1383. size_t *write_bytes)
  1384. {
  1385. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  1386. struct btrfs_root *root = inode->root;
  1387. struct btrfs_ordered_extent *ordered;
  1388. u64 lockstart, lockend;
  1389. u64 num_bytes;
  1390. int ret;
  1391. ret = btrfs_start_write_no_snapshotting(root);
  1392. if (!ret)
  1393. return -ENOSPC;
  1394. lockstart = round_down(pos, fs_info->sectorsize);
  1395. lockend = round_up(pos + *write_bytes,
  1396. fs_info->sectorsize) - 1;
  1397. while (1) {
  1398. lock_extent(&inode->io_tree, lockstart, lockend);
  1399. ordered = btrfs_lookup_ordered_range(inode, lockstart,
  1400. lockend - lockstart + 1);
  1401. if (!ordered) {
  1402. break;
  1403. }
  1404. unlock_extent(&inode->io_tree, lockstart, lockend);
  1405. btrfs_start_ordered_extent(&inode->vfs_inode, ordered, 1);
  1406. btrfs_put_ordered_extent(ordered);
  1407. }
  1408. num_bytes = lockend - lockstart + 1;
  1409. ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
  1410. NULL, NULL, NULL);
  1411. if (ret <= 0) {
  1412. ret = 0;
  1413. btrfs_end_write_no_snapshotting(root);
  1414. } else {
  1415. *write_bytes = min_t(size_t, *write_bytes ,
  1416. num_bytes - pos + lockstart);
  1417. }
  1418. unlock_extent(&inode->io_tree, lockstart, lockend);
  1419. return ret;
  1420. }
  1421. static noinline ssize_t __btrfs_buffered_write(struct file *file,
  1422. struct iov_iter *i,
  1423. loff_t pos)
  1424. {
  1425. struct inode *inode = file_inode(file);
  1426. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1427. struct btrfs_root *root = BTRFS_I(inode)->root;
  1428. struct page **pages = NULL;
  1429. struct extent_state *cached_state = NULL;
  1430. struct extent_changeset *data_reserved = NULL;
  1431. u64 release_bytes = 0;
  1432. u64 lockstart;
  1433. u64 lockend;
  1434. size_t num_written = 0;
  1435. int nrptrs;
  1436. int ret = 0;
  1437. bool only_release_metadata = false;
  1438. bool force_page_uptodate = false;
  1439. nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
  1440. PAGE_SIZE / (sizeof(struct page *)));
  1441. nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
  1442. nrptrs = max(nrptrs, 8);
  1443. pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
  1444. if (!pages)
  1445. return -ENOMEM;
  1446. while (iov_iter_count(i) > 0) {
  1447. size_t offset = pos & (PAGE_SIZE - 1);
  1448. size_t sector_offset;
  1449. size_t write_bytes = min(iov_iter_count(i),
  1450. nrptrs * (size_t)PAGE_SIZE -
  1451. offset);
  1452. size_t num_pages = DIV_ROUND_UP(write_bytes + offset,
  1453. PAGE_SIZE);
  1454. size_t reserve_bytes;
  1455. size_t dirty_pages;
  1456. size_t copied;
  1457. size_t dirty_sectors;
  1458. size_t num_sectors;
  1459. int extents_locked;
  1460. WARN_ON(num_pages > nrptrs);
  1461. /*
  1462. * Fault pages before locking them in prepare_pages
  1463. * to avoid recursive lock
  1464. */
  1465. if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
  1466. ret = -EFAULT;
  1467. break;
  1468. }
  1469. sector_offset = pos & (fs_info->sectorsize - 1);
  1470. reserve_bytes = round_up(write_bytes + sector_offset,
  1471. fs_info->sectorsize);
  1472. extent_changeset_release(data_reserved);
  1473. ret = btrfs_check_data_free_space(inode, &data_reserved, pos,
  1474. write_bytes);
  1475. if (ret < 0) {
  1476. if ((BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
  1477. BTRFS_INODE_PREALLOC)) &&
  1478. check_can_nocow(BTRFS_I(inode), pos,
  1479. &write_bytes) > 0) {
  1480. /*
  1481. * For nodata cow case, no need to reserve
  1482. * data space.
  1483. */
  1484. only_release_metadata = true;
  1485. /*
  1486. * our prealloc extent may be smaller than
  1487. * write_bytes, so scale down.
  1488. */
  1489. num_pages = DIV_ROUND_UP(write_bytes + offset,
  1490. PAGE_SIZE);
  1491. reserve_bytes = round_up(write_bytes +
  1492. sector_offset,
  1493. fs_info->sectorsize);
  1494. } else {
  1495. break;
  1496. }
  1497. }
  1498. WARN_ON(reserve_bytes == 0);
  1499. ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
  1500. reserve_bytes);
  1501. if (ret) {
  1502. if (!only_release_metadata)
  1503. btrfs_free_reserved_data_space(inode,
  1504. data_reserved, pos,
  1505. write_bytes);
  1506. else
  1507. btrfs_end_write_no_snapshotting(root);
  1508. break;
  1509. }
  1510. release_bytes = reserve_bytes;
  1511. again:
  1512. /*
  1513. * This is going to setup the pages array with the number of
  1514. * pages we want, so we don't really need to worry about the
  1515. * contents of pages from loop to loop
  1516. */
  1517. ret = prepare_pages(inode, pages, num_pages,
  1518. pos, write_bytes,
  1519. force_page_uptodate);
  1520. if (ret) {
  1521. btrfs_delalloc_release_extents(BTRFS_I(inode),
  1522. reserve_bytes);
  1523. break;
  1524. }
  1525. extents_locked = lock_and_cleanup_extent_if_need(
  1526. BTRFS_I(inode), pages,
  1527. num_pages, pos, write_bytes, &lockstart,
  1528. &lockend, &cached_state);
  1529. if (extents_locked < 0) {
  1530. if (extents_locked == -EAGAIN)
  1531. goto again;
  1532. btrfs_delalloc_release_extents(BTRFS_I(inode),
  1533. reserve_bytes);
  1534. ret = extents_locked;
  1535. break;
  1536. }
  1537. copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
  1538. num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
  1539. dirty_sectors = round_up(copied + sector_offset,
  1540. fs_info->sectorsize);
  1541. dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
  1542. /*
  1543. * if we have trouble faulting in the pages, fall
  1544. * back to one page at a time
  1545. */
  1546. if (copied < write_bytes)
  1547. nrptrs = 1;
  1548. if (copied == 0) {
  1549. force_page_uptodate = true;
  1550. dirty_sectors = 0;
  1551. dirty_pages = 0;
  1552. } else {
  1553. force_page_uptodate = false;
  1554. dirty_pages = DIV_ROUND_UP(copied + offset,
  1555. PAGE_SIZE);
  1556. }
  1557. if (num_sectors > dirty_sectors) {
  1558. /* release everything except the sectors we dirtied */
  1559. release_bytes -= dirty_sectors <<
  1560. fs_info->sb->s_blocksize_bits;
  1561. if (only_release_metadata) {
  1562. btrfs_delalloc_release_metadata(BTRFS_I(inode),
  1563. release_bytes);
  1564. } else {
  1565. u64 __pos;
  1566. __pos = round_down(pos,
  1567. fs_info->sectorsize) +
  1568. (dirty_pages << PAGE_SHIFT);
  1569. btrfs_delalloc_release_space(inode,
  1570. data_reserved, __pos,
  1571. release_bytes);
  1572. }
  1573. }
  1574. release_bytes = round_up(copied + sector_offset,
  1575. fs_info->sectorsize);
  1576. if (copied > 0)
  1577. ret = btrfs_dirty_pages(inode, pages, dirty_pages,
  1578. pos, copied, NULL);
  1579. if (extents_locked)
  1580. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1581. lockstart, lockend, &cached_state,
  1582. GFP_NOFS);
  1583. btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
  1584. if (ret) {
  1585. btrfs_drop_pages(pages, num_pages);
  1586. break;
  1587. }
  1588. release_bytes = 0;
  1589. if (only_release_metadata)
  1590. btrfs_end_write_no_snapshotting(root);
  1591. if (only_release_metadata && copied > 0) {
  1592. lockstart = round_down(pos,
  1593. fs_info->sectorsize);
  1594. lockend = round_up(pos + copied,
  1595. fs_info->sectorsize) - 1;
  1596. set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  1597. lockend, EXTENT_NORESERVE, NULL,
  1598. NULL, GFP_NOFS);
  1599. only_release_metadata = false;
  1600. }
  1601. btrfs_drop_pages(pages, num_pages);
  1602. cond_resched();
  1603. balance_dirty_pages_ratelimited(inode->i_mapping);
  1604. if (dirty_pages < (fs_info->nodesize >> PAGE_SHIFT) + 1)
  1605. btrfs_btree_balance_dirty(fs_info);
  1606. pos += copied;
  1607. num_written += copied;
  1608. }
  1609. kfree(pages);
  1610. if (release_bytes) {
  1611. if (only_release_metadata) {
  1612. btrfs_end_write_no_snapshotting(root);
  1613. btrfs_delalloc_release_metadata(BTRFS_I(inode),
  1614. release_bytes);
  1615. } else {
  1616. btrfs_delalloc_release_space(inode, data_reserved,
  1617. round_down(pos, fs_info->sectorsize),
  1618. release_bytes);
  1619. }
  1620. }
  1621. extent_changeset_free(data_reserved);
  1622. return num_written ? num_written : ret;
  1623. }
  1624. static ssize_t __btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
  1625. {
  1626. struct file *file = iocb->ki_filp;
  1627. struct inode *inode = file_inode(file);
  1628. loff_t pos = iocb->ki_pos;
  1629. ssize_t written;
  1630. ssize_t written_buffered;
  1631. loff_t endbyte;
  1632. int err;
  1633. written = generic_file_direct_write(iocb, from);
  1634. if (written < 0 || !iov_iter_count(from))
  1635. return written;
  1636. pos += written;
  1637. written_buffered = __btrfs_buffered_write(file, from, pos);
  1638. if (written_buffered < 0) {
  1639. err = written_buffered;
  1640. goto out;
  1641. }
  1642. /*
  1643. * Ensure all data is persisted. We want the next direct IO read to be
  1644. * able to read what was just written.
  1645. */
  1646. endbyte = pos + written_buffered - 1;
  1647. err = btrfs_fdatawrite_range(inode, pos, endbyte);
  1648. if (err)
  1649. goto out;
  1650. err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
  1651. if (err)
  1652. goto out;
  1653. written += written_buffered;
  1654. iocb->ki_pos = pos + written_buffered;
  1655. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
  1656. endbyte >> PAGE_SHIFT);
  1657. out:
  1658. return written ? written : err;
  1659. }
  1660. static void update_time_for_write(struct inode *inode)
  1661. {
  1662. struct timespec now;
  1663. if (IS_NOCMTIME(inode))
  1664. return;
  1665. now = current_time(inode);
  1666. if (!timespec_equal(&inode->i_mtime, &now))
  1667. inode->i_mtime = now;
  1668. if (!timespec_equal(&inode->i_ctime, &now))
  1669. inode->i_ctime = now;
  1670. if (IS_I_VERSION(inode))
  1671. inode_inc_iversion(inode);
  1672. }
  1673. static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
  1674. struct iov_iter *from)
  1675. {
  1676. struct file *file = iocb->ki_filp;
  1677. struct inode *inode = file_inode(file);
  1678. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1679. struct btrfs_root *root = BTRFS_I(inode)->root;
  1680. u64 start_pos;
  1681. u64 end_pos;
  1682. ssize_t num_written = 0;
  1683. bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
  1684. ssize_t err;
  1685. loff_t pos;
  1686. size_t count = iov_iter_count(from);
  1687. loff_t oldsize;
  1688. int clean_page = 0;
  1689. if (!(iocb->ki_flags & IOCB_DIRECT) &&
  1690. (iocb->ki_flags & IOCB_NOWAIT))
  1691. return -EOPNOTSUPP;
  1692. if (!inode_trylock(inode)) {
  1693. if (iocb->ki_flags & IOCB_NOWAIT)
  1694. return -EAGAIN;
  1695. inode_lock(inode);
  1696. }
  1697. err = generic_write_checks(iocb, from);
  1698. if (err <= 0) {
  1699. inode_unlock(inode);
  1700. return err;
  1701. }
  1702. pos = iocb->ki_pos;
  1703. if (iocb->ki_flags & IOCB_NOWAIT) {
  1704. /*
  1705. * We will allocate space in case nodatacow is not set,
  1706. * so bail
  1707. */
  1708. if (!(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
  1709. BTRFS_INODE_PREALLOC)) ||
  1710. check_can_nocow(BTRFS_I(inode), pos, &count) <= 0) {
  1711. inode_unlock(inode);
  1712. return -EAGAIN;
  1713. }
  1714. }
  1715. current->backing_dev_info = inode_to_bdi(inode);
  1716. err = file_remove_privs(file);
  1717. if (err) {
  1718. inode_unlock(inode);
  1719. goto out;
  1720. }
  1721. /*
  1722. * If BTRFS flips readonly due to some impossible error
  1723. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1724. * although we have opened a file as writable, we have
  1725. * to stop this write operation to ensure FS consistency.
  1726. */
  1727. if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
  1728. inode_unlock(inode);
  1729. err = -EROFS;
  1730. goto out;
  1731. }
  1732. /*
  1733. * We reserve space for updating the inode when we reserve space for the
  1734. * extent we are going to write, so we will enospc out there. We don't
  1735. * need to start yet another transaction to update the inode as we will
  1736. * update the inode when we finish writing whatever data we write.
  1737. */
  1738. update_time_for_write(inode);
  1739. start_pos = round_down(pos, fs_info->sectorsize);
  1740. oldsize = i_size_read(inode);
  1741. if (start_pos > oldsize) {
  1742. /* Expand hole size to cover write data, preventing empty gap */
  1743. end_pos = round_up(pos + count,
  1744. fs_info->sectorsize);
  1745. err = btrfs_cont_expand(inode, oldsize, end_pos);
  1746. if (err) {
  1747. inode_unlock(inode);
  1748. goto out;
  1749. }
  1750. if (start_pos > round_up(oldsize, fs_info->sectorsize))
  1751. clean_page = 1;
  1752. }
  1753. if (sync)
  1754. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1755. if (iocb->ki_flags & IOCB_DIRECT) {
  1756. num_written = __btrfs_direct_write(iocb, from);
  1757. } else {
  1758. num_written = __btrfs_buffered_write(file, from, pos);
  1759. if (num_written > 0)
  1760. iocb->ki_pos = pos + num_written;
  1761. if (clean_page)
  1762. pagecache_isize_extended(inode, oldsize,
  1763. i_size_read(inode));
  1764. }
  1765. inode_unlock(inode);
  1766. /*
  1767. * We also have to set last_sub_trans to the current log transid,
  1768. * otherwise subsequent syncs to a file that's been synced in this
  1769. * transaction will appear to have already occurred.
  1770. */
  1771. spin_lock(&BTRFS_I(inode)->lock);
  1772. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1773. spin_unlock(&BTRFS_I(inode)->lock);
  1774. if (num_written > 0)
  1775. num_written = generic_write_sync(iocb, num_written);
  1776. if (sync)
  1777. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1778. out:
  1779. current->backing_dev_info = NULL;
  1780. return num_written ? num_written : err;
  1781. }
  1782. int btrfs_release_file(struct inode *inode, struct file *filp)
  1783. {
  1784. struct btrfs_file_private *private = filp->private_data;
  1785. if (private && private->trans)
  1786. btrfs_ioctl_trans_end(filp);
  1787. if (private && private->filldir_buf)
  1788. kfree(private->filldir_buf);
  1789. kfree(private);
  1790. filp->private_data = NULL;
  1791. /*
  1792. * ordered_data_close is set by settattr when we are about to truncate
  1793. * a file from a non-zero size to a zero size. This tries to
  1794. * flush down new bytes that may have been written if the
  1795. * application were using truncate to replace a file in place.
  1796. */
  1797. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1798. &BTRFS_I(inode)->runtime_flags))
  1799. filemap_flush(inode->i_mapping);
  1800. return 0;
  1801. }
  1802. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1803. {
  1804. int ret;
  1805. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1806. ret = btrfs_fdatawrite_range(inode, start, end);
  1807. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1808. return ret;
  1809. }
  1810. /*
  1811. * fsync call for both files and directories. This logs the inode into
  1812. * the tree log instead of forcing full commits whenever possible.
  1813. *
  1814. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1815. * in the metadata btree are up to date for copying to the log.
  1816. *
  1817. * It drops the inode mutex before doing the tree log commit. This is an
  1818. * important optimization for directories because holding the mutex prevents
  1819. * new operations on the dir while we write to disk.
  1820. */
  1821. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1822. {
  1823. struct dentry *dentry = file_dentry(file);
  1824. struct inode *inode = d_inode(dentry);
  1825. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1826. struct btrfs_root *root = BTRFS_I(inode)->root;
  1827. struct btrfs_trans_handle *trans;
  1828. struct btrfs_log_ctx ctx;
  1829. int ret = 0, err;
  1830. bool full_sync = false;
  1831. u64 len;
  1832. /*
  1833. * The range length can be represented by u64, we have to do the typecasts
  1834. * to avoid signed overflow if it's [0, LLONG_MAX] eg. from fsync()
  1835. */
  1836. len = (u64)end - (u64)start + 1;
  1837. trace_btrfs_sync_file(file, datasync);
  1838. /*
  1839. * We write the dirty pages in the range and wait until they complete
  1840. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1841. * multi-task, and make the performance up. See
  1842. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1843. */
  1844. ret = start_ordered_ops(inode, start, end);
  1845. if (ret)
  1846. goto out;
  1847. inode_lock(inode);
  1848. atomic_inc(&root->log_batch);
  1849. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1850. &BTRFS_I(inode)->runtime_flags);
  1851. /*
  1852. * We might have have had more pages made dirty after calling
  1853. * start_ordered_ops and before acquiring the inode's i_mutex.
  1854. */
  1855. if (full_sync) {
  1856. /*
  1857. * For a full sync, we need to make sure any ordered operations
  1858. * start and finish before we start logging the inode, so that
  1859. * all extents are persisted and the respective file extent
  1860. * items are in the fs/subvol btree.
  1861. */
  1862. ret = btrfs_wait_ordered_range(inode, start, len);
  1863. } else {
  1864. /*
  1865. * Start any new ordered operations before starting to log the
  1866. * inode. We will wait for them to finish in btrfs_sync_log().
  1867. *
  1868. * Right before acquiring the inode's mutex, we might have new
  1869. * writes dirtying pages, which won't immediately start the
  1870. * respective ordered operations - that is done through the
  1871. * fill_delalloc callbacks invoked from the writepage and
  1872. * writepages address space operations. So make sure we start
  1873. * all ordered operations before starting to log our inode. Not
  1874. * doing this means that while logging the inode, writeback
  1875. * could start and invoke writepage/writepages, which would call
  1876. * the fill_delalloc callbacks (cow_file_range,
  1877. * submit_compressed_extents). These callbacks add first an
  1878. * extent map to the modified list of extents and then create
  1879. * the respective ordered operation, which means in
  1880. * tree-log.c:btrfs_log_inode() we might capture all existing
  1881. * ordered operations (with btrfs_get_logged_extents()) before
  1882. * the fill_delalloc callback adds its ordered operation, and by
  1883. * the time we visit the modified list of extent maps (with
  1884. * btrfs_log_changed_extents()), we see and process the extent
  1885. * map they created. We then use the extent map to construct a
  1886. * file extent item for logging without waiting for the
  1887. * respective ordered operation to finish - this file extent
  1888. * item points to a disk location that might not have yet been
  1889. * written to, containing random data - so after a crash a log
  1890. * replay will make our inode have file extent items that point
  1891. * to disk locations containing invalid data, as we returned
  1892. * success to userspace without waiting for the respective
  1893. * ordered operation to finish, because it wasn't captured by
  1894. * btrfs_get_logged_extents().
  1895. */
  1896. ret = start_ordered_ops(inode, start, end);
  1897. }
  1898. if (ret) {
  1899. inode_unlock(inode);
  1900. goto out;
  1901. }
  1902. atomic_inc(&root->log_batch);
  1903. /*
  1904. * If the last transaction that changed this file was before the current
  1905. * transaction and we have the full sync flag set in our inode, we can
  1906. * bail out now without any syncing.
  1907. *
  1908. * Note that we can't bail out if the full sync flag isn't set. This is
  1909. * because when the full sync flag is set we start all ordered extents
  1910. * and wait for them to fully complete - when they complete they update
  1911. * the inode's last_trans field through:
  1912. *
  1913. * btrfs_finish_ordered_io() ->
  1914. * btrfs_update_inode_fallback() ->
  1915. * btrfs_update_inode() ->
  1916. * btrfs_set_inode_last_trans()
  1917. *
  1918. * So we are sure that last_trans is up to date and can do this check to
  1919. * bail out safely. For the fast path, when the full sync flag is not
  1920. * set in our inode, we can not do it because we start only our ordered
  1921. * extents and don't wait for them to complete (that is when
  1922. * btrfs_finish_ordered_io runs), so here at this point their last_trans
  1923. * value might be less than or equals to fs_info->last_trans_committed,
  1924. * and setting a speculative last_trans for an inode when a buffered
  1925. * write is made (such as fs_info->generation + 1 for example) would not
  1926. * be reliable since after setting the value and before fsync is called
  1927. * any number of transactions can start and commit (transaction kthread
  1928. * commits the current transaction periodically), and a transaction
  1929. * commit does not start nor waits for ordered extents to complete.
  1930. */
  1931. smp_mb();
  1932. if (btrfs_inode_in_log(BTRFS_I(inode), fs_info->generation) ||
  1933. (full_sync && BTRFS_I(inode)->last_trans <=
  1934. fs_info->last_trans_committed) ||
  1935. (!btrfs_have_ordered_extents_in_range(inode, start, len) &&
  1936. BTRFS_I(inode)->last_trans
  1937. <= fs_info->last_trans_committed)) {
  1938. /*
  1939. * We've had everything committed since the last time we were
  1940. * modified so clear this flag in case it was set for whatever
  1941. * reason, it's no longer relevant.
  1942. */
  1943. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1944. &BTRFS_I(inode)->runtime_flags);
  1945. /*
  1946. * An ordered extent might have started before and completed
  1947. * already with io errors, in which case the inode was not
  1948. * updated and we end up here. So check the inode's mapping
  1949. * for any errors that might have happened since we last
  1950. * checked called fsync.
  1951. */
  1952. ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
  1953. inode_unlock(inode);
  1954. goto out;
  1955. }
  1956. /*
  1957. * ok we haven't committed the transaction yet, lets do a commit
  1958. */
  1959. if (file->private_data)
  1960. btrfs_ioctl_trans_end(file);
  1961. /*
  1962. * We use start here because we will need to wait on the IO to complete
  1963. * in btrfs_sync_log, which could require joining a transaction (for
  1964. * example checking cross references in the nocow path). If we use join
  1965. * here we could get into a situation where we're waiting on IO to
  1966. * happen that is blocked on a transaction trying to commit. With start
  1967. * we inc the extwriter counter, so we wait for all extwriters to exit
  1968. * before we start blocking join'ers. This comment is to keep somebody
  1969. * from thinking they are super smart and changing this to
  1970. * btrfs_join_transaction *cough*Josef*cough*.
  1971. */
  1972. trans = btrfs_start_transaction(root, 0);
  1973. if (IS_ERR(trans)) {
  1974. ret = PTR_ERR(trans);
  1975. inode_unlock(inode);
  1976. goto out;
  1977. }
  1978. trans->sync = true;
  1979. btrfs_init_log_ctx(&ctx, inode);
  1980. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1981. if (ret < 0) {
  1982. /* Fallthrough and commit/free transaction. */
  1983. ret = 1;
  1984. }
  1985. /* we've logged all the items and now have a consistent
  1986. * version of the file in the log. It is possible that
  1987. * someone will come in and modify the file, but that's
  1988. * fine because the log is consistent on disk, and we
  1989. * have references to all of the file's extents
  1990. *
  1991. * It is possible that someone will come in and log the
  1992. * file again, but that will end up using the synchronization
  1993. * inside btrfs_sync_log to keep things safe.
  1994. */
  1995. inode_unlock(inode);
  1996. /*
  1997. * If any of the ordered extents had an error, just return it to user
  1998. * space, so that the application knows some writes didn't succeed and
  1999. * can take proper action (retry for e.g.). Blindly committing the
  2000. * transaction in this case, would fool userspace that everything was
  2001. * successful. And we also want to make sure our log doesn't contain
  2002. * file extent items pointing to extents that weren't fully written to -
  2003. * just like in the non fast fsync path, where we check for the ordered
  2004. * operation's error flag before writing to the log tree and return -EIO
  2005. * if any of them had this flag set (btrfs_wait_ordered_range) -
  2006. * therefore we need to check for errors in the ordered operations,
  2007. * which are indicated by ctx.io_err.
  2008. */
  2009. if (ctx.io_err) {
  2010. btrfs_end_transaction(trans);
  2011. ret = ctx.io_err;
  2012. goto out;
  2013. }
  2014. if (ret != BTRFS_NO_LOG_SYNC) {
  2015. if (!ret) {
  2016. ret = btrfs_sync_log(trans, root, &ctx);
  2017. if (!ret) {
  2018. ret = btrfs_end_transaction(trans);
  2019. goto out;
  2020. }
  2021. }
  2022. if (!full_sync) {
  2023. ret = btrfs_wait_ordered_range(inode, start, len);
  2024. if (ret) {
  2025. btrfs_end_transaction(trans);
  2026. goto out;
  2027. }
  2028. }
  2029. ret = btrfs_commit_transaction(trans);
  2030. } else {
  2031. ret = btrfs_end_transaction(trans);
  2032. }
  2033. out:
  2034. err = file_check_and_advance_wb_err(file);
  2035. if (!ret)
  2036. ret = err;
  2037. return ret > 0 ? -EIO : ret;
  2038. }
  2039. static const struct vm_operations_struct btrfs_file_vm_ops = {
  2040. .fault = filemap_fault,
  2041. .map_pages = filemap_map_pages,
  2042. .page_mkwrite = btrfs_page_mkwrite,
  2043. };
  2044. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  2045. {
  2046. struct address_space *mapping = filp->f_mapping;
  2047. if (!mapping->a_ops->readpage)
  2048. return -ENOEXEC;
  2049. file_accessed(filp);
  2050. vma->vm_ops = &btrfs_file_vm_ops;
  2051. return 0;
  2052. }
  2053. static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
  2054. int slot, u64 start, u64 end)
  2055. {
  2056. struct btrfs_file_extent_item *fi;
  2057. struct btrfs_key key;
  2058. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  2059. return 0;
  2060. btrfs_item_key_to_cpu(leaf, &key, slot);
  2061. if (key.objectid != btrfs_ino(inode) ||
  2062. key.type != BTRFS_EXTENT_DATA_KEY)
  2063. return 0;
  2064. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  2065. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  2066. return 0;
  2067. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  2068. return 0;
  2069. if (key.offset == end)
  2070. return 1;
  2071. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  2072. return 1;
  2073. return 0;
  2074. }
  2075. static int fill_holes(struct btrfs_trans_handle *trans,
  2076. struct btrfs_inode *inode,
  2077. struct btrfs_path *path, u64 offset, u64 end)
  2078. {
  2079. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  2080. struct btrfs_root *root = inode->root;
  2081. struct extent_buffer *leaf;
  2082. struct btrfs_file_extent_item *fi;
  2083. struct extent_map *hole_em;
  2084. struct extent_map_tree *em_tree = &inode->extent_tree;
  2085. struct btrfs_key key;
  2086. int ret;
  2087. if (btrfs_fs_incompat(fs_info, NO_HOLES))
  2088. goto out;
  2089. key.objectid = btrfs_ino(inode);
  2090. key.type = BTRFS_EXTENT_DATA_KEY;
  2091. key.offset = offset;
  2092. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  2093. if (ret <= 0) {
  2094. /*
  2095. * We should have dropped this offset, so if we find it then
  2096. * something has gone horribly wrong.
  2097. */
  2098. if (ret == 0)
  2099. ret = -EINVAL;
  2100. return ret;
  2101. }
  2102. leaf = path->nodes[0];
  2103. if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
  2104. u64 num_bytes;
  2105. path->slots[0]--;
  2106. fi = btrfs_item_ptr(leaf, path->slots[0],
  2107. struct btrfs_file_extent_item);
  2108. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  2109. end - offset;
  2110. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  2111. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  2112. btrfs_set_file_extent_offset(leaf, fi, 0);
  2113. btrfs_mark_buffer_dirty(leaf);
  2114. goto out;
  2115. }
  2116. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  2117. u64 num_bytes;
  2118. key.offset = offset;
  2119. btrfs_set_item_key_safe(fs_info, path, &key);
  2120. fi = btrfs_item_ptr(leaf, path->slots[0],
  2121. struct btrfs_file_extent_item);
  2122. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  2123. offset;
  2124. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  2125. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  2126. btrfs_set_file_extent_offset(leaf, fi, 0);
  2127. btrfs_mark_buffer_dirty(leaf);
  2128. goto out;
  2129. }
  2130. btrfs_release_path(path);
  2131. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
  2132. offset, 0, 0, end - offset, 0, end - offset, 0, 0, 0);
  2133. if (ret)
  2134. return ret;
  2135. out:
  2136. btrfs_release_path(path);
  2137. hole_em = alloc_extent_map();
  2138. if (!hole_em) {
  2139. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2140. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
  2141. } else {
  2142. hole_em->start = offset;
  2143. hole_em->len = end - offset;
  2144. hole_em->ram_bytes = hole_em->len;
  2145. hole_em->orig_start = offset;
  2146. hole_em->block_start = EXTENT_MAP_HOLE;
  2147. hole_em->block_len = 0;
  2148. hole_em->orig_block_len = 0;
  2149. hole_em->bdev = fs_info->fs_devices->latest_bdev;
  2150. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  2151. hole_em->generation = trans->transid;
  2152. do {
  2153. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2154. write_lock(&em_tree->lock);
  2155. ret = add_extent_mapping(em_tree, hole_em, 1);
  2156. write_unlock(&em_tree->lock);
  2157. } while (ret == -EEXIST);
  2158. free_extent_map(hole_em);
  2159. if (ret)
  2160. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2161. &inode->runtime_flags);
  2162. }
  2163. return 0;
  2164. }
  2165. /*
  2166. * Find a hole extent on given inode and change start/len to the end of hole
  2167. * extent.(hole/vacuum extent whose em->start <= start &&
  2168. * em->start + em->len > start)
  2169. * When a hole extent is found, return 1 and modify start/len.
  2170. */
  2171. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  2172. {
  2173. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2174. struct extent_map *em;
  2175. int ret = 0;
  2176. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0,
  2177. round_down(*start, fs_info->sectorsize),
  2178. round_up(*len, fs_info->sectorsize), 0);
  2179. if (IS_ERR(em))
  2180. return PTR_ERR(em);
  2181. /* Hole or vacuum extent(only exists in no-hole mode) */
  2182. if (em->block_start == EXTENT_MAP_HOLE) {
  2183. ret = 1;
  2184. *len = em->start + em->len > *start + *len ?
  2185. 0 : *start + *len - em->start - em->len;
  2186. *start = em->start + em->len;
  2187. }
  2188. free_extent_map(em);
  2189. return ret;
  2190. }
  2191. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2192. {
  2193. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2194. struct btrfs_root *root = BTRFS_I(inode)->root;
  2195. struct extent_state *cached_state = NULL;
  2196. struct btrfs_path *path;
  2197. struct btrfs_block_rsv *rsv;
  2198. struct btrfs_trans_handle *trans;
  2199. u64 lockstart;
  2200. u64 lockend;
  2201. u64 tail_start;
  2202. u64 tail_len;
  2203. u64 orig_start = offset;
  2204. u64 cur_offset;
  2205. u64 min_size = btrfs_calc_trans_metadata_size(fs_info, 1);
  2206. u64 drop_end;
  2207. int ret = 0;
  2208. int err = 0;
  2209. unsigned int rsv_count;
  2210. bool same_block;
  2211. bool no_holes = btrfs_fs_incompat(fs_info, NO_HOLES);
  2212. u64 ino_size;
  2213. bool truncated_block = false;
  2214. bool updated_inode = false;
  2215. ret = btrfs_wait_ordered_range(inode, offset, len);
  2216. if (ret)
  2217. return ret;
  2218. inode_lock(inode);
  2219. ino_size = round_up(inode->i_size, fs_info->sectorsize);
  2220. ret = find_first_non_hole(inode, &offset, &len);
  2221. if (ret < 0)
  2222. goto out_only_mutex;
  2223. if (ret && !len) {
  2224. /* Already in a large hole */
  2225. ret = 0;
  2226. goto out_only_mutex;
  2227. }
  2228. lockstart = round_up(offset, btrfs_inode_sectorsize(inode));
  2229. lockend = round_down(offset + len,
  2230. btrfs_inode_sectorsize(inode)) - 1;
  2231. same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
  2232. == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
  2233. /*
  2234. * We needn't truncate any block which is beyond the end of the file
  2235. * because we are sure there is no data there.
  2236. */
  2237. /*
  2238. * Only do this if we are in the same block and we aren't doing the
  2239. * entire block.
  2240. */
  2241. if (same_block && len < fs_info->sectorsize) {
  2242. if (offset < ino_size) {
  2243. truncated_block = true;
  2244. ret = btrfs_truncate_block(inode, offset, len, 0);
  2245. } else {
  2246. ret = 0;
  2247. }
  2248. goto out_only_mutex;
  2249. }
  2250. /* zero back part of the first block */
  2251. if (offset < ino_size) {
  2252. truncated_block = true;
  2253. ret = btrfs_truncate_block(inode, offset, 0, 0);
  2254. if (ret) {
  2255. inode_unlock(inode);
  2256. return ret;
  2257. }
  2258. }
  2259. /* Check the aligned pages after the first unaligned page,
  2260. * if offset != orig_start, which means the first unaligned page
  2261. * including several following pages are already in holes,
  2262. * the extra check can be skipped */
  2263. if (offset == orig_start) {
  2264. /* after truncate page, check hole again */
  2265. len = offset + len - lockstart;
  2266. offset = lockstart;
  2267. ret = find_first_non_hole(inode, &offset, &len);
  2268. if (ret < 0)
  2269. goto out_only_mutex;
  2270. if (ret && !len) {
  2271. ret = 0;
  2272. goto out_only_mutex;
  2273. }
  2274. lockstart = offset;
  2275. }
  2276. /* Check the tail unaligned part is in a hole */
  2277. tail_start = lockend + 1;
  2278. tail_len = offset + len - tail_start;
  2279. if (tail_len) {
  2280. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2281. if (unlikely(ret < 0))
  2282. goto out_only_mutex;
  2283. if (!ret) {
  2284. /* zero the front end of the last page */
  2285. if (tail_start + tail_len < ino_size) {
  2286. truncated_block = true;
  2287. ret = btrfs_truncate_block(inode,
  2288. tail_start + tail_len,
  2289. 0, 1);
  2290. if (ret)
  2291. goto out_only_mutex;
  2292. }
  2293. }
  2294. }
  2295. if (lockend < lockstart) {
  2296. ret = 0;
  2297. goto out_only_mutex;
  2298. }
  2299. while (1) {
  2300. struct btrfs_ordered_extent *ordered;
  2301. truncate_pagecache_range(inode, lockstart, lockend);
  2302. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2303. &cached_state);
  2304. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2305. /*
  2306. * We need to make sure we have no ordered extents in this range
  2307. * and nobody raced in and read a page in this range, if we did
  2308. * we need to try again.
  2309. */
  2310. if ((!ordered ||
  2311. (ordered->file_offset + ordered->len <= lockstart ||
  2312. ordered->file_offset > lockend)) &&
  2313. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2314. if (ordered)
  2315. btrfs_put_ordered_extent(ordered);
  2316. break;
  2317. }
  2318. if (ordered)
  2319. btrfs_put_ordered_extent(ordered);
  2320. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2321. lockend, &cached_state, GFP_NOFS);
  2322. ret = btrfs_wait_ordered_range(inode, lockstart,
  2323. lockend - lockstart + 1);
  2324. if (ret) {
  2325. inode_unlock(inode);
  2326. return ret;
  2327. }
  2328. }
  2329. path = btrfs_alloc_path();
  2330. if (!path) {
  2331. ret = -ENOMEM;
  2332. goto out;
  2333. }
  2334. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  2335. if (!rsv) {
  2336. ret = -ENOMEM;
  2337. goto out_free;
  2338. }
  2339. rsv->size = btrfs_calc_trans_metadata_size(fs_info, 1);
  2340. rsv->failfast = 1;
  2341. /*
  2342. * 1 - update the inode
  2343. * 1 - removing the extents in the range
  2344. * 1 - adding the hole extent if no_holes isn't set
  2345. */
  2346. rsv_count = no_holes ? 2 : 3;
  2347. trans = btrfs_start_transaction(root, rsv_count);
  2348. if (IS_ERR(trans)) {
  2349. err = PTR_ERR(trans);
  2350. goto out_free;
  2351. }
  2352. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
  2353. min_size, 0);
  2354. BUG_ON(ret);
  2355. trans->block_rsv = rsv;
  2356. cur_offset = lockstart;
  2357. len = lockend - cur_offset;
  2358. while (cur_offset < lockend) {
  2359. ret = __btrfs_drop_extents(trans, root, inode, path,
  2360. cur_offset, lockend + 1,
  2361. &drop_end, 1, 0, 0, NULL);
  2362. if (ret != -ENOSPC)
  2363. break;
  2364. trans->block_rsv = &fs_info->trans_block_rsv;
  2365. if (cur_offset < drop_end && cur_offset < ino_size) {
  2366. ret = fill_holes(trans, BTRFS_I(inode), path,
  2367. cur_offset, drop_end);
  2368. if (ret) {
  2369. /*
  2370. * If we failed then we didn't insert our hole
  2371. * entries for the area we dropped, so now the
  2372. * fs is corrupted, so we must abort the
  2373. * transaction.
  2374. */
  2375. btrfs_abort_transaction(trans, ret);
  2376. err = ret;
  2377. break;
  2378. }
  2379. }
  2380. cur_offset = drop_end;
  2381. ret = btrfs_update_inode(trans, root, inode);
  2382. if (ret) {
  2383. err = ret;
  2384. break;
  2385. }
  2386. btrfs_end_transaction(trans);
  2387. btrfs_btree_balance_dirty(fs_info);
  2388. trans = btrfs_start_transaction(root, rsv_count);
  2389. if (IS_ERR(trans)) {
  2390. ret = PTR_ERR(trans);
  2391. trans = NULL;
  2392. break;
  2393. }
  2394. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
  2395. rsv, min_size, 0);
  2396. BUG_ON(ret); /* shouldn't happen */
  2397. trans->block_rsv = rsv;
  2398. ret = find_first_non_hole(inode, &cur_offset, &len);
  2399. if (unlikely(ret < 0))
  2400. break;
  2401. if (ret && !len) {
  2402. ret = 0;
  2403. break;
  2404. }
  2405. }
  2406. if (ret) {
  2407. err = ret;
  2408. goto out_trans;
  2409. }
  2410. trans->block_rsv = &fs_info->trans_block_rsv;
  2411. /*
  2412. * If we are using the NO_HOLES feature we might have had already an
  2413. * hole that overlaps a part of the region [lockstart, lockend] and
  2414. * ends at (or beyond) lockend. Since we have no file extent items to
  2415. * represent holes, drop_end can be less than lockend and so we must
  2416. * make sure we have an extent map representing the existing hole (the
  2417. * call to __btrfs_drop_extents() might have dropped the existing extent
  2418. * map representing the existing hole), otherwise the fast fsync path
  2419. * will not record the existence of the hole region
  2420. * [existing_hole_start, lockend].
  2421. */
  2422. if (drop_end <= lockend)
  2423. drop_end = lockend + 1;
  2424. /*
  2425. * Don't insert file hole extent item if it's for a range beyond eof
  2426. * (because it's useless) or if it represents a 0 bytes range (when
  2427. * cur_offset == drop_end).
  2428. */
  2429. if (cur_offset < ino_size && cur_offset < drop_end) {
  2430. ret = fill_holes(trans, BTRFS_I(inode), path,
  2431. cur_offset, drop_end);
  2432. if (ret) {
  2433. /* Same comment as above. */
  2434. btrfs_abort_transaction(trans, ret);
  2435. err = ret;
  2436. goto out_trans;
  2437. }
  2438. }
  2439. out_trans:
  2440. if (!trans)
  2441. goto out_free;
  2442. inode_inc_iversion(inode);
  2443. inode->i_mtime = inode->i_ctime = current_time(inode);
  2444. trans->block_rsv = &fs_info->trans_block_rsv;
  2445. ret = btrfs_update_inode(trans, root, inode);
  2446. updated_inode = true;
  2447. btrfs_end_transaction(trans);
  2448. btrfs_btree_balance_dirty(fs_info);
  2449. out_free:
  2450. btrfs_free_path(path);
  2451. btrfs_free_block_rsv(fs_info, rsv);
  2452. out:
  2453. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2454. &cached_state, GFP_NOFS);
  2455. out_only_mutex:
  2456. if (!updated_inode && truncated_block && !ret && !err) {
  2457. /*
  2458. * If we only end up zeroing part of a page, we still need to
  2459. * update the inode item, so that all the time fields are
  2460. * updated as well as the necessary btrfs inode in memory fields
  2461. * for detecting, at fsync time, if the inode isn't yet in the
  2462. * log tree or it's there but not up to date.
  2463. */
  2464. trans = btrfs_start_transaction(root, 1);
  2465. if (IS_ERR(trans)) {
  2466. err = PTR_ERR(trans);
  2467. } else {
  2468. err = btrfs_update_inode(trans, root, inode);
  2469. ret = btrfs_end_transaction(trans);
  2470. }
  2471. }
  2472. inode_unlock(inode);
  2473. if (ret && !err)
  2474. err = ret;
  2475. return err;
  2476. }
  2477. /* Helper structure to record which range is already reserved */
  2478. struct falloc_range {
  2479. struct list_head list;
  2480. u64 start;
  2481. u64 len;
  2482. };
  2483. /*
  2484. * Helper function to add falloc range
  2485. *
  2486. * Caller should have locked the larger range of extent containing
  2487. * [start, len)
  2488. */
  2489. static int add_falloc_range(struct list_head *head, u64 start, u64 len)
  2490. {
  2491. struct falloc_range *prev = NULL;
  2492. struct falloc_range *range = NULL;
  2493. if (list_empty(head))
  2494. goto insert;
  2495. /*
  2496. * As fallocate iterate by bytenr order, we only need to check
  2497. * the last range.
  2498. */
  2499. prev = list_entry(head->prev, struct falloc_range, list);
  2500. if (prev->start + prev->len == start) {
  2501. prev->len += len;
  2502. return 0;
  2503. }
  2504. insert:
  2505. range = kmalloc(sizeof(*range), GFP_KERNEL);
  2506. if (!range)
  2507. return -ENOMEM;
  2508. range->start = start;
  2509. range->len = len;
  2510. list_add_tail(&range->list, head);
  2511. return 0;
  2512. }
  2513. static long btrfs_fallocate(struct file *file, int mode,
  2514. loff_t offset, loff_t len)
  2515. {
  2516. struct inode *inode = file_inode(file);
  2517. struct extent_state *cached_state = NULL;
  2518. struct extent_changeset *data_reserved = NULL;
  2519. struct falloc_range *range;
  2520. struct falloc_range *tmp;
  2521. struct list_head reserve_list;
  2522. u64 cur_offset;
  2523. u64 last_byte;
  2524. u64 alloc_start;
  2525. u64 alloc_end;
  2526. u64 alloc_hint = 0;
  2527. u64 locked_end;
  2528. u64 actual_end = 0;
  2529. struct extent_map *em;
  2530. int blocksize = btrfs_inode_sectorsize(inode);
  2531. int ret;
  2532. alloc_start = round_down(offset, blocksize);
  2533. alloc_end = round_up(offset + len, blocksize);
  2534. cur_offset = alloc_start;
  2535. /* Make sure we aren't being give some crap mode */
  2536. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2537. return -EOPNOTSUPP;
  2538. if (mode & FALLOC_FL_PUNCH_HOLE)
  2539. return btrfs_punch_hole(inode, offset, len);
  2540. /*
  2541. * Only trigger disk allocation, don't trigger qgroup reserve
  2542. *
  2543. * For qgroup space, it will be checked later.
  2544. */
  2545. ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
  2546. alloc_end - alloc_start);
  2547. if (ret < 0)
  2548. return ret;
  2549. inode_lock(inode);
  2550. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
  2551. ret = inode_newsize_ok(inode, offset + len);
  2552. if (ret)
  2553. goto out;
  2554. }
  2555. /*
  2556. * TODO: Move these two operations after we have checked
  2557. * accurate reserved space, or fallocate can still fail but
  2558. * with page truncated or size expanded.
  2559. *
  2560. * But that's a minor problem and won't do much harm BTW.
  2561. */
  2562. if (alloc_start > inode->i_size) {
  2563. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2564. alloc_start);
  2565. if (ret)
  2566. goto out;
  2567. } else if (offset + len > inode->i_size) {
  2568. /*
  2569. * If we are fallocating from the end of the file onward we
  2570. * need to zero out the end of the block if i_size lands in the
  2571. * middle of a block.
  2572. */
  2573. ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
  2574. if (ret)
  2575. goto out;
  2576. }
  2577. /*
  2578. * wait for ordered IO before we have any locks. We'll loop again
  2579. * below with the locks held.
  2580. */
  2581. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2582. alloc_end - alloc_start);
  2583. if (ret)
  2584. goto out;
  2585. locked_end = alloc_end - 1;
  2586. while (1) {
  2587. struct btrfs_ordered_extent *ordered;
  2588. /* the extent lock is ordered inside the running
  2589. * transaction
  2590. */
  2591. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2592. locked_end, &cached_state);
  2593. ordered = btrfs_lookup_first_ordered_extent(inode,
  2594. alloc_end - 1);
  2595. if (ordered &&
  2596. ordered->file_offset + ordered->len > alloc_start &&
  2597. ordered->file_offset < alloc_end) {
  2598. btrfs_put_ordered_extent(ordered);
  2599. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2600. alloc_start, locked_end,
  2601. &cached_state, GFP_KERNEL);
  2602. /*
  2603. * we can't wait on the range with the transaction
  2604. * running or with the extent lock held
  2605. */
  2606. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2607. alloc_end - alloc_start);
  2608. if (ret)
  2609. goto out;
  2610. } else {
  2611. if (ordered)
  2612. btrfs_put_ordered_extent(ordered);
  2613. break;
  2614. }
  2615. }
  2616. /* First, check if we exceed the qgroup limit */
  2617. INIT_LIST_HEAD(&reserve_list);
  2618. while (1) {
  2619. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
  2620. alloc_end - cur_offset, 0);
  2621. if (IS_ERR(em)) {
  2622. ret = PTR_ERR(em);
  2623. break;
  2624. }
  2625. last_byte = min(extent_map_end(em), alloc_end);
  2626. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2627. last_byte = ALIGN(last_byte, blocksize);
  2628. if (em->block_start == EXTENT_MAP_HOLE ||
  2629. (cur_offset >= inode->i_size &&
  2630. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2631. ret = add_falloc_range(&reserve_list, cur_offset,
  2632. last_byte - cur_offset);
  2633. if (ret < 0) {
  2634. free_extent_map(em);
  2635. break;
  2636. }
  2637. ret = btrfs_qgroup_reserve_data(inode, &data_reserved,
  2638. cur_offset, last_byte - cur_offset);
  2639. if (ret < 0) {
  2640. free_extent_map(em);
  2641. break;
  2642. }
  2643. } else {
  2644. /*
  2645. * Do not need to reserve unwritten extent for this
  2646. * range, free reserved data space first, otherwise
  2647. * it'll result in false ENOSPC error.
  2648. */
  2649. btrfs_free_reserved_data_space(inode, data_reserved,
  2650. cur_offset, last_byte - cur_offset);
  2651. }
  2652. free_extent_map(em);
  2653. cur_offset = last_byte;
  2654. if (cur_offset >= alloc_end)
  2655. break;
  2656. }
  2657. /*
  2658. * If ret is still 0, means we're OK to fallocate.
  2659. * Or just cleanup the list and exit.
  2660. */
  2661. list_for_each_entry_safe(range, tmp, &reserve_list, list) {
  2662. if (!ret)
  2663. ret = btrfs_prealloc_file_range(inode, mode,
  2664. range->start,
  2665. range->len, i_blocksize(inode),
  2666. offset + len, &alloc_hint);
  2667. else
  2668. btrfs_free_reserved_data_space(inode,
  2669. data_reserved, range->start,
  2670. range->len);
  2671. list_del(&range->list);
  2672. kfree(range);
  2673. }
  2674. if (ret < 0)
  2675. goto out_unlock;
  2676. if (actual_end > inode->i_size &&
  2677. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2678. struct btrfs_trans_handle *trans;
  2679. struct btrfs_root *root = BTRFS_I(inode)->root;
  2680. /*
  2681. * We didn't need to allocate any more space, but we
  2682. * still extended the size of the file so we need to
  2683. * update i_size and the inode item.
  2684. */
  2685. trans = btrfs_start_transaction(root, 1);
  2686. if (IS_ERR(trans)) {
  2687. ret = PTR_ERR(trans);
  2688. } else {
  2689. inode->i_ctime = current_time(inode);
  2690. i_size_write(inode, actual_end);
  2691. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2692. ret = btrfs_update_inode(trans, root, inode);
  2693. if (ret)
  2694. btrfs_end_transaction(trans);
  2695. else
  2696. ret = btrfs_end_transaction(trans);
  2697. }
  2698. }
  2699. out_unlock:
  2700. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2701. &cached_state, GFP_KERNEL);
  2702. out:
  2703. inode_unlock(inode);
  2704. /* Let go of our reservation. */
  2705. if (ret != 0)
  2706. btrfs_free_reserved_data_space(inode, data_reserved,
  2707. alloc_start, alloc_end - cur_offset);
  2708. extent_changeset_free(data_reserved);
  2709. return ret;
  2710. }
  2711. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2712. {
  2713. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2714. struct extent_map *em = NULL;
  2715. struct extent_state *cached_state = NULL;
  2716. u64 lockstart;
  2717. u64 lockend;
  2718. u64 start;
  2719. u64 len;
  2720. int ret = 0;
  2721. if (inode->i_size == 0)
  2722. return -ENXIO;
  2723. /*
  2724. * *offset can be negative, in this case we start finding DATA/HOLE from
  2725. * the very start of the file.
  2726. */
  2727. start = max_t(loff_t, 0, *offset);
  2728. lockstart = round_down(start, fs_info->sectorsize);
  2729. lockend = round_up(i_size_read(inode),
  2730. fs_info->sectorsize);
  2731. if (lockend <= lockstart)
  2732. lockend = lockstart + fs_info->sectorsize;
  2733. lockend--;
  2734. len = lockend - lockstart + 1;
  2735. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2736. &cached_state);
  2737. while (start < inode->i_size) {
  2738. em = btrfs_get_extent_fiemap(BTRFS_I(inode), NULL, 0,
  2739. start, len, 0);
  2740. if (IS_ERR(em)) {
  2741. ret = PTR_ERR(em);
  2742. em = NULL;
  2743. break;
  2744. }
  2745. if (whence == SEEK_HOLE &&
  2746. (em->block_start == EXTENT_MAP_HOLE ||
  2747. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2748. break;
  2749. else if (whence == SEEK_DATA &&
  2750. (em->block_start != EXTENT_MAP_HOLE &&
  2751. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2752. break;
  2753. start = em->start + em->len;
  2754. free_extent_map(em);
  2755. em = NULL;
  2756. cond_resched();
  2757. }
  2758. free_extent_map(em);
  2759. if (!ret) {
  2760. if (whence == SEEK_DATA && start >= inode->i_size)
  2761. ret = -ENXIO;
  2762. else
  2763. *offset = min_t(loff_t, start, inode->i_size);
  2764. }
  2765. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2766. &cached_state, GFP_NOFS);
  2767. return ret;
  2768. }
  2769. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2770. {
  2771. struct inode *inode = file->f_mapping->host;
  2772. int ret;
  2773. inode_lock(inode);
  2774. switch (whence) {
  2775. case SEEK_END:
  2776. case SEEK_CUR:
  2777. offset = generic_file_llseek(file, offset, whence);
  2778. goto out;
  2779. case SEEK_DATA:
  2780. case SEEK_HOLE:
  2781. if (offset >= i_size_read(inode)) {
  2782. inode_unlock(inode);
  2783. return -ENXIO;
  2784. }
  2785. ret = find_desired_extent(inode, &offset, whence);
  2786. if (ret) {
  2787. inode_unlock(inode);
  2788. return ret;
  2789. }
  2790. }
  2791. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2792. out:
  2793. inode_unlock(inode);
  2794. return offset;
  2795. }
  2796. static int btrfs_file_open(struct inode *inode, struct file *filp)
  2797. {
  2798. filp->f_mode |= FMODE_NOWAIT;
  2799. return generic_file_open(inode, filp);
  2800. }
  2801. const struct file_operations btrfs_file_operations = {
  2802. .llseek = btrfs_file_llseek,
  2803. .read_iter = generic_file_read_iter,
  2804. .splice_read = generic_file_splice_read,
  2805. .write_iter = btrfs_file_write_iter,
  2806. .mmap = btrfs_file_mmap,
  2807. .open = btrfs_file_open,
  2808. .release = btrfs_release_file,
  2809. .fsync = btrfs_sync_file,
  2810. .fallocate = btrfs_fallocate,
  2811. .unlocked_ioctl = btrfs_ioctl,
  2812. #ifdef CONFIG_COMPAT
  2813. .compat_ioctl = btrfs_compat_ioctl,
  2814. #endif
  2815. .clone_file_range = btrfs_clone_file_range,
  2816. .dedupe_file_range = btrfs_dedupe_file_range,
  2817. };
  2818. void btrfs_auto_defrag_exit(void)
  2819. {
  2820. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2821. }
  2822. int btrfs_auto_defrag_init(void)
  2823. {
  2824. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2825. sizeof(struct inode_defrag), 0,
  2826. SLAB_MEM_SPREAD,
  2827. NULL);
  2828. if (!btrfs_inode_defrag_cachep)
  2829. return -ENOMEM;
  2830. return 0;
  2831. }
  2832. int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
  2833. {
  2834. int ret;
  2835. /*
  2836. * So with compression we will find and lock a dirty page and clear the
  2837. * first one as dirty, setup an async extent, and immediately return
  2838. * with the entire range locked but with nobody actually marked with
  2839. * writeback. So we can't just filemap_write_and_wait_range() and
  2840. * expect it to work since it will just kick off a thread to do the
  2841. * actual work. So we need to call filemap_fdatawrite_range _again_
  2842. * since it will wait on the page lock, which won't be unlocked until
  2843. * after the pages have been marked as writeback and so we're good to go
  2844. * from there. We have to do this otherwise we'll miss the ordered
  2845. * extents and that results in badness. Please Josef, do not think you
  2846. * know better and pull this out at some point in the future, it is
  2847. * right and you are wrong.
  2848. */
  2849. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2850. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  2851. &BTRFS_I(inode)->runtime_flags))
  2852. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2853. return ret;
  2854. }