file.c 82 KB

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