filemap.c 127 KB

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