file.c 69 KB

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