filemap.c 114 KB

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