file.c 79 KB

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