file.c 75 KB

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