file.c 108 KB

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