file.c 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <linux/fs.h>
  6. #include <linux/pagemap.h>
  7. #include <linux/time.h>
  8. #include <linux/init.h>
  9. #include <linux/string.h>
  10. #include <linux/backing-dev.h>
  11. #include <linux/falloc.h>
  12. #include <linux/filelock.h>
  13. #include <linux/writeback.h>
  14. #include <linux/compat.h>
  15. #include <linux/slab.h>
  16. #include <linux/btrfs.h>
  17. #include <linux/uio.h>
  18. #include <linux/iversion.h>
  19. #include <linux/fsverity.h>
  20. #include "ctree.h"
  21. #include "direct-io.h"
  22. #include "disk-io.h"
  23. #include "transaction.h"
  24. #include "btrfs_inode.h"
  25. #include "tree-log.h"
  26. #include "locking.h"
  27. #include "qgroup.h"
  28. #include "compression.h"
  29. #include "delalloc-space.h"
  30. #include "reflink.h"
  31. #include "subpage.h"
  32. #include "fs.h"
  33. #include "accessors.h"
  34. #include "extent-tree.h"
  35. #include "file-item.h"
  36. #include "ioctl.h"
  37. #include "file.h"
  38. #include "super.h"
  39. #include "print-tree.h"
  40. /*
  41. * Unlock folio after btrfs_file_write() is done with it.
  42. */
  43. static void btrfs_drop_folio(struct btrfs_fs_info *fs_info, struct folio *folio,
  44. u64 pos, u64 copied)
  45. {
  46. u64 block_start = round_down(pos, fs_info->sectorsize);
  47. u64 block_len = round_up(pos + copied, fs_info->sectorsize) - block_start;
  48. ASSERT(block_len <= U32_MAX);
  49. /*
  50. * Folio checked is some magic around finding folios that have been
  51. * modified without going through btrfs_dirty_folio(). Clear it here.
  52. * There should be no need to mark the pages accessed as
  53. * prepare_one_folio() should have marked them accessed in
  54. * prepare_one_folio() via find_or_create_page()
  55. */
  56. btrfs_folio_clamp_clear_checked(fs_info, folio, block_start, block_len);
  57. folio_unlock(folio);
  58. folio_put(folio);
  59. }
  60. /*
  61. * After copy_folio_from_iter_atomic(), update the following things for delalloc:
  62. * - Mark newly dirtied folio as DELALLOC in the io tree.
  63. * Used to advise which range is to be written back.
  64. * - Mark modified folio as Uptodate/Dirty and not needing COW fixup
  65. * - Update inode size for past EOF write
  66. */
  67. int btrfs_dirty_folio(struct btrfs_inode *inode, struct folio *folio, loff_t pos,
  68. size_t write_bytes, struct extent_state **cached, bool noreserve)
  69. {
  70. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  71. int ret = 0;
  72. u64 num_bytes;
  73. u64 start_pos;
  74. u64 end_of_last_block;
  75. const u64 end_pos = pos + write_bytes;
  76. loff_t isize = i_size_read(&inode->vfs_inode);
  77. unsigned int extra_bits = 0;
  78. if (write_bytes == 0)
  79. return 0;
  80. if (noreserve)
  81. extra_bits |= EXTENT_NORESERVE;
  82. start_pos = round_down(pos, fs_info->sectorsize);
  83. num_bytes = round_up(end_pos - start_pos, fs_info->sectorsize);
  84. ASSERT(num_bytes <= U32_MAX);
  85. ASSERT(folio_pos(folio) <= pos && folio_next_pos(folio) >= end_pos);
  86. end_of_last_block = start_pos + num_bytes - 1;
  87. /*
  88. * The pages may have already been dirty, clear out old accounting so
  89. * we can set things up properly
  90. */
  91. btrfs_clear_extent_bit(&inode->io_tree, start_pos, end_of_last_block,
  92. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  93. cached);
  94. ret = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
  95. extra_bits, cached);
  96. if (ret)
  97. return ret;
  98. btrfs_folio_clamp_set_uptodate(fs_info, folio, start_pos, num_bytes);
  99. btrfs_folio_clamp_clear_checked(fs_info, folio, start_pos, num_bytes);
  100. btrfs_folio_clamp_set_dirty(fs_info, folio, start_pos, num_bytes);
  101. /*
  102. * we've only changed i_size in ram, and we haven't updated
  103. * the disk i_size. There is no need to log the inode
  104. * at this time.
  105. */
  106. if (end_pos > isize)
  107. i_size_write(&inode->vfs_inode, end_pos);
  108. return 0;
  109. }
  110. /*
  111. * this is very complex, but the basic idea is to drop all extents
  112. * in the range start - end. hint_block is filled in with a block number
  113. * that would be a good hint to the block allocator for this file.
  114. *
  115. * If an extent intersects the range but is not entirely inside the range
  116. * it is either truncated or split. Anything entirely inside the range
  117. * is deleted from the tree.
  118. *
  119. * Note: the VFS' inode number of bytes is not updated, it's up to the caller
  120. * to deal with that. We set the field 'bytes_found' of the arguments structure
  121. * with the number of allocated bytes found in the target range, so that the
  122. * caller can update the inode's number of bytes in an atomic way when
  123. * replacing extents in a range to avoid races with stat(2).
  124. */
  125. int btrfs_drop_extents(struct btrfs_trans_handle *trans,
  126. struct btrfs_root *root, struct btrfs_inode *inode,
  127. struct btrfs_drop_extents_args *args)
  128. {
  129. struct btrfs_fs_info *fs_info = root->fs_info;
  130. struct extent_buffer *leaf;
  131. struct btrfs_file_extent_item *fi;
  132. struct btrfs_key key;
  133. struct btrfs_key new_key;
  134. u64 ino = btrfs_ino(inode);
  135. u64 search_start = args->start;
  136. u64 disk_bytenr = 0;
  137. u64 num_bytes = 0;
  138. u64 extent_offset = 0;
  139. u64 extent_end = 0;
  140. u64 last_end = args->start;
  141. int del_nr = 0;
  142. int del_slot = 0;
  143. int extent_type;
  144. int recow;
  145. int ret;
  146. int modify_tree = -1;
  147. int update_refs;
  148. int found = 0;
  149. struct btrfs_path *path = args->path;
  150. args->bytes_found = 0;
  151. args->extent_inserted = false;
  152. /* Must always have a path if ->replace_extent is true */
  153. ASSERT(!(args->replace_extent && !args->path));
  154. if (!path) {
  155. path = btrfs_alloc_path();
  156. if (!path) {
  157. ret = -ENOMEM;
  158. goto out;
  159. }
  160. }
  161. if (args->drop_cache)
  162. btrfs_drop_extent_map_range(inode, args->start, args->end - 1, false);
  163. if (data_race(args->start >= inode->disk_i_size) && !args->replace_extent)
  164. modify_tree = 0;
  165. update_refs = (btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID);
  166. while (1) {
  167. recow = 0;
  168. ret = btrfs_lookup_file_extent(trans, root, path, ino,
  169. search_start, modify_tree);
  170. if (ret < 0)
  171. break;
  172. if (ret > 0 && path->slots[0] > 0 && search_start == args->start) {
  173. leaf = path->nodes[0];
  174. btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
  175. if (key.objectid == ino &&
  176. key.type == BTRFS_EXTENT_DATA_KEY)
  177. path->slots[0]--;
  178. }
  179. ret = 0;
  180. next_slot:
  181. leaf = path->nodes[0];
  182. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  183. if (WARN_ON(del_nr > 0)) {
  184. btrfs_print_leaf(leaf);
  185. ret = -EINVAL;
  186. break;
  187. }
  188. ret = btrfs_next_leaf(root, path);
  189. if (ret < 0)
  190. break;
  191. if (ret > 0) {
  192. ret = 0;
  193. break;
  194. }
  195. leaf = path->nodes[0];
  196. recow = 1;
  197. }
  198. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  199. if (key.objectid > ino)
  200. break;
  201. if (WARN_ON_ONCE(key.objectid < ino) ||
  202. key.type < BTRFS_EXTENT_DATA_KEY) {
  203. ASSERT(del_nr == 0);
  204. path->slots[0]++;
  205. goto next_slot;
  206. }
  207. if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end)
  208. break;
  209. fi = btrfs_item_ptr(leaf, path->slots[0],
  210. struct btrfs_file_extent_item);
  211. extent_type = btrfs_file_extent_type(leaf, fi);
  212. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  213. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  214. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  215. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  216. extent_offset = btrfs_file_extent_offset(leaf, fi);
  217. extent_end = key.offset +
  218. btrfs_file_extent_num_bytes(leaf, fi);
  219. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  220. extent_end = key.offset +
  221. btrfs_file_extent_ram_bytes(leaf, fi);
  222. } else {
  223. /* can't happen */
  224. BUG();
  225. }
  226. /*
  227. * Don't skip extent items representing 0 byte lengths. They
  228. * used to be created (bug) if while punching holes we hit
  229. * -ENOSPC condition. So if we find one here, just ensure we
  230. * delete it, otherwise we would insert a new file extent item
  231. * with the same key (offset) as that 0 bytes length file
  232. * extent item in the call to setup_items_for_insert() later
  233. * in this function.
  234. */
  235. if (extent_end == key.offset && extent_end >= search_start) {
  236. last_end = extent_end;
  237. goto delete_extent_item;
  238. }
  239. if (extent_end <= search_start) {
  240. path->slots[0]++;
  241. goto next_slot;
  242. }
  243. found = 1;
  244. search_start = max(key.offset, args->start);
  245. if (recow || !modify_tree) {
  246. modify_tree = -1;
  247. btrfs_release_path(path);
  248. continue;
  249. }
  250. /*
  251. * | - range to drop - |
  252. * | -------- extent -------- |
  253. */
  254. if (args->start > key.offset && args->end < extent_end) {
  255. if (WARN_ON(del_nr > 0)) {
  256. btrfs_print_leaf(leaf);
  257. ret = -EINVAL;
  258. break;
  259. }
  260. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  261. ret = -EOPNOTSUPP;
  262. break;
  263. }
  264. memcpy(&new_key, &key, sizeof(new_key));
  265. new_key.offset = args->start;
  266. ret = btrfs_duplicate_item(trans, root, path,
  267. &new_key);
  268. if (ret == -EAGAIN) {
  269. btrfs_release_path(path);
  270. continue;
  271. }
  272. if (ret < 0)
  273. break;
  274. leaf = path->nodes[0];
  275. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  276. struct btrfs_file_extent_item);
  277. btrfs_set_file_extent_num_bytes(leaf, fi,
  278. args->start - key.offset);
  279. fi = btrfs_item_ptr(leaf, path->slots[0],
  280. struct btrfs_file_extent_item);
  281. extent_offset += args->start - key.offset;
  282. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  283. btrfs_set_file_extent_num_bytes(leaf, fi,
  284. extent_end - args->start);
  285. if (update_refs && disk_bytenr > 0) {
  286. struct btrfs_ref ref = {
  287. .action = BTRFS_ADD_DELAYED_REF,
  288. .bytenr = disk_bytenr,
  289. .num_bytes = num_bytes,
  290. .parent = 0,
  291. .owning_root = btrfs_root_id(root),
  292. .ref_root = btrfs_root_id(root),
  293. };
  294. btrfs_init_data_ref(&ref, new_key.objectid,
  295. args->start - extent_offset,
  296. 0, false);
  297. ret = btrfs_inc_extent_ref(trans, &ref);
  298. if (unlikely(ret)) {
  299. btrfs_abort_transaction(trans, ret);
  300. break;
  301. }
  302. }
  303. key.offset = args->start;
  304. }
  305. /*
  306. * From here on out we will have actually dropped something, so
  307. * last_end can be updated.
  308. */
  309. last_end = extent_end;
  310. /*
  311. * | ---- range to drop ----- |
  312. * | -------- extent -------- |
  313. */
  314. if (args->start <= key.offset && args->end < extent_end) {
  315. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  316. ret = -EOPNOTSUPP;
  317. break;
  318. }
  319. memcpy(&new_key, &key, sizeof(new_key));
  320. new_key.offset = args->end;
  321. btrfs_set_item_key_safe(trans, path, &new_key);
  322. extent_offset += args->end - key.offset;
  323. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  324. btrfs_set_file_extent_num_bytes(leaf, fi,
  325. extent_end - args->end);
  326. if (update_refs && disk_bytenr > 0)
  327. args->bytes_found += args->end - key.offset;
  328. break;
  329. }
  330. search_start = extent_end;
  331. /*
  332. * | ---- range to drop ----- |
  333. * | -------- extent -------- |
  334. */
  335. if (args->start > key.offset && args->end >= extent_end) {
  336. if (WARN_ON(del_nr > 0)) {
  337. btrfs_print_leaf(leaf);
  338. ret = -EINVAL;
  339. break;
  340. }
  341. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  342. ret = -EOPNOTSUPP;
  343. break;
  344. }
  345. btrfs_set_file_extent_num_bytes(leaf, fi,
  346. args->start - key.offset);
  347. if (update_refs && disk_bytenr > 0)
  348. args->bytes_found += extent_end - args->start;
  349. if (args->end == extent_end)
  350. break;
  351. path->slots[0]++;
  352. goto next_slot;
  353. }
  354. /*
  355. * | ---- range to drop ----- |
  356. * | ------ extent ------ |
  357. */
  358. if (args->start <= key.offset && args->end >= extent_end) {
  359. delete_extent_item:
  360. if (del_nr == 0) {
  361. del_slot = path->slots[0];
  362. del_nr = 1;
  363. } else {
  364. if (WARN_ON(del_slot + del_nr != path->slots[0])) {
  365. btrfs_print_leaf(leaf);
  366. ret = -EINVAL;
  367. break;
  368. }
  369. del_nr++;
  370. }
  371. if (update_refs &&
  372. extent_type == BTRFS_FILE_EXTENT_INLINE) {
  373. args->bytes_found += extent_end - key.offset;
  374. extent_end = ALIGN(extent_end,
  375. fs_info->sectorsize);
  376. } else if (update_refs && disk_bytenr > 0) {
  377. struct btrfs_ref ref = {
  378. .action = BTRFS_DROP_DELAYED_REF,
  379. .bytenr = disk_bytenr,
  380. .num_bytes = num_bytes,
  381. .parent = 0,
  382. .owning_root = btrfs_root_id(root),
  383. .ref_root = btrfs_root_id(root),
  384. };
  385. btrfs_init_data_ref(&ref, key.objectid,
  386. key.offset - extent_offset,
  387. 0, false);
  388. ret = btrfs_free_extent(trans, &ref);
  389. if (unlikely(ret)) {
  390. btrfs_abort_transaction(trans, ret);
  391. break;
  392. }
  393. args->bytes_found += extent_end - key.offset;
  394. }
  395. if (args->end == extent_end)
  396. break;
  397. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  398. path->slots[0]++;
  399. goto next_slot;
  400. }
  401. ret = btrfs_del_items(trans, root, path, del_slot,
  402. del_nr);
  403. if (unlikely(ret)) {
  404. btrfs_abort_transaction(trans, ret);
  405. break;
  406. }
  407. del_nr = 0;
  408. del_slot = 0;
  409. btrfs_release_path(path);
  410. continue;
  411. }
  412. BUG();
  413. }
  414. if (!ret && del_nr > 0) {
  415. /*
  416. * Set path->slots[0] to first slot, so that after the delete
  417. * if items are move off from our leaf to its immediate left or
  418. * right neighbor leafs, we end up with a correct and adjusted
  419. * path->slots[0] for our insertion (if args->replace_extent).
  420. */
  421. path->slots[0] = del_slot;
  422. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  423. if (ret)
  424. btrfs_abort_transaction(trans, ret);
  425. }
  426. leaf = path->nodes[0];
  427. /*
  428. * If btrfs_del_items() was called, it might have deleted a leaf, in
  429. * which case it unlocked our path, so check path->locks[0] matches a
  430. * write lock.
  431. */
  432. if (!ret && args->replace_extent &&
  433. path->locks[0] == BTRFS_WRITE_LOCK &&
  434. btrfs_leaf_free_space(leaf) >=
  435. sizeof(struct btrfs_item) + args->extent_item_size) {
  436. key.objectid = ino;
  437. key.type = BTRFS_EXTENT_DATA_KEY;
  438. key.offset = args->start;
  439. if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
  440. struct btrfs_key slot_key;
  441. btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
  442. if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
  443. path->slots[0]++;
  444. }
  445. btrfs_setup_item_for_insert(trans, root, path, &key,
  446. args->extent_item_size);
  447. args->extent_inserted = true;
  448. }
  449. if (!args->path)
  450. btrfs_free_path(path);
  451. else if (!args->extent_inserted)
  452. btrfs_release_path(path);
  453. out:
  454. args->drop_end = found ? min(args->end, last_end) : args->end;
  455. return ret;
  456. }
  457. static bool extent_mergeable(struct extent_buffer *leaf, int slot, u64 objectid,
  458. u64 bytenr, u64 orig_offset, u64 *start, u64 *end)
  459. {
  460. struct btrfs_file_extent_item *fi;
  461. struct btrfs_key key;
  462. u64 extent_end;
  463. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  464. return false;
  465. btrfs_item_key_to_cpu(leaf, &key, slot);
  466. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  467. return false;
  468. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  469. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  470. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  471. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  472. btrfs_file_extent_compression(leaf, fi) ||
  473. btrfs_file_extent_encryption(leaf, fi) ||
  474. btrfs_file_extent_other_encoding(leaf, fi))
  475. return false;
  476. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  477. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  478. return false;
  479. *start = key.offset;
  480. *end = extent_end;
  481. return true;
  482. }
  483. /*
  484. * Mark extent in the range start - end as written.
  485. *
  486. * This changes extent type from 'pre-allocated' to 'regular'. If only
  487. * part of extent is marked as written, the extent will be split into
  488. * two or three.
  489. */
  490. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  491. struct btrfs_inode *inode, u64 start, u64 end)
  492. {
  493. struct btrfs_root *root = inode->root;
  494. struct extent_buffer *leaf;
  495. BTRFS_PATH_AUTO_FREE(path);
  496. struct btrfs_file_extent_item *fi;
  497. struct btrfs_ref ref = { 0 };
  498. struct btrfs_key key;
  499. struct btrfs_key new_key;
  500. u64 bytenr;
  501. u64 num_bytes;
  502. u64 extent_end;
  503. u64 orig_offset;
  504. u64 other_start;
  505. u64 other_end;
  506. u64 split;
  507. int del_nr = 0;
  508. int del_slot = 0;
  509. int recow;
  510. int ret;
  511. u64 ino = btrfs_ino(inode);
  512. path = btrfs_alloc_path();
  513. if (!path)
  514. return -ENOMEM;
  515. again:
  516. recow = 0;
  517. split = start;
  518. key.objectid = ino;
  519. key.type = BTRFS_EXTENT_DATA_KEY;
  520. key.offset = split;
  521. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  522. if (ret < 0)
  523. return ret;
  524. if (ret > 0 && path->slots[0] > 0)
  525. path->slots[0]--;
  526. leaf = path->nodes[0];
  527. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  528. if (unlikely(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)) {
  529. ret = -EINVAL;
  530. btrfs_abort_transaction(trans, ret);
  531. return ret;
  532. }
  533. fi = btrfs_item_ptr(leaf, path->slots[0],
  534. struct btrfs_file_extent_item);
  535. if (unlikely(btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC)) {
  536. ret = -EINVAL;
  537. btrfs_abort_transaction(trans, ret);
  538. return ret;
  539. }
  540. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  541. if (unlikely(key.offset > start || extent_end < end)) {
  542. ret = -EINVAL;
  543. btrfs_abort_transaction(trans, ret);
  544. return ret;
  545. }
  546. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  547. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  548. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  549. memcpy(&new_key, &key, sizeof(new_key));
  550. if (start == key.offset && end < extent_end) {
  551. other_start = 0;
  552. other_end = start;
  553. if (extent_mergeable(leaf, path->slots[0] - 1,
  554. ino, bytenr, orig_offset,
  555. &other_start, &other_end)) {
  556. new_key.offset = end;
  557. btrfs_set_item_key_safe(trans, path, &new_key);
  558. fi = btrfs_item_ptr(leaf, path->slots[0],
  559. struct btrfs_file_extent_item);
  560. btrfs_set_file_extent_generation(leaf, fi,
  561. trans->transid);
  562. btrfs_set_file_extent_num_bytes(leaf, fi,
  563. extent_end - end);
  564. btrfs_set_file_extent_offset(leaf, fi,
  565. end - orig_offset);
  566. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  567. struct btrfs_file_extent_item);
  568. btrfs_set_file_extent_generation(leaf, fi,
  569. trans->transid);
  570. btrfs_set_file_extent_num_bytes(leaf, fi,
  571. end - other_start);
  572. return 0;
  573. }
  574. }
  575. if (start > key.offset && end == extent_end) {
  576. other_start = end;
  577. other_end = 0;
  578. if (extent_mergeable(leaf, path->slots[0] + 1,
  579. ino, bytenr, orig_offset,
  580. &other_start, &other_end)) {
  581. fi = btrfs_item_ptr(leaf, path->slots[0],
  582. struct btrfs_file_extent_item);
  583. btrfs_set_file_extent_num_bytes(leaf, fi,
  584. start - key.offset);
  585. btrfs_set_file_extent_generation(leaf, fi,
  586. trans->transid);
  587. path->slots[0]++;
  588. new_key.offset = start;
  589. btrfs_set_item_key_safe(trans, path, &new_key);
  590. fi = btrfs_item_ptr(leaf, path->slots[0],
  591. struct btrfs_file_extent_item);
  592. btrfs_set_file_extent_generation(leaf, fi,
  593. trans->transid);
  594. btrfs_set_file_extent_num_bytes(leaf, fi,
  595. other_end - start);
  596. btrfs_set_file_extent_offset(leaf, fi,
  597. start - orig_offset);
  598. return 0;
  599. }
  600. }
  601. while (start > key.offset || end < extent_end) {
  602. if (key.offset == start)
  603. split = end;
  604. new_key.offset = split;
  605. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  606. if (ret == -EAGAIN) {
  607. btrfs_release_path(path);
  608. goto again;
  609. }
  610. if (unlikely(ret < 0)) {
  611. btrfs_abort_transaction(trans, ret);
  612. return ret;
  613. }
  614. leaf = path->nodes[0];
  615. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  616. struct btrfs_file_extent_item);
  617. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  618. btrfs_set_file_extent_num_bytes(leaf, fi,
  619. split - key.offset);
  620. fi = btrfs_item_ptr(leaf, path->slots[0],
  621. struct btrfs_file_extent_item);
  622. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  623. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  624. btrfs_set_file_extent_num_bytes(leaf, fi,
  625. extent_end - split);
  626. ref.action = BTRFS_ADD_DELAYED_REF;
  627. ref.bytenr = bytenr;
  628. ref.num_bytes = num_bytes;
  629. ref.parent = 0;
  630. ref.owning_root = btrfs_root_id(root);
  631. ref.ref_root = btrfs_root_id(root);
  632. btrfs_init_data_ref(&ref, ino, orig_offset, 0, false);
  633. ret = btrfs_inc_extent_ref(trans, &ref);
  634. if (unlikely(ret)) {
  635. btrfs_abort_transaction(trans, ret);
  636. return ret;
  637. }
  638. if (split == start) {
  639. key.offset = start;
  640. } else {
  641. if (unlikely(start != key.offset)) {
  642. ret = -EINVAL;
  643. btrfs_abort_transaction(trans, ret);
  644. return ret;
  645. }
  646. path->slots[0]--;
  647. extent_end = end;
  648. }
  649. recow = 1;
  650. }
  651. other_start = end;
  652. other_end = 0;
  653. ref.action = BTRFS_DROP_DELAYED_REF;
  654. ref.bytenr = bytenr;
  655. ref.num_bytes = num_bytes;
  656. ref.parent = 0;
  657. ref.owning_root = btrfs_root_id(root);
  658. ref.ref_root = btrfs_root_id(root);
  659. btrfs_init_data_ref(&ref, ino, orig_offset, 0, false);
  660. if (extent_mergeable(leaf, path->slots[0] + 1,
  661. ino, bytenr, orig_offset,
  662. &other_start, &other_end)) {
  663. if (recow) {
  664. btrfs_release_path(path);
  665. goto again;
  666. }
  667. extent_end = other_end;
  668. del_slot = path->slots[0] + 1;
  669. del_nr++;
  670. ret = btrfs_free_extent(trans, &ref);
  671. if (unlikely(ret)) {
  672. btrfs_abort_transaction(trans, ret);
  673. return ret;
  674. }
  675. }
  676. other_start = 0;
  677. other_end = start;
  678. if (extent_mergeable(leaf, path->slots[0] - 1,
  679. ino, bytenr, orig_offset,
  680. &other_start, &other_end)) {
  681. if (recow) {
  682. btrfs_release_path(path);
  683. goto again;
  684. }
  685. key.offset = other_start;
  686. del_slot = path->slots[0];
  687. del_nr++;
  688. ret = btrfs_free_extent(trans, &ref);
  689. if (unlikely(ret)) {
  690. btrfs_abort_transaction(trans, ret);
  691. return ret;
  692. }
  693. }
  694. if (del_nr == 0) {
  695. fi = btrfs_item_ptr(leaf, path->slots[0],
  696. struct btrfs_file_extent_item);
  697. btrfs_set_file_extent_type(leaf, fi,
  698. BTRFS_FILE_EXTENT_REG);
  699. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  700. } else {
  701. fi = btrfs_item_ptr(leaf, del_slot - 1,
  702. struct btrfs_file_extent_item);
  703. btrfs_set_file_extent_type(leaf, fi,
  704. BTRFS_FILE_EXTENT_REG);
  705. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  706. btrfs_set_file_extent_num_bytes(leaf, fi,
  707. extent_end - key.offset);
  708. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  709. if (unlikely(ret < 0)) {
  710. btrfs_abort_transaction(trans, ret);
  711. return ret;
  712. }
  713. }
  714. return 0;
  715. }
  716. /*
  717. * On error return an unlocked folio and the error value
  718. * On success return a locked folio and 0
  719. */
  720. static int prepare_uptodate_folio(struct inode *inode, struct folio *folio, u64 pos,
  721. u64 len)
  722. {
  723. u64 clamp_start = max_t(u64, pos, folio_pos(folio));
  724. u64 clamp_end = min_t(u64, pos + len, folio_next_pos(folio));
  725. const u32 blocksize = inode_to_fs_info(inode)->sectorsize;
  726. int ret = 0;
  727. if (folio_test_uptodate(folio))
  728. return 0;
  729. if (IS_ALIGNED(clamp_start, blocksize) &&
  730. IS_ALIGNED(clamp_end, blocksize))
  731. return 0;
  732. ret = btrfs_read_folio(NULL, folio);
  733. if (ret)
  734. return ret;
  735. folio_lock(folio);
  736. if (unlikely(!folio_test_uptodate(folio))) {
  737. folio_unlock(folio);
  738. return -EIO;
  739. }
  740. /*
  741. * Since btrfs_read_folio() will unlock the folio before it returns,
  742. * there is a window where btrfs_release_folio() can be called to
  743. * release the page. Here we check both inode mapping and page
  744. * private to make sure the page was not released.
  745. *
  746. * The private flag check is essential for subpage as we need to store
  747. * extra bitmap using folio private.
  748. */
  749. if (folio->mapping != inode->i_mapping || !folio_test_private(folio)) {
  750. folio_unlock(folio);
  751. return -EAGAIN;
  752. }
  753. return 0;
  754. }
  755. static gfp_t get_prepare_gfp_flags(struct inode *inode, bool nowait)
  756. {
  757. gfp_t gfp;
  758. gfp = btrfs_alloc_write_mask(inode->i_mapping);
  759. if (nowait) {
  760. gfp &= ~__GFP_DIRECT_RECLAIM;
  761. gfp |= GFP_NOWAIT;
  762. }
  763. return gfp;
  764. }
  765. /*
  766. * Get folio into the page cache and lock it.
  767. */
  768. static noinline int prepare_one_folio(struct inode *inode, struct folio **folio_ret,
  769. loff_t pos, size_t write_bytes,
  770. bool nowait)
  771. {
  772. const pgoff_t index = pos >> PAGE_SHIFT;
  773. gfp_t mask = get_prepare_gfp_flags(inode, nowait);
  774. fgf_t fgp_flags = (nowait ? FGP_WRITEBEGIN | FGP_NOWAIT : FGP_WRITEBEGIN) |
  775. fgf_set_order(write_bytes);
  776. struct folio *folio;
  777. int ret;
  778. again:
  779. folio = __filemap_get_folio(inode->i_mapping, index, fgp_flags, mask);
  780. if (IS_ERR(folio))
  781. return PTR_ERR(folio);
  782. ret = set_folio_extent_mapped(folio);
  783. if (ret < 0) {
  784. folio_unlock(folio);
  785. folio_put(folio);
  786. return ret;
  787. }
  788. ret = prepare_uptodate_folio(inode, folio, pos, write_bytes);
  789. if (ret) {
  790. /* The folio is already unlocked. */
  791. folio_put(folio);
  792. if (!nowait && ret == -EAGAIN)
  793. goto again;
  794. return ret;
  795. }
  796. *folio_ret = folio;
  797. return 0;
  798. }
  799. /*
  800. * Locks the extent and properly waits for data=ordered extents to finish
  801. * before allowing the folios to be modified if need.
  802. *
  803. * Return:
  804. * 1 - the extent is locked
  805. * 0 - the extent is not locked, and everything is OK
  806. * -EAGAIN - need to prepare the folios again
  807. */
  808. static noinline int
  809. lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct folio *folio,
  810. loff_t pos, size_t write_bytes,
  811. u64 *lockstart, u64 *lockend, bool nowait,
  812. struct extent_state **cached_state)
  813. {
  814. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  815. u64 start_pos;
  816. u64 last_pos;
  817. int ret = 0;
  818. start_pos = round_down(pos, fs_info->sectorsize);
  819. last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1;
  820. if (start_pos < inode->vfs_inode.i_size) {
  821. struct btrfs_ordered_extent *ordered;
  822. if (nowait) {
  823. if (!btrfs_try_lock_extent(&inode->io_tree, start_pos,
  824. last_pos, cached_state)) {
  825. folio_unlock(folio);
  826. folio_put(folio);
  827. return -EAGAIN;
  828. }
  829. } else {
  830. btrfs_lock_extent(&inode->io_tree, start_pos, last_pos,
  831. cached_state);
  832. }
  833. ordered = btrfs_lookup_ordered_range(inode, start_pos,
  834. last_pos - start_pos + 1);
  835. if (ordered &&
  836. ordered->file_offset + ordered->num_bytes > start_pos &&
  837. ordered->file_offset <= last_pos) {
  838. btrfs_unlock_extent(&inode->io_tree, start_pos, last_pos,
  839. cached_state);
  840. folio_unlock(folio);
  841. folio_put(folio);
  842. btrfs_start_ordered_extent(ordered);
  843. btrfs_put_ordered_extent(ordered);
  844. return -EAGAIN;
  845. }
  846. if (ordered)
  847. btrfs_put_ordered_extent(ordered);
  848. *lockstart = start_pos;
  849. *lockend = last_pos;
  850. ret = 1;
  851. }
  852. /*
  853. * We should be called after prepare_one_folio() which should have locked
  854. * all pages in the range.
  855. */
  856. WARN_ON(!folio_test_locked(folio));
  857. return ret;
  858. }
  859. /*
  860. * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
  861. *
  862. * @pos: File offset.
  863. * @write_bytes: The length to write, will be updated to the nocow writeable
  864. * range.
  865. * @nowait: Indicate if we can block or not (non-blocking IO context).
  866. *
  867. * This function will flush ordered extents in the range to ensure proper
  868. * nocow checks.
  869. *
  870. * Return:
  871. * > 0 If we can nocow, and updates @write_bytes.
  872. * 0 If we can't do a nocow write.
  873. * -EAGAIN If we can't do a nocow write because snapshotting of the inode's
  874. * root is in progress or because we are in a non-blocking IO
  875. * context and need to block (@nowait is true).
  876. * < 0 If an error happened.
  877. *
  878. * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0.
  879. */
  880. int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos,
  881. size_t *write_bytes, bool nowait)
  882. {
  883. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  884. struct btrfs_root *root = inode->root;
  885. struct extent_state *cached_state = NULL;
  886. u64 lockstart, lockend;
  887. u64 cur_offset;
  888. int ret = 0;
  889. if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
  890. return 0;
  891. if (!btrfs_drew_try_write_lock(&root->snapshot_lock))
  892. return -EAGAIN;
  893. lockstart = round_down(pos, fs_info->sectorsize);
  894. lockend = round_up(pos + *write_bytes,
  895. fs_info->sectorsize) - 1;
  896. if (nowait) {
  897. if (!btrfs_try_lock_ordered_range(inode, lockstart, lockend,
  898. &cached_state)) {
  899. btrfs_drew_write_unlock(&root->snapshot_lock);
  900. return -EAGAIN;
  901. }
  902. } else {
  903. btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend,
  904. &cached_state);
  905. }
  906. cur_offset = lockstart;
  907. while (cur_offset < lockend) {
  908. u64 num_bytes = lockend - cur_offset + 1;
  909. ret = can_nocow_extent(inode, cur_offset, &num_bytes, NULL, nowait);
  910. if (ret <= 0) {
  911. /*
  912. * If cur_offset == lockstart it means we haven't found
  913. * any extent against which we can NOCOW, so unlock the
  914. * snapshot lock.
  915. */
  916. if (cur_offset == lockstart)
  917. btrfs_drew_write_unlock(&root->snapshot_lock);
  918. break;
  919. }
  920. cur_offset += num_bytes;
  921. }
  922. btrfs_unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
  923. /*
  924. * cur_offset > lockstart means there's at least a partial range we can
  925. * NOCOW, and that range can cover one or more extents.
  926. */
  927. if (cur_offset > lockstart) {
  928. *write_bytes = min_t(size_t, *write_bytes, cur_offset - pos);
  929. return 1;
  930. }
  931. return ret;
  932. }
  933. void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
  934. {
  935. btrfs_drew_write_unlock(&inode->root->snapshot_lock);
  936. }
  937. int btrfs_write_check(struct kiocb *iocb, size_t count)
  938. {
  939. struct file *file = iocb->ki_filp;
  940. struct inode *inode = file_inode(file);
  941. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  942. loff_t pos = iocb->ki_pos;
  943. int ret;
  944. loff_t oldsize;
  945. /*
  946. * Quickly bail out on NOWAIT writes if we don't have the nodatacow or
  947. * prealloc flags, as without those flags we always have to COW. We will
  948. * later check if we can really COW into the target range (using
  949. * can_nocow_extent() at btrfs_get_blocks_direct_write()).
  950. */
  951. if ((iocb->ki_flags & IOCB_NOWAIT) &&
  952. !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
  953. return -EAGAIN;
  954. ret = file_remove_privs(file);
  955. if (ret)
  956. return ret;
  957. /*
  958. * We reserve space for updating the inode when we reserve space for the
  959. * extent we are going to write, so we will enospc out there. We don't
  960. * need to start yet another transaction to update the inode as we will
  961. * update the inode when we finish writing whatever data we write.
  962. */
  963. if (!IS_NOCMTIME(inode)) {
  964. inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
  965. inode_inc_iversion(inode);
  966. }
  967. oldsize = i_size_read(inode);
  968. if (pos > oldsize) {
  969. /* Expand hole size to cover write data, preventing empty gap */
  970. loff_t end_pos = round_up(pos + count, fs_info->sectorsize);
  971. ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos);
  972. if (ret)
  973. return ret;
  974. }
  975. return 0;
  976. }
  977. static void release_space(struct btrfs_inode *inode, struct extent_changeset *data_reserved,
  978. u64 start, u64 len, bool only_release_metadata)
  979. {
  980. if (len == 0)
  981. return;
  982. if (only_release_metadata) {
  983. btrfs_check_nocow_unlock(inode);
  984. btrfs_delalloc_release_metadata(inode, len, true);
  985. } else {
  986. const struct btrfs_fs_info *fs_info = inode->root->fs_info;
  987. btrfs_delalloc_release_space(inode, data_reserved,
  988. round_down(start, fs_info->sectorsize),
  989. len, true);
  990. }
  991. }
  992. /*
  993. * Reserve data and metadata space for this buffered write range.
  994. *
  995. * Return >0 for the number of bytes reserved, which is always block aligned.
  996. * Return <0 for error.
  997. */
  998. static ssize_t reserve_space(struct btrfs_inode *inode,
  999. struct extent_changeset **data_reserved,
  1000. u64 start, size_t *len, bool nowait,
  1001. bool *only_release_metadata)
  1002. {
  1003. const struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1004. const unsigned int block_offset = (start & (fs_info->sectorsize - 1));
  1005. size_t reserve_bytes;
  1006. int ret;
  1007. ret = btrfs_check_data_free_space(inode, data_reserved, start, *len, nowait);
  1008. if (ret < 0) {
  1009. int can_nocow;
  1010. if (nowait && (ret == -ENOSPC || ret == -EAGAIN))
  1011. return -EAGAIN;
  1012. /*
  1013. * If we don't have to COW at the offset, reserve metadata only.
  1014. * write_bytes may get smaller than requested here.
  1015. */
  1016. can_nocow = btrfs_check_nocow_lock(inode, start, len, nowait);
  1017. if (can_nocow < 0)
  1018. ret = can_nocow;
  1019. if (can_nocow > 0)
  1020. ret = 0;
  1021. if (ret)
  1022. return ret;
  1023. *only_release_metadata = true;
  1024. }
  1025. reserve_bytes = round_up(*len + block_offset, fs_info->sectorsize);
  1026. WARN_ON(reserve_bytes == 0);
  1027. ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes,
  1028. reserve_bytes, nowait);
  1029. if (ret) {
  1030. if (!*only_release_metadata)
  1031. btrfs_free_reserved_data_space(inode, *data_reserved,
  1032. start, *len);
  1033. else
  1034. btrfs_check_nocow_unlock(inode);
  1035. if (nowait && ret == -ENOSPC)
  1036. ret = -EAGAIN;
  1037. return ret;
  1038. }
  1039. return reserve_bytes;
  1040. }
  1041. /* Shrink the reserved data and metadata space from @reserved_len to @new_len. */
  1042. static void shrink_reserved_space(struct btrfs_inode *inode,
  1043. struct extent_changeset *data_reserved,
  1044. u64 reserved_start, u64 reserved_len,
  1045. u64 new_len, bool only_release_metadata)
  1046. {
  1047. const u64 diff = reserved_len - new_len;
  1048. ASSERT(new_len <= reserved_len);
  1049. btrfs_delalloc_shrink_extents(inode, reserved_len, new_len);
  1050. if (only_release_metadata)
  1051. btrfs_delalloc_release_metadata(inode, diff, true);
  1052. else
  1053. btrfs_delalloc_release_space(inode, data_reserved,
  1054. reserved_start + new_len, diff, true);
  1055. }
  1056. /* Calculate the maximum amount of bytes we can write into one folio. */
  1057. static size_t calc_write_bytes(const struct btrfs_inode *inode,
  1058. const struct iov_iter *iter, u64 start)
  1059. {
  1060. const size_t max_folio_size = mapping_max_folio_size(inode->vfs_inode.i_mapping);
  1061. return min(max_folio_size - (start & (max_folio_size - 1)),
  1062. iov_iter_count(iter));
  1063. }
  1064. /*
  1065. * Do the heavy-lifting work to copy one range into one folio of the page cache.
  1066. *
  1067. * Return > 0 in case we copied all bytes or just some of them.
  1068. * Return 0 if no bytes were copied, in which case the caller should retry.
  1069. * Return <0 on error.
  1070. */
  1071. static int copy_one_range(struct btrfs_inode *inode, struct iov_iter *iter,
  1072. struct extent_changeset **data_reserved, u64 start,
  1073. bool nowait)
  1074. {
  1075. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1076. struct extent_state *cached_state = NULL;
  1077. size_t write_bytes = calc_write_bytes(inode, iter, start);
  1078. size_t copied;
  1079. const u64 reserved_start = round_down(start, fs_info->sectorsize);
  1080. u64 reserved_len;
  1081. struct folio *folio = NULL;
  1082. int extents_locked;
  1083. u64 lockstart;
  1084. u64 lockend;
  1085. bool only_release_metadata = false;
  1086. const unsigned int bdp_flags = (nowait ? BDP_ASYNC : 0);
  1087. int ret;
  1088. /*
  1089. * Fault all pages before locking them in prepare_one_folio() to avoid
  1090. * recursive lock.
  1091. */
  1092. if (unlikely(fault_in_iov_iter_readable(iter, write_bytes)))
  1093. return -EFAULT;
  1094. extent_changeset_release(*data_reserved);
  1095. ret = reserve_space(inode, data_reserved, start, &write_bytes, nowait,
  1096. &only_release_metadata);
  1097. if (ret < 0)
  1098. return ret;
  1099. reserved_len = ret;
  1100. /* Write range must be inside the reserved range. */
  1101. ASSERT(reserved_start <= start);
  1102. ASSERT(start + write_bytes <= reserved_start + reserved_len);
  1103. again:
  1104. ret = balance_dirty_pages_ratelimited_flags(inode->vfs_inode.i_mapping,
  1105. bdp_flags);
  1106. if (ret) {
  1107. btrfs_delalloc_release_extents(inode, reserved_len);
  1108. release_space(inode, *data_reserved, reserved_start, reserved_len,
  1109. only_release_metadata);
  1110. return ret;
  1111. }
  1112. ret = prepare_one_folio(&inode->vfs_inode, &folio, start, write_bytes, false);
  1113. if (ret) {
  1114. btrfs_delalloc_release_extents(inode, reserved_len);
  1115. release_space(inode, *data_reserved, reserved_start, reserved_len,
  1116. only_release_metadata);
  1117. return ret;
  1118. }
  1119. /*
  1120. * The reserved range goes beyond the current folio, shrink the reserved
  1121. * space to the folio boundary.
  1122. */
  1123. if (reserved_start + reserved_len > folio_next_pos(folio)) {
  1124. const u64 last_block = folio_next_pos(folio);
  1125. shrink_reserved_space(inode, *data_reserved, reserved_start,
  1126. reserved_len, last_block - reserved_start,
  1127. only_release_metadata);
  1128. write_bytes = last_block - start;
  1129. reserved_len = last_block - reserved_start;
  1130. }
  1131. extents_locked = lock_and_cleanup_extent_if_need(inode, folio, start,
  1132. write_bytes, &lockstart,
  1133. &lockend, nowait,
  1134. &cached_state);
  1135. if (extents_locked < 0) {
  1136. if (!nowait && extents_locked == -EAGAIN)
  1137. goto again;
  1138. btrfs_delalloc_release_extents(inode, reserved_len);
  1139. release_space(inode, *data_reserved, reserved_start, reserved_len,
  1140. only_release_metadata);
  1141. return extents_locked;
  1142. }
  1143. copied = copy_folio_from_iter_atomic(folio, offset_in_folio(folio, start),
  1144. write_bytes, iter);
  1145. flush_dcache_folio(folio);
  1146. if (unlikely(copied < write_bytes)) {
  1147. u64 last_block;
  1148. /*
  1149. * The original write range doesn't need an uptodate folio as
  1150. * the range is block aligned. But now a short copy happened.
  1151. * We cannot handle it without an uptodate folio.
  1152. *
  1153. * So just revert the range and we will retry.
  1154. */
  1155. if (!folio_test_uptodate(folio)) {
  1156. iov_iter_revert(iter, copied);
  1157. copied = 0;
  1158. }
  1159. /* No copied bytes, unlock, release reserved space and exit. */
  1160. if (copied == 0) {
  1161. if (extents_locked)
  1162. btrfs_unlock_extent(&inode->io_tree, lockstart, lockend,
  1163. &cached_state);
  1164. else
  1165. btrfs_free_extent_state(cached_state);
  1166. btrfs_delalloc_release_extents(inode, reserved_len);
  1167. release_space(inode, *data_reserved, reserved_start, reserved_len,
  1168. only_release_metadata);
  1169. btrfs_drop_folio(fs_info, folio, start, copied);
  1170. return 0;
  1171. }
  1172. /* Release the reserved space beyond the last block. */
  1173. last_block = round_up(start + copied, fs_info->sectorsize);
  1174. shrink_reserved_space(inode, *data_reserved, reserved_start,
  1175. reserved_len, last_block - reserved_start,
  1176. only_release_metadata);
  1177. reserved_len = last_block - reserved_start;
  1178. }
  1179. ret = btrfs_dirty_folio(inode, folio, start, copied, &cached_state,
  1180. only_release_metadata);
  1181. /*
  1182. * If we have not locked the extent range, because the range's start
  1183. * offset is >= i_size, we might still have a non-NULL cached extent
  1184. * state, acquired while marking the extent range as delalloc through
  1185. * btrfs_dirty_page(). Therefore free any possible cached extent state
  1186. * to avoid a memory leak.
  1187. */
  1188. if (extents_locked)
  1189. btrfs_unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
  1190. else
  1191. btrfs_free_extent_state(cached_state);
  1192. btrfs_delalloc_release_extents(inode, reserved_len);
  1193. if (ret) {
  1194. btrfs_drop_folio(fs_info, folio, start, copied);
  1195. release_space(inode, *data_reserved, reserved_start, reserved_len,
  1196. only_release_metadata);
  1197. return ret;
  1198. }
  1199. if (only_release_metadata)
  1200. btrfs_check_nocow_unlock(inode);
  1201. btrfs_drop_folio(fs_info, folio, start, copied);
  1202. return copied;
  1203. }
  1204. ssize_t btrfs_buffered_write(struct kiocb *iocb, struct iov_iter *iter)
  1205. {
  1206. struct file *file = iocb->ki_filp;
  1207. loff_t pos;
  1208. struct inode *inode = file_inode(file);
  1209. struct extent_changeset *data_reserved = NULL;
  1210. size_t num_written = 0;
  1211. ssize_t ret;
  1212. loff_t old_isize;
  1213. unsigned int ilock_flags = 0;
  1214. const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
  1215. if (nowait)
  1216. ilock_flags |= BTRFS_ILOCK_TRY;
  1217. ret = btrfs_inode_lock(BTRFS_I(inode), ilock_flags);
  1218. if (ret < 0)
  1219. return ret;
  1220. /*
  1221. * We can only trust the isize with inode lock held, or it can race with
  1222. * other buffered writes and cause incorrect call of
  1223. * pagecache_isize_extended() to overwrite existing data.
  1224. */
  1225. old_isize = i_size_read(inode);
  1226. ret = generic_write_checks(iocb, iter);
  1227. if (ret <= 0)
  1228. goto out;
  1229. ret = btrfs_write_check(iocb, ret);
  1230. if (ret < 0)
  1231. goto out;
  1232. pos = iocb->ki_pos;
  1233. while (iov_iter_count(iter) > 0) {
  1234. ret = copy_one_range(BTRFS_I(inode), iter, &data_reserved, pos, nowait);
  1235. if (ret < 0)
  1236. break;
  1237. pos += ret;
  1238. num_written += ret;
  1239. cond_resched();
  1240. }
  1241. extent_changeset_free(data_reserved);
  1242. if (num_written > 0) {
  1243. pagecache_isize_extended(inode, old_isize, iocb->ki_pos);
  1244. iocb->ki_pos += num_written;
  1245. }
  1246. out:
  1247. btrfs_inode_unlock(BTRFS_I(inode), ilock_flags);
  1248. return num_written ? num_written : ret;
  1249. }
  1250. static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from,
  1251. const struct btrfs_ioctl_encoded_io_args *encoded)
  1252. {
  1253. struct file *file = iocb->ki_filp;
  1254. struct inode *inode = file_inode(file);
  1255. loff_t count;
  1256. ssize_t ret;
  1257. btrfs_inode_lock(BTRFS_I(inode), 0);
  1258. count = encoded->len;
  1259. ret = generic_write_checks_count(iocb, &count);
  1260. if (ret == 0 && count != encoded->len) {
  1261. /*
  1262. * The write got truncated by generic_write_checks_count(). We
  1263. * can't do a partial encoded write.
  1264. */
  1265. ret = -EFBIG;
  1266. }
  1267. if (ret || encoded->len == 0)
  1268. goto out;
  1269. ret = btrfs_write_check(iocb, encoded->len);
  1270. if (ret < 0)
  1271. goto out;
  1272. ret = btrfs_do_encoded_write(iocb, from, encoded);
  1273. out:
  1274. btrfs_inode_unlock(BTRFS_I(inode), 0);
  1275. return ret;
  1276. }
  1277. ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from,
  1278. const struct btrfs_ioctl_encoded_io_args *encoded)
  1279. {
  1280. struct file *file = iocb->ki_filp;
  1281. struct btrfs_inode *inode = BTRFS_I(file_inode(file));
  1282. ssize_t num_written, num_sync;
  1283. if (btrfs_is_shutdown(inode->root->fs_info))
  1284. return -EIO;
  1285. /*
  1286. * If the fs flips readonly due to some impossible error, although we
  1287. * have opened a file as writable, we have to stop this write operation
  1288. * to ensure consistency.
  1289. */
  1290. if (BTRFS_FS_ERROR(inode->root->fs_info))
  1291. return -EROFS;
  1292. if (encoded && (iocb->ki_flags & IOCB_NOWAIT))
  1293. return -EOPNOTSUPP;
  1294. if (encoded) {
  1295. num_written = btrfs_encoded_write(iocb, from, encoded);
  1296. num_sync = encoded->len;
  1297. } else if (iocb->ki_flags & IOCB_DIRECT) {
  1298. num_written = btrfs_direct_write(iocb, from);
  1299. num_sync = num_written;
  1300. } else {
  1301. num_written = btrfs_buffered_write(iocb, from);
  1302. num_sync = num_written;
  1303. }
  1304. btrfs_set_inode_last_sub_trans(inode);
  1305. if (num_sync > 0) {
  1306. num_sync = generic_write_sync(iocb, num_sync);
  1307. if (num_sync < 0)
  1308. num_written = num_sync;
  1309. }
  1310. return num_written;
  1311. }
  1312. static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  1313. {
  1314. return btrfs_do_write_iter(iocb, from, NULL);
  1315. }
  1316. int btrfs_release_file(struct inode *inode, struct file *filp)
  1317. {
  1318. struct btrfs_file_private *private = filp->private_data;
  1319. if (private) {
  1320. kfree(private->filldir_buf);
  1321. btrfs_free_extent_state(private->llseek_cached_state);
  1322. kfree(private);
  1323. filp->private_data = NULL;
  1324. }
  1325. /*
  1326. * Set by setattr when we are about to truncate a file from a non-zero
  1327. * size to a zero size. This tries to flush down new bytes that may
  1328. * have been written if the application were using truncate to replace
  1329. * a file in place.
  1330. */
  1331. if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
  1332. &BTRFS_I(inode)->runtime_flags))
  1333. filemap_flush(inode->i_mapping);
  1334. return 0;
  1335. }
  1336. static int start_ordered_ops(struct btrfs_inode *inode, loff_t start, loff_t end)
  1337. {
  1338. int ret;
  1339. struct blk_plug plug;
  1340. /*
  1341. * This is only called in fsync, which would do synchronous writes, so
  1342. * a plug can merge adjacent IOs as much as possible. Esp. in case of
  1343. * multiple disks using raid profile, a large IO can be split to
  1344. * several segments of stripe length (currently 64K).
  1345. */
  1346. blk_start_plug(&plug);
  1347. ret = btrfs_fdatawrite_range(inode, start, end);
  1348. blk_finish_plug(&plug);
  1349. return ret;
  1350. }
  1351. static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx)
  1352. {
  1353. struct btrfs_inode *inode = ctx->inode;
  1354. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1355. if (btrfs_inode_in_log(inode, btrfs_get_fs_generation(fs_info)) &&
  1356. list_empty(&ctx->ordered_extents))
  1357. return true;
  1358. /*
  1359. * If we are doing a fast fsync we can not bail out if the inode's
  1360. * last_trans is <= then the last committed transaction, because we only
  1361. * update the last_trans of the inode during ordered extent completion,
  1362. * and for a fast fsync we don't wait for that, we only wait for the
  1363. * writeback to complete.
  1364. */
  1365. if (inode->last_trans <= btrfs_get_last_trans_committed(fs_info) &&
  1366. (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) ||
  1367. list_empty(&ctx->ordered_extents)))
  1368. return true;
  1369. return false;
  1370. }
  1371. /*
  1372. * fsync call for both files and directories. This logs the inode into
  1373. * the tree log instead of forcing full commits whenever possible.
  1374. *
  1375. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1376. * in the metadata btree are up to date for copying to the log.
  1377. *
  1378. * It drops the inode mutex before doing the tree log commit. This is an
  1379. * important optimization for directories because holding the mutex prevents
  1380. * new operations on the dir while we write to disk.
  1381. */
  1382. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1383. {
  1384. struct dentry *dentry = file_dentry(file);
  1385. struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
  1386. struct btrfs_root *root = inode->root;
  1387. struct btrfs_fs_info *fs_info = root->fs_info;
  1388. struct btrfs_trans_handle *trans;
  1389. struct btrfs_log_ctx ctx;
  1390. int ret = 0, err;
  1391. u64 len;
  1392. bool full_sync;
  1393. bool skip_ilock = false;
  1394. if (current->journal_info == BTRFS_TRANS_DIO_WRITE_STUB) {
  1395. skip_ilock = true;
  1396. current->journal_info = NULL;
  1397. btrfs_assert_inode_locked(inode);
  1398. }
  1399. trace_btrfs_sync_file(file, datasync);
  1400. btrfs_init_log_ctx(&ctx, inode);
  1401. /*
  1402. * Always set the range to a full range, otherwise we can get into
  1403. * several problems, from missing file extent items to represent holes
  1404. * when not using the NO_HOLES feature, to log tree corruption due to
  1405. * races between hole detection during logging and completion of ordered
  1406. * extents outside the range, to missing checksums due to ordered extents
  1407. * for which we flushed only a subset of their pages.
  1408. */
  1409. start = 0;
  1410. end = LLONG_MAX;
  1411. len = (u64)LLONG_MAX + 1;
  1412. /*
  1413. * We write the dirty pages in the range and wait until they complete
  1414. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1415. * multi-task, and make the performance up. See
  1416. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1417. */
  1418. ret = start_ordered_ops(inode, start, end);
  1419. if (ret)
  1420. goto out;
  1421. if (skip_ilock)
  1422. down_write(&inode->i_mmap_lock);
  1423. else
  1424. btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
  1425. atomic_inc(&root->log_batch);
  1426. /*
  1427. * Before we acquired the inode's lock and the mmap lock, someone may
  1428. * have dirtied more pages in the target range. We need to make sure
  1429. * that writeback for any such pages does not start while we are logging
  1430. * the inode, because if it does, any of the following might happen when
  1431. * we are not doing a full inode sync:
  1432. *
  1433. * 1) We log an extent after its writeback finishes but before its
  1434. * checksums are added to the csum tree, leading to -EIO errors
  1435. * when attempting to read the extent after a log replay.
  1436. *
  1437. * 2) We can end up logging an extent before its writeback finishes.
  1438. * Therefore after the log replay we will have a file extent item
  1439. * pointing to an unwritten extent (and no data checksums as well).
  1440. *
  1441. * So trigger writeback for any eventual new dirty pages and then we
  1442. * wait for all ordered extents to complete below.
  1443. */
  1444. ret = start_ordered_ops(inode, start, end);
  1445. if (ret) {
  1446. if (skip_ilock)
  1447. up_write(&inode->i_mmap_lock);
  1448. else
  1449. btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
  1450. goto out;
  1451. }
  1452. /*
  1453. * Always check for the full sync flag while holding the inode's lock,
  1454. * to avoid races with other tasks. The flag must be either set all the
  1455. * time during logging or always off all the time while logging.
  1456. * We check the flag here after starting delalloc above, because when
  1457. * running delalloc the full sync flag may be set if we need to drop
  1458. * extra extent map ranges due to temporary memory allocation failures.
  1459. */
  1460. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
  1461. /*
  1462. * We have to do this here to avoid the priority inversion of waiting on
  1463. * IO of a lower priority task while holding a transaction open.
  1464. *
  1465. * For a full fsync we wait for the ordered extents to complete while
  1466. * for a fast fsync we wait just for writeback to complete, and then
  1467. * attach the ordered extents to the transaction so that a transaction
  1468. * commit waits for their completion, to avoid data loss if we fsync,
  1469. * the current transaction commits before the ordered extents complete
  1470. * and a power failure happens right after that.
  1471. *
  1472. * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the
  1473. * logical address recorded in the ordered extent may change. We need
  1474. * to wait for the IO to stabilize the logical address.
  1475. */
  1476. if (full_sync || btrfs_is_zoned(fs_info)) {
  1477. ret = btrfs_wait_ordered_range(inode, start, len);
  1478. clear_bit(BTRFS_INODE_COW_WRITE_ERROR, &inode->runtime_flags);
  1479. } else {
  1480. /*
  1481. * Get our ordered extents as soon as possible to avoid doing
  1482. * checksum lookups in the csum tree, and use instead the
  1483. * checksums attached to the ordered extents.
  1484. */
  1485. btrfs_get_ordered_extents_for_logging(inode, &ctx.ordered_extents);
  1486. ret = filemap_fdatawait_range(inode->vfs_inode.i_mapping, start, end);
  1487. if (ret)
  1488. goto out_release_extents;
  1489. /*
  1490. * Check and clear the BTRFS_INODE_COW_WRITE_ERROR now after
  1491. * starting and waiting for writeback, because for buffered IO
  1492. * it may have been set during the end IO callback
  1493. * (end_bbio_data_write() -> btrfs_finish_ordered_extent()) in
  1494. * case an error happened and we need to wait for ordered
  1495. * extents to complete so that any extent maps that point to
  1496. * unwritten locations are dropped and we don't log them.
  1497. */
  1498. if (test_and_clear_bit(BTRFS_INODE_COW_WRITE_ERROR, &inode->runtime_flags))
  1499. ret = btrfs_wait_ordered_range(inode, start, len);
  1500. }
  1501. if (ret)
  1502. goto out_release_extents;
  1503. atomic_inc(&root->log_batch);
  1504. if (skip_inode_logging(&ctx)) {
  1505. /*
  1506. * We've had everything committed since the last time we were
  1507. * modified so clear this flag in case it was set for whatever
  1508. * reason, it's no longer relevant.
  1509. */
  1510. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
  1511. /*
  1512. * An ordered extent might have started before and completed
  1513. * already with io errors, in which case the inode was not
  1514. * updated and we end up here. So check the inode's mapping
  1515. * for any errors that might have happened since we last
  1516. * checked called fsync.
  1517. */
  1518. ret = filemap_check_wb_err(inode->vfs_inode.i_mapping, file->f_wb_err);
  1519. goto out_release_extents;
  1520. }
  1521. btrfs_init_log_ctx_scratch_eb(&ctx);
  1522. /*
  1523. * We use start here because we will need to wait on the IO to complete
  1524. * in btrfs_sync_log, which could require joining a transaction (for
  1525. * example checking cross references in the nocow path). If we use join
  1526. * here we could get into a situation where we're waiting on IO to
  1527. * happen that is blocked on a transaction trying to commit. With start
  1528. * we inc the extwriter counter, so we wait for all extwriters to exit
  1529. * before we start blocking joiners. This comment is to keep somebody
  1530. * from thinking they are super smart and changing this to
  1531. * btrfs_join_transaction *cough*Josef*cough*.
  1532. */
  1533. trans = btrfs_start_transaction(root, 0);
  1534. if (IS_ERR(trans)) {
  1535. ret = PTR_ERR(trans);
  1536. goto out_release_extents;
  1537. }
  1538. trans->in_fsync = true;
  1539. ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
  1540. /*
  1541. * Scratch eb no longer needed, release before syncing log or commit
  1542. * transaction, to avoid holding unnecessary memory during such long
  1543. * operations.
  1544. */
  1545. if (ctx.scratch_eb) {
  1546. free_extent_buffer(ctx.scratch_eb);
  1547. ctx.scratch_eb = NULL;
  1548. }
  1549. btrfs_release_log_ctx_extents(&ctx);
  1550. if (ret < 0) {
  1551. /* Fallthrough and commit/free transaction. */
  1552. ret = BTRFS_LOG_FORCE_COMMIT;
  1553. }
  1554. /* we've logged all the items and now have a consistent
  1555. * version of the file in the log. It is possible that
  1556. * someone will come in and modify the file, but that's
  1557. * fine because the log is consistent on disk, and we
  1558. * have references to all of the file's extents
  1559. *
  1560. * It is possible that someone will come in and log the
  1561. * file again, but that will end up using the synchronization
  1562. * inside btrfs_sync_log to keep things safe.
  1563. */
  1564. if (skip_ilock)
  1565. up_write(&inode->i_mmap_lock);
  1566. else
  1567. btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
  1568. if (ret == BTRFS_NO_LOG_SYNC) {
  1569. ret = btrfs_end_transaction(trans);
  1570. goto out;
  1571. }
  1572. /* We successfully logged the inode, attempt to sync the log. */
  1573. if (!ret) {
  1574. ret = btrfs_sync_log(trans, root, &ctx);
  1575. if (!ret) {
  1576. ret = btrfs_end_transaction(trans);
  1577. goto out;
  1578. }
  1579. }
  1580. /*
  1581. * At this point we need to commit the transaction because we had
  1582. * btrfs_need_log_full_commit() or some other error.
  1583. *
  1584. * If we didn't do a full sync we have to stop the trans handle, wait on
  1585. * the ordered extents, start it again and commit the transaction. If
  1586. * we attempt to wait on the ordered extents here we could deadlock with
  1587. * something like fallocate() that is holding the extent lock trying to
  1588. * start a transaction while some other thread is trying to commit the
  1589. * transaction while we (fsync) are currently holding the transaction
  1590. * open.
  1591. */
  1592. if (!full_sync) {
  1593. ret = btrfs_end_transaction(trans);
  1594. if (ret)
  1595. goto out;
  1596. ret = btrfs_wait_ordered_range(inode, start, len);
  1597. if (ret)
  1598. goto out;
  1599. /*
  1600. * This is safe to use here because we're only interested in
  1601. * making sure the transaction that had the ordered extents is
  1602. * committed. We aren't waiting on anything past this point,
  1603. * we're purely getting the transaction and committing it.
  1604. */
  1605. trans = btrfs_attach_transaction_barrier(root);
  1606. if (IS_ERR(trans)) {
  1607. ret = PTR_ERR(trans);
  1608. /*
  1609. * We committed the transaction and there's no currently
  1610. * running transaction, this means everything we care
  1611. * about made it to disk and we are done.
  1612. */
  1613. if (ret == -ENOENT)
  1614. ret = 0;
  1615. goto out;
  1616. }
  1617. }
  1618. ret = btrfs_commit_transaction(trans);
  1619. out:
  1620. free_extent_buffer(ctx.scratch_eb);
  1621. ASSERT(list_empty(&ctx.list));
  1622. ASSERT(list_empty(&ctx.conflict_inodes));
  1623. err = file_check_and_advance_wb_err(file);
  1624. if (!ret)
  1625. ret = err;
  1626. return ret > 0 ? -EIO : ret;
  1627. out_release_extents:
  1628. btrfs_release_log_ctx_extents(&ctx);
  1629. if (skip_ilock)
  1630. up_write(&inode->i_mmap_lock);
  1631. else
  1632. btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
  1633. goto out;
  1634. }
  1635. /*
  1636. * btrfs_page_mkwrite() is not allowed to change the file size as it gets
  1637. * called from a page fault handler when a page is first dirtied. Hence we must
  1638. * be careful to check for EOF conditions here. We set the page up correctly
  1639. * for a written page which means we get ENOSPC checking when writing into
  1640. * holes and correct delalloc and unwritten extent mapping on filesystems that
  1641. * support these features.
  1642. *
  1643. * We are not allowed to take the i_mutex here so we have to play games to
  1644. * protect against truncate races as the page could now be beyond EOF. Because
  1645. * truncate_setsize() writes the inode size before removing pages, once we have
  1646. * the page lock we can determine safely if the page is beyond EOF. If it is not
  1647. * beyond EOF, then the page is guaranteed safe against truncation until we
  1648. * unlock the page.
  1649. */
  1650. static vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
  1651. {
  1652. struct page *page = vmf->page;
  1653. struct folio *folio = page_folio(page);
  1654. struct btrfs_inode *inode = BTRFS_I(file_inode(vmf->vma->vm_file));
  1655. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1656. struct extent_io_tree *io_tree = &inode->io_tree;
  1657. struct btrfs_ordered_extent *ordered;
  1658. struct extent_state *cached_state = NULL;
  1659. struct extent_changeset *data_reserved = NULL;
  1660. unsigned long zero_start;
  1661. loff_t size;
  1662. size_t fsize = folio_size(folio);
  1663. int ret;
  1664. bool only_release_metadata = false;
  1665. u64 reserved_space;
  1666. u64 page_start;
  1667. u64 page_end;
  1668. u64 end;
  1669. reserved_space = fsize;
  1670. sb_start_pagefault(inode->vfs_inode.i_sb);
  1671. page_start = folio_pos(folio);
  1672. page_end = page_start + folio_size(folio) - 1;
  1673. end = page_end;
  1674. /*
  1675. * Reserving delalloc space after obtaining the page lock can lead to
  1676. * deadlock. For example, if a dirty page is locked by this function
  1677. * and the call to btrfs_delalloc_reserve_space() ends up triggering
  1678. * dirty page write out, then the btrfs_writepages() function could
  1679. * end up waiting indefinitely to get a lock on the page currently
  1680. * being processed by btrfs_page_mkwrite() function.
  1681. */
  1682. ret = btrfs_check_data_free_space(inode, &data_reserved, page_start,
  1683. reserved_space, false);
  1684. if (ret < 0) {
  1685. size_t write_bytes = reserved_space;
  1686. if (btrfs_check_nocow_lock(inode, page_start, &write_bytes, false) <= 0)
  1687. goto out_noreserve;
  1688. only_release_metadata = true;
  1689. /*
  1690. * Can't write the whole range, there may be shared extents or
  1691. * holes in the range, bail out with @only_release_metadata set
  1692. * to true so that we unlock the nocow lock before returning the
  1693. * error.
  1694. */
  1695. if (write_bytes < reserved_space)
  1696. goto out_noreserve;
  1697. }
  1698. ret = btrfs_delalloc_reserve_metadata(inode, reserved_space,
  1699. reserved_space, false);
  1700. if (ret < 0) {
  1701. if (!only_release_metadata)
  1702. btrfs_free_reserved_data_space(inode, data_reserved,
  1703. page_start, reserved_space);
  1704. goto out_noreserve;
  1705. }
  1706. ret = file_update_time(vmf->vma->vm_file);
  1707. if (ret < 0)
  1708. goto out;
  1709. again:
  1710. down_read(&inode->i_mmap_lock);
  1711. folio_lock(folio);
  1712. size = i_size_read(&inode->vfs_inode);
  1713. if ((folio->mapping != inode->vfs_inode.i_mapping) ||
  1714. (page_start >= size)) {
  1715. /* Page got truncated out from underneath us. */
  1716. goto out_unlock;
  1717. }
  1718. folio_wait_writeback(folio);
  1719. btrfs_lock_extent(io_tree, page_start, page_end, &cached_state);
  1720. ret = set_folio_extent_mapped(folio);
  1721. if (ret < 0) {
  1722. btrfs_unlock_extent(io_tree, page_start, page_end, &cached_state);
  1723. goto out_unlock;
  1724. }
  1725. /*
  1726. * We can't set the delalloc bits if there are pending ordered
  1727. * extents. Drop our locks and wait for them to finish.
  1728. */
  1729. ordered = btrfs_lookup_ordered_range(inode, page_start, fsize);
  1730. if (ordered) {
  1731. btrfs_unlock_extent(io_tree, page_start, page_end, &cached_state);
  1732. folio_unlock(folio);
  1733. up_read(&inode->i_mmap_lock);
  1734. btrfs_start_ordered_extent(ordered);
  1735. btrfs_put_ordered_extent(ordered);
  1736. goto again;
  1737. }
  1738. if (folio_contains(folio, (size - 1) >> PAGE_SHIFT)) {
  1739. reserved_space = round_up(size - page_start, fs_info->sectorsize);
  1740. if (reserved_space < fsize) {
  1741. const u64 to_free = fsize - reserved_space;
  1742. end = page_start + reserved_space - 1;
  1743. if (only_release_metadata)
  1744. btrfs_delalloc_release_metadata(inode, to_free, true);
  1745. else
  1746. btrfs_delalloc_release_space(inode, data_reserved,
  1747. end + 1, to_free, true);
  1748. }
  1749. }
  1750. /*
  1751. * page_mkwrite gets called when the page is firstly dirtied after it's
  1752. * faulted in, but write(2) could also dirty a page and set delalloc
  1753. * bits, thus in this case for space account reason, we still need to
  1754. * clear any delalloc bits within this page range since we have to
  1755. * reserve data&meta space before lock_page() (see above comments).
  1756. */
  1757. btrfs_clear_extent_bit(io_tree, page_start, end,
  1758. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
  1759. EXTENT_DEFRAG, &cached_state);
  1760. ret = btrfs_set_extent_delalloc(inode, page_start, end, 0, &cached_state);
  1761. if (ret < 0) {
  1762. btrfs_unlock_extent(io_tree, page_start, page_end, &cached_state);
  1763. goto out_unlock;
  1764. }
  1765. /* Page is wholly or partially inside EOF. */
  1766. if (page_start + folio_size(folio) > size)
  1767. zero_start = offset_in_folio(folio, size);
  1768. else
  1769. zero_start = fsize;
  1770. if (zero_start != fsize)
  1771. folio_zero_range(folio, zero_start, folio_size(folio) - zero_start);
  1772. btrfs_folio_clear_checked(fs_info, folio, page_start, fsize);
  1773. btrfs_folio_set_dirty(fs_info, folio, page_start, end + 1 - page_start);
  1774. btrfs_folio_set_uptodate(fs_info, folio, page_start, end + 1 - page_start);
  1775. btrfs_set_inode_last_sub_trans(inode);
  1776. if (only_release_metadata)
  1777. btrfs_set_extent_bit(io_tree, page_start, end, EXTENT_NORESERVE,
  1778. &cached_state);
  1779. btrfs_unlock_extent(io_tree, page_start, page_end, &cached_state);
  1780. up_read(&inode->i_mmap_lock);
  1781. btrfs_delalloc_release_extents(inode, fsize);
  1782. if (only_release_metadata)
  1783. btrfs_check_nocow_unlock(inode);
  1784. sb_end_pagefault(inode->vfs_inode.i_sb);
  1785. extent_changeset_free(data_reserved);
  1786. return VM_FAULT_LOCKED;
  1787. out_unlock:
  1788. folio_unlock(folio);
  1789. up_read(&inode->i_mmap_lock);
  1790. out:
  1791. btrfs_delalloc_release_extents(inode, fsize);
  1792. if (only_release_metadata)
  1793. btrfs_delalloc_release_metadata(inode, reserved_space, true);
  1794. else
  1795. btrfs_delalloc_release_space(inode, data_reserved, page_start,
  1796. reserved_space, true);
  1797. out_noreserve:
  1798. if (only_release_metadata)
  1799. btrfs_check_nocow_unlock(inode);
  1800. sb_end_pagefault(inode->vfs_inode.i_sb);
  1801. extent_changeset_free(data_reserved);
  1802. if (ret < 0)
  1803. return vmf_error(ret);
  1804. /* Make the VM retry the fault. */
  1805. return VM_FAULT_NOPAGE;
  1806. }
  1807. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1808. .fault = filemap_fault,
  1809. .map_pages = filemap_map_pages,
  1810. .page_mkwrite = btrfs_page_mkwrite,
  1811. };
  1812. static int btrfs_file_mmap_prepare(struct vm_area_desc *desc)
  1813. {
  1814. struct file *filp = desc->file;
  1815. struct address_space *mapping = filp->f_mapping;
  1816. if (btrfs_is_shutdown(inode_to_fs_info(file_inode(filp))))
  1817. return -EIO;
  1818. if (!mapping->a_ops->read_folio)
  1819. return -ENOEXEC;
  1820. file_accessed(filp);
  1821. desc->vm_ops = &btrfs_file_vm_ops;
  1822. return 0;
  1823. }
  1824. static bool hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
  1825. int slot, u64 start, u64 end)
  1826. {
  1827. struct btrfs_file_extent_item *fi;
  1828. struct btrfs_key key;
  1829. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1830. return false;
  1831. btrfs_item_key_to_cpu(leaf, &key, slot);
  1832. if (key.objectid != btrfs_ino(inode) ||
  1833. key.type != BTRFS_EXTENT_DATA_KEY)
  1834. return false;
  1835. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1836. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1837. return false;
  1838. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1839. return false;
  1840. if (key.offset == end)
  1841. return true;
  1842. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1843. return true;
  1844. return false;
  1845. }
  1846. static int fill_holes(struct btrfs_trans_handle *trans,
  1847. struct btrfs_inode *inode,
  1848. struct btrfs_path *path, u64 offset, u64 end)
  1849. {
  1850. struct btrfs_fs_info *fs_info = trans->fs_info;
  1851. struct btrfs_root *root = inode->root;
  1852. struct extent_buffer *leaf;
  1853. struct btrfs_file_extent_item *fi;
  1854. struct extent_map *hole_em;
  1855. struct btrfs_key key;
  1856. int ret;
  1857. if (btrfs_fs_incompat(fs_info, NO_HOLES))
  1858. goto out;
  1859. key.objectid = btrfs_ino(inode);
  1860. key.type = BTRFS_EXTENT_DATA_KEY;
  1861. key.offset = offset;
  1862. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1863. if (ret <= 0) {
  1864. /*
  1865. * We should have dropped this offset, so if we find it then
  1866. * something has gone horribly wrong.
  1867. */
  1868. if (ret == 0)
  1869. ret = -EINVAL;
  1870. return ret;
  1871. }
  1872. leaf = path->nodes[0];
  1873. if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
  1874. u64 num_bytes;
  1875. path->slots[0]--;
  1876. fi = btrfs_item_ptr(leaf, path->slots[0],
  1877. struct btrfs_file_extent_item);
  1878. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1879. end - offset;
  1880. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1881. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1882. btrfs_set_file_extent_offset(leaf, fi, 0);
  1883. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1884. goto out;
  1885. }
  1886. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1887. u64 num_bytes;
  1888. key.offset = offset;
  1889. btrfs_set_item_key_safe(trans, path, &key);
  1890. fi = btrfs_item_ptr(leaf, path->slots[0],
  1891. struct btrfs_file_extent_item);
  1892. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1893. offset;
  1894. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1895. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1896. btrfs_set_file_extent_offset(leaf, fi, 0);
  1897. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1898. goto out;
  1899. }
  1900. btrfs_release_path(path);
  1901. ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset,
  1902. end - offset);
  1903. if (ret)
  1904. return ret;
  1905. out:
  1906. btrfs_release_path(path);
  1907. hole_em = btrfs_alloc_extent_map();
  1908. if (!hole_em) {
  1909. btrfs_drop_extent_map_range(inode, offset, end - 1, false);
  1910. btrfs_set_inode_full_sync(inode);
  1911. } else {
  1912. hole_em->start = offset;
  1913. hole_em->len = end - offset;
  1914. hole_em->ram_bytes = hole_em->len;
  1915. hole_em->disk_bytenr = EXTENT_MAP_HOLE;
  1916. hole_em->disk_num_bytes = 0;
  1917. hole_em->generation = trans->transid;
  1918. ret = btrfs_replace_extent_map_range(inode, hole_em, true);
  1919. btrfs_free_extent_map(hole_em);
  1920. if (ret)
  1921. btrfs_set_inode_full_sync(inode);
  1922. }
  1923. return 0;
  1924. }
  1925. /*
  1926. * Find a hole extent on given inode and change start/len to the end of hole
  1927. * extent.(hole/vacuum extent whose em->start <= start &&
  1928. * em->start + em->len > start)
  1929. * When a hole extent is found, return 1 and modify start/len.
  1930. */
  1931. static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
  1932. {
  1933. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1934. struct extent_map *em;
  1935. int ret = 0;
  1936. em = btrfs_get_extent(inode, NULL,
  1937. round_down(*start, fs_info->sectorsize),
  1938. round_up(*len, fs_info->sectorsize));
  1939. if (IS_ERR(em))
  1940. return PTR_ERR(em);
  1941. /* Hole or vacuum extent(only exists in no-hole mode) */
  1942. if (em->disk_bytenr == EXTENT_MAP_HOLE) {
  1943. const u64 em_end = btrfs_extent_map_end(em);
  1944. ret = 1;
  1945. *len = (em_end > *start + *len) ? 0 : (*start + *len - em_end);
  1946. *start = em_end;
  1947. }
  1948. btrfs_free_extent_map(em);
  1949. return ret;
  1950. }
  1951. /*
  1952. * Check if there is no folio in the range.
  1953. *
  1954. * We cannot utilize filemap_range_has_page() in a filemap with large folios
  1955. * as we can hit the following false positive:
  1956. *
  1957. * start end
  1958. * | |
  1959. * |//|//|//|//| | | | | | | | |//|//|
  1960. * \ / \ /
  1961. * Folio A Folio B
  1962. *
  1963. * That large folio A and B cover the start and end indexes.
  1964. * In that case filemap_range_has_page() will always return true, but the above
  1965. * case is fine for btrfs_punch_hole_lock_range() usage.
  1966. *
  1967. * So here we only ensure that no other folios is in the range, excluding the
  1968. * head/tail large folio.
  1969. */
  1970. static bool check_range_has_page(struct inode *inode, u64 start, u64 end)
  1971. {
  1972. struct folio_batch fbatch;
  1973. bool ret = false;
  1974. /*
  1975. * For subpage case, if the range is not at page boundary, we could
  1976. * have pages at the leading/tailing part of the range.
  1977. * This could lead to dead loop since filemap_range_has_page()
  1978. * will always return true.
  1979. * So here we need to do extra page alignment for
  1980. * filemap_range_has_page().
  1981. *
  1982. * And do not decrease page_lockend right now, as it can be 0.
  1983. */
  1984. const u64 page_lockstart = round_up(start, PAGE_SIZE);
  1985. const u64 page_lockend = round_down(end + 1, PAGE_SIZE);
  1986. const pgoff_t start_index = page_lockstart >> PAGE_SHIFT;
  1987. const pgoff_t end_index = (page_lockend - 1) >> PAGE_SHIFT;
  1988. pgoff_t tmp = start_index;
  1989. int found_folios;
  1990. /* The same page or adjacent pages. */
  1991. if (page_lockend <= page_lockstart)
  1992. return false;
  1993. folio_batch_init(&fbatch);
  1994. found_folios = filemap_get_folios(inode->i_mapping, &tmp, end_index, &fbatch);
  1995. for (int i = 0; i < found_folios; i++) {
  1996. struct folio *folio = fbatch.folios[i];
  1997. /* A large folio begins before the start. Not a target. */
  1998. if (folio->index < start_index)
  1999. continue;
  2000. /* A large folio extends beyond the end. Not a target. */
  2001. if (folio_next_index(folio) > end_index)
  2002. continue;
  2003. /* A folio doesn't cover the head/tail index. Found a target. */
  2004. ret = true;
  2005. break;
  2006. }
  2007. folio_batch_release(&fbatch);
  2008. return ret;
  2009. }
  2010. static void btrfs_punch_hole_lock_range(struct inode *inode,
  2011. const u64 lockstart, const u64 lockend,
  2012. struct extent_state **cached_state)
  2013. {
  2014. while (1) {
  2015. truncate_pagecache_range(inode, lockstart, lockend);
  2016. btrfs_lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2017. cached_state);
  2018. /*
  2019. * We can't have ordered extents in the range, nor dirty/writeback
  2020. * pages, because we have locked the inode's VFS lock in exclusive
  2021. * mode, we have locked the inode's i_mmap_lock in exclusive mode,
  2022. * we have flushed all delalloc in the range and we have waited
  2023. * for any ordered extents in the range to complete.
  2024. * We can race with anyone reading pages from this range, so after
  2025. * locking the range check if we have pages in the range, and if
  2026. * we do, unlock the range and retry.
  2027. */
  2028. if (!check_range_has_page(inode, lockstart, lockend))
  2029. break;
  2030. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2031. cached_state);
  2032. }
  2033. btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend);
  2034. }
  2035. static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
  2036. struct btrfs_inode *inode,
  2037. struct btrfs_path *path,
  2038. struct btrfs_replace_extent_info *extent_info,
  2039. const u64 replace_len,
  2040. const u64 bytes_to_drop)
  2041. {
  2042. struct btrfs_fs_info *fs_info = trans->fs_info;
  2043. struct btrfs_root *root = inode->root;
  2044. struct btrfs_file_extent_item *extent;
  2045. struct extent_buffer *leaf;
  2046. struct btrfs_key key;
  2047. int slot;
  2048. int ret;
  2049. if (replace_len == 0)
  2050. return 0;
  2051. if (extent_info->disk_offset == 0 &&
  2052. btrfs_fs_incompat(fs_info, NO_HOLES)) {
  2053. btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
  2054. return 0;
  2055. }
  2056. key.objectid = btrfs_ino(inode);
  2057. key.type = BTRFS_EXTENT_DATA_KEY;
  2058. key.offset = extent_info->file_offset;
  2059. ret = btrfs_insert_empty_item(trans, root, path, &key,
  2060. sizeof(struct btrfs_file_extent_item));
  2061. if (ret)
  2062. return ret;
  2063. leaf = path->nodes[0];
  2064. slot = path->slots[0];
  2065. write_extent_buffer(leaf, extent_info->extent_buf,
  2066. btrfs_item_ptr_offset(leaf, slot),
  2067. sizeof(struct btrfs_file_extent_item));
  2068. extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  2069. ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
  2070. btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
  2071. btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
  2072. if (extent_info->is_new_extent)
  2073. btrfs_set_file_extent_generation(leaf, extent, trans->transid);
  2074. btrfs_release_path(path);
  2075. ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
  2076. replace_len);
  2077. if (ret)
  2078. return ret;
  2079. /* If it's a hole, nothing more needs to be done. */
  2080. if (extent_info->disk_offset == 0) {
  2081. btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
  2082. return 0;
  2083. }
  2084. btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
  2085. if (extent_info->is_new_extent && extent_info->insertions == 0) {
  2086. key.objectid = extent_info->disk_offset;
  2087. key.type = BTRFS_EXTENT_ITEM_KEY;
  2088. key.offset = extent_info->disk_len;
  2089. ret = btrfs_alloc_reserved_file_extent(trans, root,
  2090. btrfs_ino(inode),
  2091. extent_info->file_offset,
  2092. extent_info->qgroup_reserved,
  2093. &key);
  2094. } else {
  2095. struct btrfs_ref ref = {
  2096. .action = BTRFS_ADD_DELAYED_REF,
  2097. .bytenr = extent_info->disk_offset,
  2098. .num_bytes = extent_info->disk_len,
  2099. .owning_root = btrfs_root_id(root),
  2100. .ref_root = btrfs_root_id(root),
  2101. };
  2102. u64 ref_offset;
  2103. ref_offset = extent_info->file_offset - extent_info->data_offset;
  2104. btrfs_init_data_ref(&ref, btrfs_ino(inode), ref_offset, 0, false);
  2105. ret = btrfs_inc_extent_ref(trans, &ref);
  2106. }
  2107. extent_info->insertions++;
  2108. return ret;
  2109. }
  2110. /*
  2111. * The respective range must have been previously locked, as well as the inode.
  2112. * The end offset is inclusive (last byte of the range).
  2113. * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
  2114. * the file range with an extent.
  2115. * When not punching a hole, we don't want to end up in a state where we dropped
  2116. * extents without inserting a new one, so we must abort the transaction to avoid
  2117. * a corruption.
  2118. */
  2119. int btrfs_replace_file_extents(struct btrfs_inode *inode,
  2120. struct btrfs_path *path, const u64 start,
  2121. const u64 end,
  2122. struct btrfs_replace_extent_info *extent_info,
  2123. struct btrfs_trans_handle **trans_out)
  2124. {
  2125. struct btrfs_drop_extents_args drop_args = { 0 };
  2126. struct btrfs_root *root = inode->root;
  2127. struct btrfs_fs_info *fs_info = root->fs_info;
  2128. u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
  2129. u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
  2130. struct btrfs_trans_handle *trans = NULL;
  2131. struct btrfs_block_rsv rsv;
  2132. unsigned int rsv_count;
  2133. u64 cur_offset;
  2134. u64 len = end - start;
  2135. int ret = 0;
  2136. if (end <= start)
  2137. return -EINVAL;
  2138. btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
  2139. rsv.size = btrfs_calc_insert_metadata_size(fs_info, 1);
  2140. rsv.failfast = true;
  2141. /*
  2142. * 1 - update the inode
  2143. * 1 - removing the extents in the range
  2144. * 1 - adding the hole extent if no_holes isn't set or if we are
  2145. * replacing the range with a new extent
  2146. */
  2147. if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
  2148. rsv_count = 3;
  2149. else
  2150. rsv_count = 2;
  2151. trans = btrfs_start_transaction(root, rsv_count);
  2152. if (IS_ERR(trans)) {
  2153. ret = PTR_ERR(trans);
  2154. trans = NULL;
  2155. goto out_release;
  2156. }
  2157. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, &rsv,
  2158. min_size, false);
  2159. if (WARN_ON(ret))
  2160. goto out_trans;
  2161. trans->block_rsv = &rsv;
  2162. cur_offset = start;
  2163. drop_args.path = path;
  2164. drop_args.end = end + 1;
  2165. drop_args.drop_cache = true;
  2166. while (cur_offset < end) {
  2167. drop_args.start = cur_offset;
  2168. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  2169. /* If we are punching a hole decrement the inode's byte count */
  2170. if (!extent_info)
  2171. btrfs_update_inode_bytes(inode, 0,
  2172. drop_args.bytes_found);
  2173. if (ret != -ENOSPC) {
  2174. /*
  2175. * The only time we don't want to abort is if we are
  2176. * attempting to clone a partial inline extent, in which
  2177. * case we'll get EOPNOTSUPP. However if we aren't
  2178. * clone we need to abort no matter what, because if we
  2179. * got EOPNOTSUPP via prealloc then we messed up and
  2180. * need to abort.
  2181. */
  2182. if (unlikely(ret &&
  2183. (ret != -EOPNOTSUPP ||
  2184. (extent_info && extent_info->is_new_extent))))
  2185. btrfs_abort_transaction(trans, ret);
  2186. break;
  2187. }
  2188. trans->block_rsv = &fs_info->trans_block_rsv;
  2189. if (!extent_info && cur_offset < drop_args.drop_end &&
  2190. cur_offset < ino_size) {
  2191. ret = fill_holes(trans, inode, path, cur_offset,
  2192. drop_args.drop_end);
  2193. if (unlikely(ret)) {
  2194. /*
  2195. * If we failed then we didn't insert our hole
  2196. * entries for the area we dropped, so now the
  2197. * fs is corrupted, so we must abort the
  2198. * transaction.
  2199. */
  2200. btrfs_abort_transaction(trans, ret);
  2201. break;
  2202. }
  2203. } else if (!extent_info && cur_offset < drop_args.drop_end) {
  2204. /*
  2205. * We are past the i_size here, but since we didn't
  2206. * insert holes we need to clear the mapped area so we
  2207. * know to not set disk_i_size in this area until a new
  2208. * file extent is inserted here.
  2209. */
  2210. ret = btrfs_inode_clear_file_extent_range(inode,
  2211. cur_offset,
  2212. drop_args.drop_end - cur_offset);
  2213. if (unlikely(ret)) {
  2214. /*
  2215. * We couldn't clear our area, so we could
  2216. * presumably adjust up and corrupt the fs, so
  2217. * we need to abort.
  2218. */
  2219. btrfs_abort_transaction(trans, ret);
  2220. break;
  2221. }
  2222. }
  2223. if (extent_info &&
  2224. drop_args.drop_end > extent_info->file_offset) {
  2225. u64 replace_len = drop_args.drop_end -
  2226. extent_info->file_offset;
  2227. ret = btrfs_insert_replace_extent(trans, inode, path,
  2228. extent_info, replace_len,
  2229. drop_args.bytes_found);
  2230. if (unlikely(ret)) {
  2231. btrfs_abort_transaction(trans, ret);
  2232. break;
  2233. }
  2234. extent_info->data_len -= replace_len;
  2235. extent_info->data_offset += replace_len;
  2236. extent_info->file_offset += replace_len;
  2237. }
  2238. /*
  2239. * We are releasing our handle on the transaction, balance the
  2240. * dirty pages of the btree inode and flush delayed items, and
  2241. * then get a new transaction handle, which may now point to a
  2242. * new transaction in case someone else may have committed the
  2243. * transaction we used to replace/drop file extent items. So
  2244. * bump the inode's iversion and update mtime and ctime except
  2245. * if we are called from a dedupe context. This is because a
  2246. * power failure/crash may happen after the transaction is
  2247. * committed and before we finish replacing/dropping all the
  2248. * file extent items we need.
  2249. */
  2250. inode_inc_iversion(&inode->vfs_inode);
  2251. if (!extent_info || extent_info->update_times)
  2252. inode_set_mtime_to_ts(&inode->vfs_inode,
  2253. inode_set_ctime_current(&inode->vfs_inode));
  2254. ret = btrfs_update_inode(trans, inode);
  2255. if (ret)
  2256. break;
  2257. btrfs_end_transaction(trans);
  2258. btrfs_btree_balance_dirty(fs_info);
  2259. trans = btrfs_start_transaction(root, rsv_count);
  2260. if (IS_ERR(trans)) {
  2261. ret = PTR_ERR(trans);
  2262. trans = NULL;
  2263. break;
  2264. }
  2265. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
  2266. &rsv, min_size, false);
  2267. if (WARN_ON(ret))
  2268. break;
  2269. trans->block_rsv = &rsv;
  2270. cur_offset = drop_args.drop_end;
  2271. len = end - cur_offset;
  2272. if (!extent_info && len) {
  2273. ret = find_first_non_hole(inode, &cur_offset, &len);
  2274. if (unlikely(ret < 0))
  2275. break;
  2276. if (ret && !len) {
  2277. ret = 0;
  2278. break;
  2279. }
  2280. }
  2281. }
  2282. /*
  2283. * If we were cloning, force the next fsync to be a full one since we
  2284. * we replaced (or just dropped in the case of cloning holes when
  2285. * NO_HOLES is enabled) file extent items and did not setup new extent
  2286. * maps for the replacement extents (or holes).
  2287. */
  2288. if (extent_info && !extent_info->is_new_extent)
  2289. btrfs_set_inode_full_sync(inode);
  2290. if (ret)
  2291. goto out_trans;
  2292. trans->block_rsv = &fs_info->trans_block_rsv;
  2293. /*
  2294. * If we are using the NO_HOLES feature we might have had already an
  2295. * hole that overlaps a part of the region [lockstart, lockend] and
  2296. * ends at (or beyond) lockend. Since we have no file extent items to
  2297. * represent holes, drop_end can be less than lockend and so we must
  2298. * make sure we have an extent map representing the existing hole (the
  2299. * call to __btrfs_drop_extents() might have dropped the existing extent
  2300. * map representing the existing hole), otherwise the fast fsync path
  2301. * will not record the existence of the hole region
  2302. * [existing_hole_start, lockend].
  2303. */
  2304. if (drop_args.drop_end <= end)
  2305. drop_args.drop_end = end + 1;
  2306. /*
  2307. * Don't insert file hole extent item if it's for a range beyond eof
  2308. * (because it's useless) or if it represents a 0 bytes range (when
  2309. * cur_offset == drop_end).
  2310. */
  2311. if (!extent_info && cur_offset < ino_size &&
  2312. cur_offset < drop_args.drop_end) {
  2313. ret = fill_holes(trans, inode, path, cur_offset,
  2314. drop_args.drop_end);
  2315. if (unlikely(ret)) {
  2316. /* Same comment as above. */
  2317. btrfs_abort_transaction(trans, ret);
  2318. goto out_trans;
  2319. }
  2320. } else if (!extent_info && cur_offset < drop_args.drop_end) {
  2321. /* See the comment in the loop above for the reasoning here. */
  2322. ret = btrfs_inode_clear_file_extent_range(inode, cur_offset,
  2323. drop_args.drop_end - cur_offset);
  2324. if (unlikely(ret)) {
  2325. btrfs_abort_transaction(trans, ret);
  2326. goto out_trans;
  2327. }
  2328. }
  2329. if (extent_info) {
  2330. ret = btrfs_insert_replace_extent(trans, inode, path,
  2331. extent_info, extent_info->data_len,
  2332. drop_args.bytes_found);
  2333. if (unlikely(ret)) {
  2334. btrfs_abort_transaction(trans, ret);
  2335. goto out_trans;
  2336. }
  2337. }
  2338. out_trans:
  2339. if (!trans)
  2340. goto out_release;
  2341. trans->block_rsv = &fs_info->trans_block_rsv;
  2342. if (ret)
  2343. btrfs_end_transaction(trans);
  2344. else
  2345. *trans_out = trans;
  2346. out_release:
  2347. btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
  2348. return ret;
  2349. }
  2350. static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len)
  2351. {
  2352. struct inode *inode = file_inode(file);
  2353. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  2354. struct btrfs_root *root = BTRFS_I(inode)->root;
  2355. struct extent_state *cached_state = NULL;
  2356. struct btrfs_path *path;
  2357. struct btrfs_trans_handle *trans = NULL;
  2358. u64 lockstart;
  2359. u64 lockend;
  2360. u64 tail_start;
  2361. u64 tail_len;
  2362. const u64 orig_start = offset;
  2363. const u64 orig_end = offset + len - 1;
  2364. int ret = 0;
  2365. bool same_block;
  2366. u64 ino_size;
  2367. bool truncated_block = false;
  2368. bool updated_inode = false;
  2369. btrfs_inode_lock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2370. ret = btrfs_wait_ordered_range(BTRFS_I(inode), offset, len);
  2371. if (ret)
  2372. goto out_only_mutex;
  2373. ino_size = round_up(inode->i_size, fs_info->sectorsize);
  2374. ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
  2375. if (ret < 0)
  2376. goto out_only_mutex;
  2377. if (ret && !len) {
  2378. /* Already in a large hole */
  2379. ret = 0;
  2380. goto out_only_mutex;
  2381. }
  2382. ret = file_modified(file);
  2383. if (ret)
  2384. goto out_only_mutex;
  2385. lockstart = round_up(offset, fs_info->sectorsize);
  2386. lockend = round_down(offset + len, fs_info->sectorsize) - 1;
  2387. same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
  2388. == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
  2389. /*
  2390. * Only do this if we are in the same block and we aren't doing the
  2391. * entire block.
  2392. */
  2393. if (same_block && len < fs_info->sectorsize) {
  2394. if (offset < ino_size) {
  2395. truncated_block = true;
  2396. ret = btrfs_truncate_block(BTRFS_I(inode), offset + len - 1,
  2397. orig_start, orig_end);
  2398. } else {
  2399. ret = 0;
  2400. }
  2401. goto out_only_mutex;
  2402. }
  2403. /* zero back part of the first block */
  2404. if (offset < ino_size) {
  2405. truncated_block = true;
  2406. ret = btrfs_truncate_block(BTRFS_I(inode), offset, orig_start, orig_end);
  2407. if (ret) {
  2408. btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2409. return ret;
  2410. }
  2411. }
  2412. /* Check the aligned pages after the first unaligned page,
  2413. * if offset != orig_start, which means the first unaligned page
  2414. * including several following pages are already in holes,
  2415. * the extra check can be skipped */
  2416. if (offset == orig_start) {
  2417. /* after truncate page, check hole again */
  2418. len = offset + len - lockstart;
  2419. offset = lockstart;
  2420. ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
  2421. if (ret < 0)
  2422. goto out_only_mutex;
  2423. if (ret && !len) {
  2424. ret = 0;
  2425. goto out_only_mutex;
  2426. }
  2427. lockstart = offset;
  2428. }
  2429. /* Check the tail unaligned part is in a hole */
  2430. tail_start = lockend + 1;
  2431. tail_len = offset + len - tail_start;
  2432. if (tail_len) {
  2433. ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
  2434. if (unlikely(ret < 0))
  2435. goto out_only_mutex;
  2436. if (!ret) {
  2437. /* zero the front end of the last page */
  2438. if (tail_start + tail_len < ino_size) {
  2439. truncated_block = true;
  2440. ret = btrfs_truncate_block(BTRFS_I(inode),
  2441. tail_start + tail_len - 1,
  2442. orig_start, orig_end);
  2443. if (ret)
  2444. goto out_only_mutex;
  2445. }
  2446. }
  2447. }
  2448. if (lockend < lockstart) {
  2449. ret = 0;
  2450. goto out_only_mutex;
  2451. }
  2452. btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state);
  2453. path = btrfs_alloc_path();
  2454. if (!path) {
  2455. ret = -ENOMEM;
  2456. goto out;
  2457. }
  2458. ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart,
  2459. lockend, NULL, &trans);
  2460. btrfs_free_path(path);
  2461. if (ret)
  2462. goto out;
  2463. ASSERT(trans != NULL);
  2464. inode_inc_iversion(inode);
  2465. inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
  2466. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  2467. updated_inode = true;
  2468. btrfs_end_transaction(trans);
  2469. btrfs_btree_balance_dirty(fs_info);
  2470. out:
  2471. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2472. &cached_state);
  2473. out_only_mutex:
  2474. if (!updated_inode && truncated_block && !ret) {
  2475. /*
  2476. * If we only end up zeroing part of a page, we still need to
  2477. * update the inode item, so that all the time fields are
  2478. * updated as well as the necessary btrfs inode in memory fields
  2479. * for detecting, at fsync time, if the inode isn't yet in the
  2480. * log tree or it's there but not up to date.
  2481. */
  2482. struct timespec64 now = inode_set_ctime_current(inode);
  2483. inode_inc_iversion(inode);
  2484. inode_set_mtime_to_ts(inode, now);
  2485. trans = btrfs_start_transaction(root, 1);
  2486. if (IS_ERR(trans)) {
  2487. ret = PTR_ERR(trans);
  2488. } else {
  2489. int ret2;
  2490. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  2491. ret2 = btrfs_end_transaction(trans);
  2492. if (!ret)
  2493. ret = ret2;
  2494. }
  2495. }
  2496. btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2497. return ret;
  2498. }
  2499. /* Helper structure to record which range is already reserved */
  2500. struct falloc_range {
  2501. struct list_head list;
  2502. u64 start;
  2503. u64 len;
  2504. };
  2505. /*
  2506. * Helper function to add falloc range
  2507. *
  2508. * Caller should have locked the larger range of extent containing
  2509. * [start, len)
  2510. */
  2511. static int add_falloc_range(struct list_head *head, u64 start, u64 len)
  2512. {
  2513. struct falloc_range *range = NULL;
  2514. if (!list_empty(head)) {
  2515. /*
  2516. * As fallocate iterates by bytenr order, we only need to check
  2517. * the last range.
  2518. */
  2519. range = list_last_entry(head, struct falloc_range, list);
  2520. if (range->start + range->len == start) {
  2521. range->len += len;
  2522. return 0;
  2523. }
  2524. }
  2525. range = kmalloc_obj(*range);
  2526. if (!range)
  2527. return -ENOMEM;
  2528. range->start = start;
  2529. range->len = len;
  2530. list_add_tail(&range->list, head);
  2531. return 0;
  2532. }
  2533. static int btrfs_fallocate_update_isize(struct inode *inode,
  2534. const u64 end,
  2535. const int mode)
  2536. {
  2537. struct btrfs_trans_handle *trans;
  2538. struct btrfs_root *root = BTRFS_I(inode)->root;
  2539. u64 range_start;
  2540. u64 range_end;
  2541. int ret;
  2542. int ret2;
  2543. if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
  2544. return 0;
  2545. range_start = round_down(i_size_read(inode), root->fs_info->sectorsize);
  2546. range_end = round_up(end, root->fs_info->sectorsize);
  2547. ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), range_start,
  2548. range_end - range_start);
  2549. if (ret)
  2550. return ret;
  2551. trans = btrfs_start_transaction(root, 1);
  2552. if (IS_ERR(trans))
  2553. return PTR_ERR(trans);
  2554. inode_set_ctime_current(inode);
  2555. i_size_write(inode, end);
  2556. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  2557. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  2558. ret2 = btrfs_end_transaction(trans);
  2559. return ret ? ret : ret2;
  2560. }
  2561. enum {
  2562. RANGE_BOUNDARY_WRITTEN_EXTENT,
  2563. RANGE_BOUNDARY_PREALLOC_EXTENT,
  2564. RANGE_BOUNDARY_HOLE,
  2565. };
  2566. static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
  2567. u64 offset)
  2568. {
  2569. const u64 sectorsize = inode->root->fs_info->sectorsize;
  2570. struct extent_map *em;
  2571. int ret;
  2572. offset = round_down(offset, sectorsize);
  2573. em = btrfs_get_extent(inode, NULL, offset, sectorsize);
  2574. if (IS_ERR(em))
  2575. return PTR_ERR(em);
  2576. if (em->disk_bytenr == EXTENT_MAP_HOLE)
  2577. ret = RANGE_BOUNDARY_HOLE;
  2578. else if (em->flags & EXTENT_FLAG_PREALLOC)
  2579. ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
  2580. else
  2581. ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
  2582. btrfs_free_extent_map(em);
  2583. return ret;
  2584. }
  2585. static int btrfs_zero_range(struct inode *inode,
  2586. loff_t offset,
  2587. loff_t len,
  2588. const int mode)
  2589. {
  2590. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  2591. struct extent_map *em;
  2592. struct extent_changeset *data_reserved = NULL;
  2593. int ret;
  2594. u64 alloc_hint = 0;
  2595. const u64 sectorsize = fs_info->sectorsize;
  2596. const u64 orig_start = offset;
  2597. const u64 orig_end = offset + len - 1;
  2598. u64 alloc_start = round_down(offset, sectorsize);
  2599. u64 alloc_end = round_up(offset + len, sectorsize);
  2600. u64 bytes_to_reserve = 0;
  2601. bool space_reserved = false;
  2602. em = btrfs_get_extent(BTRFS_I(inode), NULL, alloc_start,
  2603. alloc_end - alloc_start);
  2604. if (IS_ERR(em)) {
  2605. ret = PTR_ERR(em);
  2606. goto out;
  2607. }
  2608. /*
  2609. * Avoid hole punching and extent allocation for some cases. More cases
  2610. * could be considered, but these are unlikely common and we keep things
  2611. * as simple as possible for now. Also, intentionally, if the target
  2612. * range contains one or more prealloc extents together with regular
  2613. * extents and holes, we drop all the existing extents and allocate a
  2614. * new prealloc extent, so that we get a larger contiguous disk extent.
  2615. */
  2616. if (em->start <= alloc_start && (em->flags & EXTENT_FLAG_PREALLOC)) {
  2617. const u64 em_end = btrfs_extent_map_end(em);
  2618. if (em_end >= offset + len) {
  2619. /*
  2620. * The whole range is already a prealloc extent,
  2621. * do nothing except updating the inode's i_size if
  2622. * needed.
  2623. */
  2624. btrfs_free_extent_map(em);
  2625. ret = btrfs_fallocate_update_isize(inode, offset + len,
  2626. mode);
  2627. goto out;
  2628. }
  2629. /*
  2630. * Part of the range is already a prealloc extent, so operate
  2631. * only on the remaining part of the range.
  2632. */
  2633. alloc_start = em_end;
  2634. ASSERT(IS_ALIGNED(alloc_start, sectorsize));
  2635. len = offset + len - alloc_start;
  2636. offset = alloc_start;
  2637. alloc_hint = btrfs_extent_map_block_start(em) + em->len;
  2638. }
  2639. btrfs_free_extent_map(em);
  2640. if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
  2641. BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
  2642. em = btrfs_get_extent(BTRFS_I(inode), NULL, alloc_start, sectorsize);
  2643. if (IS_ERR(em)) {
  2644. ret = PTR_ERR(em);
  2645. goto out;
  2646. }
  2647. if (em->flags & EXTENT_FLAG_PREALLOC) {
  2648. btrfs_free_extent_map(em);
  2649. ret = btrfs_fallocate_update_isize(inode, offset + len,
  2650. mode);
  2651. goto out;
  2652. }
  2653. if (len < sectorsize && em->disk_bytenr != EXTENT_MAP_HOLE) {
  2654. btrfs_free_extent_map(em);
  2655. ret = btrfs_truncate_block(BTRFS_I(inode), offset + len - 1,
  2656. orig_start, orig_end);
  2657. if (!ret)
  2658. ret = btrfs_fallocate_update_isize(inode,
  2659. offset + len,
  2660. mode);
  2661. return ret;
  2662. }
  2663. btrfs_free_extent_map(em);
  2664. alloc_start = round_down(offset, sectorsize);
  2665. alloc_end = alloc_start + sectorsize;
  2666. goto reserve_space;
  2667. }
  2668. alloc_start = round_up(offset, sectorsize);
  2669. alloc_end = round_down(offset + len, sectorsize);
  2670. /*
  2671. * For unaligned ranges, check the pages at the boundaries, they might
  2672. * map to an extent, in which case we need to partially zero them, or
  2673. * they might map to a hole, in which case we need our allocation range
  2674. * to cover them.
  2675. */
  2676. if (!IS_ALIGNED(offset, sectorsize)) {
  2677. ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
  2678. offset);
  2679. if (ret < 0)
  2680. goto out;
  2681. if (ret == RANGE_BOUNDARY_HOLE) {
  2682. alloc_start = round_down(offset, sectorsize);
  2683. ret = 0;
  2684. } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
  2685. ret = btrfs_truncate_block(BTRFS_I(inode), offset,
  2686. orig_start, orig_end);
  2687. if (ret)
  2688. goto out;
  2689. } else {
  2690. ret = 0;
  2691. }
  2692. }
  2693. if (!IS_ALIGNED(offset + len, sectorsize)) {
  2694. ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
  2695. offset + len);
  2696. if (ret < 0)
  2697. goto out;
  2698. if (ret == RANGE_BOUNDARY_HOLE) {
  2699. alloc_end = round_up(offset + len, sectorsize);
  2700. ret = 0;
  2701. } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
  2702. ret = btrfs_truncate_block(BTRFS_I(inode), offset + len - 1,
  2703. orig_start, orig_end);
  2704. if (ret)
  2705. goto out;
  2706. } else {
  2707. ret = 0;
  2708. }
  2709. }
  2710. reserve_space:
  2711. if (alloc_start < alloc_end) {
  2712. struct extent_state *cached_state = NULL;
  2713. const u64 lockstart = alloc_start;
  2714. const u64 lockend = alloc_end - 1;
  2715. bytes_to_reserve = alloc_end - alloc_start;
  2716. ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
  2717. bytes_to_reserve);
  2718. if (ret < 0)
  2719. goto out;
  2720. space_reserved = true;
  2721. btrfs_punch_hole_lock_range(inode, lockstart, lockend,
  2722. &cached_state);
  2723. ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
  2724. alloc_start, bytes_to_reserve);
  2725. if (ret) {
  2726. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, lockstart,
  2727. lockend, &cached_state);
  2728. goto out;
  2729. }
  2730. ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
  2731. alloc_end - alloc_start,
  2732. fs_info->sectorsize,
  2733. offset + len, &alloc_hint);
  2734. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2735. &cached_state);
  2736. /* btrfs_prealloc_file_range releases reserved space on error */
  2737. if (ret) {
  2738. space_reserved = false;
  2739. goto out;
  2740. }
  2741. }
  2742. ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
  2743. out:
  2744. if (ret && space_reserved)
  2745. btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
  2746. alloc_start, bytes_to_reserve);
  2747. extent_changeset_free(data_reserved);
  2748. return ret;
  2749. }
  2750. static long btrfs_fallocate(struct file *file, int mode,
  2751. loff_t offset, loff_t len)
  2752. {
  2753. struct inode *inode = file_inode(file);
  2754. struct extent_state *cached_state = NULL;
  2755. struct extent_changeset *data_reserved = NULL;
  2756. struct falloc_range *range;
  2757. struct falloc_range *tmp;
  2758. LIST_HEAD(reserve_list);
  2759. u64 cur_offset;
  2760. u64 last_byte;
  2761. u64 alloc_start;
  2762. u64 alloc_end;
  2763. u64 alloc_hint = 0;
  2764. u64 locked_end;
  2765. u64 actual_end = 0;
  2766. u64 data_space_needed = 0;
  2767. u64 data_space_reserved = 0;
  2768. u64 qgroup_reserved = 0;
  2769. struct extent_map *em;
  2770. int blocksize = BTRFS_I(inode)->root->fs_info->sectorsize;
  2771. int ret;
  2772. if (btrfs_is_shutdown(inode_to_fs_info(inode)))
  2773. return -EIO;
  2774. /* Do not allow fallocate in ZONED mode */
  2775. if (btrfs_is_zoned(inode_to_fs_info(inode)))
  2776. return -EOPNOTSUPP;
  2777. alloc_start = round_down(offset, blocksize);
  2778. alloc_end = round_up(offset + len, blocksize);
  2779. cur_offset = alloc_start;
  2780. /* Make sure we aren't being give some crap mode */
  2781. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
  2782. FALLOC_FL_ZERO_RANGE))
  2783. return -EOPNOTSUPP;
  2784. if (mode & FALLOC_FL_PUNCH_HOLE)
  2785. return btrfs_punch_hole(file, offset, len);
  2786. btrfs_inode_lock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2787. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
  2788. ret = inode_newsize_ok(inode, offset + len);
  2789. if (ret)
  2790. goto out;
  2791. }
  2792. ret = file_modified(file);
  2793. if (ret)
  2794. goto out;
  2795. /*
  2796. * TODO: Move these two operations after we have checked
  2797. * accurate reserved space, or fallocate can still fail but
  2798. * with page truncated or size expanded.
  2799. *
  2800. * But that's a minor problem and won't do much harm BTW.
  2801. */
  2802. if (alloc_start > inode->i_size) {
  2803. ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode),
  2804. alloc_start);
  2805. if (ret)
  2806. goto out;
  2807. } else if (offset + len > inode->i_size) {
  2808. /*
  2809. * If we are fallocating from the end of the file onward we
  2810. * need to zero out the end of the block if i_size lands in the
  2811. * middle of a block.
  2812. */
  2813. ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size,
  2814. inode->i_size, (u64)-1);
  2815. if (ret)
  2816. goto out;
  2817. }
  2818. /*
  2819. * We have locked the inode at the VFS level (in exclusive mode) and we
  2820. * have locked the i_mmap_lock lock (in exclusive mode). Now before
  2821. * locking the file range, flush all dealloc in the range and wait for
  2822. * all ordered extents in the range to complete. After this we can lock
  2823. * the file range and, due to the previous locking we did, we know there
  2824. * can't be more delalloc or ordered extents in the range.
  2825. */
  2826. ret = btrfs_wait_ordered_range(BTRFS_I(inode), alloc_start,
  2827. alloc_end - alloc_start);
  2828. if (ret)
  2829. goto out;
  2830. if (mode & FALLOC_FL_ZERO_RANGE) {
  2831. ret = btrfs_zero_range(inode, offset, len, mode);
  2832. btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2833. return ret;
  2834. }
  2835. locked_end = alloc_end - 1;
  2836. btrfs_lock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2837. &cached_state);
  2838. btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end);
  2839. /* First, check if we exceed the qgroup limit */
  2840. while (cur_offset < alloc_end) {
  2841. em = btrfs_get_extent(BTRFS_I(inode), NULL, cur_offset,
  2842. alloc_end - cur_offset);
  2843. if (IS_ERR(em)) {
  2844. ret = PTR_ERR(em);
  2845. break;
  2846. }
  2847. last_byte = min(btrfs_extent_map_end(em), alloc_end);
  2848. actual_end = min_t(u64, btrfs_extent_map_end(em), offset + len);
  2849. last_byte = ALIGN(last_byte, blocksize);
  2850. if (em->disk_bytenr == EXTENT_MAP_HOLE ||
  2851. (cur_offset >= inode->i_size &&
  2852. !(em->flags & EXTENT_FLAG_PREALLOC))) {
  2853. const u64 range_len = last_byte - cur_offset;
  2854. ret = add_falloc_range(&reserve_list, cur_offset, range_len);
  2855. if (ret < 0) {
  2856. btrfs_free_extent_map(em);
  2857. break;
  2858. }
  2859. ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
  2860. &data_reserved, cur_offset, range_len);
  2861. if (ret < 0) {
  2862. btrfs_free_extent_map(em);
  2863. break;
  2864. }
  2865. qgroup_reserved += range_len;
  2866. data_space_needed += range_len;
  2867. }
  2868. btrfs_free_extent_map(em);
  2869. cur_offset = last_byte;
  2870. }
  2871. if (!ret && data_space_needed > 0) {
  2872. /*
  2873. * We are safe to reserve space here as we can't have delalloc
  2874. * in the range, see above.
  2875. */
  2876. ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
  2877. data_space_needed);
  2878. if (!ret)
  2879. data_space_reserved = data_space_needed;
  2880. }
  2881. /*
  2882. * If ret is still 0, means we're OK to fallocate.
  2883. * Or just cleanup the list and exit.
  2884. */
  2885. list_for_each_entry_safe(range, tmp, &reserve_list, list) {
  2886. if (!ret) {
  2887. ret = btrfs_prealloc_file_range(inode, mode,
  2888. range->start,
  2889. range->len, blocksize,
  2890. offset + len, &alloc_hint);
  2891. /*
  2892. * btrfs_prealloc_file_range() releases space even
  2893. * if it returns an error.
  2894. */
  2895. data_space_reserved -= range->len;
  2896. qgroup_reserved -= range->len;
  2897. } else if (data_space_reserved > 0) {
  2898. btrfs_free_reserved_data_space(BTRFS_I(inode),
  2899. data_reserved, range->start,
  2900. range->len);
  2901. data_space_reserved -= range->len;
  2902. qgroup_reserved -= range->len;
  2903. } else if (qgroup_reserved > 0) {
  2904. btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved,
  2905. range->start, range->len, NULL);
  2906. qgroup_reserved -= range->len;
  2907. }
  2908. list_del(&range->list);
  2909. kfree(range);
  2910. }
  2911. if (ret < 0)
  2912. goto out_unlock;
  2913. /*
  2914. * We didn't need to allocate any more space, but we still extended the
  2915. * size of the file so we need to update i_size and the inode item.
  2916. */
  2917. ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
  2918. out_unlock:
  2919. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2920. &cached_state);
  2921. out:
  2922. btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_MMAP);
  2923. extent_changeset_free(data_reserved);
  2924. return ret;
  2925. }
  2926. /*
  2927. * Helper for btrfs_find_delalloc_in_range(). Find a subrange in a given range
  2928. * that has unflushed and/or flushing delalloc. There might be other adjacent
  2929. * subranges after the one it found, so btrfs_find_delalloc_in_range() keeps
  2930. * looping while it gets adjacent subranges, and merging them together.
  2931. */
  2932. static bool find_delalloc_subrange(struct btrfs_inode *inode, u64 start, u64 end,
  2933. struct extent_state **cached_state,
  2934. bool *search_io_tree,
  2935. u64 *delalloc_start_ret, u64 *delalloc_end_ret)
  2936. {
  2937. u64 len = end + 1 - start;
  2938. u64 delalloc_len = 0;
  2939. struct btrfs_ordered_extent *oe;
  2940. u64 oe_start;
  2941. u64 oe_end;
  2942. /*
  2943. * Search the io tree first for EXTENT_DELALLOC. If we find any, it
  2944. * means we have delalloc (dirty pages) for which writeback has not
  2945. * started yet.
  2946. */
  2947. if (*search_io_tree) {
  2948. spin_lock(&inode->lock);
  2949. if (inode->delalloc_bytes > 0) {
  2950. spin_unlock(&inode->lock);
  2951. *delalloc_start_ret = start;
  2952. delalloc_len = btrfs_count_range_bits(&inode->io_tree,
  2953. delalloc_start_ret, end,
  2954. len, EXTENT_DELALLOC, 1,
  2955. cached_state);
  2956. } else {
  2957. spin_unlock(&inode->lock);
  2958. }
  2959. }
  2960. if (delalloc_len > 0) {
  2961. /*
  2962. * If delalloc was found then *delalloc_start_ret has a sector size
  2963. * aligned value (rounded down).
  2964. */
  2965. *delalloc_end_ret = *delalloc_start_ret + delalloc_len - 1;
  2966. if (*delalloc_start_ret == start) {
  2967. /* Delalloc for the whole range, nothing more to do. */
  2968. if (*delalloc_end_ret == end)
  2969. return true;
  2970. /* Else trim our search range for ordered extents. */
  2971. start = *delalloc_end_ret + 1;
  2972. len = end + 1 - start;
  2973. }
  2974. } else {
  2975. /* No delalloc, future calls don't need to search again. */
  2976. *search_io_tree = false;
  2977. }
  2978. /*
  2979. * Now also check if there's any ordered extent in the range.
  2980. * We do this because:
  2981. *
  2982. * 1) When delalloc is flushed, the file range is locked, we clear the
  2983. * EXTENT_DELALLOC bit from the io tree and create an extent map and
  2984. * an ordered extent for the write. So we might just have been called
  2985. * after delalloc is flushed and before the ordered extent completes
  2986. * and inserts the new file extent item in the subvolume's btree;
  2987. *
  2988. * 2) We may have an ordered extent created by flushing delalloc for a
  2989. * subrange that starts before the subrange we found marked with
  2990. * EXTENT_DELALLOC in the io tree.
  2991. *
  2992. * We could also use the extent map tree to find such delalloc that is
  2993. * being flushed, but using the ordered extents tree is more efficient
  2994. * because it's usually much smaller as ordered extents are removed from
  2995. * the tree once they complete. With the extent maps, we may have them
  2996. * in the extent map tree for a very long time, and they were either
  2997. * created by previous writes or loaded by read operations.
  2998. */
  2999. oe = btrfs_lookup_first_ordered_range(inode, start, len);
  3000. if (!oe)
  3001. return (delalloc_len > 0);
  3002. /* The ordered extent may span beyond our search range. */
  3003. oe_start = max(oe->file_offset, start);
  3004. oe_end = min(oe->file_offset + oe->num_bytes - 1, end);
  3005. btrfs_put_ordered_extent(oe);
  3006. /* Don't have unflushed delalloc, return the ordered extent range. */
  3007. if (delalloc_len == 0) {
  3008. *delalloc_start_ret = oe_start;
  3009. *delalloc_end_ret = oe_end;
  3010. return true;
  3011. }
  3012. /*
  3013. * We have both unflushed delalloc (io_tree) and an ordered extent.
  3014. * If the ranges are adjacent returned a combined range, otherwise
  3015. * return the leftmost range.
  3016. */
  3017. if (oe_start < *delalloc_start_ret) {
  3018. if (oe_end < *delalloc_start_ret)
  3019. *delalloc_end_ret = oe_end;
  3020. *delalloc_start_ret = oe_start;
  3021. } else if (*delalloc_end_ret + 1 == oe_start) {
  3022. *delalloc_end_ret = oe_end;
  3023. }
  3024. return true;
  3025. }
  3026. /*
  3027. * Check if there's delalloc in a given range.
  3028. *
  3029. * @inode: The inode.
  3030. * @start: The start offset of the range. It does not need to be
  3031. * sector size aligned.
  3032. * @end: The end offset (inclusive value) of the search range.
  3033. * It does not need to be sector size aligned.
  3034. * @cached_state: Extent state record used for speeding up delalloc
  3035. * searches in the inode's io_tree. Can be NULL.
  3036. * @delalloc_start_ret: Output argument, set to the start offset of the
  3037. * subrange found with delalloc (may not be sector size
  3038. * aligned).
  3039. * @delalloc_end_ret: Output argument, set to he end offset (inclusive value)
  3040. * of the subrange found with delalloc.
  3041. *
  3042. * Returns true if a subrange with delalloc is found within the given range, and
  3043. * if so it sets @delalloc_start_ret and @delalloc_end_ret with the start and
  3044. * end offsets of the subrange.
  3045. */
  3046. bool btrfs_find_delalloc_in_range(struct btrfs_inode *inode, u64 start, u64 end,
  3047. struct extent_state **cached_state,
  3048. u64 *delalloc_start_ret, u64 *delalloc_end_ret)
  3049. {
  3050. u64 cur_offset = round_down(start, inode->root->fs_info->sectorsize);
  3051. u64 prev_delalloc_end = 0;
  3052. bool search_io_tree = true;
  3053. bool ret = false;
  3054. while (cur_offset <= end) {
  3055. u64 delalloc_start;
  3056. u64 delalloc_end;
  3057. bool delalloc;
  3058. delalloc = find_delalloc_subrange(inode, cur_offset, end,
  3059. cached_state, &search_io_tree,
  3060. &delalloc_start,
  3061. &delalloc_end);
  3062. if (!delalloc)
  3063. break;
  3064. if (prev_delalloc_end == 0) {
  3065. /* First subrange found. */
  3066. *delalloc_start_ret = max(delalloc_start, start);
  3067. *delalloc_end_ret = delalloc_end;
  3068. ret = true;
  3069. } else if (delalloc_start == prev_delalloc_end + 1) {
  3070. /* Subrange adjacent to the previous one, merge them. */
  3071. *delalloc_end_ret = delalloc_end;
  3072. } else {
  3073. /* Subrange not adjacent to the previous one, exit. */
  3074. break;
  3075. }
  3076. prev_delalloc_end = delalloc_end;
  3077. cur_offset = delalloc_end + 1;
  3078. cond_resched();
  3079. }
  3080. return ret;
  3081. }
  3082. /*
  3083. * Check if there's a hole or delalloc range in a range representing a hole (or
  3084. * prealloc extent) found in the inode's subvolume btree.
  3085. *
  3086. * @inode: The inode.
  3087. * @whence: Seek mode (SEEK_DATA or SEEK_HOLE).
  3088. * @start: Start offset of the hole region. It does not need to be sector
  3089. * size aligned.
  3090. * @end: End offset (inclusive value) of the hole region. It does not
  3091. * need to be sector size aligned.
  3092. * @start_ret: Return parameter, used to set the start of the subrange in the
  3093. * hole that matches the search criteria (seek mode), if such
  3094. * subrange is found (return value of the function is true).
  3095. * The value returned here may not be sector size aligned.
  3096. *
  3097. * Returns true if a subrange matching the given seek mode is found, and if one
  3098. * is found, it updates @start_ret with the start of the subrange.
  3099. */
  3100. static bool find_desired_extent_in_hole(struct btrfs_inode *inode, int whence,
  3101. struct extent_state **cached_state,
  3102. u64 start, u64 end, u64 *start_ret)
  3103. {
  3104. u64 delalloc_start;
  3105. u64 delalloc_end;
  3106. bool delalloc;
  3107. delalloc = btrfs_find_delalloc_in_range(inode, start, end, cached_state,
  3108. &delalloc_start, &delalloc_end);
  3109. if (delalloc && whence == SEEK_DATA) {
  3110. *start_ret = delalloc_start;
  3111. return true;
  3112. }
  3113. if (delalloc && whence == SEEK_HOLE) {
  3114. /*
  3115. * We found delalloc but it starts after out start offset. So we
  3116. * have a hole between our start offset and the delalloc start.
  3117. */
  3118. if (start < delalloc_start) {
  3119. *start_ret = start;
  3120. return true;
  3121. }
  3122. /*
  3123. * Delalloc range starts at our start offset.
  3124. * If the delalloc range's length is smaller than our range,
  3125. * then it means we have a hole that starts where the delalloc
  3126. * subrange ends.
  3127. */
  3128. if (delalloc_end < end) {
  3129. *start_ret = delalloc_end + 1;
  3130. return true;
  3131. }
  3132. /* There's delalloc for the whole range. */
  3133. return false;
  3134. }
  3135. if (!delalloc && whence == SEEK_HOLE) {
  3136. *start_ret = start;
  3137. return true;
  3138. }
  3139. /*
  3140. * No delalloc in the range and we are seeking for data. The caller has
  3141. * to iterate to the next extent item in the subvolume btree.
  3142. */
  3143. return false;
  3144. }
  3145. static loff_t find_desired_extent(struct file *file, loff_t offset, int whence)
  3146. {
  3147. struct btrfs_inode *inode = BTRFS_I(file->f_mapping->host);
  3148. struct btrfs_file_private *private;
  3149. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  3150. struct extent_state *cached_state = NULL;
  3151. struct extent_state **delalloc_cached_state;
  3152. const loff_t i_size = i_size_read(&inode->vfs_inode);
  3153. const u64 ino = btrfs_ino(inode);
  3154. struct btrfs_root *root = inode->root;
  3155. struct btrfs_path *path;
  3156. struct btrfs_key key;
  3157. u64 last_extent_end;
  3158. u64 lockstart;
  3159. u64 lockend;
  3160. u64 start;
  3161. int ret;
  3162. bool found = false;
  3163. if (i_size == 0 || offset >= i_size)
  3164. return -ENXIO;
  3165. /*
  3166. * Quick path. If the inode has no prealloc extents and its number of
  3167. * bytes used matches its i_size, then it can not have holes.
  3168. */
  3169. if (whence == SEEK_HOLE &&
  3170. !(inode->flags & BTRFS_INODE_PREALLOC) &&
  3171. inode_get_bytes(&inode->vfs_inode) == i_size)
  3172. return i_size;
  3173. spin_lock(&inode->lock);
  3174. private = file->private_data;
  3175. spin_unlock(&inode->lock);
  3176. if (private && private->owner_task != current) {
  3177. /*
  3178. * Not allocated by us, don't use it as its cached state is used
  3179. * by the task that allocated it and we don't want neither to
  3180. * mess with it nor get incorrect results because it reflects an
  3181. * invalid state for the current task.
  3182. */
  3183. private = NULL;
  3184. } else if (!private) {
  3185. private = kzalloc_obj(*private);
  3186. /*
  3187. * No worries if memory allocation failed.
  3188. * The private structure is used only for speeding up multiple
  3189. * lseek SEEK_HOLE/DATA calls to a file when there's delalloc,
  3190. * so everything will still be correct.
  3191. */
  3192. if (private) {
  3193. bool free = false;
  3194. private->owner_task = current;
  3195. spin_lock(&inode->lock);
  3196. if (file->private_data)
  3197. free = true;
  3198. else
  3199. file->private_data = private;
  3200. spin_unlock(&inode->lock);
  3201. if (free) {
  3202. kfree(private);
  3203. private = NULL;
  3204. }
  3205. }
  3206. }
  3207. if (private)
  3208. delalloc_cached_state = &private->llseek_cached_state;
  3209. else
  3210. delalloc_cached_state = NULL;
  3211. /*
  3212. * offset can be negative, in this case we start finding DATA/HOLE from
  3213. * the very start of the file.
  3214. */
  3215. start = max_t(loff_t, 0, offset);
  3216. lockstart = round_down(start, fs_info->sectorsize);
  3217. lockend = round_up(i_size, fs_info->sectorsize);
  3218. if (lockend <= lockstart)
  3219. lockend = lockstart + fs_info->sectorsize;
  3220. lockend--;
  3221. path = btrfs_alloc_path();
  3222. if (!path)
  3223. return -ENOMEM;
  3224. path->reada = READA_FORWARD;
  3225. key.objectid = ino;
  3226. key.type = BTRFS_EXTENT_DATA_KEY;
  3227. key.offset = start;
  3228. last_extent_end = lockstart;
  3229. btrfs_lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
  3230. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  3231. if (ret < 0) {
  3232. goto out;
  3233. } else if (ret > 0 && path->slots[0] > 0) {
  3234. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
  3235. if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
  3236. path->slots[0]--;
  3237. }
  3238. while (start < i_size) {
  3239. struct extent_buffer *leaf = path->nodes[0];
  3240. struct btrfs_file_extent_item *extent;
  3241. u64 extent_end;
  3242. u8 type;
  3243. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  3244. ret = btrfs_next_leaf(root, path);
  3245. if (ret < 0)
  3246. goto out;
  3247. else if (ret > 0)
  3248. break;
  3249. leaf = path->nodes[0];
  3250. }
  3251. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  3252. if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
  3253. break;
  3254. extent_end = btrfs_file_extent_end(path);
  3255. /*
  3256. * In the first iteration we may have a slot that points to an
  3257. * extent that ends before our start offset, so skip it.
  3258. */
  3259. if (extent_end <= start) {
  3260. path->slots[0]++;
  3261. continue;
  3262. }
  3263. /* We have an implicit hole, NO_HOLES feature is likely set. */
  3264. if (last_extent_end < key.offset) {
  3265. u64 search_start = last_extent_end;
  3266. u64 found_start;
  3267. /*
  3268. * First iteration, @start matches @offset and it's
  3269. * within the hole.
  3270. */
  3271. if (start == offset)
  3272. search_start = offset;
  3273. found = find_desired_extent_in_hole(inode, whence,
  3274. delalloc_cached_state,
  3275. search_start,
  3276. key.offset - 1,
  3277. &found_start);
  3278. if (found) {
  3279. start = found_start;
  3280. break;
  3281. }
  3282. /*
  3283. * Didn't find data or a hole (due to delalloc) in the
  3284. * implicit hole range, so need to analyze the extent.
  3285. */
  3286. }
  3287. extent = btrfs_item_ptr(leaf, path->slots[0],
  3288. struct btrfs_file_extent_item);
  3289. type = btrfs_file_extent_type(leaf, extent);
  3290. /*
  3291. * Can't access the extent's disk_bytenr field if this is an
  3292. * inline extent, since at that offset, it's where the extent
  3293. * data starts.
  3294. */
  3295. if (type == BTRFS_FILE_EXTENT_PREALLOC ||
  3296. (type == BTRFS_FILE_EXTENT_REG &&
  3297. btrfs_file_extent_disk_bytenr(leaf, extent) == 0)) {
  3298. /*
  3299. * Explicit hole or prealloc extent, search for delalloc.
  3300. * A prealloc extent is treated like a hole.
  3301. */
  3302. u64 search_start = key.offset;
  3303. u64 found_start;
  3304. /*
  3305. * First iteration, @start matches @offset and it's
  3306. * within the hole.
  3307. */
  3308. if (start == offset)
  3309. search_start = offset;
  3310. found = find_desired_extent_in_hole(inode, whence,
  3311. delalloc_cached_state,
  3312. search_start,
  3313. extent_end - 1,
  3314. &found_start);
  3315. if (found) {
  3316. start = found_start;
  3317. break;
  3318. }
  3319. /*
  3320. * Didn't find data or a hole (due to delalloc) in the
  3321. * implicit hole range, so need to analyze the next
  3322. * extent item.
  3323. */
  3324. } else {
  3325. /*
  3326. * Found a regular or inline extent.
  3327. * If we are seeking for data, adjust the start offset
  3328. * and stop, we're done.
  3329. */
  3330. if (whence == SEEK_DATA) {
  3331. start = max_t(u64, key.offset, offset);
  3332. found = true;
  3333. break;
  3334. }
  3335. /*
  3336. * Else, we are seeking for a hole, check the next file
  3337. * extent item.
  3338. */
  3339. }
  3340. start = extent_end;
  3341. last_extent_end = extent_end;
  3342. path->slots[0]++;
  3343. if (fatal_signal_pending(current)) {
  3344. ret = -EINTR;
  3345. goto out;
  3346. }
  3347. cond_resched();
  3348. }
  3349. /* We have an implicit hole from the last extent found up to i_size. */
  3350. if (!found && start < i_size) {
  3351. found = find_desired_extent_in_hole(inode, whence,
  3352. delalloc_cached_state, start,
  3353. i_size - 1, &start);
  3354. if (!found)
  3355. start = i_size;
  3356. }
  3357. out:
  3358. btrfs_unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
  3359. btrfs_free_path(path);
  3360. if (ret < 0)
  3361. return ret;
  3362. if (whence == SEEK_DATA && start >= i_size)
  3363. return -ENXIO;
  3364. return min_t(loff_t, start, i_size);
  3365. }
  3366. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  3367. {
  3368. struct inode *inode = file->f_mapping->host;
  3369. switch (whence) {
  3370. default:
  3371. return generic_file_llseek(file, offset, whence);
  3372. case SEEK_DATA:
  3373. case SEEK_HOLE:
  3374. btrfs_inode_lock(BTRFS_I(inode), BTRFS_ILOCK_SHARED);
  3375. offset = find_desired_extent(file, offset, whence);
  3376. btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_SHARED);
  3377. break;
  3378. }
  3379. if (offset < 0)
  3380. return offset;
  3381. return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  3382. }
  3383. static int btrfs_file_open(struct inode *inode, struct file *filp)
  3384. {
  3385. int ret;
  3386. if (btrfs_is_shutdown(inode_to_fs_info(inode)))
  3387. return -EIO;
  3388. filp->f_mode |= FMODE_NOWAIT | FMODE_CAN_ODIRECT;
  3389. ret = fsverity_file_open(inode, filp);
  3390. if (ret)
  3391. return ret;
  3392. return generic_file_open(inode, filp);
  3393. }
  3394. static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
  3395. {
  3396. ssize_t ret = 0;
  3397. if (btrfs_is_shutdown(inode_to_fs_info(file_inode(iocb->ki_filp))))
  3398. return -EIO;
  3399. if (iocb->ki_flags & IOCB_DIRECT) {
  3400. ret = btrfs_direct_read(iocb, to);
  3401. if (ret < 0 || !iov_iter_count(to) ||
  3402. iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
  3403. return ret;
  3404. }
  3405. return filemap_read(iocb, to, ret);
  3406. }
  3407. static ssize_t btrfs_file_splice_read(struct file *in, loff_t *ppos,
  3408. struct pipe_inode_info *pipe,
  3409. size_t len, unsigned int flags)
  3410. {
  3411. if (btrfs_is_shutdown(inode_to_fs_info(file_inode(in))))
  3412. return -EIO;
  3413. return filemap_splice_read(in, ppos, pipe, len, flags);
  3414. }
  3415. const struct file_operations btrfs_file_operations = {
  3416. .llseek = btrfs_file_llseek,
  3417. .read_iter = btrfs_file_read_iter,
  3418. .splice_read = btrfs_file_splice_read,
  3419. .write_iter = btrfs_file_write_iter,
  3420. .splice_write = iter_file_splice_write,
  3421. .mmap_prepare = btrfs_file_mmap_prepare,
  3422. .open = btrfs_file_open,
  3423. .release = btrfs_release_file,
  3424. .get_unmapped_area = thp_get_unmapped_area,
  3425. .fsync = btrfs_sync_file,
  3426. .fallocate = btrfs_fallocate,
  3427. .unlocked_ioctl = btrfs_ioctl,
  3428. #ifdef CONFIG_COMPAT
  3429. .compat_ioctl = btrfs_compat_ioctl,
  3430. #endif
  3431. .remap_file_range = btrfs_remap_file_range,
  3432. .uring_cmd = btrfs_uring_cmd,
  3433. .fop_flags = FOP_BUFFER_RASYNC | FOP_BUFFER_WASYNC,
  3434. .setlease = generic_setlease,
  3435. };
  3436. int btrfs_fdatawrite_range(struct btrfs_inode *inode, loff_t start, loff_t end)
  3437. {
  3438. struct address_space *mapping = inode->vfs_inode.i_mapping;
  3439. int ret;
  3440. /*
  3441. * So with compression we will find and lock a dirty page and clear the
  3442. * first one as dirty, setup an async extent, and immediately return
  3443. * with the entire range locked but with nobody actually marked with
  3444. * writeback. So we can't just filemap_write_and_wait_range() and
  3445. * expect it to work since it will just kick off a thread to do the
  3446. * actual work. So we need to call filemap_fdatawrite_range _again_
  3447. * since it will wait on the page lock, which won't be unlocked until
  3448. * after the pages have been marked as writeback and so we're good to go
  3449. * from there. We have to do this otherwise we'll miss the ordered
  3450. * extents and that results in badness. Please Josef, do not think you
  3451. * know better and pull this out at some point in the future, it is
  3452. * right and you are wrong.
  3453. */
  3454. ret = filemap_fdatawrite_range(mapping, start, end);
  3455. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags))
  3456. ret = filemap_fdatawrite_range(mapping, start, end);
  3457. return ret;
  3458. }