file.c 79 KB

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