file.c 71 KB

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