file.c 81 KB

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