file.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867
  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_to_bdi(inode);
  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 also have to set last_sub_trans to the current log transid,
  1614. * otherwise subsequent syncs to a file that's been synced in this
  1615. * transaction will appear to have already occured.
  1616. */
  1617. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1618. if (num_written > 0) {
  1619. err = generic_write_sync(file, pos, num_written);
  1620. if (err < 0)
  1621. num_written = err;
  1622. }
  1623. if (sync)
  1624. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1625. out:
  1626. current->backing_dev_info = NULL;
  1627. return num_written ? num_written : err;
  1628. }
  1629. int btrfs_release_file(struct inode *inode, struct file *filp)
  1630. {
  1631. if (filp->private_data)
  1632. btrfs_ioctl_trans_end(filp);
  1633. /*
  1634. * ordered_data_close is set by settattr when we are about to truncate
  1635. * a file from a non-zero size to a zero size. This tries to
  1636. * flush down new bytes that may have been written if the
  1637. * application were using truncate to replace a file in place.
  1638. */
  1639. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1640. &BTRFS_I(inode)->runtime_flags))
  1641. filemap_flush(inode->i_mapping);
  1642. return 0;
  1643. }
  1644. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1645. {
  1646. int ret;
  1647. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1648. ret = btrfs_fdatawrite_range(inode, start, end);
  1649. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1650. return ret;
  1651. }
  1652. /*
  1653. * fsync call for both files and directories. This logs the inode into
  1654. * the tree log instead of forcing full commits whenever possible.
  1655. *
  1656. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1657. * in the metadata btree are up to date for copying to the log.
  1658. *
  1659. * It drops the inode mutex before doing the tree log commit. This is an
  1660. * important optimization for directories because holding the mutex prevents
  1661. * new operations on the dir while we write to disk.
  1662. */
  1663. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1664. {
  1665. struct dentry *dentry = file->f_path.dentry;
  1666. struct inode *inode = dentry->d_inode;
  1667. struct btrfs_root *root = BTRFS_I(inode)->root;
  1668. struct btrfs_trans_handle *trans;
  1669. struct btrfs_log_ctx ctx;
  1670. int ret = 0;
  1671. bool full_sync = 0;
  1672. trace_btrfs_sync_file(file, datasync);
  1673. /*
  1674. * We write the dirty pages in the range and wait until they complete
  1675. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1676. * multi-task, and make the performance up. See
  1677. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1678. */
  1679. ret = start_ordered_ops(inode, start, end);
  1680. if (ret)
  1681. return ret;
  1682. mutex_lock(&inode->i_mutex);
  1683. atomic_inc(&root->log_batch);
  1684. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1685. &BTRFS_I(inode)->runtime_flags);
  1686. /*
  1687. * We might have have had more pages made dirty after calling
  1688. * start_ordered_ops and before acquiring the inode's i_mutex.
  1689. */
  1690. if (full_sync) {
  1691. /*
  1692. * For a full sync, we need to make sure any ordered operations
  1693. * start and finish before we start logging the inode, so that
  1694. * all extents are persisted and the respective file extent
  1695. * items are in the fs/subvol btree.
  1696. */
  1697. ret = btrfs_wait_ordered_range(inode, start, end - start + 1);
  1698. } else {
  1699. /*
  1700. * Start any new ordered operations before starting to log the
  1701. * inode. We will wait for them to finish in btrfs_sync_log().
  1702. *
  1703. * Right before acquiring the inode's mutex, we might have new
  1704. * writes dirtying pages, which won't immediately start the
  1705. * respective ordered operations - that is done through the
  1706. * fill_delalloc callbacks invoked from the writepage and
  1707. * writepages address space operations. So make sure we start
  1708. * all ordered operations before starting to log our inode. Not
  1709. * doing this means that while logging the inode, writeback
  1710. * could start and invoke writepage/writepages, which would call
  1711. * the fill_delalloc callbacks (cow_file_range,
  1712. * submit_compressed_extents). These callbacks add first an
  1713. * extent map to the modified list of extents and then create
  1714. * the respective ordered operation, which means in
  1715. * tree-log.c:btrfs_log_inode() we might capture all existing
  1716. * ordered operations (with btrfs_get_logged_extents()) before
  1717. * the fill_delalloc callback adds its ordered operation, and by
  1718. * the time we visit the modified list of extent maps (with
  1719. * btrfs_log_changed_extents()), we see and process the extent
  1720. * map they created. We then use the extent map to construct a
  1721. * file extent item for logging without waiting for the
  1722. * respective ordered operation to finish - this file extent
  1723. * item points to a disk location that might not have yet been
  1724. * written to, containing random data - so after a crash a log
  1725. * replay will make our inode have file extent items that point
  1726. * to disk locations containing invalid data, as we returned
  1727. * success to userspace without waiting for the respective
  1728. * ordered operation to finish, because it wasn't captured by
  1729. * btrfs_get_logged_extents().
  1730. */
  1731. ret = start_ordered_ops(inode, start, end);
  1732. }
  1733. if (ret) {
  1734. mutex_unlock(&inode->i_mutex);
  1735. goto out;
  1736. }
  1737. atomic_inc(&root->log_batch);
  1738. /*
  1739. * If the last transaction that changed this file was before the current
  1740. * transaction and we have the full sync flag set in our inode, we can
  1741. * bail out now without any syncing.
  1742. *
  1743. * Note that we can't bail out if the full sync flag isn't set. This is
  1744. * because when the full sync flag is set we start all ordered extents
  1745. * and wait for them to fully complete - when they complete they update
  1746. * the inode's last_trans field through:
  1747. *
  1748. * btrfs_finish_ordered_io() ->
  1749. * btrfs_update_inode_fallback() ->
  1750. * btrfs_update_inode() ->
  1751. * btrfs_set_inode_last_trans()
  1752. *
  1753. * So we are sure that last_trans is up to date and can do this check to
  1754. * bail out safely. For the fast path, when the full sync flag is not
  1755. * set in our inode, we can not do it because we start only our ordered
  1756. * extents and don't wait for them to complete (that is when
  1757. * btrfs_finish_ordered_io runs), so here at this point their last_trans
  1758. * value might be less than or equals to fs_info->last_trans_committed,
  1759. * and setting a speculative last_trans for an inode when a buffered
  1760. * write is made (such as fs_info->generation + 1 for example) would not
  1761. * be reliable since after setting the value and before fsync is called
  1762. * any number of transactions can start and commit (transaction kthread
  1763. * commits the current transaction periodically), and a transaction
  1764. * commit does not start nor waits for ordered extents to complete.
  1765. */
  1766. smp_mb();
  1767. if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
  1768. (full_sync && BTRFS_I(inode)->last_trans <=
  1769. root->fs_info->last_trans_committed)) {
  1770. /*
  1771. * We'v had everything committed since the last time we were
  1772. * modified so clear this flag in case it was set for whatever
  1773. * reason, it's no longer relevant.
  1774. */
  1775. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1776. &BTRFS_I(inode)->runtime_flags);
  1777. mutex_unlock(&inode->i_mutex);
  1778. goto out;
  1779. }
  1780. /*
  1781. * ok we haven't committed the transaction yet, lets do a commit
  1782. */
  1783. if (file->private_data)
  1784. btrfs_ioctl_trans_end(file);
  1785. /*
  1786. * We use start here because we will need to wait on the IO to complete
  1787. * in btrfs_sync_log, which could require joining a transaction (for
  1788. * example checking cross references in the nocow path). If we use join
  1789. * here we could get into a situation where we're waiting on IO to
  1790. * happen that is blocked on a transaction trying to commit. With start
  1791. * we inc the extwriter counter, so we wait for all extwriters to exit
  1792. * before we start blocking join'ers. This comment is to keep somebody
  1793. * from thinking they are super smart and changing this to
  1794. * btrfs_join_transaction *cough*Josef*cough*.
  1795. */
  1796. trans = btrfs_start_transaction(root, 0);
  1797. if (IS_ERR(trans)) {
  1798. ret = PTR_ERR(trans);
  1799. mutex_unlock(&inode->i_mutex);
  1800. goto out;
  1801. }
  1802. trans->sync = true;
  1803. btrfs_init_log_ctx(&ctx);
  1804. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1805. if (ret < 0) {
  1806. /* Fallthrough and commit/free transaction. */
  1807. ret = 1;
  1808. }
  1809. /* we've logged all the items and now have a consistent
  1810. * version of the file in the log. It is possible that
  1811. * someone will come in and modify the file, but that's
  1812. * fine because the log is consistent on disk, and we
  1813. * have references to all of the file's extents
  1814. *
  1815. * It is possible that someone will come in and log the
  1816. * file again, but that will end up using the synchronization
  1817. * inside btrfs_sync_log to keep things safe.
  1818. */
  1819. mutex_unlock(&inode->i_mutex);
  1820. /*
  1821. * If any of the ordered extents had an error, just return it to user
  1822. * space, so that the application knows some writes didn't succeed and
  1823. * can take proper action (retry for e.g.). Blindly committing the
  1824. * transaction in this case, would fool userspace that everything was
  1825. * successful. And we also want to make sure our log doesn't contain
  1826. * file extent items pointing to extents that weren't fully written to -
  1827. * just like in the non fast fsync path, where we check for the ordered
  1828. * operation's error flag before writing to the log tree and return -EIO
  1829. * if any of them had this flag set (btrfs_wait_ordered_range) -
  1830. * therefore we need to check for errors in the ordered operations,
  1831. * which are indicated by ctx.io_err.
  1832. */
  1833. if (ctx.io_err) {
  1834. btrfs_end_transaction(trans, root);
  1835. ret = ctx.io_err;
  1836. goto out;
  1837. }
  1838. if (ret != BTRFS_NO_LOG_SYNC) {
  1839. if (!ret) {
  1840. ret = btrfs_sync_log(trans, root, &ctx);
  1841. if (!ret) {
  1842. ret = btrfs_end_transaction(trans, root);
  1843. goto out;
  1844. }
  1845. }
  1846. if (!full_sync) {
  1847. ret = btrfs_wait_ordered_range(inode, start,
  1848. end - start + 1);
  1849. if (ret) {
  1850. btrfs_end_transaction(trans, root);
  1851. goto out;
  1852. }
  1853. }
  1854. ret = btrfs_commit_transaction(trans, root);
  1855. } else {
  1856. ret = btrfs_end_transaction(trans, root);
  1857. }
  1858. out:
  1859. return ret > 0 ? -EIO : ret;
  1860. }
  1861. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1862. .fault = filemap_fault,
  1863. .map_pages = filemap_map_pages,
  1864. .page_mkwrite = btrfs_page_mkwrite,
  1865. };
  1866. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1867. {
  1868. struct address_space *mapping = filp->f_mapping;
  1869. if (!mapping->a_ops->readpage)
  1870. return -ENOEXEC;
  1871. file_accessed(filp);
  1872. vma->vm_ops = &btrfs_file_vm_ops;
  1873. return 0;
  1874. }
  1875. static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
  1876. int slot, u64 start, u64 end)
  1877. {
  1878. struct btrfs_file_extent_item *fi;
  1879. struct btrfs_key key;
  1880. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1881. return 0;
  1882. btrfs_item_key_to_cpu(leaf, &key, slot);
  1883. if (key.objectid != btrfs_ino(inode) ||
  1884. key.type != BTRFS_EXTENT_DATA_KEY)
  1885. return 0;
  1886. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1887. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1888. return 0;
  1889. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1890. return 0;
  1891. if (key.offset == end)
  1892. return 1;
  1893. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1894. return 1;
  1895. return 0;
  1896. }
  1897. static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
  1898. struct btrfs_path *path, u64 offset, u64 end)
  1899. {
  1900. struct btrfs_root *root = BTRFS_I(inode)->root;
  1901. struct extent_buffer *leaf;
  1902. struct btrfs_file_extent_item *fi;
  1903. struct extent_map *hole_em;
  1904. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  1905. struct btrfs_key key;
  1906. int ret;
  1907. if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
  1908. goto out;
  1909. key.objectid = btrfs_ino(inode);
  1910. key.type = BTRFS_EXTENT_DATA_KEY;
  1911. key.offset = offset;
  1912. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1913. if (ret < 0)
  1914. return ret;
  1915. BUG_ON(!ret);
  1916. leaf = path->nodes[0];
  1917. if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
  1918. u64 num_bytes;
  1919. path->slots[0]--;
  1920. fi = btrfs_item_ptr(leaf, path->slots[0],
  1921. struct btrfs_file_extent_item);
  1922. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1923. end - offset;
  1924. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1925. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1926. btrfs_set_file_extent_offset(leaf, fi, 0);
  1927. btrfs_mark_buffer_dirty(leaf);
  1928. goto out;
  1929. }
  1930. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1931. u64 num_bytes;
  1932. key.offset = offset;
  1933. btrfs_set_item_key_safe(root, path, &key);
  1934. fi = btrfs_item_ptr(leaf, path->slots[0],
  1935. struct btrfs_file_extent_item);
  1936. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1937. offset;
  1938. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1939. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1940. btrfs_set_file_extent_offset(leaf, fi, 0);
  1941. btrfs_mark_buffer_dirty(leaf);
  1942. goto out;
  1943. }
  1944. btrfs_release_path(path);
  1945. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
  1946. 0, 0, end - offset, 0, end - offset,
  1947. 0, 0, 0);
  1948. if (ret)
  1949. return ret;
  1950. out:
  1951. btrfs_release_path(path);
  1952. hole_em = alloc_extent_map();
  1953. if (!hole_em) {
  1954. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  1955. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1956. &BTRFS_I(inode)->runtime_flags);
  1957. } else {
  1958. hole_em->start = offset;
  1959. hole_em->len = end - offset;
  1960. hole_em->ram_bytes = hole_em->len;
  1961. hole_em->orig_start = offset;
  1962. hole_em->block_start = EXTENT_MAP_HOLE;
  1963. hole_em->block_len = 0;
  1964. hole_em->orig_block_len = 0;
  1965. hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
  1966. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  1967. hole_em->generation = trans->transid;
  1968. do {
  1969. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  1970. write_lock(&em_tree->lock);
  1971. ret = add_extent_mapping(em_tree, hole_em, 1);
  1972. write_unlock(&em_tree->lock);
  1973. } while (ret == -EEXIST);
  1974. free_extent_map(hole_em);
  1975. if (ret)
  1976. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1977. &BTRFS_I(inode)->runtime_flags);
  1978. }
  1979. return 0;
  1980. }
  1981. /*
  1982. * Find a hole extent on given inode and change start/len to the end of hole
  1983. * extent.(hole/vacuum extent whose em->start <= start &&
  1984. * em->start + em->len > start)
  1985. * When a hole extent is found, return 1 and modify start/len.
  1986. */
  1987. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  1988. {
  1989. struct extent_map *em;
  1990. int ret = 0;
  1991. em = btrfs_get_extent(inode, NULL, 0, *start, *len, 0);
  1992. if (IS_ERR_OR_NULL(em)) {
  1993. if (!em)
  1994. ret = -ENOMEM;
  1995. else
  1996. ret = PTR_ERR(em);
  1997. return ret;
  1998. }
  1999. /* Hole or vacuum extent(only exists in no-hole mode) */
  2000. if (em->block_start == EXTENT_MAP_HOLE) {
  2001. ret = 1;
  2002. *len = em->start + em->len > *start + *len ?
  2003. 0 : *start + *len - em->start - em->len;
  2004. *start = em->start + em->len;
  2005. }
  2006. free_extent_map(em);
  2007. return ret;
  2008. }
  2009. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2010. {
  2011. struct btrfs_root *root = BTRFS_I(inode)->root;
  2012. struct extent_state *cached_state = NULL;
  2013. struct btrfs_path *path;
  2014. struct btrfs_block_rsv *rsv;
  2015. struct btrfs_trans_handle *trans;
  2016. u64 lockstart;
  2017. u64 lockend;
  2018. u64 tail_start;
  2019. u64 tail_len;
  2020. u64 orig_start = offset;
  2021. u64 cur_offset;
  2022. u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
  2023. u64 drop_end;
  2024. int ret = 0;
  2025. int err = 0;
  2026. int rsv_count;
  2027. bool same_page;
  2028. bool no_holes = btrfs_fs_incompat(root->fs_info, NO_HOLES);
  2029. u64 ino_size;
  2030. bool truncated_page = false;
  2031. bool updated_inode = false;
  2032. ret = btrfs_wait_ordered_range(inode, offset, len);
  2033. if (ret)
  2034. return ret;
  2035. mutex_lock(&inode->i_mutex);
  2036. ino_size = round_up(inode->i_size, PAGE_CACHE_SIZE);
  2037. ret = find_first_non_hole(inode, &offset, &len);
  2038. if (ret < 0)
  2039. goto out_only_mutex;
  2040. if (ret && !len) {
  2041. /* Already in a large hole */
  2042. ret = 0;
  2043. goto out_only_mutex;
  2044. }
  2045. lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
  2046. lockend = round_down(offset + len,
  2047. BTRFS_I(inode)->root->sectorsize) - 1;
  2048. same_page = ((offset >> PAGE_CACHE_SHIFT) ==
  2049. ((offset + len - 1) >> PAGE_CACHE_SHIFT));
  2050. /*
  2051. * We needn't truncate any page which is beyond the end of the file
  2052. * because we are sure there is no data there.
  2053. */
  2054. /*
  2055. * Only do this if we are in the same page and we aren't doing the
  2056. * entire page.
  2057. */
  2058. if (same_page && len < PAGE_CACHE_SIZE) {
  2059. if (offset < ino_size) {
  2060. truncated_page = true;
  2061. ret = btrfs_truncate_page(inode, offset, len, 0);
  2062. } else {
  2063. ret = 0;
  2064. }
  2065. goto out_only_mutex;
  2066. }
  2067. /* zero back part of the first page */
  2068. if (offset < ino_size) {
  2069. truncated_page = true;
  2070. ret = btrfs_truncate_page(inode, offset, 0, 0);
  2071. if (ret) {
  2072. mutex_unlock(&inode->i_mutex);
  2073. return ret;
  2074. }
  2075. }
  2076. /* Check the aligned pages after the first unaligned page,
  2077. * if offset != orig_start, which means the first unaligned page
  2078. * including serveral following pages are already in holes,
  2079. * the extra check can be skipped */
  2080. if (offset == orig_start) {
  2081. /* after truncate page, check hole again */
  2082. len = offset + len - lockstart;
  2083. offset = lockstart;
  2084. ret = find_first_non_hole(inode, &offset, &len);
  2085. if (ret < 0)
  2086. goto out_only_mutex;
  2087. if (ret && !len) {
  2088. ret = 0;
  2089. goto out_only_mutex;
  2090. }
  2091. lockstart = offset;
  2092. }
  2093. /* Check the tail unaligned part is in a hole */
  2094. tail_start = lockend + 1;
  2095. tail_len = offset + len - tail_start;
  2096. if (tail_len) {
  2097. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2098. if (unlikely(ret < 0))
  2099. goto out_only_mutex;
  2100. if (!ret) {
  2101. /* zero the front end of the last page */
  2102. if (tail_start + tail_len < ino_size) {
  2103. truncated_page = true;
  2104. ret = btrfs_truncate_page(inode,
  2105. tail_start + tail_len, 0, 1);
  2106. if (ret)
  2107. goto out_only_mutex;
  2108. }
  2109. }
  2110. }
  2111. if (lockend < lockstart) {
  2112. ret = 0;
  2113. goto out_only_mutex;
  2114. }
  2115. while (1) {
  2116. struct btrfs_ordered_extent *ordered;
  2117. truncate_pagecache_range(inode, lockstart, lockend);
  2118. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2119. 0, &cached_state);
  2120. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2121. /*
  2122. * We need to make sure we have no ordered extents in this range
  2123. * and nobody raced in and read a page in this range, if we did
  2124. * we need to try again.
  2125. */
  2126. if ((!ordered ||
  2127. (ordered->file_offset + ordered->len <= lockstart ||
  2128. ordered->file_offset > lockend)) &&
  2129. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2130. if (ordered)
  2131. btrfs_put_ordered_extent(ordered);
  2132. break;
  2133. }
  2134. if (ordered)
  2135. btrfs_put_ordered_extent(ordered);
  2136. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2137. lockend, &cached_state, GFP_NOFS);
  2138. ret = btrfs_wait_ordered_range(inode, lockstart,
  2139. lockend - lockstart + 1);
  2140. if (ret) {
  2141. mutex_unlock(&inode->i_mutex);
  2142. return ret;
  2143. }
  2144. }
  2145. path = btrfs_alloc_path();
  2146. if (!path) {
  2147. ret = -ENOMEM;
  2148. goto out;
  2149. }
  2150. rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
  2151. if (!rsv) {
  2152. ret = -ENOMEM;
  2153. goto out_free;
  2154. }
  2155. rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
  2156. rsv->failfast = 1;
  2157. /*
  2158. * 1 - update the inode
  2159. * 1 - removing the extents in the range
  2160. * 1 - adding the hole extent if no_holes isn't set
  2161. */
  2162. rsv_count = no_holes ? 2 : 3;
  2163. trans = btrfs_start_transaction(root, rsv_count);
  2164. if (IS_ERR(trans)) {
  2165. err = PTR_ERR(trans);
  2166. goto out_free;
  2167. }
  2168. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
  2169. min_size);
  2170. BUG_ON(ret);
  2171. trans->block_rsv = rsv;
  2172. cur_offset = lockstart;
  2173. len = lockend - cur_offset;
  2174. while (cur_offset < lockend) {
  2175. ret = __btrfs_drop_extents(trans, root, inode, path,
  2176. cur_offset, lockend + 1,
  2177. &drop_end, 1, 0, 0, NULL);
  2178. if (ret != -ENOSPC)
  2179. break;
  2180. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2181. if (cur_offset < ino_size) {
  2182. ret = fill_holes(trans, inode, path, cur_offset,
  2183. drop_end);
  2184. if (ret) {
  2185. err = ret;
  2186. break;
  2187. }
  2188. }
  2189. cur_offset = drop_end;
  2190. ret = btrfs_update_inode(trans, root, inode);
  2191. if (ret) {
  2192. err = ret;
  2193. break;
  2194. }
  2195. btrfs_end_transaction(trans, root);
  2196. btrfs_btree_balance_dirty(root);
  2197. trans = btrfs_start_transaction(root, rsv_count);
  2198. if (IS_ERR(trans)) {
  2199. ret = PTR_ERR(trans);
  2200. trans = NULL;
  2201. break;
  2202. }
  2203. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
  2204. rsv, min_size);
  2205. BUG_ON(ret); /* shouldn't happen */
  2206. trans->block_rsv = rsv;
  2207. ret = find_first_non_hole(inode, &cur_offset, &len);
  2208. if (unlikely(ret < 0))
  2209. break;
  2210. if (ret && !len) {
  2211. ret = 0;
  2212. break;
  2213. }
  2214. }
  2215. if (ret) {
  2216. err = ret;
  2217. goto out_trans;
  2218. }
  2219. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2220. /*
  2221. * Don't insert file hole extent item if it's for a range beyond eof
  2222. * (because it's useless) or if it represents a 0 bytes range (when
  2223. * cur_offset == drop_end).
  2224. */
  2225. if (cur_offset < ino_size && cur_offset < drop_end) {
  2226. ret = fill_holes(trans, inode, path, cur_offset, drop_end);
  2227. if (ret) {
  2228. err = ret;
  2229. goto out_trans;
  2230. }
  2231. }
  2232. out_trans:
  2233. if (!trans)
  2234. goto out_free;
  2235. inode_inc_iversion(inode);
  2236. inode->i_mtime = inode->i_ctime = CURRENT_TIME;
  2237. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2238. ret = btrfs_update_inode(trans, root, inode);
  2239. updated_inode = true;
  2240. btrfs_end_transaction(trans, root);
  2241. btrfs_btree_balance_dirty(root);
  2242. out_free:
  2243. btrfs_free_path(path);
  2244. btrfs_free_block_rsv(root, rsv);
  2245. out:
  2246. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2247. &cached_state, GFP_NOFS);
  2248. out_only_mutex:
  2249. if (!updated_inode && truncated_page && !ret && !err) {
  2250. /*
  2251. * If we only end up zeroing part of a page, we still need to
  2252. * update the inode item, so that all the time fields are
  2253. * updated as well as the necessary btrfs inode in memory fields
  2254. * for detecting, at fsync time, if the inode isn't yet in the
  2255. * log tree or it's there but not up to date.
  2256. */
  2257. trans = btrfs_start_transaction(root, 1);
  2258. if (IS_ERR(trans)) {
  2259. err = PTR_ERR(trans);
  2260. } else {
  2261. err = btrfs_update_inode(trans, root, inode);
  2262. ret = btrfs_end_transaction(trans, root);
  2263. }
  2264. }
  2265. mutex_unlock(&inode->i_mutex);
  2266. if (ret && !err)
  2267. err = ret;
  2268. return err;
  2269. }
  2270. static long btrfs_fallocate(struct file *file, int mode,
  2271. loff_t offset, loff_t len)
  2272. {
  2273. struct inode *inode = file_inode(file);
  2274. struct extent_state *cached_state = NULL;
  2275. struct btrfs_root *root = BTRFS_I(inode)->root;
  2276. u64 cur_offset;
  2277. u64 last_byte;
  2278. u64 alloc_start;
  2279. u64 alloc_end;
  2280. u64 alloc_hint = 0;
  2281. u64 locked_end;
  2282. struct extent_map *em;
  2283. int blocksize = BTRFS_I(inode)->root->sectorsize;
  2284. int ret;
  2285. alloc_start = round_down(offset, blocksize);
  2286. alloc_end = round_up(offset + len, blocksize);
  2287. /* Make sure we aren't being give some crap mode */
  2288. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2289. return -EOPNOTSUPP;
  2290. if (mode & FALLOC_FL_PUNCH_HOLE)
  2291. return btrfs_punch_hole(inode, offset, len);
  2292. /*
  2293. * Make sure we have enough space before we do the
  2294. * allocation.
  2295. */
  2296. ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
  2297. if (ret)
  2298. return ret;
  2299. if (root->fs_info->quota_enabled) {
  2300. ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
  2301. if (ret)
  2302. goto out_reserve_fail;
  2303. }
  2304. mutex_lock(&inode->i_mutex);
  2305. ret = inode_newsize_ok(inode, alloc_end);
  2306. if (ret)
  2307. goto out;
  2308. if (alloc_start > inode->i_size) {
  2309. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2310. alloc_start);
  2311. if (ret)
  2312. goto out;
  2313. } else {
  2314. /*
  2315. * If we are fallocating from the end of the file onward we
  2316. * need to zero out the end of the page if i_size lands in the
  2317. * middle of a page.
  2318. */
  2319. ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
  2320. if (ret)
  2321. goto out;
  2322. }
  2323. /*
  2324. * wait for ordered IO before we have any locks. We'll loop again
  2325. * below with the locks held.
  2326. */
  2327. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2328. alloc_end - alloc_start);
  2329. if (ret)
  2330. goto out;
  2331. locked_end = alloc_end - 1;
  2332. while (1) {
  2333. struct btrfs_ordered_extent *ordered;
  2334. /* the extent lock is ordered inside the running
  2335. * transaction
  2336. */
  2337. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2338. locked_end, 0, &cached_state);
  2339. ordered = btrfs_lookup_first_ordered_extent(inode,
  2340. alloc_end - 1);
  2341. if (ordered &&
  2342. ordered->file_offset + ordered->len > alloc_start &&
  2343. ordered->file_offset < alloc_end) {
  2344. btrfs_put_ordered_extent(ordered);
  2345. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2346. alloc_start, locked_end,
  2347. &cached_state, GFP_NOFS);
  2348. /*
  2349. * we can't wait on the range with the transaction
  2350. * running or with the extent lock held
  2351. */
  2352. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2353. alloc_end - alloc_start);
  2354. if (ret)
  2355. goto out;
  2356. } else {
  2357. if (ordered)
  2358. btrfs_put_ordered_extent(ordered);
  2359. break;
  2360. }
  2361. }
  2362. cur_offset = alloc_start;
  2363. while (1) {
  2364. u64 actual_end;
  2365. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  2366. alloc_end - cur_offset, 0);
  2367. if (IS_ERR_OR_NULL(em)) {
  2368. if (!em)
  2369. ret = -ENOMEM;
  2370. else
  2371. ret = PTR_ERR(em);
  2372. break;
  2373. }
  2374. last_byte = min(extent_map_end(em), alloc_end);
  2375. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2376. last_byte = ALIGN(last_byte, blocksize);
  2377. if (em->block_start == EXTENT_MAP_HOLE ||
  2378. (cur_offset >= inode->i_size &&
  2379. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2380. ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
  2381. last_byte - cur_offset,
  2382. 1 << inode->i_blkbits,
  2383. offset + len,
  2384. &alloc_hint);
  2385. if (ret < 0) {
  2386. free_extent_map(em);
  2387. break;
  2388. }
  2389. } else if (actual_end > inode->i_size &&
  2390. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2391. /*
  2392. * We didn't need to allocate any more space, but we
  2393. * still extended the size of the file so we need to
  2394. * update i_size.
  2395. */
  2396. inode->i_ctime = CURRENT_TIME;
  2397. i_size_write(inode, actual_end);
  2398. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2399. }
  2400. free_extent_map(em);
  2401. cur_offset = last_byte;
  2402. if (cur_offset >= alloc_end) {
  2403. ret = 0;
  2404. break;
  2405. }
  2406. }
  2407. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2408. &cached_state, GFP_NOFS);
  2409. out:
  2410. mutex_unlock(&inode->i_mutex);
  2411. if (root->fs_info->quota_enabled)
  2412. btrfs_qgroup_free(root, alloc_end - alloc_start);
  2413. out_reserve_fail:
  2414. /* Let go of our reservation. */
  2415. btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
  2416. return ret;
  2417. }
  2418. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2419. {
  2420. struct btrfs_root *root = BTRFS_I(inode)->root;
  2421. struct extent_map *em = NULL;
  2422. struct extent_state *cached_state = NULL;
  2423. u64 lockstart;
  2424. u64 lockend;
  2425. u64 start;
  2426. u64 len;
  2427. int ret = 0;
  2428. if (inode->i_size == 0)
  2429. return -ENXIO;
  2430. /*
  2431. * *offset can be negative, in this case we start finding DATA/HOLE from
  2432. * the very start of the file.
  2433. */
  2434. start = max_t(loff_t, 0, *offset);
  2435. lockstart = round_down(start, root->sectorsize);
  2436. lockend = round_up(i_size_read(inode), root->sectorsize);
  2437. if (lockend <= lockstart)
  2438. lockend = lockstart + root->sectorsize;
  2439. lockend--;
  2440. len = lockend - lockstart + 1;
  2441. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
  2442. &cached_state);
  2443. while (start < inode->i_size) {
  2444. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  2445. if (IS_ERR(em)) {
  2446. ret = PTR_ERR(em);
  2447. em = NULL;
  2448. break;
  2449. }
  2450. if (whence == SEEK_HOLE &&
  2451. (em->block_start == EXTENT_MAP_HOLE ||
  2452. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2453. break;
  2454. else if (whence == SEEK_DATA &&
  2455. (em->block_start != EXTENT_MAP_HOLE &&
  2456. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2457. break;
  2458. start = em->start + em->len;
  2459. free_extent_map(em);
  2460. em = NULL;
  2461. cond_resched();
  2462. }
  2463. free_extent_map(em);
  2464. if (!ret) {
  2465. if (whence == SEEK_DATA && start >= inode->i_size)
  2466. ret = -ENXIO;
  2467. else
  2468. *offset = min_t(loff_t, start, inode->i_size);
  2469. }
  2470. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2471. &cached_state, GFP_NOFS);
  2472. return ret;
  2473. }
  2474. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2475. {
  2476. struct inode *inode = file->f_mapping->host;
  2477. int ret;
  2478. mutex_lock(&inode->i_mutex);
  2479. switch (whence) {
  2480. case SEEK_END:
  2481. case SEEK_CUR:
  2482. offset = generic_file_llseek(file, offset, whence);
  2483. goto out;
  2484. case SEEK_DATA:
  2485. case SEEK_HOLE:
  2486. if (offset >= i_size_read(inode)) {
  2487. mutex_unlock(&inode->i_mutex);
  2488. return -ENXIO;
  2489. }
  2490. ret = find_desired_extent(inode, &offset, whence);
  2491. if (ret) {
  2492. mutex_unlock(&inode->i_mutex);
  2493. return ret;
  2494. }
  2495. }
  2496. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2497. out:
  2498. mutex_unlock(&inode->i_mutex);
  2499. return offset;
  2500. }
  2501. const struct file_operations btrfs_file_operations = {
  2502. .llseek = btrfs_file_llseek,
  2503. .read = new_sync_read,
  2504. .write = new_sync_write,
  2505. .read_iter = generic_file_read_iter,
  2506. .splice_read = generic_file_splice_read,
  2507. .write_iter = btrfs_file_write_iter,
  2508. .mmap = btrfs_file_mmap,
  2509. .open = generic_file_open,
  2510. .release = btrfs_release_file,
  2511. .fsync = btrfs_sync_file,
  2512. .fallocate = btrfs_fallocate,
  2513. .unlocked_ioctl = btrfs_ioctl,
  2514. #ifdef CONFIG_COMPAT
  2515. .compat_ioctl = btrfs_ioctl,
  2516. #endif
  2517. };
  2518. void btrfs_auto_defrag_exit(void)
  2519. {
  2520. if (btrfs_inode_defrag_cachep)
  2521. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2522. }
  2523. int btrfs_auto_defrag_init(void)
  2524. {
  2525. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2526. sizeof(struct inode_defrag), 0,
  2527. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
  2528. NULL);
  2529. if (!btrfs_inode_defrag_cachep)
  2530. return -ENOMEM;
  2531. return 0;
  2532. }
  2533. int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
  2534. {
  2535. int ret;
  2536. /*
  2537. * So with compression we will find and lock a dirty page and clear the
  2538. * first one as dirty, setup an async extent, and immediately return
  2539. * with the entire range locked but with nobody actually marked with
  2540. * writeback. So we can't just filemap_write_and_wait_range() and
  2541. * expect it to work since it will just kick off a thread to do the
  2542. * actual work. So we need to call filemap_fdatawrite_range _again_
  2543. * since it will wait on the page lock, which won't be unlocked until
  2544. * after the pages have been marked as writeback and so we're good to go
  2545. * from there. We have to do this otherwise we'll miss the ordered
  2546. * extents and that results in badness. Please Josef, do not think you
  2547. * know better and pull this out at some point in the future, it is
  2548. * right and you are wrong.
  2549. */
  2550. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2551. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  2552. &BTRFS_I(inode)->runtime_flags))
  2553. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2554. return ret;
  2555. }