file.c 80 KB

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