file.c 80 KB

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