filemap.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/filemap.c
  4. *
  5. * Copyright (C) 1994-1999 Linus Torvalds
  6. */
  7. /*
  8. * This file handles the generic file mmap semantics used by
  9. * most "normal" filesystems (but you don't /have/ to use this:
  10. * the NFS filesystem used to do this differently, for example)
  11. */
  12. #include <linux/export.h>
  13. #include <linux/compiler.h>
  14. #include <linux/dax.h>
  15. #include <linux/fs.h>
  16. #include <linux/sched/signal.h>
  17. #include <linux/uaccess.h>
  18. #include <linux/capability.h>
  19. #include <linux/kernel_stat.h>
  20. #include <linux/gfp.h>
  21. #include <linux/mm.h>
  22. #include <linux/swap.h>
  23. #include <linux/swapops.h>
  24. #include <linux/syscalls.h>
  25. #include <linux/mman.h>
  26. #include <linux/pagemap.h>
  27. #include <linux/file.h>
  28. #include <linux/uio.h>
  29. #include <linux/error-injection.h>
  30. #include <linux/hash.h>
  31. #include <linux/writeback.h>
  32. #include <linux/backing-dev.h>
  33. #include <linux/pagevec.h>
  34. #include <linux/security.h>
  35. #include <linux/cpuset.h>
  36. #include <linux/hugetlb.h>
  37. #include <linux/memcontrol.h>
  38. #include <linux/shmem_fs.h>
  39. #include <linux/rmap.h>
  40. #include <linux/delayacct.h>
  41. #include <linux/psi.h>
  42. #include <linux/ramfs.h>
  43. #include <linux/page_idle.h>
  44. #include <linux/migrate.h>
  45. #include <linux/pipe_fs_i.h>
  46. #include <linux/splice.h>
  47. #include <linux/rcupdate_wait.h>
  48. #include <linux/sched/mm.h>
  49. #include <asm/pgalloc.h>
  50. #include <asm/tlbflush.h>
  51. #include "internal.h"
  52. #define CREATE_TRACE_POINTS
  53. #include <trace/events/filemap.h>
  54. /*
  55. * FIXME: remove all knowledge of the buffer layer from the core VM
  56. */
  57. #include <linux/buffer_head.h> /* for try_to_free_buffers */
  58. #include <asm/mman.h>
  59. #include "swap.h"
  60. /*
  61. * Shared mappings implemented 30.11.1994. It's not fully working yet,
  62. * though.
  63. *
  64. * Shared mappings now work. 15.8.1995 Bruno.
  65. *
  66. * finished 'unifying' the page and buffer cache and SMP-threaded the
  67. * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  68. *
  69. * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  70. */
  71. /*
  72. * Lock ordering:
  73. *
  74. * ->i_mmap_rwsem (truncate_pagecache)
  75. * ->private_lock (__free_pte->block_dirty_folio)
  76. * ->swap_lock (exclusive_swap_page, others)
  77. * ->i_pages lock
  78. *
  79. * ->i_rwsem
  80. * ->invalidate_lock (acquired by fs in truncate path)
  81. * ->i_mmap_rwsem (truncate->unmap_mapping_range)
  82. *
  83. * ->mmap_lock
  84. * ->i_mmap_rwsem
  85. * ->page_table_lock or pte_lock (various, mainly in memory.c)
  86. * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
  87. *
  88. * ->mmap_lock
  89. * ->invalidate_lock (filemap_fault)
  90. * ->lock_page (filemap_fault, access_process_vm)
  91. *
  92. * ->i_rwsem (generic_perform_write)
  93. * ->mmap_lock (fault_in_readable->do_page_fault)
  94. *
  95. * bdi->wb.list_lock
  96. * sb_lock (fs/fs-writeback.c)
  97. * ->i_pages lock (__sync_single_inode)
  98. *
  99. * ->i_mmap_rwsem
  100. * ->anon_vma.lock (vma_merge)
  101. *
  102. * ->anon_vma.lock
  103. * ->page_table_lock or pte_lock (anon_vma_prepare and various)
  104. *
  105. * ->page_table_lock or pte_lock
  106. * ->swap_lock (try_to_unmap_one)
  107. * ->private_lock (try_to_unmap_one)
  108. * ->i_pages lock (try_to_unmap_one)
  109. * ->lruvec->lru_lock (follow_page_mask->mark_page_accessed)
  110. * ->lruvec->lru_lock (check_pte_range->folio_isolate_lru)
  111. * ->private_lock (folio_remove_rmap_pte->set_page_dirty)
  112. * ->i_pages lock (folio_remove_rmap_pte->set_page_dirty)
  113. * bdi.wb->list_lock (folio_remove_rmap_pte->set_page_dirty)
  114. * ->inode->i_lock (folio_remove_rmap_pte->set_page_dirty)
  115. * ->memcg->move_lock (folio_remove_rmap_pte->folio_memcg_lock)
  116. * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
  117. * ->inode->i_lock (zap_pte_range->set_page_dirty)
  118. * ->private_lock (zap_pte_range->block_dirty_folio)
  119. */
  120. static void mapping_set_update(struct xa_state *xas,
  121. struct address_space *mapping)
  122. {
  123. if (dax_mapping(mapping) || shmem_mapping(mapping))
  124. return;
  125. xas_set_update(xas, workingset_update_node);
  126. xas_set_lru(xas, &shadow_nodes);
  127. }
  128. static void page_cache_delete(struct address_space *mapping,
  129. struct folio *folio, void *shadow)
  130. {
  131. XA_STATE(xas, &mapping->i_pages, folio->index);
  132. long nr = 1;
  133. mapping_set_update(&xas, mapping);
  134. xas_set_order(&xas, folio->index, folio_order(folio));
  135. nr = folio_nr_pages(folio);
  136. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  137. xas_store(&xas, shadow);
  138. xas_init_marks(&xas);
  139. folio->mapping = NULL;
  140. /* Leave page->index set: truncation lookup relies upon it */
  141. mapping->nrpages -= nr;
  142. }
  143. static void filemap_unaccount_folio(struct address_space *mapping,
  144. struct folio *folio)
  145. {
  146. long nr;
  147. VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
  148. if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
  149. pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
  150. current->comm, folio_pfn(folio));
  151. dump_page(&folio->page, "still mapped when deleted");
  152. dump_stack();
  153. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  154. if (mapping_exiting(mapping) && !folio_test_large(folio)) {
  155. int mapcount = folio_mapcount(folio);
  156. if (folio_ref_count(folio) >= mapcount + 2) {
  157. /*
  158. * All vmas have already been torn down, so it's
  159. * a good bet that actually the page is unmapped
  160. * and we'd rather not leak it: if we're wrong,
  161. * another bad page check should catch it later.
  162. */
  163. atomic_set(&folio->_mapcount, -1);
  164. folio_ref_sub(folio, mapcount);
  165. }
  166. }
  167. }
  168. /* hugetlb folios do not participate in page cache accounting. */
  169. if (folio_test_hugetlb(folio))
  170. return;
  171. nr = folio_nr_pages(folio);
  172. __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
  173. if (folio_test_swapbacked(folio)) {
  174. __lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
  175. if (folio_test_pmd_mappable(folio))
  176. __lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr);
  177. } else if (folio_test_pmd_mappable(folio)) {
  178. __lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr);
  179. filemap_nr_thps_dec(mapping);
  180. }
  181. /*
  182. * At this point folio must be either written or cleaned by
  183. * truncate. Dirty folio here signals a bug and loss of
  184. * unwritten data - on ordinary filesystems.
  185. *
  186. * But it's harmless on in-memory filesystems like tmpfs; and can
  187. * occur when a driver which did get_user_pages() sets page dirty
  188. * before putting it, while the inode is being finally evicted.
  189. *
  190. * Below fixes dirty accounting after removing the folio entirely
  191. * but leaves the dirty flag set: it has no effect for truncated
  192. * folio and anyway will be cleared before returning folio to
  193. * buddy allocator.
  194. */
  195. if (WARN_ON_ONCE(folio_test_dirty(folio) &&
  196. mapping_can_writeback(mapping)))
  197. folio_account_cleaned(folio, inode_to_wb(mapping->host));
  198. }
  199. /*
  200. * Delete a page from the page cache and free it. Caller has to make
  201. * sure the page is locked and that nobody else uses it - or that usage
  202. * is safe. The caller must hold the i_pages lock.
  203. */
  204. void __filemap_remove_folio(struct folio *folio, void *shadow)
  205. {
  206. struct address_space *mapping = folio->mapping;
  207. trace_mm_filemap_delete_from_page_cache(folio);
  208. filemap_unaccount_folio(mapping, folio);
  209. page_cache_delete(mapping, folio, shadow);
  210. }
  211. void filemap_free_folio(struct address_space *mapping, struct folio *folio)
  212. {
  213. void (*free_folio)(struct folio *);
  214. int refs = 1;
  215. free_folio = mapping->a_ops->free_folio;
  216. if (free_folio)
  217. free_folio(folio);
  218. if (folio_test_large(folio))
  219. refs = folio_nr_pages(folio);
  220. folio_put_refs(folio, refs);
  221. }
  222. /**
  223. * filemap_remove_folio - Remove folio from page cache.
  224. * @folio: The folio.
  225. *
  226. * This must be called only on folios that are locked and have been
  227. * verified to be in the page cache. It will never put the folio into
  228. * the free list because the caller has a reference on the page.
  229. */
  230. void filemap_remove_folio(struct folio *folio)
  231. {
  232. struct address_space *mapping = folio->mapping;
  233. BUG_ON(!folio_test_locked(folio));
  234. spin_lock(&mapping->host->i_lock);
  235. xa_lock_irq(&mapping->i_pages);
  236. __filemap_remove_folio(folio, NULL);
  237. xa_unlock_irq(&mapping->i_pages);
  238. if (mapping_shrinkable(mapping))
  239. inode_add_lru(mapping->host);
  240. spin_unlock(&mapping->host->i_lock);
  241. filemap_free_folio(mapping, folio);
  242. }
  243. /*
  244. * page_cache_delete_batch - delete several folios from page cache
  245. * @mapping: the mapping to which folios belong
  246. * @fbatch: batch of folios to delete
  247. *
  248. * The function walks over mapping->i_pages and removes folios passed in
  249. * @fbatch from the mapping. The function expects @fbatch to be sorted
  250. * by page index and is optimised for it to be dense.
  251. * It tolerates holes in @fbatch (mapping entries at those indices are not
  252. * modified).
  253. *
  254. * The function expects the i_pages lock to be held.
  255. */
  256. static void page_cache_delete_batch(struct address_space *mapping,
  257. struct folio_batch *fbatch)
  258. {
  259. XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
  260. long total_pages = 0;
  261. int i = 0;
  262. struct folio *folio;
  263. mapping_set_update(&xas, mapping);
  264. xas_for_each(&xas, folio, ULONG_MAX) {
  265. if (i >= folio_batch_count(fbatch))
  266. break;
  267. /* A swap/dax/shadow entry got inserted? Skip it. */
  268. if (xa_is_value(folio))
  269. continue;
  270. /*
  271. * A page got inserted in our range? Skip it. We have our
  272. * pages locked so they are protected from being removed.
  273. * If we see a page whose index is higher than ours, it
  274. * means our page has been removed, which shouldn't be
  275. * possible because we're holding the PageLock.
  276. */
  277. if (folio != fbatch->folios[i]) {
  278. VM_BUG_ON_FOLIO(folio->index >
  279. fbatch->folios[i]->index, folio);
  280. continue;
  281. }
  282. WARN_ON_ONCE(!folio_test_locked(folio));
  283. folio->mapping = NULL;
  284. /* Leave folio->index set: truncation lookup relies on it */
  285. i++;
  286. xas_store(&xas, NULL);
  287. total_pages += folio_nr_pages(folio);
  288. }
  289. mapping->nrpages -= total_pages;
  290. }
  291. void delete_from_page_cache_batch(struct address_space *mapping,
  292. struct folio_batch *fbatch)
  293. {
  294. int i;
  295. if (!folio_batch_count(fbatch))
  296. return;
  297. spin_lock(&mapping->host->i_lock);
  298. xa_lock_irq(&mapping->i_pages);
  299. for (i = 0; i < folio_batch_count(fbatch); i++) {
  300. struct folio *folio = fbatch->folios[i];
  301. trace_mm_filemap_delete_from_page_cache(folio);
  302. filemap_unaccount_folio(mapping, folio);
  303. }
  304. page_cache_delete_batch(mapping, fbatch);
  305. xa_unlock_irq(&mapping->i_pages);
  306. if (mapping_shrinkable(mapping))
  307. inode_add_lru(mapping->host);
  308. spin_unlock(&mapping->host->i_lock);
  309. for (i = 0; i < folio_batch_count(fbatch); i++)
  310. filemap_free_folio(mapping, fbatch->folios[i]);
  311. }
  312. int filemap_check_errors(struct address_space *mapping)
  313. {
  314. int ret = 0;
  315. /* Check for outstanding write errors */
  316. if (test_bit(AS_ENOSPC, &mapping->flags) &&
  317. test_and_clear_bit(AS_ENOSPC, &mapping->flags))
  318. ret = -ENOSPC;
  319. if (test_bit(AS_EIO, &mapping->flags) &&
  320. test_and_clear_bit(AS_EIO, &mapping->flags))
  321. ret = -EIO;
  322. return ret;
  323. }
  324. EXPORT_SYMBOL(filemap_check_errors);
  325. static int filemap_check_and_keep_errors(struct address_space *mapping)
  326. {
  327. /* Check for outstanding write errors */
  328. if (test_bit(AS_EIO, &mapping->flags))
  329. return -EIO;
  330. if (test_bit(AS_ENOSPC, &mapping->flags))
  331. return -ENOSPC;
  332. return 0;
  333. }
  334. /**
  335. * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
  336. * @mapping: address space structure to write
  337. * @wbc: the writeback_control controlling the writeout
  338. *
  339. * Call writepages on the mapping using the provided wbc to control the
  340. * writeout.
  341. *
  342. * Return: %0 on success, negative error code otherwise.
  343. */
  344. int filemap_fdatawrite_wbc(struct address_space *mapping,
  345. struct writeback_control *wbc)
  346. {
  347. int ret;
  348. if (!mapping_can_writeback(mapping) ||
  349. !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  350. return 0;
  351. wbc_attach_fdatawrite_inode(wbc, mapping->host);
  352. ret = do_writepages(mapping, wbc);
  353. wbc_detach_inode(wbc);
  354. return ret;
  355. }
  356. EXPORT_SYMBOL(filemap_fdatawrite_wbc);
  357. /**
  358. * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
  359. * @mapping: address space structure to write
  360. * @start: offset in bytes where the range starts
  361. * @end: offset in bytes where the range ends (inclusive)
  362. * @sync_mode: enable synchronous operation
  363. *
  364. * Start writeback against all of a mapping's dirty pages that lie
  365. * within the byte offsets <start, end> inclusive.
  366. *
  367. * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
  368. * opposed to a regular memory cleansing writeback. The difference between
  369. * these two operations is that if a dirty page/buffer is encountered, it must
  370. * be waited upon, and not just skipped over.
  371. *
  372. * Return: %0 on success, negative error code otherwise.
  373. */
  374. int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  375. loff_t end, int sync_mode)
  376. {
  377. struct writeback_control wbc = {
  378. .sync_mode = sync_mode,
  379. .nr_to_write = LONG_MAX,
  380. .range_start = start,
  381. .range_end = end,
  382. };
  383. return filemap_fdatawrite_wbc(mapping, &wbc);
  384. }
  385. static inline int __filemap_fdatawrite(struct address_space *mapping,
  386. int sync_mode)
  387. {
  388. return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
  389. }
  390. int filemap_fdatawrite(struct address_space *mapping)
  391. {
  392. return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
  393. }
  394. EXPORT_SYMBOL(filemap_fdatawrite);
  395. int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  396. loff_t end)
  397. {
  398. return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
  399. }
  400. EXPORT_SYMBOL(filemap_fdatawrite_range);
  401. /**
  402. * filemap_flush - mostly a non-blocking flush
  403. * @mapping: target address_space
  404. *
  405. * This is a mostly non-blocking flush. Not suitable for data-integrity
  406. * purposes - I/O may not be started against all dirty pages.
  407. *
  408. * Return: %0 on success, negative error code otherwise.
  409. */
  410. int filemap_flush(struct address_space *mapping)
  411. {
  412. return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
  413. }
  414. EXPORT_SYMBOL(filemap_flush);
  415. /**
  416. * filemap_range_has_page - check if a page exists in range.
  417. * @mapping: address space within which to check
  418. * @start_byte: offset in bytes where the range starts
  419. * @end_byte: offset in bytes where the range ends (inclusive)
  420. *
  421. * Find at least one page in the range supplied, usually used to check if
  422. * direct writing in this range will trigger a writeback.
  423. *
  424. * Return: %true if at least one page exists in the specified range,
  425. * %false otherwise.
  426. */
  427. bool filemap_range_has_page(struct address_space *mapping,
  428. loff_t start_byte, loff_t end_byte)
  429. {
  430. struct folio *folio;
  431. XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
  432. pgoff_t max = end_byte >> PAGE_SHIFT;
  433. if (end_byte < start_byte)
  434. return false;
  435. rcu_read_lock();
  436. for (;;) {
  437. folio = xas_find(&xas, max);
  438. if (xas_retry(&xas, folio))
  439. continue;
  440. /* Shadow entries don't count */
  441. if (xa_is_value(folio))
  442. continue;
  443. /*
  444. * We don't need to try to pin this page; we're about to
  445. * release the RCU lock anyway. It is enough to know that
  446. * there was a page here recently.
  447. */
  448. break;
  449. }
  450. rcu_read_unlock();
  451. return folio != NULL;
  452. }
  453. EXPORT_SYMBOL(filemap_range_has_page);
  454. static void __filemap_fdatawait_range(struct address_space *mapping,
  455. loff_t start_byte, loff_t end_byte)
  456. {
  457. pgoff_t index = start_byte >> PAGE_SHIFT;
  458. pgoff_t end = end_byte >> PAGE_SHIFT;
  459. struct folio_batch fbatch;
  460. unsigned nr_folios;
  461. folio_batch_init(&fbatch);
  462. while (index <= end) {
  463. unsigned i;
  464. nr_folios = filemap_get_folios_tag(mapping, &index, end,
  465. PAGECACHE_TAG_WRITEBACK, &fbatch);
  466. if (!nr_folios)
  467. break;
  468. for (i = 0; i < nr_folios; i++) {
  469. struct folio *folio = fbatch.folios[i];
  470. folio_wait_writeback(folio);
  471. }
  472. folio_batch_release(&fbatch);
  473. cond_resched();
  474. }
  475. }
  476. /**
  477. * filemap_fdatawait_range - wait for writeback to complete
  478. * @mapping: address space structure to wait for
  479. * @start_byte: offset in bytes where the range starts
  480. * @end_byte: offset in bytes where the range ends (inclusive)
  481. *
  482. * Walk the list of under-writeback pages of the given address space
  483. * in the given range and wait for all of them. Check error status of
  484. * the address space and return it.
  485. *
  486. * Since the error status of the address space is cleared by this function,
  487. * callers are responsible for checking the return value and handling and/or
  488. * reporting the error.
  489. *
  490. * Return: error status of the address space.
  491. */
  492. int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
  493. loff_t end_byte)
  494. {
  495. __filemap_fdatawait_range(mapping, start_byte, end_byte);
  496. return filemap_check_errors(mapping);
  497. }
  498. EXPORT_SYMBOL(filemap_fdatawait_range);
  499. /**
  500. * filemap_fdatawait_range_keep_errors - wait for writeback to complete
  501. * @mapping: address space structure to wait for
  502. * @start_byte: offset in bytes where the range starts
  503. * @end_byte: offset in bytes where the range ends (inclusive)
  504. *
  505. * Walk the list of under-writeback pages of the given address space in the
  506. * given range and wait for all of them. Unlike filemap_fdatawait_range(),
  507. * this function does not clear error status of the address space.
  508. *
  509. * Use this function if callers don't handle errors themselves. Expected
  510. * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
  511. * fsfreeze(8)
  512. */
  513. int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
  514. loff_t start_byte, loff_t end_byte)
  515. {
  516. __filemap_fdatawait_range(mapping, start_byte, end_byte);
  517. return filemap_check_and_keep_errors(mapping);
  518. }
  519. EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
  520. /**
  521. * file_fdatawait_range - wait for writeback to complete
  522. * @file: file pointing to address space structure to wait for
  523. * @start_byte: offset in bytes where the range starts
  524. * @end_byte: offset in bytes where the range ends (inclusive)
  525. *
  526. * Walk the list of under-writeback pages of the address space that file
  527. * refers to, in the given range and wait for all of them. Check error
  528. * status of the address space vs. the file->f_wb_err cursor and return it.
  529. *
  530. * Since the error status of the file is advanced by this function,
  531. * callers are responsible for checking the return value and handling and/or
  532. * reporting the error.
  533. *
  534. * Return: error status of the address space vs. the file->f_wb_err cursor.
  535. */
  536. int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
  537. {
  538. struct address_space *mapping = file->f_mapping;
  539. __filemap_fdatawait_range(mapping, start_byte, end_byte);
  540. return file_check_and_advance_wb_err(file);
  541. }
  542. EXPORT_SYMBOL(file_fdatawait_range);
  543. /**
  544. * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
  545. * @mapping: address space structure to wait for
  546. *
  547. * Walk the list of under-writeback pages of the given address space
  548. * and wait for all of them. Unlike filemap_fdatawait(), this function
  549. * does not clear error status of the address space.
  550. *
  551. * Use this function if callers don't handle errors themselves. Expected
  552. * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
  553. * fsfreeze(8)
  554. *
  555. * Return: error status of the address space.
  556. */
  557. int filemap_fdatawait_keep_errors(struct address_space *mapping)
  558. {
  559. __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
  560. return filemap_check_and_keep_errors(mapping);
  561. }
  562. EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
  563. /* Returns true if writeback might be needed or already in progress. */
  564. static bool mapping_needs_writeback(struct address_space *mapping)
  565. {
  566. return mapping->nrpages;
  567. }
  568. bool filemap_range_has_writeback(struct address_space *mapping,
  569. loff_t start_byte, loff_t end_byte)
  570. {
  571. XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
  572. pgoff_t max = end_byte >> PAGE_SHIFT;
  573. struct folio *folio;
  574. if (end_byte < start_byte)
  575. return false;
  576. rcu_read_lock();
  577. xas_for_each(&xas, folio, max) {
  578. if (xas_retry(&xas, folio))
  579. continue;
  580. if (xa_is_value(folio))
  581. continue;
  582. if (folio_test_dirty(folio) || folio_test_locked(folio) ||
  583. folio_test_writeback(folio))
  584. break;
  585. }
  586. rcu_read_unlock();
  587. return folio != NULL;
  588. }
  589. EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
  590. /**
  591. * filemap_write_and_wait_range - write out & wait on a file range
  592. * @mapping: the address_space for the pages
  593. * @lstart: offset in bytes where the range starts
  594. * @lend: offset in bytes where the range ends (inclusive)
  595. *
  596. * Write out and wait upon file offsets lstart->lend, inclusive.
  597. *
  598. * Note that @lend is inclusive (describes the last byte to be written) so
  599. * that this function can be used to write to the very end-of-file (end = -1).
  600. *
  601. * Return: error status of the address space.
  602. */
  603. int filemap_write_and_wait_range(struct address_space *mapping,
  604. loff_t lstart, loff_t lend)
  605. {
  606. int err = 0, err2;
  607. if (lend < lstart)
  608. return 0;
  609. if (mapping_needs_writeback(mapping)) {
  610. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  611. WB_SYNC_ALL);
  612. /*
  613. * Even if the above returned error, the pages may be
  614. * written partially (e.g. -ENOSPC), so we wait for it.
  615. * But the -EIO is special case, it may indicate the worst
  616. * thing (e.g. bug) happened, so we avoid waiting for it.
  617. */
  618. if (err != -EIO)
  619. __filemap_fdatawait_range(mapping, lstart, lend);
  620. }
  621. err2 = filemap_check_errors(mapping);
  622. if (!err)
  623. err = err2;
  624. return err;
  625. }
  626. EXPORT_SYMBOL(filemap_write_and_wait_range);
  627. void __filemap_set_wb_err(struct address_space *mapping, int err)
  628. {
  629. errseq_t eseq = errseq_set(&mapping->wb_err, err);
  630. trace_filemap_set_wb_err(mapping, eseq);
  631. }
  632. EXPORT_SYMBOL(__filemap_set_wb_err);
  633. /**
  634. * file_check_and_advance_wb_err - report wb error (if any) that was previously
  635. * and advance wb_err to current one
  636. * @file: struct file on which the error is being reported
  637. *
  638. * When userland calls fsync (or something like nfsd does the equivalent), we
  639. * want to report any writeback errors that occurred since the last fsync (or
  640. * since the file was opened if there haven't been any).
  641. *
  642. * Grab the wb_err from the mapping. If it matches what we have in the file,
  643. * then just quickly return 0. The file is all caught up.
  644. *
  645. * If it doesn't match, then take the mapping value, set the "seen" flag in
  646. * it and try to swap it into place. If it works, or another task beat us
  647. * to it with the new value, then update the f_wb_err and return the error
  648. * portion. The error at this point must be reported via proper channels
  649. * (a'la fsync, or NFS COMMIT operation, etc.).
  650. *
  651. * While we handle mapping->wb_err with atomic operations, the f_wb_err
  652. * value is protected by the f_lock since we must ensure that it reflects
  653. * the latest value swapped in for this file descriptor.
  654. *
  655. * Return: %0 on success, negative error code otherwise.
  656. */
  657. int file_check_and_advance_wb_err(struct file *file)
  658. {
  659. int err = 0;
  660. errseq_t old = READ_ONCE(file->f_wb_err);
  661. struct address_space *mapping = file->f_mapping;
  662. /* Locklessly handle the common case where nothing has changed */
  663. if (errseq_check(&mapping->wb_err, old)) {
  664. /* Something changed, must use slow path */
  665. spin_lock(&file->f_lock);
  666. old = file->f_wb_err;
  667. err = errseq_check_and_advance(&mapping->wb_err,
  668. &file->f_wb_err);
  669. trace_file_check_and_advance_wb_err(file, old);
  670. spin_unlock(&file->f_lock);
  671. }
  672. /*
  673. * We're mostly using this function as a drop in replacement for
  674. * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
  675. * that the legacy code would have had on these flags.
  676. */
  677. clear_bit(AS_EIO, &mapping->flags);
  678. clear_bit(AS_ENOSPC, &mapping->flags);
  679. return err;
  680. }
  681. EXPORT_SYMBOL(file_check_and_advance_wb_err);
  682. /**
  683. * file_write_and_wait_range - write out & wait on a file range
  684. * @file: file pointing to address_space with pages
  685. * @lstart: offset in bytes where the range starts
  686. * @lend: offset in bytes where the range ends (inclusive)
  687. *
  688. * Write out and wait upon file offsets lstart->lend, inclusive.
  689. *
  690. * Note that @lend is inclusive (describes the last byte to be written) so
  691. * that this function can be used to write to the very end-of-file (end = -1).
  692. *
  693. * After writing out and waiting on the data, we check and advance the
  694. * f_wb_err cursor to the latest value, and return any errors detected there.
  695. *
  696. * Return: %0 on success, negative error code otherwise.
  697. */
  698. int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
  699. {
  700. int err = 0, err2;
  701. struct address_space *mapping = file->f_mapping;
  702. if (lend < lstart)
  703. return 0;
  704. if (mapping_needs_writeback(mapping)) {
  705. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  706. WB_SYNC_ALL);
  707. /* See comment of filemap_write_and_wait() */
  708. if (err != -EIO)
  709. __filemap_fdatawait_range(mapping, lstart, lend);
  710. }
  711. err2 = file_check_and_advance_wb_err(file);
  712. if (!err)
  713. err = err2;
  714. return err;
  715. }
  716. EXPORT_SYMBOL(file_write_and_wait_range);
  717. /**
  718. * replace_page_cache_folio - replace a pagecache folio with a new one
  719. * @old: folio to be replaced
  720. * @new: folio to replace with
  721. *
  722. * This function replaces a folio in the pagecache with a new one. On
  723. * success it acquires the pagecache reference for the new folio and
  724. * drops it for the old folio. Both the old and new folios must be
  725. * locked. This function does not add the new folio to the LRU, the
  726. * caller must do that.
  727. *
  728. * The remove + add is atomic. This function cannot fail.
  729. */
  730. void replace_page_cache_folio(struct folio *old, struct folio *new)
  731. {
  732. struct address_space *mapping = old->mapping;
  733. void (*free_folio)(struct folio *) = mapping->a_ops->free_folio;
  734. pgoff_t offset = old->index;
  735. XA_STATE(xas, &mapping->i_pages, offset);
  736. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  737. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  738. VM_BUG_ON_FOLIO(new->mapping, new);
  739. folio_get(new);
  740. new->mapping = mapping;
  741. new->index = offset;
  742. mem_cgroup_replace_folio(old, new);
  743. xas_lock_irq(&xas);
  744. xas_store(&xas, new);
  745. old->mapping = NULL;
  746. /* hugetlb pages do not participate in page cache accounting. */
  747. if (!folio_test_hugetlb(old))
  748. __lruvec_stat_sub_folio(old, NR_FILE_PAGES);
  749. if (!folio_test_hugetlb(new))
  750. __lruvec_stat_add_folio(new, NR_FILE_PAGES);
  751. if (folio_test_swapbacked(old))
  752. __lruvec_stat_sub_folio(old, NR_SHMEM);
  753. if (folio_test_swapbacked(new))
  754. __lruvec_stat_add_folio(new, NR_SHMEM);
  755. xas_unlock_irq(&xas);
  756. if (free_folio)
  757. free_folio(old);
  758. folio_put(old);
  759. }
  760. EXPORT_SYMBOL_GPL(replace_page_cache_folio);
  761. noinline int __filemap_add_folio(struct address_space *mapping,
  762. struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
  763. {
  764. XA_STATE(xas, &mapping->i_pages, index);
  765. void *alloced_shadow = NULL;
  766. int alloced_order = 0;
  767. bool huge;
  768. long nr;
  769. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  770. VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
  771. VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping),
  772. folio);
  773. mapping_set_update(&xas, mapping);
  774. VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
  775. xas_set_order(&xas, index, folio_order(folio));
  776. huge = folio_test_hugetlb(folio);
  777. nr = folio_nr_pages(folio);
  778. gfp &= GFP_RECLAIM_MASK;
  779. folio_ref_add(folio, nr);
  780. folio->mapping = mapping;
  781. folio->index = xas.xa_index;
  782. for (;;) {
  783. int order = -1, split_order = 0;
  784. void *entry, *old = NULL;
  785. xas_lock_irq(&xas);
  786. xas_for_each_conflict(&xas, entry) {
  787. old = entry;
  788. if (!xa_is_value(entry)) {
  789. xas_set_err(&xas, -EEXIST);
  790. goto unlock;
  791. }
  792. /*
  793. * If a larger entry exists,
  794. * it will be the first and only entry iterated.
  795. */
  796. if (order == -1)
  797. order = xas_get_order(&xas);
  798. }
  799. /* entry may have changed before we re-acquire the lock */
  800. if (alloced_order && (old != alloced_shadow || order != alloced_order)) {
  801. xas_destroy(&xas);
  802. alloced_order = 0;
  803. }
  804. if (old) {
  805. if (order > 0 && order > folio_order(folio)) {
  806. /* How to handle large swap entries? */
  807. BUG_ON(shmem_mapping(mapping));
  808. if (!alloced_order) {
  809. split_order = order;
  810. goto unlock;
  811. }
  812. xas_split(&xas, old, order);
  813. xas_reset(&xas);
  814. }
  815. if (shadowp)
  816. *shadowp = old;
  817. }
  818. xas_store(&xas, folio);
  819. if (xas_error(&xas))
  820. goto unlock;
  821. mapping->nrpages += nr;
  822. /* hugetlb pages do not participate in page cache accounting */
  823. if (!huge) {
  824. __lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
  825. if (folio_test_pmd_mappable(folio))
  826. __lruvec_stat_mod_folio(folio,
  827. NR_FILE_THPS, nr);
  828. }
  829. unlock:
  830. xas_unlock_irq(&xas);
  831. /* split needed, alloc here and retry. */
  832. if (split_order) {
  833. xas_split_alloc(&xas, old, split_order, gfp);
  834. if (xas_error(&xas))
  835. goto error;
  836. alloced_shadow = old;
  837. alloced_order = split_order;
  838. xas_reset(&xas);
  839. continue;
  840. }
  841. if (!xas_nomem(&xas, gfp))
  842. break;
  843. }
  844. if (xas_error(&xas))
  845. goto error;
  846. trace_mm_filemap_add_to_page_cache(folio);
  847. return 0;
  848. error:
  849. folio->mapping = NULL;
  850. /* Leave page->index set: truncation relies upon it */
  851. folio_put_refs(folio, nr);
  852. return xas_error(&xas);
  853. }
  854. ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
  855. int filemap_add_folio(struct address_space *mapping, struct folio *folio,
  856. pgoff_t index, gfp_t gfp)
  857. {
  858. void *shadow = NULL;
  859. int ret;
  860. ret = mem_cgroup_charge(folio, NULL, gfp);
  861. if (ret)
  862. return ret;
  863. __folio_set_locked(folio);
  864. ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
  865. if (unlikely(ret)) {
  866. mem_cgroup_uncharge(folio);
  867. __folio_clear_locked(folio);
  868. } else {
  869. /*
  870. * The folio might have been evicted from cache only
  871. * recently, in which case it should be activated like
  872. * any other repeatedly accessed folio.
  873. * The exception is folios getting rewritten; evicting other
  874. * data from the working set, only to cache data that will
  875. * get overwritten with something else, is a waste of memory.
  876. */
  877. WARN_ON_ONCE(folio_test_active(folio));
  878. if (!(gfp & __GFP_WRITE) && shadow)
  879. workingset_refault(folio, shadow);
  880. folio_add_lru(folio);
  881. }
  882. return ret;
  883. }
  884. EXPORT_SYMBOL_GPL(filemap_add_folio);
  885. #ifdef CONFIG_NUMA
  886. struct folio *filemap_alloc_folio_noprof(gfp_t gfp, unsigned int order)
  887. {
  888. int n;
  889. struct folio *folio;
  890. if (cpuset_do_page_mem_spread()) {
  891. unsigned int cpuset_mems_cookie;
  892. do {
  893. cpuset_mems_cookie = read_mems_allowed_begin();
  894. n = cpuset_mem_spread_node();
  895. folio = __folio_alloc_node_noprof(gfp, order, n);
  896. } while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
  897. return folio;
  898. }
  899. return folio_alloc_noprof(gfp, order);
  900. }
  901. EXPORT_SYMBOL(filemap_alloc_folio_noprof);
  902. #endif
  903. /*
  904. * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
  905. *
  906. * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
  907. *
  908. * @mapping1: the first mapping to lock
  909. * @mapping2: the second mapping to lock
  910. */
  911. void filemap_invalidate_lock_two(struct address_space *mapping1,
  912. struct address_space *mapping2)
  913. {
  914. if (mapping1 > mapping2)
  915. swap(mapping1, mapping2);
  916. if (mapping1)
  917. down_write(&mapping1->invalidate_lock);
  918. if (mapping2 && mapping1 != mapping2)
  919. down_write_nested(&mapping2->invalidate_lock, 1);
  920. }
  921. EXPORT_SYMBOL(filemap_invalidate_lock_two);
  922. /*
  923. * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
  924. *
  925. * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
  926. *
  927. * @mapping1: the first mapping to unlock
  928. * @mapping2: the second mapping to unlock
  929. */
  930. void filemap_invalidate_unlock_two(struct address_space *mapping1,
  931. struct address_space *mapping2)
  932. {
  933. if (mapping1)
  934. up_write(&mapping1->invalidate_lock);
  935. if (mapping2 && mapping1 != mapping2)
  936. up_write(&mapping2->invalidate_lock);
  937. }
  938. EXPORT_SYMBOL(filemap_invalidate_unlock_two);
  939. /*
  940. * In order to wait for pages to become available there must be
  941. * waitqueues associated with pages. By using a hash table of
  942. * waitqueues where the bucket discipline is to maintain all
  943. * waiters on the same queue and wake all when any of the pages
  944. * become available, and for the woken contexts to check to be
  945. * sure the appropriate page became available, this saves space
  946. * at a cost of "thundering herd" phenomena during rare hash
  947. * collisions.
  948. */
  949. #define PAGE_WAIT_TABLE_BITS 8
  950. #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
  951. static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
  952. static wait_queue_head_t *folio_waitqueue(struct folio *folio)
  953. {
  954. return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
  955. }
  956. void __init pagecache_init(void)
  957. {
  958. int i;
  959. for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
  960. init_waitqueue_head(&folio_wait_table[i]);
  961. page_writeback_init();
  962. }
  963. /*
  964. * The page wait code treats the "wait->flags" somewhat unusually, because
  965. * we have multiple different kinds of waits, not just the usual "exclusive"
  966. * one.
  967. *
  968. * We have:
  969. *
  970. * (a) no special bits set:
  971. *
  972. * We're just waiting for the bit to be released, and when a waker
  973. * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
  974. * and remove it from the wait queue.
  975. *
  976. * Simple and straightforward.
  977. *
  978. * (b) WQ_FLAG_EXCLUSIVE:
  979. *
  980. * The waiter is waiting to get the lock, and only one waiter should
  981. * be woken up to avoid any thundering herd behavior. We'll set the
  982. * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
  983. *
  984. * This is the traditional exclusive wait.
  985. *
  986. * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
  987. *
  988. * The waiter is waiting to get the bit, and additionally wants the
  989. * lock to be transferred to it for fair lock behavior. If the lock
  990. * cannot be taken, we stop walking the wait queue without waking
  991. * the waiter.
  992. *
  993. * This is the "fair lock handoff" case, and in addition to setting
  994. * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
  995. * that it now has the lock.
  996. */
  997. static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
  998. {
  999. unsigned int flags;
  1000. struct wait_page_key *key = arg;
  1001. struct wait_page_queue *wait_page
  1002. = container_of(wait, struct wait_page_queue, wait);
  1003. if (!wake_page_match(wait_page, key))
  1004. return 0;
  1005. /*
  1006. * If it's a lock handoff wait, we get the bit for it, and
  1007. * stop walking (and do not wake it up) if we can't.
  1008. */
  1009. flags = wait->flags;
  1010. if (flags & WQ_FLAG_EXCLUSIVE) {
  1011. if (test_bit(key->bit_nr, &key->folio->flags))
  1012. return -1;
  1013. if (flags & WQ_FLAG_CUSTOM) {
  1014. if (test_and_set_bit(key->bit_nr, &key->folio->flags))
  1015. return -1;
  1016. flags |= WQ_FLAG_DONE;
  1017. }
  1018. }
  1019. /*
  1020. * We are holding the wait-queue lock, but the waiter that
  1021. * is waiting for this will be checking the flags without
  1022. * any locking.
  1023. *
  1024. * So update the flags atomically, and wake up the waiter
  1025. * afterwards to avoid any races. This store-release pairs
  1026. * with the load-acquire in folio_wait_bit_common().
  1027. */
  1028. smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
  1029. wake_up_state(wait->private, mode);
  1030. /*
  1031. * Ok, we have successfully done what we're waiting for,
  1032. * and we can unconditionally remove the wait entry.
  1033. *
  1034. * Note that this pairs with the "finish_wait()" in the
  1035. * waiter, and has to be the absolute last thing we do.
  1036. * After this list_del_init(&wait->entry) the wait entry
  1037. * might be de-allocated and the process might even have
  1038. * exited.
  1039. */
  1040. list_del_init_careful(&wait->entry);
  1041. return (flags & WQ_FLAG_EXCLUSIVE) != 0;
  1042. }
  1043. static void folio_wake_bit(struct folio *folio, int bit_nr)
  1044. {
  1045. wait_queue_head_t *q = folio_waitqueue(folio);
  1046. struct wait_page_key key;
  1047. unsigned long flags;
  1048. key.folio = folio;
  1049. key.bit_nr = bit_nr;
  1050. key.page_match = 0;
  1051. spin_lock_irqsave(&q->lock, flags);
  1052. __wake_up_locked_key(q, TASK_NORMAL, &key);
  1053. /*
  1054. * It's possible to miss clearing waiters here, when we woke our page
  1055. * waiters, but the hashed waitqueue has waiters for other pages on it.
  1056. * That's okay, it's a rare case. The next waker will clear it.
  1057. *
  1058. * Note that, depending on the page pool (buddy, hugetlb, ZONE_DEVICE,
  1059. * other), the flag may be cleared in the course of freeing the page;
  1060. * but that is not required for correctness.
  1061. */
  1062. if (!waitqueue_active(q) || !key.page_match)
  1063. folio_clear_waiters(folio);
  1064. spin_unlock_irqrestore(&q->lock, flags);
  1065. }
  1066. /*
  1067. * A choice of three behaviors for folio_wait_bit_common():
  1068. */
  1069. enum behavior {
  1070. EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
  1071. * __folio_lock() waiting on then setting PG_locked.
  1072. */
  1073. SHARED, /* Hold ref to page and check the bit when woken, like
  1074. * folio_wait_writeback() waiting on PG_writeback.
  1075. */
  1076. DROP, /* Drop ref to page before wait, no check when woken,
  1077. * like folio_put_wait_locked() on PG_locked.
  1078. */
  1079. };
  1080. /*
  1081. * Attempt to check (or get) the folio flag, and mark us done
  1082. * if successful.
  1083. */
  1084. static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
  1085. struct wait_queue_entry *wait)
  1086. {
  1087. if (wait->flags & WQ_FLAG_EXCLUSIVE) {
  1088. if (test_and_set_bit(bit_nr, &folio->flags))
  1089. return false;
  1090. } else if (test_bit(bit_nr, &folio->flags))
  1091. return false;
  1092. wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
  1093. return true;
  1094. }
  1095. /* How many times do we accept lock stealing from under a waiter? */
  1096. int sysctl_page_lock_unfairness = 5;
  1097. static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
  1098. int state, enum behavior behavior)
  1099. {
  1100. wait_queue_head_t *q = folio_waitqueue(folio);
  1101. int unfairness = sysctl_page_lock_unfairness;
  1102. struct wait_page_queue wait_page;
  1103. wait_queue_entry_t *wait = &wait_page.wait;
  1104. bool thrashing = false;
  1105. unsigned long pflags;
  1106. bool in_thrashing;
  1107. if (bit_nr == PG_locked &&
  1108. !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
  1109. delayacct_thrashing_start(&in_thrashing);
  1110. psi_memstall_enter(&pflags);
  1111. thrashing = true;
  1112. }
  1113. init_wait(wait);
  1114. wait->func = wake_page_function;
  1115. wait_page.folio = folio;
  1116. wait_page.bit_nr = bit_nr;
  1117. repeat:
  1118. wait->flags = 0;
  1119. if (behavior == EXCLUSIVE) {
  1120. wait->flags = WQ_FLAG_EXCLUSIVE;
  1121. if (--unfairness < 0)
  1122. wait->flags |= WQ_FLAG_CUSTOM;
  1123. }
  1124. /*
  1125. * Do one last check whether we can get the
  1126. * page bit synchronously.
  1127. *
  1128. * Do the folio_set_waiters() marking before that
  1129. * to let any waker we _just_ missed know they
  1130. * need to wake us up (otherwise they'll never
  1131. * even go to the slow case that looks at the
  1132. * page queue), and add ourselves to the wait
  1133. * queue if we need to sleep.
  1134. *
  1135. * This part needs to be done under the queue
  1136. * lock to avoid races.
  1137. */
  1138. spin_lock_irq(&q->lock);
  1139. folio_set_waiters(folio);
  1140. if (!folio_trylock_flag(folio, bit_nr, wait))
  1141. __add_wait_queue_entry_tail(q, wait);
  1142. spin_unlock_irq(&q->lock);
  1143. /*
  1144. * From now on, all the logic will be based on
  1145. * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
  1146. * see whether the page bit testing has already
  1147. * been done by the wake function.
  1148. *
  1149. * We can drop our reference to the folio.
  1150. */
  1151. if (behavior == DROP)
  1152. folio_put(folio);
  1153. /*
  1154. * Note that until the "finish_wait()", or until
  1155. * we see the WQ_FLAG_WOKEN flag, we need to
  1156. * be very careful with the 'wait->flags', because
  1157. * we may race with a waker that sets them.
  1158. */
  1159. for (;;) {
  1160. unsigned int flags;
  1161. set_current_state(state);
  1162. /* Loop until we've been woken or interrupted */
  1163. flags = smp_load_acquire(&wait->flags);
  1164. if (!(flags & WQ_FLAG_WOKEN)) {
  1165. if (signal_pending_state(state, current))
  1166. break;
  1167. io_schedule();
  1168. continue;
  1169. }
  1170. /* If we were non-exclusive, we're done */
  1171. if (behavior != EXCLUSIVE)
  1172. break;
  1173. /* If the waker got the lock for us, we're done */
  1174. if (flags & WQ_FLAG_DONE)
  1175. break;
  1176. /*
  1177. * Otherwise, if we're getting the lock, we need to
  1178. * try to get it ourselves.
  1179. *
  1180. * And if that fails, we'll have to retry this all.
  1181. */
  1182. if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
  1183. goto repeat;
  1184. wait->flags |= WQ_FLAG_DONE;
  1185. break;
  1186. }
  1187. /*
  1188. * If a signal happened, this 'finish_wait()' may remove the last
  1189. * waiter from the wait-queues, but the folio waiters bit will remain
  1190. * set. That's ok. The next wakeup will take care of it, and trying
  1191. * to do it here would be difficult and prone to races.
  1192. */
  1193. finish_wait(q, wait);
  1194. if (thrashing) {
  1195. delayacct_thrashing_end(&in_thrashing);
  1196. psi_memstall_leave(&pflags);
  1197. }
  1198. /*
  1199. * NOTE! The wait->flags weren't stable until we've done the
  1200. * 'finish_wait()', and we could have exited the loop above due
  1201. * to a signal, and had a wakeup event happen after the signal
  1202. * test but before the 'finish_wait()'.
  1203. *
  1204. * So only after the finish_wait() can we reliably determine
  1205. * if we got woken up or not, so we can now figure out the final
  1206. * return value based on that state without races.
  1207. *
  1208. * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
  1209. * waiter, but an exclusive one requires WQ_FLAG_DONE.
  1210. */
  1211. if (behavior == EXCLUSIVE)
  1212. return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
  1213. return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
  1214. }
  1215. #ifdef CONFIG_MIGRATION
  1216. /**
  1217. * migration_entry_wait_on_locked - Wait for a migration entry to be removed
  1218. * @entry: migration swap entry.
  1219. * @ptl: already locked ptl. This function will drop the lock.
  1220. *
  1221. * Wait for a migration entry referencing the given page to be removed. This is
  1222. * equivalent to put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE) except
  1223. * this can be called without taking a reference on the page. Instead this
  1224. * should be called while holding the ptl for the migration entry referencing
  1225. * the page.
  1226. *
  1227. * Returns after unlocking the ptl.
  1228. *
  1229. * This follows the same logic as folio_wait_bit_common() so see the comments
  1230. * there.
  1231. */
  1232. void migration_entry_wait_on_locked(swp_entry_t entry, spinlock_t *ptl)
  1233. __releases(ptl)
  1234. {
  1235. struct wait_page_queue wait_page;
  1236. wait_queue_entry_t *wait = &wait_page.wait;
  1237. bool thrashing = false;
  1238. unsigned long pflags;
  1239. bool in_thrashing;
  1240. wait_queue_head_t *q;
  1241. struct folio *folio = pfn_swap_entry_folio(entry);
  1242. q = folio_waitqueue(folio);
  1243. if (!folio_test_uptodate(folio) && folio_test_workingset(folio)) {
  1244. delayacct_thrashing_start(&in_thrashing);
  1245. psi_memstall_enter(&pflags);
  1246. thrashing = true;
  1247. }
  1248. init_wait(wait);
  1249. wait->func = wake_page_function;
  1250. wait_page.folio = folio;
  1251. wait_page.bit_nr = PG_locked;
  1252. wait->flags = 0;
  1253. spin_lock_irq(&q->lock);
  1254. folio_set_waiters(folio);
  1255. if (!folio_trylock_flag(folio, PG_locked, wait))
  1256. __add_wait_queue_entry_tail(q, wait);
  1257. spin_unlock_irq(&q->lock);
  1258. /*
  1259. * If a migration entry exists for the page the migration path must hold
  1260. * a valid reference to the page, and it must take the ptl to remove the
  1261. * migration entry. So the page is valid until the ptl is dropped.
  1262. */
  1263. spin_unlock(ptl);
  1264. for (;;) {
  1265. unsigned int flags;
  1266. set_current_state(TASK_UNINTERRUPTIBLE);
  1267. /* Loop until we've been woken or interrupted */
  1268. flags = smp_load_acquire(&wait->flags);
  1269. if (!(flags & WQ_FLAG_WOKEN)) {
  1270. if (signal_pending_state(TASK_UNINTERRUPTIBLE, current))
  1271. break;
  1272. io_schedule();
  1273. continue;
  1274. }
  1275. break;
  1276. }
  1277. finish_wait(q, wait);
  1278. if (thrashing) {
  1279. delayacct_thrashing_end(&in_thrashing);
  1280. psi_memstall_leave(&pflags);
  1281. }
  1282. }
  1283. #endif
  1284. void folio_wait_bit(struct folio *folio, int bit_nr)
  1285. {
  1286. folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
  1287. }
  1288. EXPORT_SYMBOL(folio_wait_bit);
  1289. int folio_wait_bit_killable(struct folio *folio, int bit_nr)
  1290. {
  1291. return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
  1292. }
  1293. EXPORT_SYMBOL(folio_wait_bit_killable);
  1294. /**
  1295. * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
  1296. * @folio: The folio to wait for.
  1297. * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
  1298. *
  1299. * The caller should hold a reference on @folio. They expect the page to
  1300. * become unlocked relatively soon, but do not wish to hold up migration
  1301. * (for example) by holding the reference while waiting for the folio to
  1302. * come unlocked. After this function returns, the caller should not
  1303. * dereference @folio.
  1304. *
  1305. * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
  1306. */
  1307. static int folio_put_wait_locked(struct folio *folio, int state)
  1308. {
  1309. return folio_wait_bit_common(folio, PG_locked, state, DROP);
  1310. }
  1311. /**
  1312. * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
  1313. * @folio: Folio defining the wait queue of interest
  1314. * @waiter: Waiter to add to the queue
  1315. *
  1316. * Add an arbitrary @waiter to the wait queue for the nominated @folio.
  1317. */
  1318. void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
  1319. {
  1320. wait_queue_head_t *q = folio_waitqueue(folio);
  1321. unsigned long flags;
  1322. spin_lock_irqsave(&q->lock, flags);
  1323. __add_wait_queue_entry_tail(q, waiter);
  1324. folio_set_waiters(folio);
  1325. spin_unlock_irqrestore(&q->lock, flags);
  1326. }
  1327. EXPORT_SYMBOL_GPL(folio_add_wait_queue);
  1328. /**
  1329. * folio_unlock - Unlock a locked folio.
  1330. * @folio: The folio.
  1331. *
  1332. * Unlocks the folio and wakes up any thread sleeping on the page lock.
  1333. *
  1334. * Context: May be called from interrupt or process context. May not be
  1335. * called from NMI context.
  1336. */
  1337. void folio_unlock(struct folio *folio)
  1338. {
  1339. /* Bit 7 allows x86 to check the byte's sign bit */
  1340. BUILD_BUG_ON(PG_waiters != 7);
  1341. BUILD_BUG_ON(PG_locked > 7);
  1342. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  1343. if (folio_xor_flags_has_waiters(folio, 1 << PG_locked))
  1344. folio_wake_bit(folio, PG_locked);
  1345. }
  1346. EXPORT_SYMBOL(folio_unlock);
  1347. /**
  1348. * folio_end_read - End read on a folio.
  1349. * @folio: The folio.
  1350. * @success: True if all reads completed successfully.
  1351. *
  1352. * When all reads against a folio have completed, filesystems should
  1353. * call this function to let the pagecache know that no more reads
  1354. * are outstanding. This will unlock the folio and wake up any thread
  1355. * sleeping on the lock. The folio will also be marked uptodate if all
  1356. * reads succeeded.
  1357. *
  1358. * Context: May be called from interrupt or process context. May not be
  1359. * called from NMI context.
  1360. */
  1361. void folio_end_read(struct folio *folio, bool success)
  1362. {
  1363. unsigned long mask = 1 << PG_locked;
  1364. /* Must be in bottom byte for x86 to work */
  1365. BUILD_BUG_ON(PG_uptodate > 7);
  1366. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  1367. VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio);
  1368. if (likely(success))
  1369. mask |= 1 << PG_uptodate;
  1370. if (folio_xor_flags_has_waiters(folio, mask))
  1371. folio_wake_bit(folio, PG_locked);
  1372. }
  1373. EXPORT_SYMBOL(folio_end_read);
  1374. /**
  1375. * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
  1376. * @folio: The folio.
  1377. *
  1378. * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
  1379. * it. The folio reference held for PG_private_2 being set is released.
  1380. *
  1381. * This is, for example, used when a netfs folio is being written to a local
  1382. * disk cache, thereby allowing writes to the cache for the same folio to be
  1383. * serialised.
  1384. */
  1385. void folio_end_private_2(struct folio *folio)
  1386. {
  1387. VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
  1388. clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
  1389. folio_wake_bit(folio, PG_private_2);
  1390. folio_put(folio);
  1391. }
  1392. EXPORT_SYMBOL(folio_end_private_2);
  1393. /**
  1394. * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
  1395. * @folio: The folio to wait on.
  1396. *
  1397. * Wait for PG_private_2 to be cleared on a folio.
  1398. */
  1399. void folio_wait_private_2(struct folio *folio)
  1400. {
  1401. while (folio_test_private_2(folio))
  1402. folio_wait_bit(folio, PG_private_2);
  1403. }
  1404. EXPORT_SYMBOL(folio_wait_private_2);
  1405. /**
  1406. * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
  1407. * @folio: The folio to wait on.
  1408. *
  1409. * Wait for PG_private_2 to be cleared on a folio or until a fatal signal is
  1410. * received by the calling task.
  1411. *
  1412. * Return:
  1413. * - 0 if successful.
  1414. * - -EINTR if a fatal signal was encountered.
  1415. */
  1416. int folio_wait_private_2_killable(struct folio *folio)
  1417. {
  1418. int ret = 0;
  1419. while (folio_test_private_2(folio)) {
  1420. ret = folio_wait_bit_killable(folio, PG_private_2);
  1421. if (ret < 0)
  1422. break;
  1423. }
  1424. return ret;
  1425. }
  1426. EXPORT_SYMBOL(folio_wait_private_2_killable);
  1427. /**
  1428. * folio_end_writeback - End writeback against a folio.
  1429. * @folio: The folio.
  1430. *
  1431. * The folio must actually be under writeback.
  1432. *
  1433. * Context: May be called from process or interrupt context.
  1434. */
  1435. void folio_end_writeback(struct folio *folio)
  1436. {
  1437. VM_BUG_ON_FOLIO(!folio_test_writeback(folio), folio);
  1438. /*
  1439. * folio_test_clear_reclaim() could be used here but it is an
  1440. * atomic operation and overkill in this particular case. Failing
  1441. * to shuffle a folio marked for immediate reclaim is too mild
  1442. * a gain to justify taking an atomic operation penalty at the
  1443. * end of every folio writeback.
  1444. */
  1445. if (folio_test_reclaim(folio)) {
  1446. folio_clear_reclaim(folio);
  1447. folio_rotate_reclaimable(folio);
  1448. }
  1449. /*
  1450. * Writeback does not hold a folio reference of its own, relying
  1451. * on truncation to wait for the clearing of PG_writeback.
  1452. * But here we must make sure that the folio is not freed and
  1453. * reused before the folio_wake_bit().
  1454. */
  1455. folio_get(folio);
  1456. if (__folio_end_writeback(folio))
  1457. folio_wake_bit(folio, PG_writeback);
  1458. acct_reclaim_writeback(folio);
  1459. folio_put(folio);
  1460. }
  1461. EXPORT_SYMBOL(folio_end_writeback);
  1462. /**
  1463. * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
  1464. * @folio: The folio to lock
  1465. */
  1466. void __folio_lock(struct folio *folio)
  1467. {
  1468. folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
  1469. EXCLUSIVE);
  1470. }
  1471. EXPORT_SYMBOL(__folio_lock);
  1472. int __folio_lock_killable(struct folio *folio)
  1473. {
  1474. return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
  1475. EXCLUSIVE);
  1476. }
  1477. EXPORT_SYMBOL_GPL(__folio_lock_killable);
  1478. static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
  1479. {
  1480. struct wait_queue_head *q = folio_waitqueue(folio);
  1481. int ret;
  1482. wait->folio = folio;
  1483. wait->bit_nr = PG_locked;
  1484. spin_lock_irq(&q->lock);
  1485. __add_wait_queue_entry_tail(q, &wait->wait);
  1486. folio_set_waiters(folio);
  1487. ret = !folio_trylock(folio);
  1488. /*
  1489. * If we were successful now, we know we're still on the
  1490. * waitqueue as we're still under the lock. This means it's
  1491. * safe to remove and return success, we know the callback
  1492. * isn't going to trigger.
  1493. */
  1494. if (!ret)
  1495. __remove_wait_queue(q, &wait->wait);
  1496. else
  1497. ret = -EIOCBQUEUED;
  1498. spin_unlock_irq(&q->lock);
  1499. return ret;
  1500. }
  1501. /*
  1502. * Return values:
  1503. * 0 - folio is locked.
  1504. * non-zero - folio is not locked.
  1505. * mmap_lock or per-VMA lock has been released (mmap_read_unlock() or
  1506. * vma_end_read()), unless flags had both FAULT_FLAG_ALLOW_RETRY and
  1507. * FAULT_FLAG_RETRY_NOWAIT set, in which case the lock is still held.
  1508. *
  1509. * If neither ALLOW_RETRY nor KILLABLE are set, will always return 0
  1510. * with the folio locked and the mmap_lock/per-VMA lock is left unperturbed.
  1511. */
  1512. vm_fault_t __folio_lock_or_retry(struct folio *folio, struct vm_fault *vmf)
  1513. {
  1514. unsigned int flags = vmf->flags;
  1515. if (fault_flag_allow_retry_first(flags)) {
  1516. /*
  1517. * CAUTION! In this case, mmap_lock/per-VMA lock is not
  1518. * released even though returning VM_FAULT_RETRY.
  1519. */
  1520. if (flags & FAULT_FLAG_RETRY_NOWAIT)
  1521. return VM_FAULT_RETRY;
  1522. release_fault_lock(vmf);
  1523. if (flags & FAULT_FLAG_KILLABLE)
  1524. folio_wait_locked_killable(folio);
  1525. else
  1526. folio_wait_locked(folio);
  1527. return VM_FAULT_RETRY;
  1528. }
  1529. if (flags & FAULT_FLAG_KILLABLE) {
  1530. bool ret;
  1531. ret = __folio_lock_killable(folio);
  1532. if (ret) {
  1533. release_fault_lock(vmf);
  1534. return VM_FAULT_RETRY;
  1535. }
  1536. } else {
  1537. __folio_lock(folio);
  1538. }
  1539. return 0;
  1540. }
  1541. /**
  1542. * page_cache_next_miss() - Find the next gap in the page cache.
  1543. * @mapping: Mapping.
  1544. * @index: Index.
  1545. * @max_scan: Maximum range to search.
  1546. *
  1547. * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
  1548. * gap with the lowest index.
  1549. *
  1550. * This function may be called under the rcu_read_lock. However, this will
  1551. * not atomically search a snapshot of the cache at a single point in time.
  1552. * For example, if a gap is created at index 5, then subsequently a gap is
  1553. * created at index 10, page_cache_next_miss covering both indices may
  1554. * return 10 if called under the rcu_read_lock.
  1555. *
  1556. * Return: The index of the gap if found, otherwise an index outside the
  1557. * range specified (in which case 'return - index >= max_scan' will be true).
  1558. * In the rare case of index wrap-around, 0 will be returned.
  1559. */
  1560. pgoff_t page_cache_next_miss(struct address_space *mapping,
  1561. pgoff_t index, unsigned long max_scan)
  1562. {
  1563. XA_STATE(xas, &mapping->i_pages, index);
  1564. while (max_scan--) {
  1565. void *entry = xas_next(&xas);
  1566. if (!entry || xa_is_value(entry))
  1567. return xas.xa_index;
  1568. if (xas.xa_index == 0)
  1569. return 0;
  1570. }
  1571. return index + max_scan;
  1572. }
  1573. EXPORT_SYMBOL(page_cache_next_miss);
  1574. /**
  1575. * page_cache_prev_miss() - Find the previous gap in the page cache.
  1576. * @mapping: Mapping.
  1577. * @index: Index.
  1578. * @max_scan: Maximum range to search.
  1579. *
  1580. * Search the range [max(index - max_scan + 1, 0), index] for the
  1581. * gap with the highest index.
  1582. *
  1583. * This function may be called under the rcu_read_lock. However, this will
  1584. * not atomically search a snapshot of the cache at a single point in time.
  1585. * For example, if a gap is created at index 10, then subsequently a gap is
  1586. * created at index 5, page_cache_prev_miss() covering both indices may
  1587. * return 5 if called under the rcu_read_lock.
  1588. *
  1589. * Return: The index of the gap if found, otherwise an index outside the
  1590. * range specified (in which case 'index - return >= max_scan' will be true).
  1591. * In the rare case of wrap-around, ULONG_MAX will be returned.
  1592. */
  1593. pgoff_t page_cache_prev_miss(struct address_space *mapping,
  1594. pgoff_t index, unsigned long max_scan)
  1595. {
  1596. XA_STATE(xas, &mapping->i_pages, index);
  1597. while (max_scan--) {
  1598. void *entry = xas_prev(&xas);
  1599. if (!entry || xa_is_value(entry))
  1600. break;
  1601. if (xas.xa_index == ULONG_MAX)
  1602. break;
  1603. }
  1604. return xas.xa_index;
  1605. }
  1606. EXPORT_SYMBOL(page_cache_prev_miss);
  1607. /*
  1608. * Lockless page cache protocol:
  1609. * On the lookup side:
  1610. * 1. Load the folio from i_pages
  1611. * 2. Increment the refcount if it's not zero
  1612. * 3. If the folio is not found by xas_reload(), put the refcount and retry
  1613. *
  1614. * On the removal side:
  1615. * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
  1616. * B. Remove the page from i_pages
  1617. * C. Return the page to the page allocator
  1618. *
  1619. * This means that any page may have its reference count temporarily
  1620. * increased by a speculative page cache (or GUP-fast) lookup as it can
  1621. * be allocated by another user before the RCU grace period expires.
  1622. * Because the refcount temporarily acquired here may end up being the
  1623. * last refcount on the page, any page allocation must be freeable by
  1624. * folio_put().
  1625. */
  1626. /*
  1627. * filemap_get_entry - Get a page cache entry.
  1628. * @mapping: the address_space to search
  1629. * @index: The page cache index.
  1630. *
  1631. * Looks up the page cache entry at @mapping & @index. If it is a folio,
  1632. * it is returned with an increased refcount. If it is a shadow entry
  1633. * of a previously evicted folio, or a swap entry from shmem/tmpfs,
  1634. * it is returned without further action.
  1635. *
  1636. * Return: The folio, swap or shadow entry, %NULL if nothing is found.
  1637. */
  1638. void *filemap_get_entry(struct address_space *mapping, pgoff_t index)
  1639. {
  1640. XA_STATE(xas, &mapping->i_pages, index);
  1641. struct folio *folio;
  1642. rcu_read_lock();
  1643. repeat:
  1644. xas_reset(&xas);
  1645. folio = xas_load(&xas);
  1646. if (xas_retry(&xas, folio))
  1647. goto repeat;
  1648. /*
  1649. * A shadow entry of a recently evicted page, or a swap entry from
  1650. * shmem/tmpfs. Return it without attempting to raise page count.
  1651. */
  1652. if (!folio || xa_is_value(folio))
  1653. goto out;
  1654. if (!folio_try_get(folio))
  1655. goto repeat;
  1656. if (unlikely(folio != xas_reload(&xas))) {
  1657. folio_put(folio);
  1658. goto repeat;
  1659. }
  1660. out:
  1661. rcu_read_unlock();
  1662. return folio;
  1663. }
  1664. /**
  1665. * __filemap_get_folio - Find and get a reference to a folio.
  1666. * @mapping: The address_space to search.
  1667. * @index: The page index.
  1668. * @fgp_flags: %FGP flags modify how the folio is returned.
  1669. * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
  1670. *
  1671. * Looks up the page cache entry at @mapping & @index.
  1672. *
  1673. * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
  1674. * if the %GFP flags specified for %FGP_CREAT are atomic.
  1675. *
  1676. * If this function returns a folio, it is returned with an increased refcount.
  1677. *
  1678. * Return: The found folio or an ERR_PTR() otherwise.
  1679. */
  1680. struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
  1681. fgf_t fgp_flags, gfp_t gfp)
  1682. {
  1683. struct folio *folio;
  1684. repeat:
  1685. folio = filemap_get_entry(mapping, index);
  1686. if (xa_is_value(folio))
  1687. folio = NULL;
  1688. if (!folio)
  1689. goto no_page;
  1690. if (fgp_flags & FGP_LOCK) {
  1691. if (fgp_flags & FGP_NOWAIT) {
  1692. if (!folio_trylock(folio)) {
  1693. folio_put(folio);
  1694. return ERR_PTR(-EAGAIN);
  1695. }
  1696. } else {
  1697. folio_lock(folio);
  1698. }
  1699. /* Has the page been truncated? */
  1700. if (unlikely(folio->mapping != mapping)) {
  1701. folio_unlock(folio);
  1702. folio_put(folio);
  1703. goto repeat;
  1704. }
  1705. VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
  1706. }
  1707. if (fgp_flags & FGP_ACCESSED)
  1708. folio_mark_accessed(folio);
  1709. else if (fgp_flags & FGP_WRITE) {
  1710. /* Clear idle flag for buffer write */
  1711. if (folio_test_idle(folio))
  1712. folio_clear_idle(folio);
  1713. }
  1714. if (fgp_flags & FGP_STABLE)
  1715. folio_wait_stable(folio);
  1716. no_page:
  1717. if (!folio && (fgp_flags & FGP_CREAT)) {
  1718. unsigned int min_order = mapping_min_folio_order(mapping);
  1719. unsigned int order = max(min_order, FGF_GET_ORDER(fgp_flags));
  1720. int err;
  1721. index = mapping_align_index(mapping, index);
  1722. if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
  1723. gfp |= __GFP_WRITE;
  1724. if (fgp_flags & FGP_NOFS)
  1725. gfp &= ~__GFP_FS;
  1726. if (fgp_flags & FGP_NOWAIT) {
  1727. gfp &= ~GFP_KERNEL;
  1728. gfp |= GFP_NOWAIT | __GFP_NOWARN;
  1729. }
  1730. if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
  1731. fgp_flags |= FGP_LOCK;
  1732. if (order > mapping_max_folio_order(mapping))
  1733. order = mapping_max_folio_order(mapping);
  1734. /* If we're not aligned, allocate a smaller folio */
  1735. if (index & ((1UL << order) - 1))
  1736. order = __ffs(index);
  1737. do {
  1738. gfp_t alloc_gfp = gfp;
  1739. err = -ENOMEM;
  1740. if (order > min_order)
  1741. alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN;
  1742. folio = filemap_alloc_folio(alloc_gfp, order);
  1743. if (!folio)
  1744. continue;
  1745. /* Init accessed so avoid atomic mark_page_accessed later */
  1746. if (fgp_flags & FGP_ACCESSED)
  1747. __folio_set_referenced(folio);
  1748. err = filemap_add_folio(mapping, folio, index, gfp);
  1749. if (!err)
  1750. break;
  1751. folio_put(folio);
  1752. folio = NULL;
  1753. } while (order-- > min_order);
  1754. if (err == -EEXIST)
  1755. goto repeat;
  1756. if (err)
  1757. return ERR_PTR(err);
  1758. /*
  1759. * filemap_add_folio locks the page, and for mmap
  1760. * we expect an unlocked page.
  1761. */
  1762. if (folio && (fgp_flags & FGP_FOR_MMAP))
  1763. folio_unlock(folio);
  1764. }
  1765. if (!folio)
  1766. return ERR_PTR(-ENOENT);
  1767. return folio;
  1768. }
  1769. EXPORT_SYMBOL(__filemap_get_folio);
  1770. static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
  1771. xa_mark_t mark)
  1772. {
  1773. struct folio *folio;
  1774. retry:
  1775. if (mark == XA_PRESENT)
  1776. folio = xas_find(xas, max);
  1777. else
  1778. folio = xas_find_marked(xas, max, mark);
  1779. if (xas_retry(xas, folio))
  1780. goto retry;
  1781. /*
  1782. * A shadow entry of a recently evicted page, a swap
  1783. * entry from shmem/tmpfs or a DAX entry. Return it
  1784. * without attempting to raise page count.
  1785. */
  1786. if (!folio || xa_is_value(folio))
  1787. return folio;
  1788. if (!folio_try_get(folio))
  1789. goto reset;
  1790. if (unlikely(folio != xas_reload(xas))) {
  1791. folio_put(folio);
  1792. goto reset;
  1793. }
  1794. return folio;
  1795. reset:
  1796. xas_reset(xas);
  1797. goto retry;
  1798. }
  1799. /**
  1800. * find_get_entries - gang pagecache lookup
  1801. * @mapping: The address_space to search
  1802. * @start: The starting page cache index
  1803. * @end: The final page index (inclusive).
  1804. * @fbatch: Where the resulting entries are placed.
  1805. * @indices: The cache indices corresponding to the entries in @entries
  1806. *
  1807. * find_get_entries() will search for and return a batch of entries in
  1808. * the mapping. The entries are placed in @fbatch. find_get_entries()
  1809. * takes a reference on any actual folios it returns.
  1810. *
  1811. * The entries have ascending indexes. The indices may not be consecutive
  1812. * due to not-present entries or large folios.
  1813. *
  1814. * Any shadow entries of evicted folios, or swap entries from
  1815. * shmem/tmpfs, are included in the returned array.
  1816. *
  1817. * Return: The number of entries which were found.
  1818. */
  1819. unsigned find_get_entries(struct address_space *mapping, pgoff_t *start,
  1820. pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
  1821. {
  1822. XA_STATE(xas, &mapping->i_pages, *start);
  1823. struct folio *folio;
  1824. rcu_read_lock();
  1825. while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
  1826. indices[fbatch->nr] = xas.xa_index;
  1827. if (!folio_batch_add(fbatch, folio))
  1828. break;
  1829. }
  1830. if (folio_batch_count(fbatch)) {
  1831. unsigned long nr;
  1832. int idx = folio_batch_count(fbatch) - 1;
  1833. folio = fbatch->folios[idx];
  1834. if (!xa_is_value(folio))
  1835. nr = folio_nr_pages(folio);
  1836. else
  1837. nr = 1 << xa_get_order(&mapping->i_pages, indices[idx]);
  1838. *start = round_down(indices[idx] + nr, nr);
  1839. }
  1840. rcu_read_unlock();
  1841. return folio_batch_count(fbatch);
  1842. }
  1843. /**
  1844. * find_lock_entries - Find a batch of pagecache entries.
  1845. * @mapping: The address_space to search.
  1846. * @start: The starting page cache index.
  1847. * @end: The final page index (inclusive).
  1848. * @fbatch: Where the resulting entries are placed.
  1849. * @indices: The cache indices of the entries in @fbatch.
  1850. *
  1851. * find_lock_entries() will return a batch of entries from @mapping.
  1852. * Swap, shadow and DAX entries are included. Folios are returned
  1853. * locked and with an incremented refcount. Folios which are locked
  1854. * by somebody else or under writeback are skipped. Folios which are
  1855. * partially outside the range are not returned.
  1856. *
  1857. * The entries have ascending indexes. The indices may not be consecutive
  1858. * due to not-present entries, large folios, folios which could not be
  1859. * locked or folios under writeback.
  1860. *
  1861. * Return: The number of entries which were found.
  1862. */
  1863. unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,
  1864. pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
  1865. {
  1866. XA_STATE(xas, &mapping->i_pages, *start);
  1867. struct folio *folio;
  1868. rcu_read_lock();
  1869. while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
  1870. unsigned long base;
  1871. unsigned long nr;
  1872. if (!xa_is_value(folio)) {
  1873. nr = folio_nr_pages(folio);
  1874. base = folio->index;
  1875. /* Omit large folio which begins before the start */
  1876. if (base < *start)
  1877. goto put;
  1878. /* Omit large folio which extends beyond the end */
  1879. if (base + nr - 1 > end)
  1880. goto put;
  1881. if (!folio_trylock(folio))
  1882. goto put;
  1883. if (folio->mapping != mapping ||
  1884. folio_test_writeback(folio))
  1885. goto unlock;
  1886. VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
  1887. folio);
  1888. } else {
  1889. nr = 1 << xas_get_order(&xas);
  1890. base = xas.xa_index & ~(nr - 1);
  1891. /* Omit order>0 value which begins before the start */
  1892. if (base < *start)
  1893. continue;
  1894. /* Omit order>0 value which extends beyond the end */
  1895. if (base + nr - 1 > end)
  1896. break;
  1897. }
  1898. /* Update start now so that last update is correct on return */
  1899. *start = base + nr;
  1900. indices[fbatch->nr] = xas.xa_index;
  1901. if (!folio_batch_add(fbatch, folio))
  1902. break;
  1903. continue;
  1904. unlock:
  1905. folio_unlock(folio);
  1906. put:
  1907. folio_put(folio);
  1908. }
  1909. rcu_read_unlock();
  1910. return folio_batch_count(fbatch);
  1911. }
  1912. /**
  1913. * filemap_get_folios - Get a batch of folios
  1914. * @mapping: The address_space to search
  1915. * @start: The starting page index
  1916. * @end: The final page index (inclusive)
  1917. * @fbatch: The batch to fill.
  1918. *
  1919. * Search for and return a batch of folios in the mapping starting at
  1920. * index @start and up to index @end (inclusive). The folios are returned
  1921. * in @fbatch with an elevated reference count.
  1922. *
  1923. * Return: The number of folios which were found.
  1924. * We also update @start to index the next folio for the traversal.
  1925. */
  1926. unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start,
  1927. pgoff_t end, struct folio_batch *fbatch)
  1928. {
  1929. return filemap_get_folios_tag(mapping, start, end, XA_PRESENT, fbatch);
  1930. }
  1931. EXPORT_SYMBOL(filemap_get_folios);
  1932. /**
  1933. * filemap_get_folios_contig - Get a batch of contiguous folios
  1934. * @mapping: The address_space to search
  1935. * @start: The starting page index
  1936. * @end: The final page index (inclusive)
  1937. * @fbatch: The batch to fill
  1938. *
  1939. * filemap_get_folios_contig() works exactly like filemap_get_folios(),
  1940. * except the returned folios are guaranteed to be contiguous. This may
  1941. * not return all contiguous folios if the batch gets filled up.
  1942. *
  1943. * Return: The number of folios found.
  1944. * Also update @start to be positioned for traversal of the next folio.
  1945. */
  1946. unsigned filemap_get_folios_contig(struct address_space *mapping,
  1947. pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
  1948. {
  1949. XA_STATE(xas, &mapping->i_pages, *start);
  1950. unsigned long nr;
  1951. struct folio *folio;
  1952. rcu_read_lock();
  1953. for (folio = xas_load(&xas); folio && xas.xa_index <= end;
  1954. folio = xas_next(&xas)) {
  1955. if (xas_retry(&xas, folio))
  1956. continue;
  1957. /*
  1958. * If the entry has been swapped out, we can stop looking.
  1959. * No current caller is looking for DAX entries.
  1960. */
  1961. if (xa_is_value(folio))
  1962. goto update_start;
  1963. /* If we landed in the middle of a THP, continue at its end. */
  1964. if (xa_is_sibling(folio))
  1965. goto update_start;
  1966. if (!folio_try_get(folio))
  1967. goto retry;
  1968. if (unlikely(folio != xas_reload(&xas)))
  1969. goto put_folio;
  1970. if (!folio_batch_add(fbatch, folio)) {
  1971. nr = folio_nr_pages(folio);
  1972. *start = folio->index + nr;
  1973. goto out;
  1974. }
  1975. continue;
  1976. put_folio:
  1977. folio_put(folio);
  1978. retry:
  1979. xas_reset(&xas);
  1980. }
  1981. update_start:
  1982. nr = folio_batch_count(fbatch);
  1983. if (nr) {
  1984. folio = fbatch->folios[nr - 1];
  1985. *start = folio_next_index(folio);
  1986. }
  1987. out:
  1988. rcu_read_unlock();
  1989. return folio_batch_count(fbatch);
  1990. }
  1991. EXPORT_SYMBOL(filemap_get_folios_contig);
  1992. /**
  1993. * filemap_get_folios_tag - Get a batch of folios matching @tag
  1994. * @mapping: The address_space to search
  1995. * @start: The starting page index
  1996. * @end: The final page index (inclusive)
  1997. * @tag: The tag index
  1998. * @fbatch: The batch to fill
  1999. *
  2000. * The first folio may start before @start; if it does, it will contain
  2001. * @start. The final folio may extend beyond @end; if it does, it will
  2002. * contain @end. The folios have ascending indices. There may be gaps
  2003. * between the folios if there are indices which have no folio in the
  2004. * page cache. If folios are added to or removed from the page cache
  2005. * while this is running, they may or may not be found by this call.
  2006. * Only returns folios that are tagged with @tag.
  2007. *
  2008. * Return: The number of folios found.
  2009. * Also update @start to index the next folio for traversal.
  2010. */
  2011. unsigned filemap_get_folios_tag(struct address_space *mapping, pgoff_t *start,
  2012. pgoff_t end, xa_mark_t tag, struct folio_batch *fbatch)
  2013. {
  2014. XA_STATE(xas, &mapping->i_pages, *start);
  2015. struct folio *folio;
  2016. rcu_read_lock();
  2017. while ((folio = find_get_entry(&xas, end, tag)) != NULL) {
  2018. /*
  2019. * Shadow entries should never be tagged, but this iteration
  2020. * is lockless so there is a window for page reclaim to evict
  2021. * a page we saw tagged. Skip over it.
  2022. */
  2023. if (xa_is_value(folio))
  2024. continue;
  2025. if (!folio_batch_add(fbatch, folio)) {
  2026. unsigned long nr = folio_nr_pages(folio);
  2027. *start = folio->index + nr;
  2028. goto out;
  2029. }
  2030. }
  2031. /*
  2032. * We come here when there is no page beyond @end. We take care to not
  2033. * overflow the index @start as it confuses some of the callers. This
  2034. * breaks the iteration when there is a page at index -1 but that is
  2035. * already broke anyway.
  2036. */
  2037. if (end == (pgoff_t)-1)
  2038. *start = (pgoff_t)-1;
  2039. else
  2040. *start = end + 1;
  2041. out:
  2042. rcu_read_unlock();
  2043. return folio_batch_count(fbatch);
  2044. }
  2045. EXPORT_SYMBOL(filemap_get_folios_tag);
  2046. /*
  2047. * CD/DVDs are error prone. When a medium error occurs, the driver may fail
  2048. * a _large_ part of the i/o request. Imagine the worst scenario:
  2049. *
  2050. * ---R__________________________________________B__________
  2051. * ^ reading here ^ bad block(assume 4k)
  2052. *
  2053. * read(R) => miss => readahead(R...B) => media error => frustrating retries
  2054. * => failing the whole request => read(R) => read(R+1) =>
  2055. * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
  2056. * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
  2057. * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
  2058. *
  2059. * It is going insane. Fix it by quickly scaling down the readahead size.
  2060. */
  2061. static void shrink_readahead_size_eio(struct file_ra_state *ra)
  2062. {
  2063. ra->ra_pages /= 4;
  2064. }
  2065. /*
  2066. * filemap_get_read_batch - Get a batch of folios for read
  2067. *
  2068. * Get a batch of folios which represent a contiguous range of bytes in
  2069. * the file. No exceptional entries will be returned. If @index is in
  2070. * the middle of a folio, the entire folio will be returned. The last
  2071. * folio in the batch may have the readahead flag set or the uptodate flag
  2072. * clear so that the caller can take the appropriate action.
  2073. */
  2074. static void filemap_get_read_batch(struct address_space *mapping,
  2075. pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
  2076. {
  2077. XA_STATE(xas, &mapping->i_pages, index);
  2078. struct folio *folio;
  2079. rcu_read_lock();
  2080. for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
  2081. if (xas_retry(&xas, folio))
  2082. continue;
  2083. if (xas.xa_index > max || xa_is_value(folio))
  2084. break;
  2085. if (xa_is_sibling(folio))
  2086. break;
  2087. if (!folio_try_get(folio))
  2088. goto retry;
  2089. if (unlikely(folio != xas_reload(&xas)))
  2090. goto put_folio;
  2091. if (!folio_batch_add(fbatch, folio))
  2092. break;
  2093. if (!folio_test_uptodate(folio))
  2094. break;
  2095. if (folio_test_readahead(folio))
  2096. break;
  2097. xas_advance(&xas, folio_next_index(folio) - 1);
  2098. continue;
  2099. put_folio:
  2100. folio_put(folio);
  2101. retry:
  2102. xas_reset(&xas);
  2103. }
  2104. rcu_read_unlock();
  2105. }
  2106. static int filemap_read_folio(struct file *file, filler_t filler,
  2107. struct folio *folio)
  2108. {
  2109. bool workingset = folio_test_workingset(folio);
  2110. unsigned long pflags;
  2111. int error;
  2112. /* Start the actual read. The read will unlock the page. */
  2113. if (unlikely(workingset))
  2114. psi_memstall_enter(&pflags);
  2115. error = filler(file, folio);
  2116. if (unlikely(workingset))
  2117. psi_memstall_leave(&pflags);
  2118. if (error)
  2119. return error;
  2120. error = folio_wait_locked_killable(folio);
  2121. if (error)
  2122. return error;
  2123. if (folio_test_uptodate(folio))
  2124. return 0;
  2125. if (file)
  2126. shrink_readahead_size_eio(&file->f_ra);
  2127. return -EIO;
  2128. }
  2129. static bool filemap_range_uptodate(struct address_space *mapping,
  2130. loff_t pos, size_t count, struct folio *folio,
  2131. bool need_uptodate)
  2132. {
  2133. if (folio_test_uptodate(folio))
  2134. return true;
  2135. /* pipes can't handle partially uptodate pages */
  2136. if (need_uptodate)
  2137. return false;
  2138. if (!mapping->a_ops->is_partially_uptodate)
  2139. return false;
  2140. if (mapping->host->i_blkbits >= folio_shift(folio))
  2141. return false;
  2142. if (folio_pos(folio) > pos) {
  2143. count -= folio_pos(folio) - pos;
  2144. pos = 0;
  2145. } else {
  2146. pos -= folio_pos(folio);
  2147. }
  2148. return mapping->a_ops->is_partially_uptodate(folio, pos, count);
  2149. }
  2150. static int filemap_update_page(struct kiocb *iocb,
  2151. struct address_space *mapping, size_t count,
  2152. struct folio *folio, bool need_uptodate)
  2153. {
  2154. int error;
  2155. if (iocb->ki_flags & IOCB_NOWAIT) {
  2156. if (!filemap_invalidate_trylock_shared(mapping))
  2157. return -EAGAIN;
  2158. } else {
  2159. filemap_invalidate_lock_shared(mapping);
  2160. }
  2161. if (!folio_trylock(folio)) {
  2162. error = -EAGAIN;
  2163. if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
  2164. goto unlock_mapping;
  2165. if (!(iocb->ki_flags & IOCB_WAITQ)) {
  2166. filemap_invalidate_unlock_shared(mapping);
  2167. /*
  2168. * This is where we usually end up waiting for a
  2169. * previously submitted readahead to finish.
  2170. */
  2171. folio_put_wait_locked(folio, TASK_KILLABLE);
  2172. return AOP_TRUNCATED_PAGE;
  2173. }
  2174. error = __folio_lock_async(folio, iocb->ki_waitq);
  2175. if (error)
  2176. goto unlock_mapping;
  2177. }
  2178. error = AOP_TRUNCATED_PAGE;
  2179. if (!folio->mapping)
  2180. goto unlock;
  2181. error = 0;
  2182. if (filemap_range_uptodate(mapping, iocb->ki_pos, count, folio,
  2183. need_uptodate))
  2184. goto unlock;
  2185. error = -EAGAIN;
  2186. if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
  2187. goto unlock;
  2188. error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio,
  2189. folio);
  2190. goto unlock_mapping;
  2191. unlock:
  2192. folio_unlock(folio);
  2193. unlock_mapping:
  2194. filemap_invalidate_unlock_shared(mapping);
  2195. if (error == AOP_TRUNCATED_PAGE)
  2196. folio_put(folio);
  2197. return error;
  2198. }
  2199. static int filemap_create_folio(struct file *file,
  2200. struct address_space *mapping, loff_t pos,
  2201. struct folio_batch *fbatch)
  2202. {
  2203. struct folio *folio;
  2204. int error;
  2205. unsigned int min_order = mapping_min_folio_order(mapping);
  2206. pgoff_t index;
  2207. folio = filemap_alloc_folio(mapping_gfp_mask(mapping), min_order);
  2208. if (!folio)
  2209. return -ENOMEM;
  2210. /*
  2211. * Protect against truncate / hole punch. Grabbing invalidate_lock
  2212. * here assures we cannot instantiate and bring uptodate new
  2213. * pagecache folios after evicting page cache during truncate
  2214. * and before actually freeing blocks. Note that we could
  2215. * release invalidate_lock after inserting the folio into
  2216. * the page cache as the locked folio would then be enough to
  2217. * synchronize with hole punching. But there are code paths
  2218. * such as filemap_update_page() filling in partially uptodate
  2219. * pages or ->readahead() that need to hold invalidate_lock
  2220. * while mapping blocks for IO so let's hold the lock here as
  2221. * well to keep locking rules simple.
  2222. */
  2223. filemap_invalidate_lock_shared(mapping);
  2224. index = (pos >> (PAGE_SHIFT + min_order)) << min_order;
  2225. error = filemap_add_folio(mapping, folio, index,
  2226. mapping_gfp_constraint(mapping, GFP_KERNEL));
  2227. if (error == -EEXIST)
  2228. error = AOP_TRUNCATED_PAGE;
  2229. if (error)
  2230. goto error;
  2231. error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
  2232. if (error)
  2233. goto error;
  2234. filemap_invalidate_unlock_shared(mapping);
  2235. folio_batch_add(fbatch, folio);
  2236. return 0;
  2237. error:
  2238. filemap_invalidate_unlock_shared(mapping);
  2239. folio_put(folio);
  2240. return error;
  2241. }
  2242. static int filemap_readahead(struct kiocb *iocb, struct file *file,
  2243. struct address_space *mapping, struct folio *folio,
  2244. pgoff_t last_index)
  2245. {
  2246. DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
  2247. if (iocb->ki_flags & IOCB_NOIO)
  2248. return -EAGAIN;
  2249. page_cache_async_ra(&ractl, folio, last_index - folio->index);
  2250. return 0;
  2251. }
  2252. static int filemap_get_pages(struct kiocb *iocb, size_t count,
  2253. struct folio_batch *fbatch, bool need_uptodate)
  2254. {
  2255. struct file *filp = iocb->ki_filp;
  2256. struct address_space *mapping = filp->f_mapping;
  2257. struct file_ra_state *ra = &filp->f_ra;
  2258. pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
  2259. pgoff_t last_index;
  2260. struct folio *folio;
  2261. unsigned int flags;
  2262. int err = 0;
  2263. /* "last_index" is the index of the page beyond the end of the read */
  2264. last_index = DIV_ROUND_UP(iocb->ki_pos + count, PAGE_SIZE);
  2265. retry:
  2266. if (fatal_signal_pending(current))
  2267. return -EINTR;
  2268. filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
  2269. if (!folio_batch_count(fbatch)) {
  2270. if (iocb->ki_flags & IOCB_NOIO)
  2271. return -EAGAIN;
  2272. if (iocb->ki_flags & IOCB_NOWAIT)
  2273. flags = memalloc_noio_save();
  2274. page_cache_sync_readahead(mapping, ra, filp, index,
  2275. last_index - index);
  2276. if (iocb->ki_flags & IOCB_NOWAIT)
  2277. memalloc_noio_restore(flags);
  2278. filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
  2279. }
  2280. if (!folio_batch_count(fbatch)) {
  2281. if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
  2282. return -EAGAIN;
  2283. err = filemap_create_folio(filp, mapping, iocb->ki_pos, fbatch);
  2284. if (err == AOP_TRUNCATED_PAGE)
  2285. goto retry;
  2286. return err;
  2287. }
  2288. folio = fbatch->folios[folio_batch_count(fbatch) - 1];
  2289. if (folio_test_readahead(folio)) {
  2290. err = filemap_readahead(iocb, filp, mapping, folio, last_index);
  2291. if (err)
  2292. goto err;
  2293. }
  2294. if (!folio_test_uptodate(folio)) {
  2295. if ((iocb->ki_flags & IOCB_WAITQ) &&
  2296. folio_batch_count(fbatch) > 1)
  2297. iocb->ki_flags |= IOCB_NOWAIT;
  2298. err = filemap_update_page(iocb, mapping, count, folio,
  2299. need_uptodate);
  2300. if (err)
  2301. goto err;
  2302. }
  2303. trace_mm_filemap_get_pages(mapping, index, last_index - 1);
  2304. return 0;
  2305. err:
  2306. if (err < 0)
  2307. folio_put(folio);
  2308. if (likely(--fbatch->nr))
  2309. return 0;
  2310. if (err == AOP_TRUNCATED_PAGE)
  2311. goto retry;
  2312. return err;
  2313. }
  2314. static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)
  2315. {
  2316. unsigned int shift = folio_shift(folio);
  2317. return (pos1 >> shift == pos2 >> shift);
  2318. }
  2319. /**
  2320. * filemap_read - Read data from the page cache.
  2321. * @iocb: The iocb to read.
  2322. * @iter: Destination for the data.
  2323. * @already_read: Number of bytes already read by the caller.
  2324. *
  2325. * Copies data from the page cache. If the data is not currently present,
  2326. * uses the readahead and read_folio address_space operations to fetch it.
  2327. *
  2328. * Return: Total number of bytes copied, including those already read by
  2329. * the caller. If an error happens before any bytes are copied, returns
  2330. * a negative error number.
  2331. */
  2332. ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
  2333. ssize_t already_read)
  2334. {
  2335. struct file *filp = iocb->ki_filp;
  2336. struct file_ra_state *ra = &filp->f_ra;
  2337. struct address_space *mapping = filp->f_mapping;
  2338. struct inode *inode = mapping->host;
  2339. struct folio_batch fbatch;
  2340. int i, error = 0;
  2341. bool writably_mapped;
  2342. loff_t isize, end_offset;
  2343. loff_t last_pos = ra->prev_pos;
  2344. if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
  2345. return 0;
  2346. if (unlikely(!iov_iter_count(iter)))
  2347. return 0;
  2348. iov_iter_truncate(iter, inode->i_sb->s_maxbytes - iocb->ki_pos);
  2349. folio_batch_init(&fbatch);
  2350. do {
  2351. cond_resched();
  2352. /*
  2353. * If we've already successfully copied some data, then we
  2354. * can no longer safely return -EIOCBQUEUED. Hence mark
  2355. * an async read NOWAIT at that point.
  2356. */
  2357. if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
  2358. iocb->ki_flags |= IOCB_NOWAIT;
  2359. if (unlikely(iocb->ki_pos >= i_size_read(inode)))
  2360. break;
  2361. error = filemap_get_pages(iocb, iter->count, &fbatch, false);
  2362. if (error < 0)
  2363. break;
  2364. /*
  2365. * i_size must be checked after we know the pages are Uptodate.
  2366. *
  2367. * Checking i_size after the check allows us to calculate
  2368. * the correct value for "nr", which means the zero-filled
  2369. * part of the page is not copied back to userspace (unless
  2370. * another truncate extends the file - this is desired though).
  2371. */
  2372. isize = i_size_read(inode);
  2373. if (unlikely(iocb->ki_pos >= isize))
  2374. goto put_folios;
  2375. end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
  2376. /*
  2377. * Once we start copying data, we don't want to be touching any
  2378. * cachelines that might be contended:
  2379. */
  2380. writably_mapped = mapping_writably_mapped(mapping);
  2381. /*
  2382. * When a read accesses the same folio several times, only
  2383. * mark it as accessed the first time.
  2384. */
  2385. if (!pos_same_folio(iocb->ki_pos, last_pos - 1,
  2386. fbatch.folios[0]))
  2387. folio_mark_accessed(fbatch.folios[0]);
  2388. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  2389. struct folio *folio = fbatch.folios[i];
  2390. size_t fsize = folio_size(folio);
  2391. size_t offset = iocb->ki_pos & (fsize - 1);
  2392. size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
  2393. fsize - offset);
  2394. size_t copied;
  2395. if (end_offset < folio_pos(folio))
  2396. break;
  2397. if (i > 0)
  2398. folio_mark_accessed(folio);
  2399. /*
  2400. * If users can be writing to this folio using arbitrary
  2401. * virtual addresses, take care of potential aliasing
  2402. * before reading the folio on the kernel side.
  2403. */
  2404. if (writably_mapped)
  2405. flush_dcache_folio(folio);
  2406. copied = copy_folio_to_iter(folio, offset, bytes, iter);
  2407. already_read += copied;
  2408. iocb->ki_pos += copied;
  2409. last_pos = iocb->ki_pos;
  2410. if (copied < bytes) {
  2411. error = -EFAULT;
  2412. break;
  2413. }
  2414. }
  2415. put_folios:
  2416. for (i = 0; i < folio_batch_count(&fbatch); i++)
  2417. folio_put(fbatch.folios[i]);
  2418. folio_batch_init(&fbatch);
  2419. } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
  2420. file_accessed(filp);
  2421. ra->prev_pos = last_pos;
  2422. return already_read ? already_read : error;
  2423. }
  2424. EXPORT_SYMBOL_GPL(filemap_read);
  2425. int kiocb_write_and_wait(struct kiocb *iocb, size_t count)
  2426. {
  2427. struct address_space *mapping = iocb->ki_filp->f_mapping;
  2428. loff_t pos = iocb->ki_pos;
  2429. loff_t end = pos + count - 1;
  2430. if (iocb->ki_flags & IOCB_NOWAIT) {
  2431. if (filemap_range_needs_writeback(mapping, pos, end))
  2432. return -EAGAIN;
  2433. return 0;
  2434. }
  2435. return filemap_write_and_wait_range(mapping, pos, end);
  2436. }
  2437. EXPORT_SYMBOL_GPL(kiocb_write_and_wait);
  2438. int filemap_invalidate_pages(struct address_space *mapping,
  2439. loff_t pos, loff_t end, bool nowait)
  2440. {
  2441. int ret;
  2442. if (nowait) {
  2443. /* we could block if there are any pages in the range */
  2444. if (filemap_range_has_page(mapping, pos, end))
  2445. return -EAGAIN;
  2446. } else {
  2447. ret = filemap_write_and_wait_range(mapping, pos, end);
  2448. if (ret)
  2449. return ret;
  2450. }
  2451. /*
  2452. * After a write we want buffered reads to be sure to go to disk to get
  2453. * the new data. We invalidate clean cached page from the region we're
  2454. * about to write. We do this *before* the write so that we can return
  2455. * without clobbering -EIOCBQUEUED from ->direct_IO().
  2456. */
  2457. return invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT,
  2458. end >> PAGE_SHIFT);
  2459. }
  2460. int kiocb_invalidate_pages(struct kiocb *iocb, size_t count)
  2461. {
  2462. struct address_space *mapping = iocb->ki_filp->f_mapping;
  2463. return filemap_invalidate_pages(mapping, iocb->ki_pos,
  2464. iocb->ki_pos + count - 1,
  2465. iocb->ki_flags & IOCB_NOWAIT);
  2466. }
  2467. EXPORT_SYMBOL_GPL(kiocb_invalidate_pages);
  2468. /**
  2469. * generic_file_read_iter - generic filesystem read routine
  2470. * @iocb: kernel I/O control block
  2471. * @iter: destination for the data read
  2472. *
  2473. * This is the "read_iter()" routine for all filesystems
  2474. * that can use the page cache directly.
  2475. *
  2476. * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
  2477. * be returned when no data can be read without waiting for I/O requests
  2478. * to complete; it doesn't prevent readahead.
  2479. *
  2480. * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
  2481. * requests shall be made for the read or for readahead. When no data
  2482. * can be read, -EAGAIN shall be returned. When readahead would be
  2483. * triggered, a partial, possibly empty read shall be returned.
  2484. *
  2485. * Return:
  2486. * * number of bytes copied, even for partial reads
  2487. * * negative error code (or 0 if IOCB_NOIO) if nothing was read
  2488. */
  2489. ssize_t
  2490. generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
  2491. {
  2492. size_t count = iov_iter_count(iter);
  2493. ssize_t retval = 0;
  2494. if (!count)
  2495. return 0; /* skip atime */
  2496. if (iocb->ki_flags & IOCB_DIRECT) {
  2497. struct file *file = iocb->ki_filp;
  2498. struct address_space *mapping = file->f_mapping;
  2499. struct inode *inode = mapping->host;
  2500. retval = kiocb_write_and_wait(iocb, count);
  2501. if (retval < 0)
  2502. return retval;
  2503. file_accessed(file);
  2504. retval = mapping->a_ops->direct_IO(iocb, iter);
  2505. if (retval >= 0) {
  2506. iocb->ki_pos += retval;
  2507. count -= retval;
  2508. }
  2509. if (retval != -EIOCBQUEUED)
  2510. iov_iter_revert(iter, count - iov_iter_count(iter));
  2511. /*
  2512. * Btrfs can have a short DIO read if we encounter
  2513. * compressed extents, so if there was an error, or if
  2514. * we've already read everything we wanted to, or if
  2515. * there was a short read because we hit EOF, go ahead
  2516. * and return. Otherwise fallthrough to buffered io for
  2517. * the rest of the read. Buffered reads will not work for
  2518. * DAX files, so don't bother trying.
  2519. */
  2520. if (retval < 0 || !count || IS_DAX(inode))
  2521. return retval;
  2522. if (iocb->ki_pos >= i_size_read(inode))
  2523. return retval;
  2524. }
  2525. return filemap_read(iocb, iter, retval);
  2526. }
  2527. EXPORT_SYMBOL(generic_file_read_iter);
  2528. /*
  2529. * Splice subpages from a folio into a pipe.
  2530. */
  2531. size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
  2532. struct folio *folio, loff_t fpos, size_t size)
  2533. {
  2534. struct page *page;
  2535. size_t spliced = 0, offset = offset_in_folio(folio, fpos);
  2536. page = folio_page(folio, offset / PAGE_SIZE);
  2537. size = min(size, folio_size(folio) - offset);
  2538. offset %= PAGE_SIZE;
  2539. while (spliced < size &&
  2540. !pipe_full(pipe->head, pipe->tail, pipe->max_usage)) {
  2541. struct pipe_buffer *buf = pipe_head_buf(pipe);
  2542. size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced);
  2543. *buf = (struct pipe_buffer) {
  2544. .ops = &page_cache_pipe_buf_ops,
  2545. .page = page,
  2546. .offset = offset,
  2547. .len = part,
  2548. };
  2549. folio_get(folio);
  2550. pipe->head++;
  2551. page++;
  2552. spliced += part;
  2553. offset = 0;
  2554. }
  2555. return spliced;
  2556. }
  2557. /**
  2558. * filemap_splice_read - Splice data from a file's pagecache into a pipe
  2559. * @in: The file to read from
  2560. * @ppos: Pointer to the file position to read from
  2561. * @pipe: The pipe to splice into
  2562. * @len: The amount to splice
  2563. * @flags: The SPLICE_F_* flags
  2564. *
  2565. * This function gets folios from a file's pagecache and splices them into the
  2566. * pipe. Readahead will be called as necessary to fill more folios. This may
  2567. * be used for blockdevs also.
  2568. *
  2569. * Return: On success, the number of bytes read will be returned and *@ppos
  2570. * will be updated if appropriate; 0 will be returned if there is no more data
  2571. * to be read; -EAGAIN will be returned if the pipe had no space, and some
  2572. * other negative error code will be returned on error. A short read may occur
  2573. * if the pipe has insufficient space, we reach the end of the data or we hit a
  2574. * hole.
  2575. */
  2576. ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
  2577. struct pipe_inode_info *pipe,
  2578. size_t len, unsigned int flags)
  2579. {
  2580. struct folio_batch fbatch;
  2581. struct kiocb iocb;
  2582. size_t total_spliced = 0, used, npages;
  2583. loff_t isize, end_offset;
  2584. bool writably_mapped;
  2585. int i, error = 0;
  2586. if (unlikely(*ppos >= in->f_mapping->host->i_sb->s_maxbytes))
  2587. return 0;
  2588. init_sync_kiocb(&iocb, in);
  2589. iocb.ki_pos = *ppos;
  2590. /* Work out how much data we can actually add into the pipe */
  2591. used = pipe_occupancy(pipe->head, pipe->tail);
  2592. npages = max_t(ssize_t, pipe->max_usage - used, 0);
  2593. len = min_t(size_t, len, npages * PAGE_SIZE);
  2594. folio_batch_init(&fbatch);
  2595. do {
  2596. cond_resched();
  2597. if (*ppos >= i_size_read(in->f_mapping->host))
  2598. break;
  2599. iocb.ki_pos = *ppos;
  2600. error = filemap_get_pages(&iocb, len, &fbatch, true);
  2601. if (error < 0)
  2602. break;
  2603. /*
  2604. * i_size must be checked after we know the pages are Uptodate.
  2605. *
  2606. * Checking i_size after the check allows us to calculate
  2607. * the correct value for "nr", which means the zero-filled
  2608. * part of the page is not copied back to userspace (unless
  2609. * another truncate extends the file - this is desired though).
  2610. */
  2611. isize = i_size_read(in->f_mapping->host);
  2612. if (unlikely(*ppos >= isize))
  2613. break;
  2614. end_offset = min_t(loff_t, isize, *ppos + len);
  2615. /*
  2616. * Once we start copying data, we don't want to be touching any
  2617. * cachelines that might be contended:
  2618. */
  2619. writably_mapped = mapping_writably_mapped(in->f_mapping);
  2620. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  2621. struct folio *folio = fbatch.folios[i];
  2622. size_t n;
  2623. if (folio_pos(folio) >= end_offset)
  2624. goto out;
  2625. folio_mark_accessed(folio);
  2626. /*
  2627. * If users can be writing to this folio using arbitrary
  2628. * virtual addresses, take care of potential aliasing
  2629. * before reading the folio on the kernel side.
  2630. */
  2631. if (writably_mapped)
  2632. flush_dcache_folio(folio);
  2633. n = min_t(loff_t, len, isize - *ppos);
  2634. n = splice_folio_into_pipe(pipe, folio, *ppos, n);
  2635. if (!n)
  2636. goto out;
  2637. len -= n;
  2638. total_spliced += n;
  2639. *ppos += n;
  2640. in->f_ra.prev_pos = *ppos;
  2641. if (pipe_full(pipe->head, pipe->tail, pipe->max_usage))
  2642. goto out;
  2643. }
  2644. folio_batch_release(&fbatch);
  2645. } while (len);
  2646. out:
  2647. folio_batch_release(&fbatch);
  2648. file_accessed(in);
  2649. return total_spliced ? total_spliced : error;
  2650. }
  2651. EXPORT_SYMBOL(filemap_splice_read);
  2652. static inline loff_t folio_seek_hole_data(struct xa_state *xas,
  2653. struct address_space *mapping, struct folio *folio,
  2654. loff_t start, loff_t end, bool seek_data)
  2655. {
  2656. const struct address_space_operations *ops = mapping->a_ops;
  2657. size_t offset, bsz = i_blocksize(mapping->host);
  2658. if (xa_is_value(folio) || folio_test_uptodate(folio))
  2659. return seek_data ? start : end;
  2660. if (!ops->is_partially_uptodate)
  2661. return seek_data ? end : start;
  2662. xas_pause(xas);
  2663. rcu_read_unlock();
  2664. folio_lock(folio);
  2665. if (unlikely(folio->mapping != mapping))
  2666. goto unlock;
  2667. offset = offset_in_folio(folio, start) & ~(bsz - 1);
  2668. do {
  2669. if (ops->is_partially_uptodate(folio, offset, bsz) ==
  2670. seek_data)
  2671. break;
  2672. start = (start + bsz) & ~((u64)bsz - 1);
  2673. offset += bsz;
  2674. } while (offset < folio_size(folio));
  2675. unlock:
  2676. folio_unlock(folio);
  2677. rcu_read_lock();
  2678. return start;
  2679. }
  2680. static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
  2681. {
  2682. if (xa_is_value(folio))
  2683. return PAGE_SIZE << xas_get_order(xas);
  2684. return folio_size(folio);
  2685. }
  2686. /**
  2687. * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
  2688. * @mapping: Address space to search.
  2689. * @start: First byte to consider.
  2690. * @end: Limit of search (exclusive).
  2691. * @whence: Either SEEK_HOLE or SEEK_DATA.
  2692. *
  2693. * If the page cache knows which blocks contain holes and which blocks
  2694. * contain data, your filesystem can use this function to implement
  2695. * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
  2696. * entirely memory-based such as tmpfs, and filesystems which support
  2697. * unwritten extents.
  2698. *
  2699. * Return: The requested offset on success, or -ENXIO if @whence specifies
  2700. * SEEK_DATA and there is no data after @start. There is an implicit hole
  2701. * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
  2702. * and @end contain data.
  2703. */
  2704. loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
  2705. loff_t end, int whence)
  2706. {
  2707. XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
  2708. pgoff_t max = (end - 1) >> PAGE_SHIFT;
  2709. bool seek_data = (whence == SEEK_DATA);
  2710. struct folio *folio;
  2711. if (end <= start)
  2712. return -ENXIO;
  2713. rcu_read_lock();
  2714. while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
  2715. loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
  2716. size_t seek_size;
  2717. if (start < pos) {
  2718. if (!seek_data)
  2719. goto unlock;
  2720. start = pos;
  2721. }
  2722. seek_size = seek_folio_size(&xas, folio);
  2723. pos = round_up((u64)pos + 1, seek_size);
  2724. start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
  2725. seek_data);
  2726. if (start < pos)
  2727. goto unlock;
  2728. if (start >= end)
  2729. break;
  2730. if (seek_size > PAGE_SIZE)
  2731. xas_set(&xas, pos >> PAGE_SHIFT);
  2732. if (!xa_is_value(folio))
  2733. folio_put(folio);
  2734. }
  2735. if (seek_data)
  2736. start = -ENXIO;
  2737. unlock:
  2738. rcu_read_unlock();
  2739. if (folio && !xa_is_value(folio))
  2740. folio_put(folio);
  2741. if (start > end)
  2742. return end;
  2743. return start;
  2744. }
  2745. #ifdef CONFIG_MMU
  2746. #define MMAP_LOTSAMISS (100)
  2747. /*
  2748. * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
  2749. * @vmf - the vm_fault for this fault.
  2750. * @folio - the folio to lock.
  2751. * @fpin - the pointer to the file we may pin (or is already pinned).
  2752. *
  2753. * This works similar to lock_folio_or_retry in that it can drop the
  2754. * mmap_lock. It differs in that it actually returns the folio locked
  2755. * if it returns 1 and 0 if it couldn't lock the folio. If we did have
  2756. * to drop the mmap_lock then fpin will point to the pinned file and
  2757. * needs to be fput()'ed at a later point.
  2758. */
  2759. static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
  2760. struct file **fpin)
  2761. {
  2762. if (folio_trylock(folio))
  2763. return 1;
  2764. /*
  2765. * NOTE! This will make us return with VM_FAULT_RETRY, but with
  2766. * the fault lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
  2767. * is supposed to work. We have way too many special cases..
  2768. */
  2769. if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
  2770. return 0;
  2771. *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
  2772. if (vmf->flags & FAULT_FLAG_KILLABLE) {
  2773. if (__folio_lock_killable(folio)) {
  2774. /*
  2775. * We didn't have the right flags to drop the
  2776. * fault lock, but all fault_handlers only check
  2777. * for fatal signals if we return VM_FAULT_RETRY,
  2778. * so we need to drop the fault lock here and
  2779. * return 0 if we don't have a fpin.
  2780. */
  2781. if (*fpin == NULL)
  2782. release_fault_lock(vmf);
  2783. return 0;
  2784. }
  2785. } else
  2786. __folio_lock(folio);
  2787. return 1;
  2788. }
  2789. /*
  2790. * Synchronous readahead happens when we don't even find a page in the page
  2791. * cache at all. We don't want to perform IO under the mmap sem, so if we have
  2792. * to drop the mmap sem we return the file that was pinned in order for us to do
  2793. * that. If we didn't pin a file then we return NULL. The file that is
  2794. * returned needs to be fput()'ed when we're done with it.
  2795. */
  2796. static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
  2797. {
  2798. struct file *file = vmf->vma->vm_file;
  2799. struct file_ra_state *ra = &file->f_ra;
  2800. struct address_space *mapping = file->f_mapping;
  2801. DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
  2802. struct file *fpin = NULL;
  2803. unsigned long vm_flags = vmf->vma->vm_flags;
  2804. unsigned int mmap_miss;
  2805. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2806. /* Use the readahead code, even if readahead is disabled */
  2807. if ((vm_flags & VM_HUGEPAGE) && HPAGE_PMD_ORDER <= MAX_PAGECACHE_ORDER) {
  2808. fpin = maybe_unlock_mmap_for_io(vmf, fpin);
  2809. ractl._index &= ~((unsigned long)HPAGE_PMD_NR - 1);
  2810. ra->size = HPAGE_PMD_NR;
  2811. /*
  2812. * Fetch two PMD folios, so we get the chance to actually
  2813. * readahead, unless we've been told not to.
  2814. */
  2815. if (!(vm_flags & VM_RAND_READ))
  2816. ra->size *= 2;
  2817. ra->async_size = HPAGE_PMD_NR;
  2818. page_cache_ra_order(&ractl, ra, HPAGE_PMD_ORDER);
  2819. return fpin;
  2820. }
  2821. #endif
  2822. /* If we don't want any read-ahead, don't bother */
  2823. if (vm_flags & VM_RAND_READ)
  2824. return fpin;
  2825. if (!ra->ra_pages)
  2826. return fpin;
  2827. if (vm_flags & VM_SEQ_READ) {
  2828. fpin = maybe_unlock_mmap_for_io(vmf, fpin);
  2829. page_cache_sync_ra(&ractl, ra->ra_pages);
  2830. return fpin;
  2831. }
  2832. /* Avoid banging the cache line if not needed */
  2833. mmap_miss = READ_ONCE(ra->mmap_miss);
  2834. if (mmap_miss < MMAP_LOTSAMISS * 10)
  2835. WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
  2836. /*
  2837. * Do we miss much more than hit in this file? If so,
  2838. * stop bothering with read-ahead. It will only hurt.
  2839. */
  2840. if (mmap_miss > MMAP_LOTSAMISS)
  2841. return fpin;
  2842. /*
  2843. * mmap read-around
  2844. */
  2845. fpin = maybe_unlock_mmap_for_io(vmf, fpin);
  2846. ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
  2847. ra->size = ra->ra_pages;
  2848. ra->async_size = ra->ra_pages / 4;
  2849. ractl._index = ra->start;
  2850. page_cache_ra_order(&ractl, ra, 0);
  2851. return fpin;
  2852. }
  2853. /*
  2854. * Asynchronous readahead happens when we find the page and PG_readahead,
  2855. * so we want to possibly extend the readahead further. We return the file that
  2856. * was pinned if we have to drop the mmap_lock in order to do IO.
  2857. */
  2858. static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
  2859. struct folio *folio)
  2860. {
  2861. struct file *file = vmf->vma->vm_file;
  2862. struct file_ra_state *ra = &file->f_ra;
  2863. DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
  2864. struct file *fpin = NULL;
  2865. unsigned int mmap_miss;
  2866. /* If we don't want any read-ahead, don't bother */
  2867. if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
  2868. return fpin;
  2869. mmap_miss = READ_ONCE(ra->mmap_miss);
  2870. if (mmap_miss)
  2871. WRITE_ONCE(ra->mmap_miss, --mmap_miss);
  2872. if (folio_test_readahead(folio)) {
  2873. fpin = maybe_unlock_mmap_for_io(vmf, fpin);
  2874. page_cache_async_ra(&ractl, folio, ra->ra_pages);
  2875. }
  2876. return fpin;
  2877. }
  2878. static vm_fault_t filemap_fault_recheck_pte_none(struct vm_fault *vmf)
  2879. {
  2880. struct vm_area_struct *vma = vmf->vma;
  2881. vm_fault_t ret = 0;
  2882. pte_t *ptep;
  2883. /*
  2884. * We might have COW'ed a pagecache folio and might now have an mlocked
  2885. * anon folio mapped. The original pagecache folio is not mlocked and
  2886. * might have been evicted. During a read+clear/modify/write update of
  2887. * the PTE, such as done in do_numa_page()/change_pte_range(), we
  2888. * temporarily clear the PTE under PT lock and might detect it here as
  2889. * "none" when not holding the PT lock.
  2890. *
  2891. * Not rechecking the PTE under PT lock could result in an unexpected
  2892. * major fault in an mlock'ed region. Recheck only for this special
  2893. * scenario while holding the PT lock, to not degrade non-mlocked
  2894. * scenarios. Recheck the PTE without PT lock firstly, thereby reducing
  2895. * the number of times we hold PT lock.
  2896. */
  2897. if (!(vma->vm_flags & VM_LOCKED))
  2898. return 0;
  2899. if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID))
  2900. return 0;
  2901. ptep = pte_offset_map_nolock(vma->vm_mm, vmf->pmd, vmf->address,
  2902. &vmf->ptl);
  2903. if (unlikely(!ptep))
  2904. return VM_FAULT_NOPAGE;
  2905. if (unlikely(!pte_none(ptep_get_lockless(ptep)))) {
  2906. ret = VM_FAULT_NOPAGE;
  2907. } else {
  2908. spin_lock(vmf->ptl);
  2909. if (unlikely(!pte_none(ptep_get(ptep))))
  2910. ret = VM_FAULT_NOPAGE;
  2911. spin_unlock(vmf->ptl);
  2912. }
  2913. pte_unmap(ptep);
  2914. return ret;
  2915. }
  2916. /**
  2917. * filemap_fault - read in file data for page fault handling
  2918. * @vmf: struct vm_fault containing details of the fault
  2919. *
  2920. * filemap_fault() is invoked via the vma operations vector for a
  2921. * mapped memory region to read in file data during a page fault.
  2922. *
  2923. * The goto's are kind of ugly, but this streamlines the normal case of having
  2924. * it in the page cache, and handles the special cases reasonably without
  2925. * having a lot of duplicated code.
  2926. *
  2927. * vma->vm_mm->mmap_lock must be held on entry.
  2928. *
  2929. * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
  2930. * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
  2931. *
  2932. * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
  2933. * has not been released.
  2934. *
  2935. * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
  2936. *
  2937. * Return: bitwise-OR of %VM_FAULT_ codes.
  2938. */
  2939. vm_fault_t filemap_fault(struct vm_fault *vmf)
  2940. {
  2941. int error;
  2942. struct file *file = vmf->vma->vm_file;
  2943. struct file *fpin = NULL;
  2944. struct address_space *mapping = file->f_mapping;
  2945. struct inode *inode = mapping->host;
  2946. pgoff_t max_idx, index = vmf->pgoff;
  2947. struct folio *folio;
  2948. vm_fault_t ret = 0;
  2949. bool mapping_locked = false;
  2950. max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
  2951. if (unlikely(index >= max_idx))
  2952. return VM_FAULT_SIGBUS;
  2953. trace_mm_filemap_fault(mapping, index);
  2954. /*
  2955. * Do we have something in the page cache already?
  2956. */
  2957. folio = filemap_get_folio(mapping, index);
  2958. if (likely(!IS_ERR(folio))) {
  2959. /*
  2960. * We found the page, so try async readahead before waiting for
  2961. * the lock.
  2962. */
  2963. if (!(vmf->flags & FAULT_FLAG_TRIED))
  2964. fpin = do_async_mmap_readahead(vmf, folio);
  2965. if (unlikely(!folio_test_uptodate(folio))) {
  2966. filemap_invalidate_lock_shared(mapping);
  2967. mapping_locked = true;
  2968. }
  2969. } else {
  2970. ret = filemap_fault_recheck_pte_none(vmf);
  2971. if (unlikely(ret))
  2972. return ret;
  2973. /* No page in the page cache at all */
  2974. count_vm_event(PGMAJFAULT);
  2975. count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
  2976. ret = VM_FAULT_MAJOR;
  2977. fpin = do_sync_mmap_readahead(vmf);
  2978. retry_find:
  2979. /*
  2980. * See comment in filemap_create_folio() why we need
  2981. * invalidate_lock
  2982. */
  2983. if (!mapping_locked) {
  2984. filemap_invalidate_lock_shared(mapping);
  2985. mapping_locked = true;
  2986. }
  2987. folio = __filemap_get_folio(mapping, index,
  2988. FGP_CREAT|FGP_FOR_MMAP,
  2989. vmf->gfp_mask);
  2990. if (IS_ERR(folio)) {
  2991. if (fpin)
  2992. goto out_retry;
  2993. filemap_invalidate_unlock_shared(mapping);
  2994. return VM_FAULT_OOM;
  2995. }
  2996. }
  2997. if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
  2998. goto out_retry;
  2999. /* Did it get truncated? */
  3000. if (unlikely(folio->mapping != mapping)) {
  3001. folio_unlock(folio);
  3002. folio_put(folio);
  3003. goto retry_find;
  3004. }
  3005. VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
  3006. /*
  3007. * We have a locked folio in the page cache, now we need to check
  3008. * that it's up-to-date. If not, it is going to be due to an error,
  3009. * or because readahead was otherwise unable to retrieve it.
  3010. */
  3011. if (unlikely(!folio_test_uptodate(folio))) {
  3012. /*
  3013. * If the invalidate lock is not held, the folio was in cache
  3014. * and uptodate and now it is not. Strange but possible since we
  3015. * didn't hold the page lock all the time. Let's drop
  3016. * everything, get the invalidate lock and try again.
  3017. */
  3018. if (!mapping_locked) {
  3019. folio_unlock(folio);
  3020. folio_put(folio);
  3021. goto retry_find;
  3022. }
  3023. /*
  3024. * OK, the folio is really not uptodate. This can be because the
  3025. * VMA has the VM_RAND_READ flag set, or because an error
  3026. * arose. Let's read it in directly.
  3027. */
  3028. goto page_not_uptodate;
  3029. }
  3030. /*
  3031. * We've made it this far and we had to drop our mmap_lock, now is the
  3032. * time to return to the upper layer and have it re-find the vma and
  3033. * redo the fault.
  3034. */
  3035. if (fpin) {
  3036. folio_unlock(folio);
  3037. goto out_retry;
  3038. }
  3039. if (mapping_locked)
  3040. filemap_invalidate_unlock_shared(mapping);
  3041. /*
  3042. * Found the page and have a reference on it.
  3043. * We must recheck i_size under page lock.
  3044. */
  3045. max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
  3046. if (unlikely(index >= max_idx)) {
  3047. folio_unlock(folio);
  3048. folio_put(folio);
  3049. return VM_FAULT_SIGBUS;
  3050. }
  3051. vmf->page = folio_file_page(folio, index);
  3052. return ret | VM_FAULT_LOCKED;
  3053. page_not_uptodate:
  3054. /*
  3055. * Umm, take care of errors if the page isn't up-to-date.
  3056. * Try to re-read it _once_. We do this synchronously,
  3057. * because there really aren't any performance issues here
  3058. * and we need to check for errors.
  3059. */
  3060. fpin = maybe_unlock_mmap_for_io(vmf, fpin);
  3061. error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
  3062. if (fpin)
  3063. goto out_retry;
  3064. folio_put(folio);
  3065. if (!error || error == AOP_TRUNCATED_PAGE)
  3066. goto retry_find;
  3067. filemap_invalidate_unlock_shared(mapping);
  3068. return VM_FAULT_SIGBUS;
  3069. out_retry:
  3070. /*
  3071. * We dropped the mmap_lock, we need to return to the fault handler to
  3072. * re-find the vma and come back and find our hopefully still populated
  3073. * page.
  3074. */
  3075. if (!IS_ERR(folio))
  3076. folio_put(folio);
  3077. if (mapping_locked)
  3078. filemap_invalidate_unlock_shared(mapping);
  3079. if (fpin)
  3080. fput(fpin);
  3081. return ret | VM_FAULT_RETRY;
  3082. }
  3083. EXPORT_SYMBOL(filemap_fault);
  3084. static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio,
  3085. pgoff_t start)
  3086. {
  3087. struct mm_struct *mm = vmf->vma->vm_mm;
  3088. /* Huge page is mapped? No need to proceed. */
  3089. if (pmd_trans_huge(*vmf->pmd)) {
  3090. folio_unlock(folio);
  3091. folio_put(folio);
  3092. return true;
  3093. }
  3094. if (pmd_none(*vmf->pmd) && folio_test_pmd_mappable(folio)) {
  3095. struct page *page = folio_file_page(folio, start);
  3096. vm_fault_t ret = do_set_pmd(vmf, page);
  3097. if (!ret) {
  3098. /* The page is mapped successfully, reference consumed. */
  3099. folio_unlock(folio);
  3100. return true;
  3101. }
  3102. }
  3103. if (pmd_none(*vmf->pmd) && vmf->prealloc_pte)
  3104. pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
  3105. return false;
  3106. }
  3107. static struct folio *next_uptodate_folio(struct xa_state *xas,
  3108. struct address_space *mapping, pgoff_t end_pgoff)
  3109. {
  3110. struct folio *folio = xas_next_entry(xas, end_pgoff);
  3111. unsigned long max_idx;
  3112. do {
  3113. if (!folio)
  3114. return NULL;
  3115. if (xas_retry(xas, folio))
  3116. continue;
  3117. if (xa_is_value(folio))
  3118. continue;
  3119. if (folio_test_locked(folio))
  3120. continue;
  3121. if (!folio_try_get(folio))
  3122. continue;
  3123. /* Has the page moved or been split? */
  3124. if (unlikely(folio != xas_reload(xas)))
  3125. goto skip;
  3126. if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
  3127. goto skip;
  3128. if (!folio_trylock(folio))
  3129. goto skip;
  3130. if (folio->mapping != mapping)
  3131. goto unlock;
  3132. if (!folio_test_uptodate(folio))
  3133. goto unlock;
  3134. max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
  3135. if (xas->xa_index >= max_idx)
  3136. goto unlock;
  3137. return folio;
  3138. unlock:
  3139. folio_unlock(folio);
  3140. skip:
  3141. folio_put(folio);
  3142. } while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
  3143. return NULL;
  3144. }
  3145. /*
  3146. * Map page range [start_page, start_page + nr_pages) of folio.
  3147. * start_page is gotten from start by folio_page(folio, start)
  3148. */
  3149. static vm_fault_t filemap_map_folio_range(struct vm_fault *vmf,
  3150. struct folio *folio, unsigned long start,
  3151. unsigned long addr, unsigned int nr_pages,
  3152. unsigned long *rss, unsigned int *mmap_miss)
  3153. {
  3154. vm_fault_t ret = 0;
  3155. struct page *page = folio_page(folio, start);
  3156. unsigned int count = 0;
  3157. pte_t *old_ptep = vmf->pte;
  3158. do {
  3159. if (PageHWPoison(page + count))
  3160. goto skip;
  3161. /*
  3162. * If there are too many folios that are recently evicted
  3163. * in a file, they will probably continue to be evicted.
  3164. * In such situation, read-ahead is only a waste of IO.
  3165. * Don't decrease mmap_miss in this scenario to make sure
  3166. * we can stop read-ahead.
  3167. */
  3168. if (!folio_test_workingset(folio))
  3169. (*mmap_miss)++;
  3170. /*
  3171. * NOTE: If there're PTE markers, we'll leave them to be
  3172. * handled in the specific fault path, and it'll prohibit the
  3173. * fault-around logic.
  3174. */
  3175. if (!pte_none(ptep_get(&vmf->pte[count])))
  3176. goto skip;
  3177. count++;
  3178. continue;
  3179. skip:
  3180. if (count) {
  3181. set_pte_range(vmf, folio, page, count, addr);
  3182. *rss += count;
  3183. folio_ref_add(folio, count);
  3184. if (in_range(vmf->address, addr, count * PAGE_SIZE))
  3185. ret = VM_FAULT_NOPAGE;
  3186. }
  3187. count++;
  3188. page += count;
  3189. vmf->pte += count;
  3190. addr += count * PAGE_SIZE;
  3191. count = 0;
  3192. } while (--nr_pages > 0);
  3193. if (count) {
  3194. set_pte_range(vmf, folio, page, count, addr);
  3195. *rss += count;
  3196. folio_ref_add(folio, count);
  3197. if (in_range(vmf->address, addr, count * PAGE_SIZE))
  3198. ret = VM_FAULT_NOPAGE;
  3199. }
  3200. vmf->pte = old_ptep;
  3201. return ret;
  3202. }
  3203. static vm_fault_t filemap_map_order0_folio(struct vm_fault *vmf,
  3204. struct folio *folio, unsigned long addr,
  3205. unsigned long *rss, unsigned int *mmap_miss)
  3206. {
  3207. vm_fault_t ret = 0;
  3208. struct page *page = &folio->page;
  3209. if (PageHWPoison(page))
  3210. return ret;
  3211. /* See comment of filemap_map_folio_range() */
  3212. if (!folio_test_workingset(folio))
  3213. (*mmap_miss)++;
  3214. /*
  3215. * NOTE: If there're PTE markers, we'll leave them to be
  3216. * handled in the specific fault path, and it'll prohibit
  3217. * the fault-around logic.
  3218. */
  3219. if (!pte_none(ptep_get(vmf->pte)))
  3220. return ret;
  3221. if (vmf->address == addr)
  3222. ret = VM_FAULT_NOPAGE;
  3223. set_pte_range(vmf, folio, page, 1, addr);
  3224. (*rss)++;
  3225. folio_ref_inc(folio);
  3226. return ret;
  3227. }
  3228. vm_fault_t filemap_map_pages(struct vm_fault *vmf,
  3229. pgoff_t start_pgoff, pgoff_t end_pgoff)
  3230. {
  3231. struct vm_area_struct *vma = vmf->vma;
  3232. struct file *file = vma->vm_file;
  3233. struct address_space *mapping = file->f_mapping;
  3234. pgoff_t file_end, last_pgoff = start_pgoff;
  3235. unsigned long addr;
  3236. XA_STATE(xas, &mapping->i_pages, start_pgoff);
  3237. struct folio *folio;
  3238. vm_fault_t ret = 0;
  3239. unsigned long rss = 0;
  3240. unsigned int nr_pages = 0, mmap_miss = 0, mmap_miss_saved, folio_type;
  3241. rcu_read_lock();
  3242. folio = next_uptodate_folio(&xas, mapping, end_pgoff);
  3243. if (!folio)
  3244. goto out;
  3245. if (filemap_map_pmd(vmf, folio, start_pgoff)) {
  3246. ret = VM_FAULT_NOPAGE;
  3247. goto out;
  3248. }
  3249. addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
  3250. vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
  3251. if (!vmf->pte) {
  3252. folio_unlock(folio);
  3253. folio_put(folio);
  3254. goto out;
  3255. }
  3256. file_end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE) - 1;
  3257. if (end_pgoff > file_end)
  3258. end_pgoff = file_end;
  3259. folio_type = mm_counter_file(folio);
  3260. do {
  3261. unsigned long end;
  3262. addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
  3263. vmf->pte += xas.xa_index - last_pgoff;
  3264. last_pgoff = xas.xa_index;
  3265. end = folio_next_index(folio) - 1;
  3266. nr_pages = min(end, end_pgoff) - xas.xa_index + 1;
  3267. if (!folio_test_large(folio))
  3268. ret |= filemap_map_order0_folio(vmf,
  3269. folio, addr, &rss, &mmap_miss);
  3270. else
  3271. ret |= filemap_map_folio_range(vmf, folio,
  3272. xas.xa_index - folio->index, addr,
  3273. nr_pages, &rss, &mmap_miss);
  3274. folio_unlock(folio);
  3275. folio_put(folio);
  3276. } while ((folio = next_uptodate_folio(&xas, mapping, end_pgoff)) != NULL);
  3277. add_mm_counter(vma->vm_mm, folio_type, rss);
  3278. pte_unmap_unlock(vmf->pte, vmf->ptl);
  3279. trace_mm_filemap_map_pages(mapping, start_pgoff, end_pgoff);
  3280. out:
  3281. rcu_read_unlock();
  3282. mmap_miss_saved = READ_ONCE(file->f_ra.mmap_miss);
  3283. if (mmap_miss >= mmap_miss_saved)
  3284. WRITE_ONCE(file->f_ra.mmap_miss, 0);
  3285. else
  3286. WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss_saved - mmap_miss);
  3287. return ret;
  3288. }
  3289. EXPORT_SYMBOL(filemap_map_pages);
  3290. vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
  3291. {
  3292. struct address_space *mapping = vmf->vma->vm_file->f_mapping;
  3293. struct folio *folio = page_folio(vmf->page);
  3294. vm_fault_t ret = VM_FAULT_LOCKED;
  3295. sb_start_pagefault(mapping->host->i_sb);
  3296. file_update_time(vmf->vma->vm_file);
  3297. folio_lock(folio);
  3298. if (folio->mapping != mapping) {
  3299. folio_unlock(folio);
  3300. ret = VM_FAULT_NOPAGE;
  3301. goto out;
  3302. }
  3303. /*
  3304. * We mark the folio dirty already here so that when freeze is in
  3305. * progress, we are guaranteed that writeback during freezing will
  3306. * see the dirty folio and writeprotect it again.
  3307. */
  3308. folio_mark_dirty(folio);
  3309. folio_wait_stable(folio);
  3310. out:
  3311. sb_end_pagefault(mapping->host->i_sb);
  3312. return ret;
  3313. }
  3314. const struct vm_operations_struct generic_file_vm_ops = {
  3315. .fault = filemap_fault,
  3316. .map_pages = filemap_map_pages,
  3317. .page_mkwrite = filemap_page_mkwrite,
  3318. };
  3319. /* This is used for a general mmap of a disk file */
  3320. int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
  3321. {
  3322. struct address_space *mapping = file->f_mapping;
  3323. if (!mapping->a_ops->read_folio)
  3324. return -ENOEXEC;
  3325. file_accessed(file);
  3326. vma->vm_ops = &generic_file_vm_ops;
  3327. return 0;
  3328. }
  3329. /*
  3330. * This is for filesystems which do not implement ->writepage.
  3331. */
  3332. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  3333. {
  3334. if (vma_is_shared_maywrite(vma))
  3335. return -EINVAL;
  3336. return generic_file_mmap(file, vma);
  3337. }
  3338. #else
  3339. vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
  3340. {
  3341. return VM_FAULT_SIGBUS;
  3342. }
  3343. int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
  3344. {
  3345. return -ENOSYS;
  3346. }
  3347. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  3348. {
  3349. return -ENOSYS;
  3350. }
  3351. #endif /* CONFIG_MMU */
  3352. EXPORT_SYMBOL(filemap_page_mkwrite);
  3353. EXPORT_SYMBOL(generic_file_mmap);
  3354. EXPORT_SYMBOL(generic_file_readonly_mmap);
  3355. static struct folio *do_read_cache_folio(struct address_space *mapping,
  3356. pgoff_t index, filler_t filler, struct file *file, gfp_t gfp)
  3357. {
  3358. struct folio *folio;
  3359. int err;
  3360. if (!filler)
  3361. filler = mapping->a_ops->read_folio;
  3362. repeat:
  3363. folio = filemap_get_folio(mapping, index);
  3364. if (IS_ERR(folio)) {
  3365. folio = filemap_alloc_folio(gfp,
  3366. mapping_min_folio_order(mapping));
  3367. if (!folio)
  3368. return ERR_PTR(-ENOMEM);
  3369. index = mapping_align_index(mapping, index);
  3370. err = filemap_add_folio(mapping, folio, index, gfp);
  3371. if (unlikely(err)) {
  3372. folio_put(folio);
  3373. if (err == -EEXIST)
  3374. goto repeat;
  3375. /* Presumably ENOMEM for xarray node */
  3376. return ERR_PTR(err);
  3377. }
  3378. goto filler;
  3379. }
  3380. if (folio_test_uptodate(folio))
  3381. goto out;
  3382. if (!folio_trylock(folio)) {
  3383. folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
  3384. goto repeat;
  3385. }
  3386. /* Folio was truncated from mapping */
  3387. if (!folio->mapping) {
  3388. folio_unlock(folio);
  3389. folio_put(folio);
  3390. goto repeat;
  3391. }
  3392. /* Someone else locked and filled the page in a very small window */
  3393. if (folio_test_uptodate(folio)) {
  3394. folio_unlock(folio);
  3395. goto out;
  3396. }
  3397. filler:
  3398. err = filemap_read_folio(file, filler, folio);
  3399. if (err) {
  3400. folio_put(folio);
  3401. if (err == AOP_TRUNCATED_PAGE)
  3402. goto repeat;
  3403. return ERR_PTR(err);
  3404. }
  3405. out:
  3406. folio_mark_accessed(folio);
  3407. return folio;
  3408. }
  3409. /**
  3410. * read_cache_folio - Read into page cache, fill it if needed.
  3411. * @mapping: The address_space to read from.
  3412. * @index: The index to read.
  3413. * @filler: Function to perform the read, or NULL to use aops->read_folio().
  3414. * @file: Passed to filler function, may be NULL if not required.
  3415. *
  3416. * Read one page into the page cache. If it succeeds, the folio returned
  3417. * will contain @index, but it may not be the first page of the folio.
  3418. *
  3419. * If the filler function returns an error, it will be returned to the
  3420. * caller.
  3421. *
  3422. * Context: May sleep. Expects mapping->invalidate_lock to be held.
  3423. * Return: An uptodate folio on success, ERR_PTR() on failure.
  3424. */
  3425. struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
  3426. filler_t filler, struct file *file)
  3427. {
  3428. return do_read_cache_folio(mapping, index, filler, file,
  3429. mapping_gfp_mask(mapping));
  3430. }
  3431. EXPORT_SYMBOL(read_cache_folio);
  3432. /**
  3433. * mapping_read_folio_gfp - Read into page cache, using specified allocation flags.
  3434. * @mapping: The address_space for the folio.
  3435. * @index: The index that the allocated folio will contain.
  3436. * @gfp: The page allocator flags to use if allocating.
  3437. *
  3438. * This is the same as "read_cache_folio(mapping, index, NULL, NULL)", but with
  3439. * any new memory allocations done using the specified allocation flags.
  3440. *
  3441. * The most likely error from this function is EIO, but ENOMEM is
  3442. * possible and so is EINTR. If ->read_folio returns another error,
  3443. * that will be returned to the caller.
  3444. *
  3445. * The function expects mapping->invalidate_lock to be already held.
  3446. *
  3447. * Return: Uptodate folio on success, ERR_PTR() on failure.
  3448. */
  3449. struct folio *mapping_read_folio_gfp(struct address_space *mapping,
  3450. pgoff_t index, gfp_t gfp)
  3451. {
  3452. return do_read_cache_folio(mapping, index, NULL, NULL, gfp);
  3453. }
  3454. EXPORT_SYMBOL(mapping_read_folio_gfp);
  3455. static struct page *do_read_cache_page(struct address_space *mapping,
  3456. pgoff_t index, filler_t *filler, struct file *file, gfp_t gfp)
  3457. {
  3458. struct folio *folio;
  3459. folio = do_read_cache_folio(mapping, index, filler, file, gfp);
  3460. if (IS_ERR(folio))
  3461. return &folio->page;
  3462. return folio_file_page(folio, index);
  3463. }
  3464. struct page *read_cache_page(struct address_space *mapping,
  3465. pgoff_t index, filler_t *filler, struct file *file)
  3466. {
  3467. return do_read_cache_page(mapping, index, filler, file,
  3468. mapping_gfp_mask(mapping));
  3469. }
  3470. EXPORT_SYMBOL(read_cache_page);
  3471. /**
  3472. * read_cache_page_gfp - read into page cache, using specified page allocation flags.
  3473. * @mapping: the page's address_space
  3474. * @index: the page index
  3475. * @gfp: the page allocator flags to use if allocating
  3476. *
  3477. * This is the same as "read_mapping_page(mapping, index, NULL)", but with
  3478. * any new page allocations done using the specified allocation flags.
  3479. *
  3480. * If the page does not get brought uptodate, return -EIO.
  3481. *
  3482. * The function expects mapping->invalidate_lock to be already held.
  3483. *
  3484. * Return: up to date page on success, ERR_PTR() on failure.
  3485. */
  3486. struct page *read_cache_page_gfp(struct address_space *mapping,
  3487. pgoff_t index,
  3488. gfp_t gfp)
  3489. {
  3490. return do_read_cache_page(mapping, index, NULL, NULL, gfp);
  3491. }
  3492. EXPORT_SYMBOL(read_cache_page_gfp);
  3493. /*
  3494. * Warn about a page cache invalidation failure during a direct I/O write.
  3495. */
  3496. static void dio_warn_stale_pagecache(struct file *filp)
  3497. {
  3498. static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
  3499. char pathname[128];
  3500. char *path;
  3501. errseq_set(&filp->f_mapping->wb_err, -EIO);
  3502. if (__ratelimit(&_rs)) {
  3503. path = file_path(filp, pathname, sizeof(pathname));
  3504. if (IS_ERR(path))
  3505. path = "(unknown)";
  3506. pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
  3507. pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
  3508. current->comm);
  3509. }
  3510. }
  3511. void kiocb_invalidate_post_direct_write(struct kiocb *iocb, size_t count)
  3512. {
  3513. struct address_space *mapping = iocb->ki_filp->f_mapping;
  3514. if (mapping->nrpages &&
  3515. invalidate_inode_pages2_range(mapping,
  3516. iocb->ki_pos >> PAGE_SHIFT,
  3517. (iocb->ki_pos + count - 1) >> PAGE_SHIFT))
  3518. dio_warn_stale_pagecache(iocb->ki_filp);
  3519. }
  3520. ssize_t
  3521. generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
  3522. {
  3523. struct address_space *mapping = iocb->ki_filp->f_mapping;
  3524. size_t write_len = iov_iter_count(from);
  3525. ssize_t written;
  3526. /*
  3527. * If a page can not be invalidated, return 0 to fall back
  3528. * to buffered write.
  3529. */
  3530. written = kiocb_invalidate_pages(iocb, write_len);
  3531. if (written) {
  3532. if (written == -EBUSY)
  3533. return 0;
  3534. return written;
  3535. }
  3536. written = mapping->a_ops->direct_IO(iocb, from);
  3537. /*
  3538. * Finally, try again to invalidate clean pages which might have been
  3539. * cached by non-direct readahead, or faulted in by get_user_pages()
  3540. * if the source of the write was an mmap'ed region of the file
  3541. * we're writing. Either one is a pretty crazy thing to do,
  3542. * so we don't support it 100%. If this invalidation
  3543. * fails, tough, the write still worked...
  3544. *
  3545. * Most of the time we do not need this since dio_complete() will do
  3546. * the invalidation for us. However there are some file systems that
  3547. * do not end up with dio_complete() being called, so let's not break
  3548. * them by removing it completely.
  3549. *
  3550. * Noticeable example is a blkdev_direct_IO().
  3551. *
  3552. * Skip invalidation for async writes or if mapping has no pages.
  3553. */
  3554. if (written > 0) {
  3555. struct inode *inode = mapping->host;
  3556. loff_t pos = iocb->ki_pos;
  3557. kiocb_invalidate_post_direct_write(iocb, written);
  3558. pos += written;
  3559. write_len -= written;
  3560. if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
  3561. i_size_write(inode, pos);
  3562. mark_inode_dirty(inode);
  3563. }
  3564. iocb->ki_pos = pos;
  3565. }
  3566. if (written != -EIOCBQUEUED)
  3567. iov_iter_revert(from, write_len - iov_iter_count(from));
  3568. return written;
  3569. }
  3570. EXPORT_SYMBOL(generic_file_direct_write);
  3571. ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i)
  3572. {
  3573. struct file *file = iocb->ki_filp;
  3574. loff_t pos = iocb->ki_pos;
  3575. struct address_space *mapping = file->f_mapping;
  3576. const struct address_space_operations *a_ops = mapping->a_ops;
  3577. size_t chunk = mapping_max_folio_size(mapping);
  3578. long status = 0;
  3579. ssize_t written = 0;
  3580. do {
  3581. struct folio *folio;
  3582. size_t offset; /* Offset into folio */
  3583. size_t bytes; /* Bytes to write to folio */
  3584. size_t copied; /* Bytes copied from user */
  3585. void *fsdata = NULL;
  3586. bytes = iov_iter_count(i);
  3587. retry:
  3588. offset = pos & (chunk - 1);
  3589. bytes = min(chunk - offset, bytes);
  3590. balance_dirty_pages_ratelimited(mapping);
  3591. /*
  3592. * Bring in the user page that we will copy from _first_.
  3593. * Otherwise there's a nasty deadlock on copying from the
  3594. * same page as we're writing to, without it being marked
  3595. * up-to-date.
  3596. */
  3597. if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
  3598. status = -EFAULT;
  3599. break;
  3600. }
  3601. if (fatal_signal_pending(current)) {
  3602. status = -EINTR;
  3603. break;
  3604. }
  3605. status = a_ops->write_begin(file, mapping, pos, bytes,
  3606. &folio, &fsdata);
  3607. if (unlikely(status < 0))
  3608. break;
  3609. offset = offset_in_folio(folio, pos);
  3610. if (bytes > folio_size(folio) - offset)
  3611. bytes = folio_size(folio) - offset;
  3612. if (mapping_writably_mapped(mapping))
  3613. flush_dcache_folio(folio);
  3614. copied = copy_folio_from_iter_atomic(folio, offset, bytes, i);
  3615. flush_dcache_folio(folio);
  3616. status = a_ops->write_end(file, mapping, pos, bytes, copied,
  3617. folio, fsdata);
  3618. if (unlikely(status != copied)) {
  3619. iov_iter_revert(i, copied - max(status, 0L));
  3620. if (unlikely(status < 0))
  3621. break;
  3622. }
  3623. cond_resched();
  3624. if (unlikely(status == 0)) {
  3625. /*
  3626. * A short copy made ->write_end() reject the
  3627. * thing entirely. Might be memory poisoning
  3628. * halfway through, might be a race with munmap,
  3629. * might be severe memory pressure.
  3630. */
  3631. if (chunk > PAGE_SIZE)
  3632. chunk /= 2;
  3633. if (copied) {
  3634. bytes = copied;
  3635. goto retry;
  3636. }
  3637. } else {
  3638. pos += status;
  3639. written += status;
  3640. }
  3641. } while (iov_iter_count(i));
  3642. if (!written)
  3643. return status;
  3644. iocb->ki_pos += written;
  3645. return written;
  3646. }
  3647. EXPORT_SYMBOL(generic_perform_write);
  3648. /**
  3649. * __generic_file_write_iter - write data to a file
  3650. * @iocb: IO state structure (file, offset, etc.)
  3651. * @from: iov_iter with data to write
  3652. *
  3653. * This function does all the work needed for actually writing data to a
  3654. * file. It does all basic checks, removes SUID from the file, updates
  3655. * modification times and calls proper subroutines depending on whether we
  3656. * do direct IO or a standard buffered write.
  3657. *
  3658. * It expects i_rwsem to be grabbed unless we work on a block device or similar
  3659. * object which does not need locking at all.
  3660. *
  3661. * This function does *not* take care of syncing data in case of O_SYNC write.
  3662. * A caller has to handle it. This is mainly due to the fact that we want to
  3663. * avoid syncing under i_rwsem.
  3664. *
  3665. * Return:
  3666. * * number of bytes written, even for truncated writes
  3667. * * negative error code if no data has been written at all
  3668. */
  3669. ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  3670. {
  3671. struct file *file = iocb->ki_filp;
  3672. struct address_space *mapping = file->f_mapping;
  3673. struct inode *inode = mapping->host;
  3674. ssize_t ret;
  3675. ret = file_remove_privs(file);
  3676. if (ret)
  3677. return ret;
  3678. ret = file_update_time(file);
  3679. if (ret)
  3680. return ret;
  3681. if (iocb->ki_flags & IOCB_DIRECT) {
  3682. ret = generic_file_direct_write(iocb, from);
  3683. /*
  3684. * If the write stopped short of completing, fall back to
  3685. * buffered writes. Some filesystems do this for writes to
  3686. * holes, for example. For DAX files, a buffered write will
  3687. * not succeed (even if it did, DAX does not handle dirty
  3688. * page-cache pages correctly).
  3689. */
  3690. if (ret < 0 || !iov_iter_count(from) || IS_DAX(inode))
  3691. return ret;
  3692. return direct_write_fallback(iocb, from, ret,
  3693. generic_perform_write(iocb, from));
  3694. }
  3695. return generic_perform_write(iocb, from);
  3696. }
  3697. EXPORT_SYMBOL(__generic_file_write_iter);
  3698. /**
  3699. * generic_file_write_iter - write data to a file
  3700. * @iocb: IO state structure
  3701. * @from: iov_iter with data to write
  3702. *
  3703. * This is a wrapper around __generic_file_write_iter() to be used by most
  3704. * filesystems. It takes care of syncing the file in case of O_SYNC file
  3705. * and acquires i_rwsem as needed.
  3706. * Return:
  3707. * * negative error code if no data has been written at all of
  3708. * vfs_fsync_range() failed for a synchronous write
  3709. * * number of bytes written, even for truncated writes
  3710. */
  3711. ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  3712. {
  3713. struct file *file = iocb->ki_filp;
  3714. struct inode *inode = file->f_mapping->host;
  3715. ssize_t ret;
  3716. inode_lock(inode);
  3717. ret = generic_write_checks(iocb, from);
  3718. if (ret > 0)
  3719. ret = __generic_file_write_iter(iocb, from);
  3720. inode_unlock(inode);
  3721. if (ret > 0)
  3722. ret = generic_write_sync(iocb, ret);
  3723. return ret;
  3724. }
  3725. EXPORT_SYMBOL(generic_file_write_iter);
  3726. /**
  3727. * filemap_release_folio() - Release fs-specific metadata on a folio.
  3728. * @folio: The folio which the kernel is trying to free.
  3729. * @gfp: Memory allocation flags (and I/O mode).
  3730. *
  3731. * The address_space is trying to release any data attached to a folio
  3732. * (presumably at folio->private).
  3733. *
  3734. * This will also be called if the private_2 flag is set on a page,
  3735. * indicating that the folio has other metadata associated with it.
  3736. *
  3737. * The @gfp argument specifies whether I/O may be performed to release
  3738. * this page (__GFP_IO), and whether the call may block
  3739. * (__GFP_RECLAIM & __GFP_FS).
  3740. *
  3741. * Return: %true if the release was successful, otherwise %false.
  3742. */
  3743. bool filemap_release_folio(struct folio *folio, gfp_t gfp)
  3744. {
  3745. struct address_space * const mapping = folio->mapping;
  3746. BUG_ON(!folio_test_locked(folio));
  3747. if (!folio_needs_release(folio))
  3748. return true;
  3749. if (folio_test_writeback(folio))
  3750. return false;
  3751. if (mapping && mapping->a_ops->release_folio)
  3752. return mapping->a_ops->release_folio(folio, gfp);
  3753. return try_to_free_buffers(folio);
  3754. }
  3755. EXPORT_SYMBOL(filemap_release_folio);
  3756. /**
  3757. * filemap_invalidate_inode - Invalidate/forcibly write back a range of an inode's pagecache
  3758. * @inode: The inode to flush
  3759. * @flush: Set to write back rather than simply invalidate.
  3760. * @start: First byte to in range.
  3761. * @end: Last byte in range (inclusive), or LLONG_MAX for everything from start
  3762. * onwards.
  3763. *
  3764. * Invalidate all the folios on an inode that contribute to the specified
  3765. * range, possibly writing them back first. Whilst the operation is
  3766. * undertaken, the invalidate lock is held to prevent new folios from being
  3767. * installed.
  3768. */
  3769. int filemap_invalidate_inode(struct inode *inode, bool flush,
  3770. loff_t start, loff_t end)
  3771. {
  3772. struct address_space *mapping = inode->i_mapping;
  3773. pgoff_t first = start >> PAGE_SHIFT;
  3774. pgoff_t last = end >> PAGE_SHIFT;
  3775. pgoff_t nr = end == LLONG_MAX ? ULONG_MAX : last - first + 1;
  3776. if (!mapping || !mapping->nrpages || end < start)
  3777. goto out;
  3778. /* Prevent new folios from being added to the inode. */
  3779. filemap_invalidate_lock(mapping);
  3780. if (!mapping->nrpages)
  3781. goto unlock;
  3782. unmap_mapping_pages(mapping, first, nr, false);
  3783. /* Write back the data if we're asked to. */
  3784. if (flush) {
  3785. struct writeback_control wbc = {
  3786. .sync_mode = WB_SYNC_ALL,
  3787. .nr_to_write = LONG_MAX,
  3788. .range_start = start,
  3789. .range_end = end,
  3790. };
  3791. filemap_fdatawrite_wbc(mapping, &wbc);
  3792. }
  3793. /* Wait for writeback to complete on all folios and discard. */
  3794. invalidate_inode_pages2_range(mapping, start / PAGE_SIZE, end / PAGE_SIZE);
  3795. unlock:
  3796. filemap_invalidate_unlock(mapping);
  3797. out:
  3798. return filemap_check_errors(mapping);
  3799. }
  3800. EXPORT_SYMBOL_GPL(filemap_invalidate_inode);
  3801. #ifdef CONFIG_CACHESTAT_SYSCALL
  3802. /**
  3803. * filemap_cachestat() - compute the page cache statistics of a mapping
  3804. * @mapping: The mapping to compute the statistics for.
  3805. * @first_index: The starting page cache index.
  3806. * @last_index: The final page index (inclusive).
  3807. * @cs: the cachestat struct to write the result to.
  3808. *
  3809. * This will query the page cache statistics of a mapping in the
  3810. * page range of [first_index, last_index] (inclusive). The statistics
  3811. * queried include: number of dirty pages, number of pages marked for
  3812. * writeback, and the number of (recently) evicted pages.
  3813. */
  3814. static void filemap_cachestat(struct address_space *mapping,
  3815. pgoff_t first_index, pgoff_t last_index, struct cachestat *cs)
  3816. {
  3817. XA_STATE(xas, &mapping->i_pages, first_index);
  3818. struct folio *folio;
  3819. /* Flush stats (and potentially sleep) outside the RCU read section. */
  3820. mem_cgroup_flush_stats_ratelimited(NULL);
  3821. rcu_read_lock();
  3822. xas_for_each(&xas, folio, last_index) {
  3823. int order;
  3824. unsigned long nr_pages;
  3825. pgoff_t folio_first_index, folio_last_index;
  3826. /*
  3827. * Don't deref the folio. It is not pinned, and might
  3828. * get freed (and reused) underneath us.
  3829. *
  3830. * We *could* pin it, but that would be expensive for
  3831. * what should be a fast and lightweight syscall.
  3832. *
  3833. * Instead, derive all information of interest from
  3834. * the rcu-protected xarray.
  3835. */
  3836. if (xas_retry(&xas, folio))
  3837. continue;
  3838. order = xas_get_order(&xas);
  3839. nr_pages = 1 << order;
  3840. folio_first_index = round_down(xas.xa_index, 1 << order);
  3841. folio_last_index = folio_first_index + nr_pages - 1;
  3842. /* Folios might straddle the range boundaries, only count covered pages */
  3843. if (folio_first_index < first_index)
  3844. nr_pages -= first_index - folio_first_index;
  3845. if (folio_last_index > last_index)
  3846. nr_pages -= folio_last_index - last_index;
  3847. if (xa_is_value(folio)) {
  3848. /* page is evicted */
  3849. void *shadow = (void *)folio;
  3850. bool workingset; /* not used */
  3851. cs->nr_evicted += nr_pages;
  3852. #ifdef CONFIG_SWAP /* implies CONFIG_MMU */
  3853. if (shmem_mapping(mapping)) {
  3854. /* shmem file - in swap cache */
  3855. swp_entry_t swp = radix_to_swp_entry(folio);
  3856. /* swapin error results in poisoned entry */
  3857. if (non_swap_entry(swp))
  3858. goto resched;
  3859. /*
  3860. * Getting a swap entry from the shmem
  3861. * inode means we beat
  3862. * shmem_unuse(). rcu_read_lock()
  3863. * ensures swapoff waits for us before
  3864. * freeing the swapper space. However,
  3865. * we can race with swapping and
  3866. * invalidation, so there might not be
  3867. * a shadow in the swapcache (yet).
  3868. */
  3869. shadow = get_shadow_from_swap_cache(swp);
  3870. if (!shadow)
  3871. goto resched;
  3872. }
  3873. #endif
  3874. if (workingset_test_recent(shadow, true, &workingset, false))
  3875. cs->nr_recently_evicted += nr_pages;
  3876. goto resched;
  3877. }
  3878. /* page is in cache */
  3879. cs->nr_cache += nr_pages;
  3880. if (xas_get_mark(&xas, PAGECACHE_TAG_DIRTY))
  3881. cs->nr_dirty += nr_pages;
  3882. if (xas_get_mark(&xas, PAGECACHE_TAG_WRITEBACK))
  3883. cs->nr_writeback += nr_pages;
  3884. resched:
  3885. if (need_resched()) {
  3886. xas_pause(&xas);
  3887. cond_resched_rcu();
  3888. }
  3889. }
  3890. rcu_read_unlock();
  3891. }
  3892. /*
  3893. * See mincore: reveal pagecache information only for files
  3894. * that the calling process has write access to, or could (if
  3895. * tried) open for writing.
  3896. */
  3897. static inline bool can_do_cachestat(struct file *f)
  3898. {
  3899. if (f->f_mode & FMODE_WRITE)
  3900. return true;
  3901. if (inode_owner_or_capable(file_mnt_idmap(f), file_inode(f)))
  3902. return true;
  3903. return file_permission(f, MAY_WRITE) == 0;
  3904. }
  3905. /*
  3906. * The cachestat(2) system call.
  3907. *
  3908. * cachestat() returns the page cache statistics of a file in the
  3909. * bytes range specified by `off` and `len`: number of cached pages,
  3910. * number of dirty pages, number of pages marked for writeback,
  3911. * number of evicted pages, and number of recently evicted pages.
  3912. *
  3913. * An evicted page is a page that is previously in the page cache
  3914. * but has been evicted since. A page is recently evicted if its last
  3915. * eviction was recent enough that its reentry to the cache would
  3916. * indicate that it is actively being used by the system, and that
  3917. * there is memory pressure on the system.
  3918. *
  3919. * `off` and `len` must be non-negative integers. If `len` > 0,
  3920. * the queried range is [`off`, `off` + `len`]. If `len` == 0,
  3921. * we will query in the range from `off` to the end of the file.
  3922. *
  3923. * The `flags` argument is unused for now, but is included for future
  3924. * extensibility. User should pass 0 (i.e no flag specified).
  3925. *
  3926. * Currently, hugetlbfs is not supported.
  3927. *
  3928. * Because the status of a page can change after cachestat() checks it
  3929. * but before it returns to the application, the returned values may
  3930. * contain stale information.
  3931. *
  3932. * return values:
  3933. * zero - success
  3934. * -EFAULT - cstat or cstat_range points to an illegal address
  3935. * -EINVAL - invalid flags
  3936. * -EBADF - invalid file descriptor
  3937. * -EOPNOTSUPP - file descriptor is of a hugetlbfs file
  3938. */
  3939. SYSCALL_DEFINE4(cachestat, unsigned int, fd,
  3940. struct cachestat_range __user *, cstat_range,
  3941. struct cachestat __user *, cstat, unsigned int, flags)
  3942. {
  3943. struct fd f = fdget(fd);
  3944. struct address_space *mapping;
  3945. struct cachestat_range csr;
  3946. struct cachestat cs;
  3947. pgoff_t first_index, last_index;
  3948. if (!fd_file(f))
  3949. return -EBADF;
  3950. if (copy_from_user(&csr, cstat_range,
  3951. sizeof(struct cachestat_range))) {
  3952. fdput(f);
  3953. return -EFAULT;
  3954. }
  3955. /* hugetlbfs is not supported */
  3956. if (is_file_hugepages(fd_file(f))) {
  3957. fdput(f);
  3958. return -EOPNOTSUPP;
  3959. }
  3960. if (!can_do_cachestat(fd_file(f))) {
  3961. fdput(f);
  3962. return -EPERM;
  3963. }
  3964. if (flags != 0) {
  3965. fdput(f);
  3966. return -EINVAL;
  3967. }
  3968. first_index = csr.off >> PAGE_SHIFT;
  3969. last_index =
  3970. csr.len == 0 ? ULONG_MAX : (csr.off + csr.len - 1) >> PAGE_SHIFT;
  3971. memset(&cs, 0, sizeof(struct cachestat));
  3972. mapping = fd_file(f)->f_mapping;
  3973. filemap_cachestat(mapping, first_index, last_index, &cs);
  3974. fdput(f);
  3975. if (copy_to_user(cstat, &cs, sizeof(struct cachestat)))
  3976. return -EFAULT;
  3977. return 0;
  3978. }
  3979. #endif /* CONFIG_CACHESTAT_SYSCALL */