file.c 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  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. check_can_nocow(inode, pos, &write_bytes) > 0) {
  1372. /*
  1373. * For nodata cow case, no need to reserve
  1374. * data space.
  1375. */
  1376. only_release_metadata = true;
  1377. /*
  1378. * our prealloc extent may be smaller than
  1379. * write_bytes, so scale down.
  1380. */
  1381. num_pages = DIV_ROUND_UP(write_bytes + offset,
  1382. PAGE_CACHE_SIZE);
  1383. reserve_bytes = num_pages << PAGE_CACHE_SHIFT;
  1384. goto reserve_metadata;
  1385. }
  1386. ret = btrfs_check_data_free_space(inode, pos, write_bytes);
  1387. if (ret < 0)
  1388. break;
  1389. reserve_metadata:
  1390. ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes);
  1391. if (ret) {
  1392. if (!only_release_metadata)
  1393. btrfs_free_reserved_data_space(inode, pos,
  1394. write_bytes);
  1395. else
  1396. btrfs_end_write_no_snapshoting(root);
  1397. break;
  1398. }
  1399. release_bytes = reserve_bytes;
  1400. need_unlock = false;
  1401. again:
  1402. /*
  1403. * This is going to setup the pages array with the number of
  1404. * pages we want, so we don't really need to worry about the
  1405. * contents of pages from loop to loop
  1406. */
  1407. ret = prepare_pages(inode, pages, num_pages,
  1408. pos, write_bytes,
  1409. force_page_uptodate);
  1410. if (ret)
  1411. break;
  1412. ret = lock_and_cleanup_extent_if_need(inode, pages, num_pages,
  1413. pos, &lockstart, &lockend,
  1414. &cached_state);
  1415. if (ret < 0) {
  1416. if (ret == -EAGAIN)
  1417. goto again;
  1418. break;
  1419. } else if (ret > 0) {
  1420. need_unlock = true;
  1421. ret = 0;
  1422. }
  1423. copied = btrfs_copy_from_user(pos, num_pages,
  1424. write_bytes, pages, i);
  1425. /*
  1426. * if we have trouble faulting in the pages, fall
  1427. * back to one page at a time
  1428. */
  1429. if (copied < write_bytes)
  1430. nrptrs = 1;
  1431. if (copied == 0) {
  1432. force_page_uptodate = true;
  1433. dirty_pages = 0;
  1434. } else {
  1435. force_page_uptodate = false;
  1436. dirty_pages = DIV_ROUND_UP(copied + offset,
  1437. PAGE_CACHE_SIZE);
  1438. }
  1439. /*
  1440. * If we had a short copy we need to release the excess delaloc
  1441. * bytes we reserved. We need to increment outstanding_extents
  1442. * because btrfs_delalloc_release_space will decrement it, but
  1443. * we still have an outstanding extent for the chunk we actually
  1444. * managed to copy.
  1445. */
  1446. if (num_pages > dirty_pages) {
  1447. release_bytes = (num_pages - dirty_pages) <<
  1448. PAGE_CACHE_SHIFT;
  1449. if (copied > 0) {
  1450. spin_lock(&BTRFS_I(inode)->lock);
  1451. BTRFS_I(inode)->outstanding_extents++;
  1452. spin_unlock(&BTRFS_I(inode)->lock);
  1453. }
  1454. if (only_release_metadata) {
  1455. btrfs_delalloc_release_metadata(inode,
  1456. release_bytes);
  1457. } else {
  1458. u64 __pos;
  1459. __pos = round_down(pos, root->sectorsize) +
  1460. (dirty_pages << PAGE_CACHE_SHIFT);
  1461. btrfs_delalloc_release_space(inode, __pos,
  1462. release_bytes);
  1463. }
  1464. }
  1465. release_bytes = dirty_pages << PAGE_CACHE_SHIFT;
  1466. if (copied > 0)
  1467. ret = btrfs_dirty_pages(root, inode, pages,
  1468. dirty_pages, pos, copied,
  1469. NULL);
  1470. if (need_unlock)
  1471. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1472. lockstart, lockend, &cached_state,
  1473. GFP_NOFS);
  1474. if (ret) {
  1475. btrfs_drop_pages(pages, num_pages);
  1476. break;
  1477. }
  1478. release_bytes = 0;
  1479. if (only_release_metadata)
  1480. btrfs_end_write_no_snapshoting(root);
  1481. if (only_release_metadata && copied > 0) {
  1482. lockstart = round_down(pos, root->sectorsize);
  1483. lockend = lockstart +
  1484. (dirty_pages << PAGE_CACHE_SHIFT) - 1;
  1485. set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  1486. lockend, EXTENT_NORESERVE, NULL,
  1487. NULL, GFP_NOFS);
  1488. only_release_metadata = false;
  1489. }
  1490. btrfs_drop_pages(pages, num_pages);
  1491. cond_resched();
  1492. balance_dirty_pages_ratelimited(inode->i_mapping);
  1493. if (dirty_pages < (root->nodesize >> PAGE_CACHE_SHIFT) + 1)
  1494. btrfs_btree_balance_dirty(root);
  1495. pos += copied;
  1496. num_written += copied;
  1497. }
  1498. kfree(pages);
  1499. if (release_bytes) {
  1500. if (only_release_metadata) {
  1501. btrfs_end_write_no_snapshoting(root);
  1502. btrfs_delalloc_release_metadata(inode, release_bytes);
  1503. } else {
  1504. btrfs_delalloc_release_space(inode, pos, release_bytes);
  1505. }
  1506. }
  1507. return num_written ? num_written : ret;
  1508. }
  1509. static ssize_t __btrfs_direct_write(struct kiocb *iocb,
  1510. struct iov_iter *from,
  1511. loff_t pos)
  1512. {
  1513. struct file *file = iocb->ki_filp;
  1514. struct inode *inode = file_inode(file);
  1515. ssize_t written;
  1516. ssize_t written_buffered;
  1517. loff_t endbyte;
  1518. int err;
  1519. written = generic_file_direct_write(iocb, from, pos);
  1520. if (written < 0 || !iov_iter_count(from))
  1521. return written;
  1522. pos += written;
  1523. written_buffered = __btrfs_buffered_write(file, from, pos);
  1524. if (written_buffered < 0) {
  1525. err = written_buffered;
  1526. goto out;
  1527. }
  1528. /*
  1529. * Ensure all data is persisted. We want the next direct IO read to be
  1530. * able to read what was just written.
  1531. */
  1532. endbyte = pos + written_buffered - 1;
  1533. err = btrfs_fdatawrite_range(inode, pos, endbyte);
  1534. if (err)
  1535. goto out;
  1536. err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
  1537. if (err)
  1538. goto out;
  1539. written += written_buffered;
  1540. iocb->ki_pos = pos + written_buffered;
  1541. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
  1542. endbyte >> PAGE_CACHE_SHIFT);
  1543. out:
  1544. return written ? written : err;
  1545. }
  1546. static void update_time_for_write(struct inode *inode)
  1547. {
  1548. struct timespec now;
  1549. if (IS_NOCMTIME(inode))
  1550. return;
  1551. now = current_fs_time(inode->i_sb);
  1552. if (!timespec_equal(&inode->i_mtime, &now))
  1553. inode->i_mtime = now;
  1554. if (!timespec_equal(&inode->i_ctime, &now))
  1555. inode->i_ctime = now;
  1556. if (IS_I_VERSION(inode))
  1557. inode_inc_iversion(inode);
  1558. }
  1559. static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
  1560. struct iov_iter *from)
  1561. {
  1562. struct file *file = iocb->ki_filp;
  1563. struct inode *inode = file_inode(file);
  1564. struct btrfs_root *root = BTRFS_I(inode)->root;
  1565. u64 start_pos;
  1566. u64 end_pos;
  1567. ssize_t num_written = 0;
  1568. bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
  1569. ssize_t err;
  1570. loff_t pos;
  1571. size_t count;
  1572. mutex_lock(&inode->i_mutex);
  1573. err = generic_write_checks(iocb, from);
  1574. if (err <= 0) {
  1575. mutex_unlock(&inode->i_mutex);
  1576. return err;
  1577. }
  1578. current->backing_dev_info = inode_to_bdi(inode);
  1579. err = file_remove_privs(file);
  1580. if (err) {
  1581. mutex_unlock(&inode->i_mutex);
  1582. goto out;
  1583. }
  1584. /*
  1585. * If BTRFS flips readonly due to some impossible error
  1586. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1587. * although we have opened a file as writable, we have
  1588. * to stop this write operation to ensure FS consistency.
  1589. */
  1590. if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
  1591. mutex_unlock(&inode->i_mutex);
  1592. err = -EROFS;
  1593. goto out;
  1594. }
  1595. /*
  1596. * We reserve space for updating the inode when we reserve space for the
  1597. * extent we are going to write, so we will enospc out there. We don't
  1598. * need to start yet another transaction to update the inode as we will
  1599. * update the inode when we finish writing whatever data we write.
  1600. */
  1601. update_time_for_write(inode);
  1602. pos = iocb->ki_pos;
  1603. count = iov_iter_count(from);
  1604. start_pos = round_down(pos, root->sectorsize);
  1605. if (start_pos > i_size_read(inode)) {
  1606. /* Expand hole size to cover write data, preventing empty gap */
  1607. end_pos = round_up(pos + count, root->sectorsize);
  1608. err = btrfs_cont_expand(inode, i_size_read(inode), end_pos);
  1609. if (err) {
  1610. mutex_unlock(&inode->i_mutex);
  1611. goto out;
  1612. }
  1613. }
  1614. if (sync)
  1615. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1616. if (iocb->ki_flags & IOCB_DIRECT) {
  1617. num_written = __btrfs_direct_write(iocb, from, pos);
  1618. } else {
  1619. num_written = __btrfs_buffered_write(file, from, pos);
  1620. if (num_written > 0)
  1621. iocb->ki_pos = pos + num_written;
  1622. }
  1623. mutex_unlock(&inode->i_mutex);
  1624. /*
  1625. * We also have to set last_sub_trans to the current log transid,
  1626. * otherwise subsequent syncs to a file that's been synced in this
  1627. * transaction will appear to have already occured.
  1628. */
  1629. spin_lock(&BTRFS_I(inode)->lock);
  1630. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1631. spin_unlock(&BTRFS_I(inode)->lock);
  1632. if (num_written > 0) {
  1633. err = generic_write_sync(file, pos, num_written);
  1634. if (err < 0)
  1635. num_written = err;
  1636. }
  1637. if (sync)
  1638. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1639. out:
  1640. current->backing_dev_info = NULL;
  1641. return num_written ? num_written : err;
  1642. }
  1643. int btrfs_release_file(struct inode *inode, struct file *filp)
  1644. {
  1645. if (filp->private_data)
  1646. btrfs_ioctl_trans_end(filp);
  1647. /*
  1648. * ordered_data_close is set by settattr when we are about to truncate
  1649. * a file from a non-zero size to a zero size. This tries to
  1650. * flush down new bytes that may have been written if the
  1651. * application were using truncate to replace a file in place.
  1652. */
  1653. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1654. &BTRFS_I(inode)->runtime_flags))
  1655. filemap_flush(inode->i_mapping);
  1656. return 0;
  1657. }
  1658. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1659. {
  1660. int ret;
  1661. struct blk_plug plug;
  1662. /*
  1663. * This is only called in fsync, which would do synchronous writes, so
  1664. * a plug can merge adjacent IOs as much as possible. Esp. in case of
  1665. * multiple disks using raid profile, a large IO can be split to
  1666. * several segments of stripe length (currently 64K).
  1667. */
  1668. blk_start_plug(&plug);
  1669. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1670. ret = btrfs_fdatawrite_range(inode, start, end);
  1671. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1672. blk_finish_plug(&plug);
  1673. return ret;
  1674. }
  1675. /*
  1676. * fsync call for both files and directories. This logs the inode into
  1677. * the tree log instead of forcing full commits whenever possible.
  1678. *
  1679. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1680. * in the metadata btree are up to date for copying to the log.
  1681. *
  1682. * It drops the inode mutex before doing the tree log commit. This is an
  1683. * important optimization for directories because holding the mutex prevents
  1684. * new operations on the dir while we write to disk.
  1685. */
  1686. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1687. {
  1688. struct dentry *dentry = file_dentry(file);
  1689. struct inode *inode = d_inode(dentry);
  1690. struct btrfs_root *root = BTRFS_I(inode)->root;
  1691. struct btrfs_trans_handle *trans;
  1692. struct btrfs_log_ctx ctx;
  1693. int ret = 0;
  1694. bool full_sync = 0;
  1695. u64 len;
  1696. /*
  1697. * The range length can be represented by u64, we have to do the typecasts
  1698. * to avoid signed overflow if it's [0, LLONG_MAX] eg. from fsync()
  1699. */
  1700. len = (u64)end - (u64)start + 1;
  1701. trace_btrfs_sync_file(file, datasync);
  1702. /*
  1703. * We write the dirty pages in the range and wait until they complete
  1704. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1705. * multi-task, and make the performance up. See
  1706. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1707. */
  1708. ret = start_ordered_ops(inode, start, end);
  1709. if (ret)
  1710. return ret;
  1711. mutex_lock(&inode->i_mutex);
  1712. atomic_inc(&root->log_batch);
  1713. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1714. &BTRFS_I(inode)->runtime_flags);
  1715. /*
  1716. * We might have have had more pages made dirty after calling
  1717. * start_ordered_ops and before acquiring the inode's i_mutex.
  1718. */
  1719. if (full_sync) {
  1720. /*
  1721. * For a full sync, we need to make sure any ordered operations
  1722. * start and finish before we start logging the inode, so that
  1723. * all extents are persisted and the respective file extent
  1724. * items are in the fs/subvol btree.
  1725. */
  1726. ret = btrfs_wait_ordered_range(inode, start, len);
  1727. } else {
  1728. /*
  1729. * Start any new ordered operations before starting to log the
  1730. * inode. We will wait for them to finish in btrfs_sync_log().
  1731. *
  1732. * Right before acquiring the inode's mutex, we might have new
  1733. * writes dirtying pages, which won't immediately start the
  1734. * respective ordered operations - that is done through the
  1735. * fill_delalloc callbacks invoked from the writepage and
  1736. * writepages address space operations. So make sure we start
  1737. * all ordered operations before starting to log our inode. Not
  1738. * doing this means that while logging the inode, writeback
  1739. * could start and invoke writepage/writepages, which would call
  1740. * the fill_delalloc callbacks (cow_file_range,
  1741. * submit_compressed_extents). These callbacks add first an
  1742. * extent map to the modified list of extents and then create
  1743. * the respective ordered operation, which means in
  1744. * tree-log.c:btrfs_log_inode() we might capture all existing
  1745. * ordered operations (with btrfs_get_logged_extents()) before
  1746. * the fill_delalloc callback adds its ordered operation, and by
  1747. * the time we visit the modified list of extent maps (with
  1748. * btrfs_log_changed_extents()), we see and process the extent
  1749. * map they created. We then use the extent map to construct a
  1750. * file extent item for logging without waiting for the
  1751. * respective ordered operation to finish - this file extent
  1752. * item points to a disk location that might not have yet been
  1753. * written to, containing random data - so after a crash a log
  1754. * replay will make our inode have file extent items that point
  1755. * to disk locations containing invalid data, as we returned
  1756. * success to userspace without waiting for the respective
  1757. * ordered operation to finish, because it wasn't captured by
  1758. * btrfs_get_logged_extents().
  1759. */
  1760. ret = start_ordered_ops(inode, start, end);
  1761. }
  1762. if (ret) {
  1763. mutex_unlock(&inode->i_mutex);
  1764. goto out;
  1765. }
  1766. atomic_inc(&root->log_batch);
  1767. /*
  1768. * If the last transaction that changed this file was before the current
  1769. * transaction and we have the full sync flag set in our inode, we can
  1770. * bail out now without any syncing.
  1771. *
  1772. * Note that we can't bail out if the full sync flag isn't set. This is
  1773. * because when the full sync flag is set we start all ordered extents
  1774. * and wait for them to fully complete - when they complete they update
  1775. * the inode's last_trans field through:
  1776. *
  1777. * btrfs_finish_ordered_io() ->
  1778. * btrfs_update_inode_fallback() ->
  1779. * btrfs_update_inode() ->
  1780. * btrfs_set_inode_last_trans()
  1781. *
  1782. * So we are sure that last_trans is up to date and can do this check to
  1783. * bail out safely. For the fast path, when the full sync flag is not
  1784. * set in our inode, we can not do it because we start only our ordered
  1785. * extents and don't wait for them to complete (that is when
  1786. * btrfs_finish_ordered_io runs), so here at this point their last_trans
  1787. * value might be less than or equals to fs_info->last_trans_committed,
  1788. * and setting a speculative last_trans for an inode when a buffered
  1789. * write is made (such as fs_info->generation + 1 for example) would not
  1790. * be reliable since after setting the value and before fsync is called
  1791. * any number of transactions can start and commit (transaction kthread
  1792. * commits the current transaction periodically), and a transaction
  1793. * commit does not start nor waits for ordered extents to complete.
  1794. */
  1795. smp_mb();
  1796. if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
  1797. (BTRFS_I(inode)->last_trans <=
  1798. root->fs_info->last_trans_committed &&
  1799. (full_sync ||
  1800. !btrfs_have_ordered_extents_in_range(inode, start, len)))) {
  1801. /*
  1802. * We'v had everything committed since the last time we were
  1803. * modified so clear this flag in case it was set for whatever
  1804. * reason, it's no longer relevant.
  1805. */
  1806. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1807. &BTRFS_I(inode)->runtime_flags);
  1808. mutex_unlock(&inode->i_mutex);
  1809. goto out;
  1810. }
  1811. /*
  1812. * ok we haven't committed the transaction yet, lets do a commit
  1813. */
  1814. if (file->private_data)
  1815. btrfs_ioctl_trans_end(file);
  1816. /*
  1817. * We use start here because we will need to wait on the IO to complete
  1818. * in btrfs_sync_log, which could require joining a transaction (for
  1819. * example checking cross references in the nocow path). If we use join
  1820. * here we could get into a situation where we're waiting on IO to
  1821. * happen that is blocked on a transaction trying to commit. With start
  1822. * we inc the extwriter counter, so we wait for all extwriters to exit
  1823. * before we start blocking join'ers. This comment is to keep somebody
  1824. * from thinking they are super smart and changing this to
  1825. * btrfs_join_transaction *cough*Josef*cough*.
  1826. */
  1827. trans = btrfs_start_transaction(root, 0);
  1828. if (IS_ERR(trans)) {
  1829. ret = PTR_ERR(trans);
  1830. mutex_unlock(&inode->i_mutex);
  1831. goto out;
  1832. }
  1833. trans->sync = true;
  1834. btrfs_init_log_ctx(&ctx);
  1835. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1836. if (ret < 0) {
  1837. /* Fallthrough and commit/free transaction. */
  1838. ret = 1;
  1839. }
  1840. /* we've logged all the items and now have a consistent
  1841. * version of the file in the log. It is possible that
  1842. * someone will come in and modify the file, but that's
  1843. * fine because the log is consistent on disk, and we
  1844. * have references to all of the file's extents
  1845. *
  1846. * It is possible that someone will come in and log the
  1847. * file again, but that will end up using the synchronization
  1848. * inside btrfs_sync_log to keep things safe.
  1849. */
  1850. mutex_unlock(&inode->i_mutex);
  1851. /*
  1852. * If any of the ordered extents had an error, just return it to user
  1853. * space, so that the application knows some writes didn't succeed and
  1854. * can take proper action (retry for e.g.). Blindly committing the
  1855. * transaction in this case, would fool userspace that everything was
  1856. * successful. And we also want to make sure our log doesn't contain
  1857. * file extent items pointing to extents that weren't fully written to -
  1858. * just like in the non fast fsync path, where we check for the ordered
  1859. * operation's error flag before writing to the log tree and return -EIO
  1860. * if any of them had this flag set (btrfs_wait_ordered_range) -
  1861. * therefore we need to check for errors in the ordered operations,
  1862. * which are indicated by ctx.io_err.
  1863. */
  1864. if (ctx.io_err) {
  1865. btrfs_end_transaction(trans, root);
  1866. ret = ctx.io_err;
  1867. goto out;
  1868. }
  1869. if (ret != BTRFS_NO_LOG_SYNC) {
  1870. if (!ret) {
  1871. ret = btrfs_sync_log(trans, root, &ctx);
  1872. if (!ret) {
  1873. ret = btrfs_end_transaction(trans, root);
  1874. goto out;
  1875. }
  1876. }
  1877. if (!full_sync) {
  1878. ret = btrfs_wait_ordered_range(inode, start, len);
  1879. if (ret) {
  1880. btrfs_end_transaction(trans, root);
  1881. goto out;
  1882. }
  1883. }
  1884. ret = btrfs_commit_transaction(trans, root);
  1885. } else {
  1886. ret = btrfs_end_transaction(trans, root);
  1887. }
  1888. out:
  1889. return ret > 0 ? -EIO : ret;
  1890. }
  1891. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1892. .fault = filemap_fault,
  1893. .map_pages = filemap_map_pages,
  1894. .page_mkwrite = btrfs_page_mkwrite,
  1895. };
  1896. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1897. {
  1898. struct address_space *mapping = filp->f_mapping;
  1899. if (!mapping->a_ops->readpage)
  1900. return -ENOEXEC;
  1901. file_accessed(filp);
  1902. vma->vm_ops = &btrfs_file_vm_ops;
  1903. return 0;
  1904. }
  1905. static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
  1906. int slot, u64 start, u64 end)
  1907. {
  1908. struct btrfs_file_extent_item *fi;
  1909. struct btrfs_key key;
  1910. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1911. return 0;
  1912. btrfs_item_key_to_cpu(leaf, &key, slot);
  1913. if (key.objectid != btrfs_ino(inode) ||
  1914. key.type != BTRFS_EXTENT_DATA_KEY)
  1915. return 0;
  1916. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1917. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1918. return 0;
  1919. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1920. return 0;
  1921. if (key.offset == end)
  1922. return 1;
  1923. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1924. return 1;
  1925. return 0;
  1926. }
  1927. static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
  1928. struct btrfs_path *path, u64 offset, u64 end)
  1929. {
  1930. struct btrfs_root *root = BTRFS_I(inode)->root;
  1931. struct extent_buffer *leaf;
  1932. struct btrfs_file_extent_item *fi;
  1933. struct extent_map *hole_em;
  1934. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  1935. struct btrfs_key key;
  1936. int ret;
  1937. if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
  1938. goto out;
  1939. key.objectid = btrfs_ino(inode);
  1940. key.type = BTRFS_EXTENT_DATA_KEY;
  1941. key.offset = offset;
  1942. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1943. if (ret < 0)
  1944. return ret;
  1945. BUG_ON(!ret);
  1946. leaf = path->nodes[0];
  1947. if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
  1948. u64 num_bytes;
  1949. path->slots[0]--;
  1950. fi = btrfs_item_ptr(leaf, path->slots[0],
  1951. struct btrfs_file_extent_item);
  1952. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1953. end - offset;
  1954. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1955. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1956. btrfs_set_file_extent_offset(leaf, fi, 0);
  1957. btrfs_mark_buffer_dirty(leaf);
  1958. goto out;
  1959. }
  1960. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1961. u64 num_bytes;
  1962. key.offset = offset;
  1963. btrfs_set_item_key_safe(root->fs_info, path, &key);
  1964. fi = btrfs_item_ptr(leaf, path->slots[0],
  1965. struct btrfs_file_extent_item);
  1966. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1967. offset;
  1968. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1969. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1970. btrfs_set_file_extent_offset(leaf, fi, 0);
  1971. btrfs_mark_buffer_dirty(leaf);
  1972. goto out;
  1973. }
  1974. btrfs_release_path(path);
  1975. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
  1976. 0, 0, end - offset, 0, end - offset,
  1977. 0, 0, 0);
  1978. if (ret)
  1979. return ret;
  1980. out:
  1981. btrfs_release_path(path);
  1982. hole_em = alloc_extent_map();
  1983. if (!hole_em) {
  1984. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  1985. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1986. &BTRFS_I(inode)->runtime_flags);
  1987. } else {
  1988. hole_em->start = offset;
  1989. hole_em->len = end - offset;
  1990. hole_em->ram_bytes = hole_em->len;
  1991. hole_em->orig_start = offset;
  1992. hole_em->block_start = EXTENT_MAP_HOLE;
  1993. hole_em->block_len = 0;
  1994. hole_em->orig_block_len = 0;
  1995. hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
  1996. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  1997. hole_em->generation = trans->transid;
  1998. do {
  1999. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2000. write_lock(&em_tree->lock);
  2001. ret = add_extent_mapping(em_tree, hole_em, 1);
  2002. write_unlock(&em_tree->lock);
  2003. } while (ret == -EEXIST);
  2004. free_extent_map(hole_em);
  2005. if (ret)
  2006. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2007. &BTRFS_I(inode)->runtime_flags);
  2008. }
  2009. return 0;
  2010. }
  2011. /*
  2012. * Find a hole extent on given inode and change start/len to the end of hole
  2013. * extent.(hole/vacuum extent whose em->start <= start &&
  2014. * em->start + em->len > start)
  2015. * When a hole extent is found, return 1 and modify start/len.
  2016. */
  2017. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  2018. {
  2019. struct extent_map *em;
  2020. int ret = 0;
  2021. em = btrfs_get_extent(inode, NULL, 0, *start, *len, 0);
  2022. if (IS_ERR_OR_NULL(em)) {
  2023. if (!em)
  2024. ret = -ENOMEM;
  2025. else
  2026. ret = PTR_ERR(em);
  2027. return ret;
  2028. }
  2029. /* Hole or vacuum extent(only exists in no-hole mode) */
  2030. if (em->block_start == EXTENT_MAP_HOLE) {
  2031. ret = 1;
  2032. *len = em->start + em->len > *start + *len ?
  2033. 0 : *start + *len - em->start - em->len;
  2034. *start = em->start + em->len;
  2035. }
  2036. free_extent_map(em);
  2037. return ret;
  2038. }
  2039. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2040. {
  2041. struct btrfs_root *root = BTRFS_I(inode)->root;
  2042. struct extent_state *cached_state = NULL;
  2043. struct btrfs_path *path;
  2044. struct btrfs_block_rsv *rsv;
  2045. struct btrfs_trans_handle *trans;
  2046. u64 lockstart;
  2047. u64 lockend;
  2048. u64 tail_start;
  2049. u64 tail_len;
  2050. u64 orig_start = offset;
  2051. u64 cur_offset;
  2052. u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
  2053. u64 drop_end;
  2054. int ret = 0;
  2055. int err = 0;
  2056. unsigned int rsv_count;
  2057. bool same_page;
  2058. bool no_holes = btrfs_fs_incompat(root->fs_info, NO_HOLES);
  2059. u64 ino_size;
  2060. bool truncated_page = false;
  2061. bool updated_inode = false;
  2062. ret = btrfs_wait_ordered_range(inode, offset, len);
  2063. if (ret)
  2064. return ret;
  2065. mutex_lock(&inode->i_mutex);
  2066. ino_size = round_up(inode->i_size, PAGE_CACHE_SIZE);
  2067. ret = find_first_non_hole(inode, &offset, &len);
  2068. if (ret < 0)
  2069. goto out_only_mutex;
  2070. if (ret && !len) {
  2071. /* Already in a large hole */
  2072. ret = 0;
  2073. goto out_only_mutex;
  2074. }
  2075. lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
  2076. lockend = round_down(offset + len,
  2077. BTRFS_I(inode)->root->sectorsize) - 1;
  2078. same_page = ((offset >> PAGE_CACHE_SHIFT) ==
  2079. ((offset + len - 1) >> PAGE_CACHE_SHIFT));
  2080. /*
  2081. * We needn't truncate any page which is beyond the end of the file
  2082. * because we are sure there is no data there.
  2083. */
  2084. /*
  2085. * Only do this if we are in the same page and we aren't doing the
  2086. * entire page.
  2087. */
  2088. if (same_page && len < PAGE_CACHE_SIZE) {
  2089. if (offset < ino_size) {
  2090. truncated_page = true;
  2091. ret = btrfs_truncate_page(inode, offset, len, 0);
  2092. } else {
  2093. ret = 0;
  2094. }
  2095. goto out_only_mutex;
  2096. }
  2097. /* zero back part of the first page */
  2098. if (offset < ino_size) {
  2099. truncated_page = true;
  2100. ret = btrfs_truncate_page(inode, offset, 0, 0);
  2101. if (ret) {
  2102. mutex_unlock(&inode->i_mutex);
  2103. return ret;
  2104. }
  2105. }
  2106. /* Check the aligned pages after the first unaligned page,
  2107. * if offset != orig_start, which means the first unaligned page
  2108. * including serveral following pages are already in holes,
  2109. * the extra check can be skipped */
  2110. if (offset == orig_start) {
  2111. /* after truncate page, check hole again */
  2112. len = offset + len - lockstart;
  2113. offset = lockstart;
  2114. ret = find_first_non_hole(inode, &offset, &len);
  2115. if (ret < 0)
  2116. goto out_only_mutex;
  2117. if (ret && !len) {
  2118. ret = 0;
  2119. goto out_only_mutex;
  2120. }
  2121. lockstart = offset;
  2122. }
  2123. /* Check the tail unaligned part is in a hole */
  2124. tail_start = lockend + 1;
  2125. tail_len = offset + len - tail_start;
  2126. if (tail_len) {
  2127. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2128. if (unlikely(ret < 0))
  2129. goto out_only_mutex;
  2130. if (!ret) {
  2131. /* zero the front end of the last page */
  2132. if (tail_start + tail_len < ino_size) {
  2133. truncated_page = true;
  2134. ret = btrfs_truncate_page(inode,
  2135. tail_start + tail_len, 0, 1);
  2136. if (ret)
  2137. goto out_only_mutex;
  2138. }
  2139. }
  2140. }
  2141. if (lockend < lockstart) {
  2142. ret = 0;
  2143. goto out_only_mutex;
  2144. }
  2145. while (1) {
  2146. struct btrfs_ordered_extent *ordered;
  2147. truncate_pagecache_range(inode, lockstart, lockend);
  2148. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2149. 0, &cached_state);
  2150. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2151. /*
  2152. * We need to make sure we have no ordered extents in this range
  2153. * and nobody raced in and read a page in this range, if we did
  2154. * we need to try again.
  2155. */
  2156. if ((!ordered ||
  2157. (ordered->file_offset + ordered->len <= lockstart ||
  2158. ordered->file_offset > lockend)) &&
  2159. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2160. if (ordered)
  2161. btrfs_put_ordered_extent(ordered);
  2162. break;
  2163. }
  2164. if (ordered)
  2165. btrfs_put_ordered_extent(ordered);
  2166. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2167. lockend, &cached_state, GFP_NOFS);
  2168. ret = btrfs_wait_ordered_range(inode, lockstart,
  2169. lockend - lockstart + 1);
  2170. if (ret) {
  2171. mutex_unlock(&inode->i_mutex);
  2172. return ret;
  2173. }
  2174. }
  2175. path = btrfs_alloc_path();
  2176. if (!path) {
  2177. ret = -ENOMEM;
  2178. goto out;
  2179. }
  2180. rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
  2181. if (!rsv) {
  2182. ret = -ENOMEM;
  2183. goto out_free;
  2184. }
  2185. rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
  2186. rsv->failfast = 1;
  2187. /*
  2188. * 1 - update the inode
  2189. * 1 - removing the extents in the range
  2190. * 1 - adding the hole extent if no_holes isn't set
  2191. */
  2192. rsv_count = no_holes ? 2 : 3;
  2193. trans = btrfs_start_transaction(root, rsv_count);
  2194. if (IS_ERR(trans)) {
  2195. err = PTR_ERR(trans);
  2196. goto out_free;
  2197. }
  2198. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
  2199. min_size);
  2200. BUG_ON(ret);
  2201. trans->block_rsv = rsv;
  2202. cur_offset = lockstart;
  2203. len = lockend - cur_offset;
  2204. while (cur_offset < lockend) {
  2205. ret = __btrfs_drop_extents(trans, root, inode, path,
  2206. cur_offset, lockend + 1,
  2207. &drop_end, 1, 0, 0, NULL);
  2208. if (ret != -ENOSPC)
  2209. break;
  2210. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2211. if (cur_offset < ino_size) {
  2212. ret = fill_holes(trans, inode, path, cur_offset,
  2213. drop_end);
  2214. if (ret) {
  2215. err = ret;
  2216. break;
  2217. }
  2218. }
  2219. cur_offset = drop_end;
  2220. ret = btrfs_update_inode(trans, root, inode);
  2221. if (ret) {
  2222. err = ret;
  2223. break;
  2224. }
  2225. btrfs_end_transaction(trans, root);
  2226. btrfs_btree_balance_dirty(root);
  2227. trans = btrfs_start_transaction(root, rsv_count);
  2228. if (IS_ERR(trans)) {
  2229. ret = PTR_ERR(trans);
  2230. trans = NULL;
  2231. break;
  2232. }
  2233. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
  2234. rsv, min_size);
  2235. BUG_ON(ret); /* shouldn't happen */
  2236. trans->block_rsv = rsv;
  2237. ret = find_first_non_hole(inode, &cur_offset, &len);
  2238. if (unlikely(ret < 0))
  2239. break;
  2240. if (ret && !len) {
  2241. ret = 0;
  2242. break;
  2243. }
  2244. }
  2245. if (ret) {
  2246. err = ret;
  2247. goto out_trans;
  2248. }
  2249. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2250. /*
  2251. * If we are using the NO_HOLES feature we might have had already an
  2252. * hole that overlaps a part of the region [lockstart, lockend] and
  2253. * ends at (or beyond) lockend. Since we have no file extent items to
  2254. * represent holes, drop_end can be less than lockend and so we must
  2255. * make sure we have an extent map representing the existing hole (the
  2256. * call to __btrfs_drop_extents() might have dropped the existing extent
  2257. * map representing the existing hole), otherwise the fast fsync path
  2258. * will not record the existence of the hole region
  2259. * [existing_hole_start, lockend].
  2260. */
  2261. if (drop_end <= lockend)
  2262. drop_end = lockend + 1;
  2263. /*
  2264. * Don't insert file hole extent item if it's for a range beyond eof
  2265. * (because it's useless) or if it represents a 0 bytes range (when
  2266. * cur_offset == drop_end).
  2267. */
  2268. if (cur_offset < ino_size && cur_offset < drop_end) {
  2269. ret = fill_holes(trans, inode, path, cur_offset, drop_end);
  2270. if (ret) {
  2271. err = ret;
  2272. goto out_trans;
  2273. }
  2274. }
  2275. out_trans:
  2276. if (!trans)
  2277. goto out_free;
  2278. inode_inc_iversion(inode);
  2279. inode->i_mtime = inode->i_ctime = CURRENT_TIME;
  2280. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2281. ret = btrfs_update_inode(trans, root, inode);
  2282. updated_inode = true;
  2283. btrfs_end_transaction(trans, root);
  2284. btrfs_btree_balance_dirty(root);
  2285. out_free:
  2286. btrfs_free_path(path);
  2287. btrfs_free_block_rsv(root, rsv);
  2288. out:
  2289. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2290. &cached_state, GFP_NOFS);
  2291. out_only_mutex:
  2292. if (!updated_inode && truncated_page && !ret && !err) {
  2293. /*
  2294. * If we only end up zeroing part of a page, we still need to
  2295. * update the inode item, so that all the time fields are
  2296. * updated as well as the necessary btrfs inode in memory fields
  2297. * for detecting, at fsync time, if the inode isn't yet in the
  2298. * log tree or it's there but not up to date.
  2299. */
  2300. trans = btrfs_start_transaction(root, 1);
  2301. if (IS_ERR(trans)) {
  2302. err = PTR_ERR(trans);
  2303. } else {
  2304. err = btrfs_update_inode(trans, root, inode);
  2305. ret = btrfs_end_transaction(trans, root);
  2306. }
  2307. }
  2308. mutex_unlock(&inode->i_mutex);
  2309. if (ret && !err)
  2310. err = ret;
  2311. return err;
  2312. }
  2313. /* Helper structure to record which range is already reserved */
  2314. struct falloc_range {
  2315. struct list_head list;
  2316. u64 start;
  2317. u64 len;
  2318. };
  2319. /*
  2320. * Helper function to add falloc range
  2321. *
  2322. * Caller should have locked the larger range of extent containing
  2323. * [start, len)
  2324. */
  2325. static int add_falloc_range(struct list_head *head, u64 start, u64 len)
  2326. {
  2327. struct falloc_range *prev = NULL;
  2328. struct falloc_range *range = NULL;
  2329. if (list_empty(head))
  2330. goto insert;
  2331. /*
  2332. * As fallocate iterate by bytenr order, we only need to check
  2333. * the last range.
  2334. */
  2335. prev = list_entry(head->prev, struct falloc_range, list);
  2336. if (prev->start + prev->len == start) {
  2337. prev->len += len;
  2338. return 0;
  2339. }
  2340. insert:
  2341. range = kmalloc(sizeof(*range), GFP_NOFS);
  2342. if (!range)
  2343. return -ENOMEM;
  2344. range->start = start;
  2345. range->len = len;
  2346. list_add_tail(&range->list, head);
  2347. return 0;
  2348. }
  2349. static long btrfs_fallocate(struct file *file, int mode,
  2350. loff_t offset, loff_t len)
  2351. {
  2352. struct inode *inode = file_inode(file);
  2353. struct extent_state *cached_state = NULL;
  2354. struct falloc_range *range;
  2355. struct falloc_range *tmp;
  2356. struct list_head reserve_list;
  2357. u64 cur_offset;
  2358. u64 last_byte;
  2359. u64 alloc_start;
  2360. u64 alloc_end;
  2361. u64 alloc_hint = 0;
  2362. u64 locked_end;
  2363. u64 actual_end = 0;
  2364. struct extent_map *em;
  2365. int blocksize = BTRFS_I(inode)->root->sectorsize;
  2366. int ret;
  2367. alloc_start = round_down(offset, blocksize);
  2368. alloc_end = round_up(offset + len, blocksize);
  2369. /* Make sure we aren't being give some crap mode */
  2370. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2371. return -EOPNOTSUPP;
  2372. if (mode & FALLOC_FL_PUNCH_HOLE)
  2373. return btrfs_punch_hole(inode, offset, len);
  2374. /*
  2375. * Only trigger disk allocation, don't trigger qgroup reserve
  2376. *
  2377. * For qgroup space, it will be checked later.
  2378. */
  2379. ret = btrfs_alloc_data_chunk_ondemand(inode, alloc_end - alloc_start);
  2380. if (ret < 0)
  2381. return ret;
  2382. mutex_lock(&inode->i_mutex);
  2383. ret = inode_newsize_ok(inode, alloc_end);
  2384. if (ret)
  2385. goto out;
  2386. /*
  2387. * TODO: Move these two operations after we have checked
  2388. * accurate reserved space, or fallocate can still fail but
  2389. * with page truncated or size expanded.
  2390. *
  2391. * But that's a minor problem and won't do much harm BTW.
  2392. */
  2393. if (alloc_start > inode->i_size) {
  2394. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2395. alloc_start);
  2396. if (ret)
  2397. goto out;
  2398. } else if (offset + len > inode->i_size) {
  2399. /*
  2400. * If we are fallocating from the end of the file onward we
  2401. * need to zero out the end of the page if i_size lands in the
  2402. * middle of a page.
  2403. */
  2404. ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
  2405. if (ret)
  2406. goto out;
  2407. }
  2408. /*
  2409. * wait for ordered IO before we have any locks. We'll loop again
  2410. * below with the locks held.
  2411. */
  2412. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2413. alloc_end - alloc_start);
  2414. if (ret)
  2415. goto out;
  2416. locked_end = alloc_end - 1;
  2417. while (1) {
  2418. struct btrfs_ordered_extent *ordered;
  2419. /* the extent lock is ordered inside the running
  2420. * transaction
  2421. */
  2422. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2423. locked_end, 0, &cached_state);
  2424. ordered = btrfs_lookup_first_ordered_extent(inode,
  2425. alloc_end - 1);
  2426. if (ordered &&
  2427. ordered->file_offset + ordered->len > alloc_start &&
  2428. ordered->file_offset < alloc_end) {
  2429. btrfs_put_ordered_extent(ordered);
  2430. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2431. alloc_start, locked_end,
  2432. &cached_state, GFP_NOFS);
  2433. /*
  2434. * we can't wait on the range with the transaction
  2435. * running or with the extent lock held
  2436. */
  2437. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2438. alloc_end - alloc_start);
  2439. if (ret)
  2440. goto out;
  2441. } else {
  2442. if (ordered)
  2443. btrfs_put_ordered_extent(ordered);
  2444. break;
  2445. }
  2446. }
  2447. /* First, check if we exceed the qgroup limit */
  2448. INIT_LIST_HEAD(&reserve_list);
  2449. cur_offset = alloc_start;
  2450. while (1) {
  2451. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  2452. alloc_end - cur_offset, 0);
  2453. if (IS_ERR_OR_NULL(em)) {
  2454. if (!em)
  2455. ret = -ENOMEM;
  2456. else
  2457. ret = PTR_ERR(em);
  2458. break;
  2459. }
  2460. last_byte = min(extent_map_end(em), alloc_end);
  2461. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2462. last_byte = ALIGN(last_byte, blocksize);
  2463. if (em->block_start == EXTENT_MAP_HOLE ||
  2464. (cur_offset >= inode->i_size &&
  2465. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2466. ret = add_falloc_range(&reserve_list, cur_offset,
  2467. last_byte - cur_offset);
  2468. if (ret < 0) {
  2469. free_extent_map(em);
  2470. break;
  2471. }
  2472. ret = btrfs_qgroup_reserve_data(inode, cur_offset,
  2473. last_byte - cur_offset);
  2474. if (ret < 0)
  2475. break;
  2476. }
  2477. free_extent_map(em);
  2478. cur_offset = last_byte;
  2479. if (cur_offset >= alloc_end)
  2480. break;
  2481. }
  2482. /*
  2483. * If ret is still 0, means we're OK to fallocate.
  2484. * Or just cleanup the list and exit.
  2485. */
  2486. list_for_each_entry_safe(range, tmp, &reserve_list, list) {
  2487. if (!ret)
  2488. ret = btrfs_prealloc_file_range(inode, mode,
  2489. range->start,
  2490. range->len, i_blocksize(inode),
  2491. offset + len, &alloc_hint);
  2492. list_del(&range->list);
  2493. kfree(range);
  2494. }
  2495. if (ret < 0)
  2496. goto out_unlock;
  2497. if (actual_end > inode->i_size &&
  2498. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2499. struct btrfs_trans_handle *trans;
  2500. struct btrfs_root *root = BTRFS_I(inode)->root;
  2501. /*
  2502. * We didn't need to allocate any more space, but we
  2503. * still extended the size of the file so we need to
  2504. * update i_size and the inode item.
  2505. */
  2506. trans = btrfs_start_transaction(root, 1);
  2507. if (IS_ERR(trans)) {
  2508. ret = PTR_ERR(trans);
  2509. } else {
  2510. inode->i_ctime = CURRENT_TIME;
  2511. i_size_write(inode, actual_end);
  2512. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2513. ret = btrfs_update_inode(trans, root, inode);
  2514. if (ret)
  2515. btrfs_end_transaction(trans, root);
  2516. else
  2517. ret = btrfs_end_transaction(trans, root);
  2518. }
  2519. }
  2520. out_unlock:
  2521. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2522. &cached_state, GFP_NOFS);
  2523. out:
  2524. /*
  2525. * As we waited the extent range, the data_rsv_map must be empty
  2526. * in the range, as written data range will be released from it.
  2527. * And for prealloacted extent, it will also be released when
  2528. * its metadata is written.
  2529. * So this is completely used as cleanup.
  2530. */
  2531. btrfs_qgroup_free_data(inode, alloc_start, alloc_end - alloc_start);
  2532. mutex_unlock(&inode->i_mutex);
  2533. /* Let go of our reservation. */
  2534. btrfs_free_reserved_data_space(inode, alloc_start,
  2535. alloc_end - alloc_start);
  2536. return ret;
  2537. }
  2538. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2539. {
  2540. struct btrfs_root *root = BTRFS_I(inode)->root;
  2541. struct extent_map *em = NULL;
  2542. struct extent_state *cached_state = NULL;
  2543. u64 lockstart;
  2544. u64 lockend;
  2545. u64 start;
  2546. u64 len;
  2547. int ret = 0;
  2548. if (inode->i_size == 0)
  2549. return -ENXIO;
  2550. /*
  2551. * *offset can be negative, in this case we start finding DATA/HOLE from
  2552. * the very start of the file.
  2553. */
  2554. start = max_t(loff_t, 0, *offset);
  2555. lockstart = round_down(start, root->sectorsize);
  2556. lockend = round_up(i_size_read(inode), root->sectorsize);
  2557. if (lockend <= lockstart)
  2558. lockend = lockstart + root->sectorsize;
  2559. lockend--;
  2560. len = lockend - lockstart + 1;
  2561. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
  2562. &cached_state);
  2563. while (start < inode->i_size) {
  2564. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  2565. if (IS_ERR(em)) {
  2566. ret = PTR_ERR(em);
  2567. em = NULL;
  2568. break;
  2569. }
  2570. if (whence == SEEK_HOLE &&
  2571. (em->block_start == EXTENT_MAP_HOLE ||
  2572. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2573. break;
  2574. else if (whence == SEEK_DATA &&
  2575. (em->block_start != EXTENT_MAP_HOLE &&
  2576. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2577. break;
  2578. start = em->start + em->len;
  2579. free_extent_map(em);
  2580. em = NULL;
  2581. cond_resched();
  2582. }
  2583. free_extent_map(em);
  2584. if (!ret) {
  2585. if (whence == SEEK_DATA && start >= inode->i_size)
  2586. ret = -ENXIO;
  2587. else
  2588. *offset = min_t(loff_t, start, inode->i_size);
  2589. }
  2590. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2591. &cached_state, GFP_NOFS);
  2592. return ret;
  2593. }
  2594. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2595. {
  2596. struct inode *inode = file->f_mapping->host;
  2597. int ret;
  2598. mutex_lock(&inode->i_mutex);
  2599. switch (whence) {
  2600. case SEEK_END:
  2601. case SEEK_CUR:
  2602. offset = generic_file_llseek(file, offset, whence);
  2603. goto out;
  2604. case SEEK_DATA:
  2605. case SEEK_HOLE:
  2606. if (offset >= i_size_read(inode)) {
  2607. mutex_unlock(&inode->i_mutex);
  2608. return -ENXIO;
  2609. }
  2610. ret = find_desired_extent(inode, &offset, whence);
  2611. if (ret) {
  2612. mutex_unlock(&inode->i_mutex);
  2613. return ret;
  2614. }
  2615. }
  2616. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2617. out:
  2618. mutex_unlock(&inode->i_mutex);
  2619. return offset;
  2620. }
  2621. const struct file_operations btrfs_file_operations = {
  2622. .llseek = btrfs_file_llseek,
  2623. .read_iter = generic_file_read_iter,
  2624. .splice_read = generic_file_splice_read,
  2625. .write_iter = btrfs_file_write_iter,
  2626. .mmap = btrfs_file_mmap,
  2627. .open = generic_file_open,
  2628. .release = btrfs_release_file,
  2629. .fsync = btrfs_sync_file,
  2630. .fallocate = btrfs_fallocate,
  2631. .unlocked_ioctl = btrfs_ioctl,
  2632. #ifdef CONFIG_COMPAT
  2633. .compat_ioctl = btrfs_ioctl,
  2634. #endif
  2635. };
  2636. void btrfs_auto_defrag_exit(void)
  2637. {
  2638. if (btrfs_inode_defrag_cachep)
  2639. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2640. }
  2641. int btrfs_auto_defrag_init(void)
  2642. {
  2643. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2644. sizeof(struct inode_defrag), 0,
  2645. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
  2646. NULL);
  2647. if (!btrfs_inode_defrag_cachep)
  2648. return -ENOMEM;
  2649. return 0;
  2650. }
  2651. int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
  2652. {
  2653. int ret;
  2654. /*
  2655. * So with compression we will find and lock a dirty page and clear the
  2656. * first one as dirty, setup an async extent, and immediately return
  2657. * with the entire range locked but with nobody actually marked with
  2658. * writeback. So we can't just filemap_write_and_wait_range() and
  2659. * expect it to work since it will just kick off a thread to do the
  2660. * actual work. So we need to call filemap_fdatawrite_range _again_
  2661. * since it will wait on the page lock, which won't be unlocked until
  2662. * after the pages have been marked as writeback and so we're good to go
  2663. * from there. We have to do this otherwise we'll miss the ordered
  2664. * extents and that results in badness. Please Josef, do not think you
  2665. * know better and pull this out at some point in the future, it is
  2666. * right and you are wrong.
  2667. */
  2668. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2669. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  2670. &BTRFS_I(inode)->runtime_flags))
  2671. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2672. return ret;
  2673. }