vmscan.c 219 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  4. *
  5. * Swap reorganised 29.12.95, Stephen Tweedie.
  6. * kswapd added: 7.1.96 sct
  7. * Removed kswapd_ctl limits, and swap out as many pages as needed
  8. * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
  9. * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
  10. * Multiqueue VM started 5.8.00, Rik van Riel.
  11. */
  12. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  13. #include <linux/mm.h>
  14. #include <linux/sched/mm.h>
  15. #include <linux/module.h>
  16. #include <linux/gfp.h>
  17. #include <linux/kernel_stat.h>
  18. #include <linux/swap.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/init.h>
  21. #include <linux/highmem.h>
  22. #include <linux/vmpressure.h>
  23. #include <linux/vmstat.h>
  24. #include <linux/file.h>
  25. #include <linux/writeback.h>
  26. #include <linux/blkdev.h>
  27. #include <linux/buffer_head.h> /* for buffer_heads_over_limit */
  28. #include <linux/mm_inline.h>
  29. #include <linux/backing-dev.h>
  30. #include <linux/rmap.h>
  31. #include <linux/topology.h>
  32. #include <linux/cpu.h>
  33. #include <linux/cpuset.h>
  34. #include <linux/compaction.h>
  35. #include <linux/notifier.h>
  36. #include <linux/delay.h>
  37. #include <linux/kthread.h>
  38. #include <linux/freezer.h>
  39. #include <linux/memcontrol.h>
  40. #include <linux/migrate.h>
  41. #include <linux/delayacct.h>
  42. #include <linux/sysctl.h>
  43. #include <linux/memory-tiers.h>
  44. #include <linux/oom.h>
  45. #include <linux/pagevec.h>
  46. #include <linux/prefetch.h>
  47. #include <linux/printk.h>
  48. #include <linux/dax.h>
  49. #include <linux/psi.h>
  50. #include <linux/pagewalk.h>
  51. #include <linux/shmem_fs.h>
  52. #include <linux/ctype.h>
  53. #include <linux/debugfs.h>
  54. #include <linux/khugepaged.h>
  55. #include <linux/rculist_nulls.h>
  56. #include <linux/random.h>
  57. #include <linux/mmu_notifier.h>
  58. #include <linux/parser.h>
  59. #include <asm/tlbflush.h>
  60. #include <asm/div64.h>
  61. #include <linux/swapops.h>
  62. #include <linux/sched/sysctl.h>
  63. #include "internal.h"
  64. #include "swap.h"
  65. #define CREATE_TRACE_POINTS
  66. #include <trace/events/vmscan.h>
  67. struct scan_control {
  68. /* How many pages shrink_list() should reclaim */
  69. unsigned long nr_to_reclaim;
  70. /*
  71. * Nodemask of nodes allowed by the caller. If NULL, all nodes
  72. * are scanned.
  73. */
  74. nodemask_t *nodemask;
  75. /*
  76. * The memory cgroup that hit its limit and as a result is the
  77. * primary target of this reclaim invocation.
  78. */
  79. struct mem_cgroup *target_mem_cgroup;
  80. /*
  81. * Scan pressure balancing between anon and file LRUs
  82. */
  83. unsigned long anon_cost;
  84. unsigned long file_cost;
  85. /* Swappiness value for proactive reclaim. Always use sc_swappiness()! */
  86. int *proactive_swappiness;
  87. /* Can active folios be deactivated as part of reclaim? */
  88. #define DEACTIVATE_ANON 1
  89. #define DEACTIVATE_FILE 2
  90. unsigned int may_deactivate:2;
  91. unsigned int force_deactivate:1;
  92. unsigned int skipped_deactivate:1;
  93. /* zone_reclaim_mode, boost reclaim */
  94. unsigned int may_writepage:1;
  95. /* zone_reclaim_mode */
  96. unsigned int may_unmap:1;
  97. /* zome_reclaim_mode, boost reclaim, cgroup restrictions */
  98. unsigned int may_swap:1;
  99. /* Not allow cache_trim_mode to be turned on as part of reclaim? */
  100. unsigned int no_cache_trim_mode:1;
  101. /* Has cache_trim_mode failed at least once? */
  102. unsigned int cache_trim_mode_failed:1;
  103. /* Proactive reclaim invoked by userspace */
  104. unsigned int proactive:1;
  105. /*
  106. * Cgroup memory below memory.low is protected as long as we
  107. * don't threaten to OOM. If any cgroup is reclaimed at
  108. * reduced force or passed over entirely due to its memory.low
  109. * setting (memcg_low_skipped), and nothing is reclaimed as a
  110. * result, then go back for one more cycle that reclaims the protected
  111. * memory (memcg_low_reclaim) to avert OOM.
  112. */
  113. unsigned int memcg_low_reclaim:1;
  114. unsigned int memcg_low_skipped:1;
  115. /* Shared cgroup tree walk failed, rescan the whole tree */
  116. unsigned int memcg_full_walk:1;
  117. unsigned int hibernation_mode:1;
  118. /* One of the zones is ready for compaction */
  119. unsigned int compaction_ready:1;
  120. /* There is easily reclaimable cold cache in the current node */
  121. unsigned int cache_trim_mode:1;
  122. /* The file folios on the current node are dangerously low */
  123. unsigned int file_is_tiny:1;
  124. /* Always discard instead of demoting to lower tier memory */
  125. unsigned int no_demotion:1;
  126. /* Allocation order */
  127. s8 order;
  128. /* Scan (total_size >> priority) pages at once */
  129. s8 priority;
  130. /* The highest zone to isolate folios for reclaim from */
  131. s8 reclaim_idx;
  132. /* This context's GFP mask */
  133. gfp_t gfp_mask;
  134. /* Incremented by the number of inactive pages that were scanned */
  135. unsigned long nr_scanned;
  136. /* Number of pages freed so far during a call to shrink_zones() */
  137. unsigned long nr_reclaimed;
  138. struct {
  139. unsigned int dirty;
  140. unsigned int unqueued_dirty;
  141. unsigned int congested;
  142. unsigned int writeback;
  143. unsigned int immediate;
  144. unsigned int file_taken;
  145. unsigned int taken;
  146. } nr;
  147. /* for recording the reclaimed slab by now */
  148. struct reclaim_state reclaim_state;
  149. };
  150. #ifdef ARCH_HAS_PREFETCHW
  151. #define prefetchw_prev_lru_folio(_folio, _base, _field) \
  152. do { \
  153. if ((_folio)->lru.prev != _base) { \
  154. struct folio *prev; \
  155. \
  156. prev = lru_to_folio(&(_folio->lru)); \
  157. prefetchw(&prev->_field); \
  158. } \
  159. } while (0)
  160. #else
  161. #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
  162. #endif
  163. /*
  164. * From 0 .. MAX_SWAPPINESS. Higher means more swappy.
  165. */
  166. int vm_swappiness = 60;
  167. #ifdef CONFIG_MEMCG
  168. /* Returns true for reclaim through cgroup limits or cgroup interfaces. */
  169. static bool cgroup_reclaim(struct scan_control *sc)
  170. {
  171. return sc->target_mem_cgroup;
  172. }
  173. /*
  174. * Returns true for reclaim on the root cgroup. This is true for direct
  175. * allocator reclaim and reclaim through cgroup interfaces on the root cgroup.
  176. */
  177. static bool root_reclaim(struct scan_control *sc)
  178. {
  179. return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
  180. }
  181. /**
  182. * writeback_throttling_sane - is the usual dirty throttling mechanism available?
  183. * @sc: scan_control in question
  184. *
  185. * The normal page dirty throttling mechanism in balance_dirty_pages() is
  186. * completely broken with the legacy memcg and direct stalling in
  187. * shrink_folio_list() is used for throttling instead, which lacks all the
  188. * niceties such as fairness, adaptive pausing, bandwidth proportional
  189. * allocation and configurability.
  190. *
  191. * This function tests whether the vmscan currently in progress can assume
  192. * that the normal dirty throttling mechanism is operational.
  193. */
  194. static bool writeback_throttling_sane(struct scan_control *sc)
  195. {
  196. if (!cgroup_reclaim(sc))
  197. return true;
  198. #ifdef CONFIG_CGROUP_WRITEBACK
  199. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  200. return true;
  201. #endif
  202. return false;
  203. }
  204. static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
  205. {
  206. if (sc->proactive && sc->proactive_swappiness)
  207. return *sc->proactive_swappiness;
  208. return mem_cgroup_swappiness(memcg);
  209. }
  210. #else
  211. static bool cgroup_reclaim(struct scan_control *sc)
  212. {
  213. return false;
  214. }
  215. static bool root_reclaim(struct scan_control *sc)
  216. {
  217. return true;
  218. }
  219. static bool writeback_throttling_sane(struct scan_control *sc)
  220. {
  221. return true;
  222. }
  223. static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
  224. {
  225. return READ_ONCE(vm_swappiness);
  226. }
  227. #endif
  228. /* for_each_managed_zone_pgdat - helper macro to iterate over all managed zones in a pgdat up to
  229. * and including the specified highidx
  230. * @zone: The current zone in the iterator
  231. * @pgdat: The pgdat which node_zones are being iterated
  232. * @idx: The index variable
  233. * @highidx: The index of the highest zone to return
  234. *
  235. * This macro iterates through all managed zones up to and including the specified highidx.
  236. * The zone iterator enters an invalid state after macro call and must be reinitialized
  237. * before it can be used again.
  238. */
  239. #define for_each_managed_zone_pgdat(zone, pgdat, idx, highidx) \
  240. for ((idx) = 0, (zone) = (pgdat)->node_zones; \
  241. (idx) <= (highidx); \
  242. (idx)++, (zone)++) \
  243. if (!managed_zone(zone)) \
  244. continue; \
  245. else
  246. static void set_task_reclaim_state(struct task_struct *task,
  247. struct reclaim_state *rs)
  248. {
  249. /* Check for an overwrite */
  250. WARN_ON_ONCE(rs && task->reclaim_state);
  251. /* Check for the nulling of an already-nulled member */
  252. WARN_ON_ONCE(!rs && !task->reclaim_state);
  253. task->reclaim_state = rs;
  254. }
  255. /*
  256. * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
  257. * scan_control->nr_reclaimed.
  258. */
  259. static void flush_reclaim_state(struct scan_control *sc)
  260. {
  261. /*
  262. * Currently, reclaim_state->reclaimed includes three types of pages
  263. * freed outside of vmscan:
  264. * (1) Slab pages.
  265. * (2) Clean file pages from pruned inodes (on highmem systems).
  266. * (3) XFS freed buffer pages.
  267. *
  268. * For all of these cases, we cannot universally link the pages to a
  269. * single memcg. For example, a memcg-aware shrinker can free one object
  270. * charged to the target memcg, causing an entire page to be freed.
  271. * If we count the entire page as reclaimed from the memcg, we end up
  272. * overestimating the reclaimed amount (potentially under-reclaiming).
  273. *
  274. * Only count such pages for global reclaim to prevent under-reclaiming
  275. * from the target memcg; preventing unnecessary retries during memcg
  276. * charging and false positives from proactive reclaim.
  277. *
  278. * For uncommon cases where the freed pages were actually mostly
  279. * charged to the target memcg, we end up underestimating the reclaimed
  280. * amount. This should be fine. The freed pages will be uncharged
  281. * anyway, even if they are not counted here properly, and we will be
  282. * able to make forward progress in charging (which is usually in a
  283. * retry loop).
  284. *
  285. * We can go one step further, and report the uncharged objcg pages in
  286. * memcg reclaim, to make reporting more accurate and reduce
  287. * underestimation, but it's probably not worth the complexity for now.
  288. */
  289. if (current->reclaim_state && root_reclaim(sc)) {
  290. sc->nr_reclaimed += current->reclaim_state->reclaimed;
  291. current->reclaim_state->reclaimed = 0;
  292. }
  293. }
  294. static bool can_demote(int nid, struct scan_control *sc,
  295. struct mem_cgroup *memcg)
  296. {
  297. struct pglist_data *pgdat = NODE_DATA(nid);
  298. nodemask_t allowed_mask;
  299. if (!pgdat || !numa_demotion_enabled)
  300. return false;
  301. if (sc && sc->no_demotion)
  302. return false;
  303. node_get_allowed_targets(pgdat, &allowed_mask);
  304. if (nodes_empty(allowed_mask))
  305. return false;
  306. /* Filter out nodes that are not in cgroup's mems_allowed. */
  307. mem_cgroup_node_filter_allowed(memcg, &allowed_mask);
  308. return !nodes_empty(allowed_mask);
  309. }
  310. static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
  311. int nid,
  312. struct scan_control *sc)
  313. {
  314. if (memcg == NULL) {
  315. /*
  316. * For non-memcg reclaim, is there
  317. * space in any swap device?
  318. */
  319. if (get_nr_swap_pages() > 0)
  320. return true;
  321. } else {
  322. /* Is the memcg below its swap limit? */
  323. if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
  324. return true;
  325. }
  326. /*
  327. * The page can not be swapped.
  328. *
  329. * Can it be reclaimed from this node via demotion?
  330. */
  331. return can_demote(nid, sc, memcg);
  332. }
  333. /*
  334. * This misses isolated folios which are not accounted for to save counters.
  335. * As the data only determines if reclaim or compaction continues, it is
  336. * not expected that isolated folios will be a dominating factor.
  337. */
  338. unsigned long zone_reclaimable_pages(struct zone *zone)
  339. {
  340. unsigned long nr;
  341. nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
  342. zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
  343. if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
  344. nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
  345. zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
  346. return nr;
  347. }
  348. /**
  349. * lruvec_lru_size - Returns the number of pages on the given LRU list.
  350. * @lruvec: lru vector
  351. * @lru: lru to use
  352. * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
  353. */
  354. static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
  355. int zone_idx)
  356. {
  357. unsigned long size = 0;
  358. int zid;
  359. struct zone *zone;
  360. for_each_managed_zone_pgdat(zone, lruvec_pgdat(lruvec), zid, zone_idx) {
  361. if (!mem_cgroup_disabled())
  362. size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
  363. else
  364. size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
  365. }
  366. return size;
  367. }
  368. static unsigned long drop_slab_node(int nid)
  369. {
  370. unsigned long freed = 0;
  371. struct mem_cgroup *memcg = NULL;
  372. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  373. do {
  374. freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
  375. } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
  376. return freed;
  377. }
  378. void drop_slab(void)
  379. {
  380. int nid;
  381. int shift = 0;
  382. unsigned long freed;
  383. do {
  384. freed = 0;
  385. for_each_online_node(nid) {
  386. if (fatal_signal_pending(current))
  387. return;
  388. freed += drop_slab_node(nid);
  389. }
  390. } while ((freed >> shift++) > 1);
  391. }
  392. #define CHECK_RECLAIMER_OFFSET(type) \
  393. do { \
  394. BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \
  395. PGDEMOTE_##type - PGDEMOTE_KSWAPD); \
  396. BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \
  397. PGSCAN_##type - PGSCAN_KSWAPD); \
  398. } while (0)
  399. static int reclaimer_offset(struct scan_control *sc)
  400. {
  401. CHECK_RECLAIMER_OFFSET(DIRECT);
  402. CHECK_RECLAIMER_OFFSET(KHUGEPAGED);
  403. CHECK_RECLAIMER_OFFSET(PROACTIVE);
  404. if (current_is_kswapd())
  405. return 0;
  406. if (current_is_khugepaged())
  407. return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
  408. if (sc->proactive)
  409. return PGSTEAL_PROACTIVE - PGSTEAL_KSWAPD;
  410. return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
  411. }
  412. /*
  413. * We detected a synchronous write error writing a folio out. Probably
  414. * -ENOSPC. We need to propagate that into the address_space for a subsequent
  415. * fsync(), msync() or close().
  416. *
  417. * The tricky part is that after writepage we cannot touch the mapping: nothing
  418. * prevents it from being freed up. But we have a ref on the folio and once
  419. * that folio is locked, the mapping is pinned.
  420. *
  421. * We're allowed to run sleeping folio_lock() here because we know the caller has
  422. * __GFP_FS.
  423. */
  424. static void handle_write_error(struct address_space *mapping,
  425. struct folio *folio, int error)
  426. {
  427. folio_lock(folio);
  428. if (folio_mapping(folio) == mapping)
  429. mapping_set_error(mapping, error);
  430. folio_unlock(folio);
  431. }
  432. static bool skip_throttle_noprogress(pg_data_t *pgdat)
  433. {
  434. int reclaimable = 0, write_pending = 0;
  435. int i;
  436. struct zone *zone;
  437. /*
  438. * If kswapd is disabled, reschedule if necessary but do not
  439. * throttle as the system is likely near OOM.
  440. */
  441. if (kswapd_test_hopeless(pgdat))
  442. return true;
  443. /*
  444. * If there are a lot of dirty/writeback folios then do not
  445. * throttle as throttling will occur when the folios cycle
  446. * towards the end of the LRU if still under writeback.
  447. */
  448. for_each_managed_zone_pgdat(zone, pgdat, i, MAX_NR_ZONES - 1) {
  449. reclaimable += zone_reclaimable_pages(zone);
  450. write_pending += zone_page_state_snapshot(zone,
  451. NR_ZONE_WRITE_PENDING);
  452. }
  453. if (2 * write_pending <= reclaimable)
  454. return true;
  455. return false;
  456. }
  457. void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
  458. {
  459. wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
  460. long timeout, ret;
  461. DEFINE_WAIT(wait);
  462. /*
  463. * Do not throttle user workers, kthreads other than kswapd or
  464. * workqueues. They may be required for reclaim to make
  465. * forward progress (e.g. journalling workqueues or kthreads).
  466. */
  467. if (!current_is_kswapd() &&
  468. current->flags & (PF_USER_WORKER|PF_KTHREAD)) {
  469. cond_resched();
  470. return;
  471. }
  472. /*
  473. * These figures are pulled out of thin air.
  474. * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
  475. * parallel reclaimers which is a short-lived event so the timeout is
  476. * short. Failing to make progress or waiting on writeback are
  477. * potentially long-lived events so use a longer timeout. This is shaky
  478. * logic as a failure to make progress could be due to anything from
  479. * writeback to a slow device to excessive referenced folios at the tail
  480. * of the inactive LRU.
  481. */
  482. switch(reason) {
  483. case VMSCAN_THROTTLE_WRITEBACK:
  484. timeout = HZ/10;
  485. if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
  486. WRITE_ONCE(pgdat->nr_reclaim_start,
  487. node_page_state(pgdat, NR_THROTTLED_WRITTEN));
  488. }
  489. break;
  490. case VMSCAN_THROTTLE_CONGESTED:
  491. fallthrough;
  492. case VMSCAN_THROTTLE_NOPROGRESS:
  493. if (skip_throttle_noprogress(pgdat)) {
  494. cond_resched();
  495. return;
  496. }
  497. timeout = 1;
  498. break;
  499. case VMSCAN_THROTTLE_ISOLATED:
  500. timeout = HZ/50;
  501. break;
  502. default:
  503. WARN_ON_ONCE(1);
  504. timeout = HZ;
  505. break;
  506. }
  507. prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
  508. ret = schedule_timeout(timeout);
  509. finish_wait(wqh, &wait);
  510. if (reason == VMSCAN_THROTTLE_WRITEBACK)
  511. atomic_dec(&pgdat->nr_writeback_throttled);
  512. trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
  513. jiffies_to_usecs(timeout - ret),
  514. reason);
  515. }
  516. /*
  517. * Account for folios written if tasks are throttled waiting on dirty
  518. * folios to clean. If enough folios have been cleaned since throttling
  519. * started then wakeup the throttled tasks.
  520. */
  521. void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
  522. int nr_throttled)
  523. {
  524. unsigned long nr_written;
  525. node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
  526. /*
  527. * This is an inaccurate read as the per-cpu deltas may not
  528. * be synchronised. However, given that the system is
  529. * writeback throttled, it is not worth taking the penalty
  530. * of getting an accurate count. At worst, the throttle
  531. * timeout guarantees forward progress.
  532. */
  533. nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
  534. READ_ONCE(pgdat->nr_reclaim_start);
  535. if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
  536. wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
  537. }
  538. /* possible outcome of pageout() */
  539. typedef enum {
  540. /* failed to write folio out, folio is locked */
  541. PAGE_KEEP,
  542. /* move folio to the active list, folio is locked */
  543. PAGE_ACTIVATE,
  544. /* folio has been sent to the disk successfully, folio is unlocked */
  545. PAGE_SUCCESS,
  546. /* folio is clean and locked */
  547. PAGE_CLEAN,
  548. } pageout_t;
  549. static pageout_t writeout(struct folio *folio, struct address_space *mapping,
  550. struct swap_iocb **plug, struct list_head *folio_list)
  551. {
  552. int res;
  553. folio_set_reclaim(folio);
  554. /*
  555. * The large shmem folio can be split if CONFIG_THP_SWAP is not enabled
  556. * or we failed to allocate contiguous swap entries, in which case
  557. * the split out folios get added back to folio_list.
  558. */
  559. if (shmem_mapping(mapping))
  560. res = shmem_writeout(folio, plug, folio_list);
  561. else
  562. res = swap_writeout(folio, plug);
  563. if (res < 0)
  564. handle_write_error(mapping, folio, res);
  565. if (res == AOP_WRITEPAGE_ACTIVATE) {
  566. folio_clear_reclaim(folio);
  567. return PAGE_ACTIVATE;
  568. }
  569. /* synchronous write? */
  570. if (!folio_test_writeback(folio))
  571. folio_clear_reclaim(folio);
  572. trace_mm_vmscan_write_folio(folio);
  573. node_stat_add_folio(folio, NR_VMSCAN_WRITE);
  574. return PAGE_SUCCESS;
  575. }
  576. /*
  577. * pageout is called by shrink_folio_list() for each dirty folio.
  578. */
  579. static pageout_t pageout(struct folio *folio, struct address_space *mapping,
  580. struct swap_iocb **plug, struct list_head *folio_list)
  581. {
  582. /*
  583. * We no longer attempt to writeback filesystem folios here, other
  584. * than tmpfs/shmem. That's taken care of in page-writeback.
  585. * If we find a dirty filesystem folio at the end of the LRU list,
  586. * typically that means the filesystem is saturating the storage
  587. * with contiguous writes and telling it to write a folio here
  588. * would only make the situation worse by injecting an element
  589. * of random access.
  590. *
  591. * If the folio is swapcache, write it back even if that would
  592. * block, for some throttling. This happens by accident, because
  593. * swap_backing_dev_info is bust: it doesn't reflect the
  594. * congestion state of the swapdevs. Easy to fix, if needed.
  595. *
  596. * A freeable shmem or swapcache folio is referenced only by the
  597. * caller that isolated the folio and the page cache.
  598. */
  599. if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping)
  600. return PAGE_KEEP;
  601. if (!shmem_mapping(mapping) && !folio_test_anon(folio))
  602. return PAGE_ACTIVATE;
  603. if (!folio_clear_dirty_for_io(folio))
  604. return PAGE_CLEAN;
  605. return writeout(folio, mapping, plug, folio_list);
  606. }
  607. /*
  608. * Same as remove_mapping, but if the folio is removed from the mapping, it
  609. * gets returned with a refcount of 0.
  610. */
  611. static int __remove_mapping(struct address_space *mapping, struct folio *folio,
  612. bool reclaimed, struct mem_cgroup *target_memcg)
  613. {
  614. int refcount;
  615. void *shadow = NULL;
  616. struct swap_cluster_info *ci;
  617. BUG_ON(!folio_test_locked(folio));
  618. BUG_ON(mapping != folio_mapping(folio));
  619. if (folio_test_swapcache(folio)) {
  620. ci = swap_cluster_get_and_lock_irq(folio);
  621. } else {
  622. spin_lock(&mapping->host->i_lock);
  623. xa_lock_irq(&mapping->i_pages);
  624. }
  625. /*
  626. * The non racy check for a busy folio.
  627. *
  628. * Must be careful with the order of the tests. When someone has
  629. * a ref to the folio, it may be possible that they dirty it then
  630. * drop the reference. So if the dirty flag is tested before the
  631. * refcount here, then the following race may occur:
  632. *
  633. * get_user_pages(&page);
  634. * [user mapping goes away]
  635. * write_to(page);
  636. * !folio_test_dirty(folio) [good]
  637. * folio_set_dirty(folio);
  638. * folio_put(folio);
  639. * !refcount(folio) [good, discard it]
  640. *
  641. * [oops, our write_to data is lost]
  642. *
  643. * Reversing the order of the tests ensures such a situation cannot
  644. * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
  645. * load is not satisfied before that of folio->_refcount.
  646. *
  647. * Note that if the dirty flag is always set via folio_mark_dirty,
  648. * and thus under the i_pages lock, then this ordering is not required.
  649. */
  650. refcount = 1 + folio_nr_pages(folio);
  651. if (!folio_ref_freeze(folio, refcount))
  652. goto cannot_free;
  653. /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
  654. if (unlikely(folio_test_dirty(folio))) {
  655. folio_ref_unfreeze(folio, refcount);
  656. goto cannot_free;
  657. }
  658. if (folio_test_swapcache(folio)) {
  659. swp_entry_t swap = folio->swap;
  660. if (reclaimed && !mapping_exiting(mapping))
  661. shadow = workingset_eviction(folio, target_memcg);
  662. memcg1_swapout(folio, swap);
  663. __swap_cache_del_folio(ci, folio, swap, shadow);
  664. swap_cluster_unlock_irq(ci);
  665. } else {
  666. void (*free_folio)(struct folio *);
  667. free_folio = mapping->a_ops->free_folio;
  668. /*
  669. * Remember a shadow entry for reclaimed file cache in
  670. * order to detect refaults, thus thrashing, later on.
  671. *
  672. * But don't store shadows in an address space that is
  673. * already exiting. This is not just an optimization,
  674. * inode reclaim needs to empty out the radix tree or
  675. * the nodes are lost. Don't plant shadows behind its
  676. * back.
  677. *
  678. * We also don't store shadows for DAX mappings because the
  679. * only page cache folios found in these are zero pages
  680. * covering holes, and because we don't want to mix DAX
  681. * exceptional entries and shadow exceptional entries in the
  682. * same address_space.
  683. */
  684. if (reclaimed && folio_is_file_lru(folio) &&
  685. !mapping_exiting(mapping) && !dax_mapping(mapping))
  686. shadow = workingset_eviction(folio, target_memcg);
  687. __filemap_remove_folio(folio, shadow);
  688. xa_unlock_irq(&mapping->i_pages);
  689. if (mapping_shrinkable(mapping))
  690. inode_lru_list_add(mapping->host);
  691. spin_unlock(&mapping->host->i_lock);
  692. if (free_folio)
  693. free_folio(folio);
  694. }
  695. return 1;
  696. cannot_free:
  697. if (folio_test_swapcache(folio)) {
  698. swap_cluster_unlock_irq(ci);
  699. } else {
  700. xa_unlock_irq(&mapping->i_pages);
  701. spin_unlock(&mapping->host->i_lock);
  702. }
  703. return 0;
  704. }
  705. /**
  706. * remove_mapping() - Attempt to remove a folio from its mapping.
  707. * @mapping: The address space.
  708. * @folio: The folio to remove.
  709. *
  710. * If the folio is dirty, under writeback or if someone else has a ref
  711. * on it, removal will fail.
  712. * Return: The number of pages removed from the mapping. 0 if the folio
  713. * could not be removed.
  714. * Context: The caller should have a single refcount on the folio and
  715. * hold its lock.
  716. */
  717. long remove_mapping(struct address_space *mapping, struct folio *folio)
  718. {
  719. if (__remove_mapping(mapping, folio, false, NULL)) {
  720. /*
  721. * Unfreezing the refcount with 1 effectively
  722. * drops the pagecache ref for us without requiring another
  723. * atomic operation.
  724. */
  725. folio_ref_unfreeze(folio, 1);
  726. return folio_nr_pages(folio);
  727. }
  728. return 0;
  729. }
  730. /**
  731. * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
  732. * @folio: Folio to be returned to an LRU list.
  733. *
  734. * Add previously isolated @folio to appropriate LRU list.
  735. * The folio may still be unevictable for other reasons.
  736. *
  737. * Context: lru_lock must not be held, interrupts must be enabled.
  738. */
  739. void folio_putback_lru(struct folio *folio)
  740. {
  741. folio_add_lru(folio);
  742. folio_put(folio); /* drop ref from isolate */
  743. }
  744. enum folio_references {
  745. FOLIOREF_RECLAIM,
  746. FOLIOREF_RECLAIM_CLEAN,
  747. FOLIOREF_KEEP,
  748. FOLIOREF_ACTIVATE,
  749. };
  750. #ifdef CONFIG_LRU_GEN
  751. /*
  752. * Only used on a mapped folio in the eviction (rmap walk) path, where promotion
  753. * needs to be done by taking the folio off the LRU list and then adding it back
  754. * with PG_active set. In contrast, the aging (page table walk) path uses
  755. * folio_update_gen().
  756. */
  757. static bool lru_gen_set_refs(struct folio *folio)
  758. {
  759. /* see the comment on LRU_REFS_FLAGS */
  760. if (!folio_test_referenced(folio) && !folio_test_workingset(folio)) {
  761. set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced));
  762. return false;
  763. }
  764. set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_workingset));
  765. return true;
  766. }
  767. #else
  768. static bool lru_gen_set_refs(struct folio *folio)
  769. {
  770. return false;
  771. }
  772. #endif /* CONFIG_LRU_GEN */
  773. static enum folio_references folio_check_references(struct folio *folio,
  774. struct scan_control *sc)
  775. {
  776. int referenced_ptes, referenced_folio;
  777. vm_flags_t vm_flags;
  778. referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
  779. &vm_flags);
  780. /*
  781. * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
  782. * Let the folio, now marked Mlocked, be moved to the unevictable list.
  783. */
  784. if (vm_flags & VM_LOCKED)
  785. return FOLIOREF_ACTIVATE;
  786. /*
  787. * There are two cases to consider.
  788. * 1) Rmap lock contention: rotate.
  789. * 2) Skip the non-shared swapbacked folio mapped solely by
  790. * the exiting or OOM-reaped process.
  791. */
  792. if (referenced_ptes == -1)
  793. return FOLIOREF_KEEP;
  794. if (lru_gen_enabled()) {
  795. if (!referenced_ptes)
  796. return FOLIOREF_RECLAIM;
  797. return lru_gen_set_refs(folio) ? FOLIOREF_ACTIVATE : FOLIOREF_KEEP;
  798. }
  799. referenced_folio = folio_test_clear_referenced(folio);
  800. if (referenced_ptes) {
  801. /*
  802. * All mapped folios start out with page table
  803. * references from the instantiating fault, so we need
  804. * to look twice if a mapped file/anon folio is used more
  805. * than once.
  806. *
  807. * Mark it and spare it for another trip around the
  808. * inactive list. Another page table reference will
  809. * lead to its activation.
  810. *
  811. * Note: the mark is set for activated folios as well
  812. * so that recently deactivated but used folios are
  813. * quickly recovered.
  814. */
  815. folio_set_referenced(folio);
  816. if (referenced_folio || referenced_ptes > 1)
  817. return FOLIOREF_ACTIVATE;
  818. /*
  819. * Activate file-backed executable folios after first usage.
  820. */
  821. if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
  822. return FOLIOREF_ACTIVATE;
  823. return FOLIOREF_KEEP;
  824. }
  825. /* Reclaim if clean, defer dirty folios to writeback */
  826. if (referenced_folio && folio_is_file_lru(folio))
  827. return FOLIOREF_RECLAIM_CLEAN;
  828. return FOLIOREF_RECLAIM;
  829. }
  830. /* Check if a folio is dirty or under writeback */
  831. static void folio_check_dirty_writeback(struct folio *folio,
  832. bool *dirty, bool *writeback)
  833. {
  834. struct address_space *mapping;
  835. /*
  836. * Anonymous folios are not handled by flushers and must be written
  837. * from reclaim context. Do not stall reclaim based on them.
  838. * MADV_FREE anonymous folios are put into inactive file list too.
  839. * They could be mistakenly treated as file lru. So further anon
  840. * test is needed.
  841. */
  842. if (!folio_is_file_lru(folio) ||
  843. (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
  844. *dirty = false;
  845. *writeback = false;
  846. return;
  847. }
  848. /* By default assume that the folio flags are accurate */
  849. *dirty = folio_test_dirty(folio);
  850. *writeback = folio_test_writeback(folio);
  851. /* Verify dirty/writeback state if the filesystem supports it */
  852. if (!folio_test_private(folio))
  853. return;
  854. mapping = folio_mapping(folio);
  855. if (mapping && mapping->a_ops->is_dirty_writeback)
  856. mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
  857. }
  858. static struct folio *alloc_demote_folio(struct folio *src,
  859. unsigned long private)
  860. {
  861. struct folio *dst;
  862. nodemask_t *allowed_mask;
  863. struct migration_target_control *mtc;
  864. mtc = (struct migration_target_control *)private;
  865. allowed_mask = mtc->nmask;
  866. /*
  867. * make sure we allocate from the target node first also trying to
  868. * demote or reclaim pages from the target node via kswapd if we are
  869. * low on free memory on target node. If we don't do this and if
  870. * we have free memory on the slower(lower) memtier, we would start
  871. * allocating pages from slower(lower) memory tiers without even forcing
  872. * a demotion of cold pages from the target memtier. This can result
  873. * in the kernel placing hot pages in slower(lower) memory tiers.
  874. */
  875. mtc->nmask = NULL;
  876. mtc->gfp_mask |= __GFP_THISNODE;
  877. dst = alloc_migration_target(src, (unsigned long)mtc);
  878. if (dst)
  879. return dst;
  880. mtc->gfp_mask &= ~__GFP_THISNODE;
  881. mtc->nmask = allowed_mask;
  882. return alloc_migration_target(src, (unsigned long)mtc);
  883. }
  884. /*
  885. * Take folios on @demote_folios and attempt to demote them to another node.
  886. * Folios which are not demoted are left on @demote_folios.
  887. */
  888. static unsigned int demote_folio_list(struct list_head *demote_folios,
  889. struct pglist_data *pgdat,
  890. struct mem_cgroup *memcg)
  891. {
  892. int target_nid;
  893. unsigned int nr_succeeded;
  894. nodemask_t allowed_mask;
  895. struct migration_target_control mtc = {
  896. /*
  897. * Allocate from 'node', or fail quickly and quietly.
  898. * When this happens, 'page' will likely just be discarded
  899. * instead of migrated.
  900. */
  901. .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
  902. __GFP_NOMEMALLOC | GFP_NOWAIT,
  903. .nmask = &allowed_mask,
  904. .reason = MR_DEMOTION,
  905. };
  906. if (list_empty(demote_folios))
  907. return 0;
  908. node_get_allowed_targets(pgdat, &allowed_mask);
  909. mem_cgroup_node_filter_allowed(memcg, &allowed_mask);
  910. if (nodes_empty(allowed_mask))
  911. return 0;
  912. target_nid = next_demotion_node(pgdat->node_id, &allowed_mask);
  913. if (target_nid == NUMA_NO_NODE)
  914. /* No lower-tier nodes or nodes were hot-unplugged. */
  915. return 0;
  916. mtc.nid = target_nid;
  917. /* Demotion ignores all cpuset and mempolicy settings */
  918. migrate_pages(demote_folios, alloc_demote_folio, NULL,
  919. (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
  920. &nr_succeeded);
  921. return nr_succeeded;
  922. }
  923. static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
  924. {
  925. if (gfp_mask & __GFP_FS)
  926. return true;
  927. if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
  928. return false;
  929. /*
  930. * We can "enter_fs" for swap-cache with only __GFP_IO
  931. * providing this isn't SWP_FS_OPS.
  932. * ->flags can be updated non-atomically (scan_swap_map_slots),
  933. * but that will never affect SWP_FS_OPS, so the data_race
  934. * is safe.
  935. */
  936. return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
  937. }
  938. /*
  939. * shrink_folio_list() returns the number of reclaimed pages
  940. */
  941. static unsigned int shrink_folio_list(struct list_head *folio_list,
  942. struct pglist_data *pgdat, struct scan_control *sc,
  943. struct reclaim_stat *stat, bool ignore_references,
  944. struct mem_cgroup *memcg)
  945. {
  946. struct folio_batch free_folios;
  947. LIST_HEAD(ret_folios);
  948. LIST_HEAD(demote_folios);
  949. unsigned int nr_reclaimed = 0, nr_demoted = 0;
  950. unsigned int pgactivate = 0;
  951. bool do_demote_pass;
  952. struct swap_iocb *plug = NULL;
  953. folio_batch_init(&free_folios);
  954. memset(stat, 0, sizeof(*stat));
  955. cond_resched();
  956. do_demote_pass = can_demote(pgdat->node_id, sc, memcg);
  957. retry:
  958. while (!list_empty(folio_list)) {
  959. struct address_space *mapping;
  960. struct folio *folio;
  961. enum folio_references references = FOLIOREF_RECLAIM;
  962. bool dirty, writeback;
  963. unsigned int nr_pages;
  964. cond_resched();
  965. folio = lru_to_folio(folio_list);
  966. list_del(&folio->lru);
  967. if (!folio_trylock(folio))
  968. goto keep;
  969. if (folio_contain_hwpoisoned_page(folio)) {
  970. /*
  971. * unmap_poisoned_folio() can't handle large
  972. * folio, just skip it. memory_failure() will
  973. * handle it if the UCE is triggered again.
  974. */
  975. if (folio_test_large(folio))
  976. goto keep_locked;
  977. unmap_poisoned_folio(folio, folio_pfn(folio), false);
  978. folio_unlock(folio);
  979. folio_put(folio);
  980. continue;
  981. }
  982. VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
  983. nr_pages = folio_nr_pages(folio);
  984. /* Account the number of base pages */
  985. sc->nr_scanned += nr_pages;
  986. if (unlikely(!folio_evictable(folio)))
  987. goto activate_locked;
  988. if (!sc->may_unmap && folio_mapped(folio))
  989. goto keep_locked;
  990. /*
  991. * The number of dirty pages determines if a node is marked
  992. * reclaim_congested. kswapd will stall and start writing
  993. * folios if the tail of the LRU is all dirty unqueued folios.
  994. */
  995. folio_check_dirty_writeback(folio, &dirty, &writeback);
  996. if (dirty || writeback)
  997. stat->nr_dirty += nr_pages;
  998. if (dirty && !writeback)
  999. stat->nr_unqueued_dirty += nr_pages;
  1000. /*
  1001. * Treat this folio as congested if folios are cycling
  1002. * through the LRU so quickly that the folios marked
  1003. * for immediate reclaim are making it to the end of
  1004. * the LRU a second time.
  1005. */
  1006. if (writeback && folio_test_reclaim(folio))
  1007. stat->nr_congested += nr_pages;
  1008. /*
  1009. * If a folio at the tail of the LRU is under writeback, there
  1010. * are three cases to consider.
  1011. *
  1012. * 1) If reclaim is encountering an excessive number
  1013. * of folios under writeback and this folio has both
  1014. * the writeback and reclaim flags set, then it
  1015. * indicates that folios are being queued for I/O but
  1016. * are being recycled through the LRU before the I/O
  1017. * can complete. Waiting on the folio itself risks an
  1018. * indefinite stall if it is impossible to writeback
  1019. * the folio due to I/O error or disconnected storage
  1020. * so instead note that the LRU is being scanned too
  1021. * quickly and the caller can stall after the folio
  1022. * list has been processed.
  1023. *
  1024. * 2) Global or new memcg reclaim encounters a folio that is
  1025. * not marked for immediate reclaim, or the caller does not
  1026. * have __GFP_FS (or __GFP_IO if it's simply going to swap,
  1027. * not to fs), or the folio belongs to a mapping where
  1028. * waiting on writeback during reclaim may lead to a deadlock.
  1029. * In this case mark the folio for immediate reclaim and
  1030. * continue scanning.
  1031. *
  1032. * Require may_enter_fs() because we would wait on fs, which
  1033. * may not have submitted I/O yet. And the loop driver might
  1034. * enter reclaim, and deadlock if it waits on a folio for
  1035. * which it is needed to do the write (loop masks off
  1036. * __GFP_IO|__GFP_FS for this reason); but more thought
  1037. * would probably show more reasons.
  1038. *
  1039. * 3) Legacy memcg encounters a folio that already has the
  1040. * reclaim flag set. memcg does not have any dirty folio
  1041. * throttling so we could easily OOM just because too many
  1042. * folios are in writeback and there is nothing else to
  1043. * reclaim. Wait for the writeback to complete.
  1044. *
  1045. * In cases 1) and 2) we activate the folios to get them out of
  1046. * the way while we continue scanning for clean folios on the
  1047. * inactive list and refilling from the active list. The
  1048. * observation here is that waiting for disk writes is more
  1049. * expensive than potentially causing reloads down the line.
  1050. * Since they're marked for immediate reclaim, they won't put
  1051. * memory pressure on the cache working set any longer than it
  1052. * takes to write them to disk.
  1053. */
  1054. if (folio_test_writeback(folio)) {
  1055. mapping = folio_mapping(folio);
  1056. /* Case 1 above */
  1057. if (current_is_kswapd() &&
  1058. folio_test_reclaim(folio) &&
  1059. test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
  1060. stat->nr_immediate += nr_pages;
  1061. goto activate_locked;
  1062. /* Case 2 above */
  1063. } else if (writeback_throttling_sane(sc) ||
  1064. !folio_test_reclaim(folio) ||
  1065. !may_enter_fs(folio, sc->gfp_mask) ||
  1066. (mapping &&
  1067. mapping_writeback_may_deadlock_on_reclaim(mapping))) {
  1068. /*
  1069. * This is slightly racy -
  1070. * folio_end_writeback() might have
  1071. * just cleared the reclaim flag, then
  1072. * setting the reclaim flag here ends up
  1073. * interpreted as the readahead flag - but
  1074. * that does not matter enough to care.
  1075. * What we do want is for this folio to
  1076. * have the reclaim flag set next time
  1077. * memcg reclaim reaches the tests above,
  1078. * so it will then wait for writeback to
  1079. * avoid OOM; and it's also appropriate
  1080. * in global reclaim.
  1081. */
  1082. folio_set_reclaim(folio);
  1083. stat->nr_writeback += nr_pages;
  1084. goto activate_locked;
  1085. /* Case 3 above */
  1086. } else {
  1087. folio_unlock(folio);
  1088. folio_wait_writeback(folio);
  1089. /* then go back and try same folio again */
  1090. list_add_tail(&folio->lru, folio_list);
  1091. continue;
  1092. }
  1093. }
  1094. if (!ignore_references)
  1095. references = folio_check_references(folio, sc);
  1096. switch (references) {
  1097. case FOLIOREF_ACTIVATE:
  1098. goto activate_locked;
  1099. case FOLIOREF_KEEP:
  1100. stat->nr_ref_keep += nr_pages;
  1101. goto keep_locked;
  1102. case FOLIOREF_RECLAIM:
  1103. case FOLIOREF_RECLAIM_CLEAN:
  1104. ; /* try to reclaim the folio below */
  1105. }
  1106. /*
  1107. * Before reclaiming the folio, try to relocate
  1108. * its contents to another node.
  1109. */
  1110. if (do_demote_pass &&
  1111. (thp_migration_supported() || !folio_test_large(folio))) {
  1112. list_add(&folio->lru, &demote_folios);
  1113. folio_unlock(folio);
  1114. continue;
  1115. }
  1116. /*
  1117. * Anonymous process memory has backing store?
  1118. * Try to allocate it some swap space here.
  1119. * Lazyfree folio could be freed directly
  1120. */
  1121. if (folio_test_anon(folio) && folio_test_swapbacked(folio) &&
  1122. !folio_test_swapcache(folio)) {
  1123. if (!(sc->gfp_mask & __GFP_IO))
  1124. goto keep_locked;
  1125. if (folio_maybe_dma_pinned(folio))
  1126. goto keep_locked;
  1127. if (folio_test_large(folio)) {
  1128. /* cannot split folio, skip it */
  1129. if (folio_expected_ref_count(folio) !=
  1130. folio_ref_count(folio) - 1)
  1131. goto activate_locked;
  1132. /*
  1133. * Split partially mapped folios right away.
  1134. * We can free the unmapped pages without IO.
  1135. */
  1136. if (data_race(!list_empty(&folio->_deferred_list) &&
  1137. folio_test_partially_mapped(folio)) &&
  1138. split_folio_to_list(folio, folio_list))
  1139. goto activate_locked;
  1140. }
  1141. if (folio_alloc_swap(folio)) {
  1142. int __maybe_unused order = folio_order(folio);
  1143. if (!folio_test_large(folio))
  1144. goto activate_locked_split;
  1145. /* Fallback to swap normal pages */
  1146. if (split_folio_to_list(folio, folio_list))
  1147. goto activate_locked;
  1148. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1149. if (nr_pages >= HPAGE_PMD_NR) {
  1150. count_memcg_folio_events(folio,
  1151. THP_SWPOUT_FALLBACK, 1);
  1152. count_vm_event(THP_SWPOUT_FALLBACK);
  1153. }
  1154. #endif
  1155. count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
  1156. if (folio_alloc_swap(folio))
  1157. goto activate_locked_split;
  1158. }
  1159. /*
  1160. * Normally the folio will be dirtied in unmap because
  1161. * its pte should be dirty. A special case is MADV_FREE
  1162. * page. The page's pte could have dirty bit cleared but
  1163. * the folio's SwapBacked flag is still set because
  1164. * clearing the dirty bit and SwapBacked flag has no
  1165. * lock protected. For such folio, unmap will not set
  1166. * dirty bit for it, so folio reclaim will not write the
  1167. * folio out. This can cause data corruption when the
  1168. * folio is swapped in later. Always setting the dirty
  1169. * flag for the folio solves the problem.
  1170. */
  1171. folio_mark_dirty(folio);
  1172. }
  1173. /*
  1174. * If the folio was split above, the tail pages will make
  1175. * their own pass through this function and be accounted
  1176. * then.
  1177. */
  1178. if ((nr_pages > 1) && !folio_test_large(folio)) {
  1179. sc->nr_scanned -= (nr_pages - 1);
  1180. nr_pages = 1;
  1181. }
  1182. /*
  1183. * The folio is mapped into the page tables of one or more
  1184. * processes. Try to unmap it here.
  1185. */
  1186. if (folio_mapped(folio)) {
  1187. enum ttu_flags flags = TTU_BATCH_FLUSH;
  1188. bool was_swapbacked = folio_test_swapbacked(folio);
  1189. if (folio_test_pmd_mappable(folio))
  1190. flags |= TTU_SPLIT_HUGE_PMD;
  1191. /*
  1192. * Without TTU_SYNC, try_to_unmap will only begin to
  1193. * hold PTL from the first present PTE within a large
  1194. * folio. Some initial PTEs might be skipped due to
  1195. * races with parallel PTE writes in which PTEs can be
  1196. * cleared temporarily before being written new present
  1197. * values. This will lead to a large folio is still
  1198. * mapped while some subpages have been partially
  1199. * unmapped after try_to_unmap; TTU_SYNC helps
  1200. * try_to_unmap acquire PTL from the first PTE,
  1201. * eliminating the influence of temporary PTE values.
  1202. */
  1203. if (folio_test_large(folio))
  1204. flags |= TTU_SYNC;
  1205. try_to_unmap(folio, flags);
  1206. if (folio_mapped(folio)) {
  1207. stat->nr_unmap_fail += nr_pages;
  1208. if (!was_swapbacked &&
  1209. folio_test_swapbacked(folio))
  1210. stat->nr_lazyfree_fail += nr_pages;
  1211. goto activate_locked;
  1212. }
  1213. }
  1214. /*
  1215. * Folio is unmapped now so it cannot be newly pinned anymore.
  1216. * No point in trying to reclaim folio if it is pinned.
  1217. * Furthermore we don't want to reclaim underlying fs metadata
  1218. * if the folio is pinned and thus potentially modified by the
  1219. * pinning process as that may upset the filesystem.
  1220. */
  1221. if (folio_maybe_dma_pinned(folio))
  1222. goto activate_locked;
  1223. mapping = folio_mapping(folio);
  1224. if (folio_test_dirty(folio)) {
  1225. if (folio_is_file_lru(folio)) {
  1226. /*
  1227. * Immediately reclaim when written back.
  1228. * Similar in principle to folio_deactivate()
  1229. * except we already have the folio isolated
  1230. * and know it's dirty
  1231. */
  1232. node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
  1233. nr_pages);
  1234. if (!folio_test_reclaim(folio))
  1235. folio_set_reclaim(folio);
  1236. goto activate_locked;
  1237. }
  1238. if (references == FOLIOREF_RECLAIM_CLEAN)
  1239. goto keep_locked;
  1240. if (!may_enter_fs(folio, sc->gfp_mask))
  1241. goto keep_locked;
  1242. if (!sc->may_writepage)
  1243. goto keep_locked;
  1244. /*
  1245. * Folio is dirty. Flush the TLB if a writable entry
  1246. * potentially exists to avoid CPU writes after I/O
  1247. * starts and then write it out here.
  1248. */
  1249. try_to_unmap_flush_dirty();
  1250. switch (pageout(folio, mapping, &plug, folio_list)) {
  1251. case PAGE_KEEP:
  1252. goto keep_locked;
  1253. case PAGE_ACTIVATE:
  1254. /*
  1255. * If shmem folio is split when writeback to swap,
  1256. * the tail pages will make their own pass through
  1257. * this function and be accounted then.
  1258. */
  1259. if (nr_pages > 1 && !folio_test_large(folio)) {
  1260. sc->nr_scanned -= (nr_pages - 1);
  1261. nr_pages = 1;
  1262. }
  1263. goto activate_locked;
  1264. case PAGE_SUCCESS:
  1265. if (nr_pages > 1 && !folio_test_large(folio)) {
  1266. sc->nr_scanned -= (nr_pages - 1);
  1267. nr_pages = 1;
  1268. }
  1269. stat->nr_pageout += nr_pages;
  1270. if (folio_test_writeback(folio))
  1271. goto keep;
  1272. if (folio_test_dirty(folio))
  1273. goto keep;
  1274. /*
  1275. * A synchronous write - probably a ramdisk. Go
  1276. * ahead and try to reclaim the folio.
  1277. */
  1278. if (!folio_trylock(folio))
  1279. goto keep;
  1280. if (folio_test_dirty(folio) ||
  1281. folio_test_writeback(folio))
  1282. goto keep_locked;
  1283. mapping = folio_mapping(folio);
  1284. fallthrough;
  1285. case PAGE_CLEAN:
  1286. ; /* try to free the folio below */
  1287. }
  1288. }
  1289. /*
  1290. * If the folio has buffers, try to free the buffer
  1291. * mappings associated with this folio. If we succeed
  1292. * we try to free the folio as well.
  1293. *
  1294. * We do this even if the folio is dirty.
  1295. * filemap_release_folio() does not perform I/O, but it
  1296. * is possible for a folio to have the dirty flag set,
  1297. * but it is actually clean (all its buffers are clean).
  1298. * This happens if the buffers were written out directly,
  1299. * with submit_bh(). ext3 will do this, as well as
  1300. * the blockdev mapping. filemap_release_folio() will
  1301. * discover that cleanness and will drop the buffers
  1302. * and mark the folio clean - it can be freed.
  1303. *
  1304. * Rarely, folios can have buffers and no ->mapping.
  1305. * These are the folios which were not successfully
  1306. * invalidated in truncate_cleanup_folio(). We try to
  1307. * drop those buffers here and if that worked, and the
  1308. * folio is no longer mapped into process address space
  1309. * (refcount == 1) it can be freed. Otherwise, leave
  1310. * the folio on the LRU so it is swappable.
  1311. */
  1312. if (folio_needs_release(folio)) {
  1313. if (!filemap_release_folio(folio, sc->gfp_mask))
  1314. goto activate_locked;
  1315. if (!mapping && folio_ref_count(folio) == 1) {
  1316. folio_unlock(folio);
  1317. if (folio_put_testzero(folio))
  1318. goto free_it;
  1319. else {
  1320. /*
  1321. * rare race with speculative reference.
  1322. * the speculative reference will free
  1323. * this folio shortly, so we may
  1324. * increment nr_reclaimed here (and
  1325. * leave it off the LRU).
  1326. */
  1327. nr_reclaimed += nr_pages;
  1328. continue;
  1329. }
  1330. }
  1331. }
  1332. if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
  1333. /* follow __remove_mapping for reference */
  1334. if (!folio_ref_freeze(folio, 1))
  1335. goto keep_locked;
  1336. /*
  1337. * The folio has only one reference left, which is
  1338. * from the isolation. After the caller puts the
  1339. * folio back on the lru and drops the reference, the
  1340. * folio will be freed anyway. It doesn't matter
  1341. * which lru it goes on. So we don't bother checking
  1342. * the dirty flag here.
  1343. */
  1344. count_vm_events(PGLAZYFREED, nr_pages);
  1345. count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
  1346. } else if (!mapping || !__remove_mapping(mapping, folio, true,
  1347. sc->target_mem_cgroup))
  1348. goto keep_locked;
  1349. folio_unlock(folio);
  1350. free_it:
  1351. /*
  1352. * Folio may get swapped out as a whole, need to account
  1353. * all pages in it.
  1354. */
  1355. nr_reclaimed += nr_pages;
  1356. folio_unqueue_deferred_split(folio);
  1357. if (folio_batch_add(&free_folios, folio) == 0) {
  1358. mem_cgroup_uncharge_folios(&free_folios);
  1359. try_to_unmap_flush();
  1360. free_unref_folios(&free_folios);
  1361. }
  1362. continue;
  1363. activate_locked_split:
  1364. /*
  1365. * The tail pages that are failed to add into swap cache
  1366. * reach here. Fixup nr_scanned and nr_pages.
  1367. */
  1368. if (nr_pages > 1) {
  1369. sc->nr_scanned -= (nr_pages - 1);
  1370. nr_pages = 1;
  1371. }
  1372. activate_locked:
  1373. /* Not a candidate for swapping, so reclaim swap space. */
  1374. if (folio_test_swapcache(folio) &&
  1375. (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
  1376. folio_free_swap(folio);
  1377. VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
  1378. if (!folio_test_mlocked(folio)) {
  1379. int type = folio_is_file_lru(folio);
  1380. folio_set_active(folio);
  1381. stat->nr_activate[type] += nr_pages;
  1382. count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
  1383. }
  1384. keep_locked:
  1385. folio_unlock(folio);
  1386. keep:
  1387. list_add(&folio->lru, &ret_folios);
  1388. VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
  1389. folio_test_unevictable(folio), folio);
  1390. }
  1391. /* 'folio_list' is always empty here */
  1392. /* Migrate folios selected for demotion */
  1393. nr_demoted = demote_folio_list(&demote_folios, pgdat, memcg);
  1394. nr_reclaimed += nr_demoted;
  1395. stat->nr_demoted += nr_demoted;
  1396. /* Folios that could not be demoted are still in @demote_folios */
  1397. if (!list_empty(&demote_folios)) {
  1398. /* Folios which weren't demoted go back on @folio_list */
  1399. list_splice_init(&demote_folios, folio_list);
  1400. /*
  1401. * goto retry to reclaim the undemoted folios in folio_list if
  1402. * desired.
  1403. *
  1404. * Reclaiming directly from top tier nodes is not often desired
  1405. * due to it breaking the LRU ordering: in general memory
  1406. * should be reclaimed from lower tier nodes and demoted from
  1407. * top tier nodes.
  1408. *
  1409. * However, disabling reclaim from top tier nodes entirely
  1410. * would cause ooms in edge scenarios where lower tier memory
  1411. * is unreclaimable for whatever reason, eg memory being
  1412. * mlocked or too hot to reclaim. We can disable reclaim
  1413. * from top tier nodes in proactive reclaim though as that is
  1414. * not real memory pressure.
  1415. */
  1416. if (!sc->proactive) {
  1417. do_demote_pass = false;
  1418. goto retry;
  1419. }
  1420. }
  1421. pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
  1422. mem_cgroup_uncharge_folios(&free_folios);
  1423. try_to_unmap_flush();
  1424. free_unref_folios(&free_folios);
  1425. list_splice(&ret_folios, folio_list);
  1426. count_vm_events(PGACTIVATE, pgactivate);
  1427. if (plug)
  1428. swap_write_unplug(plug);
  1429. return nr_reclaimed;
  1430. }
  1431. unsigned int reclaim_clean_pages_from_list(struct zone *zone,
  1432. struct list_head *folio_list)
  1433. {
  1434. struct scan_control sc = {
  1435. .gfp_mask = GFP_KERNEL,
  1436. .may_unmap = 1,
  1437. };
  1438. struct reclaim_stat stat;
  1439. unsigned int nr_reclaimed;
  1440. struct folio *folio, *next;
  1441. LIST_HEAD(clean_folios);
  1442. unsigned int noreclaim_flag;
  1443. list_for_each_entry_safe(folio, next, folio_list, lru) {
  1444. /* TODO: these pages should not even appear in this list. */
  1445. if (page_has_movable_ops(&folio->page))
  1446. continue;
  1447. if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
  1448. !folio_test_dirty(folio) && !folio_test_unevictable(folio)) {
  1449. folio_clear_active(folio);
  1450. list_move(&folio->lru, &clean_folios);
  1451. }
  1452. }
  1453. /*
  1454. * We should be safe here since we are only dealing with file pages and
  1455. * we are not kswapd and therefore cannot write dirty file pages. But
  1456. * call memalloc_noreclaim_save() anyway, just in case these conditions
  1457. * change in the future.
  1458. */
  1459. noreclaim_flag = memalloc_noreclaim_save();
  1460. nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
  1461. &stat, true, NULL);
  1462. memalloc_noreclaim_restore(noreclaim_flag);
  1463. list_splice(&clean_folios, folio_list);
  1464. mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
  1465. -(long)nr_reclaimed);
  1466. /*
  1467. * Since lazyfree pages are isolated from file LRU from the beginning,
  1468. * they will rotate back to anonymous LRU in the end if it failed to
  1469. * discard so isolated count will be mismatched.
  1470. * Compensate the isolated count for both LRU lists.
  1471. */
  1472. mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
  1473. stat.nr_lazyfree_fail);
  1474. mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
  1475. -(long)stat.nr_lazyfree_fail);
  1476. return nr_reclaimed;
  1477. }
  1478. /*
  1479. * Update LRU sizes after isolating pages. The LRU size updates must
  1480. * be complete before mem_cgroup_update_lru_size due to a sanity check.
  1481. */
  1482. static __always_inline void update_lru_sizes(struct lruvec *lruvec,
  1483. enum lru_list lru, unsigned long *nr_zone_taken)
  1484. {
  1485. int zid;
  1486. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  1487. if (!nr_zone_taken[zid])
  1488. continue;
  1489. update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
  1490. }
  1491. }
  1492. /*
  1493. * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
  1494. *
  1495. * lruvec->lru_lock is heavily contended. Some of the functions that
  1496. * shrink the lists perform better by taking out a batch of pages
  1497. * and working on them outside the LRU lock.
  1498. *
  1499. * For pagecache intensive workloads, this function is the hottest
  1500. * spot in the kernel (apart from copy_*_user functions).
  1501. *
  1502. * Lru_lock must be held before calling this function.
  1503. *
  1504. * @nr_to_scan: The number of eligible pages to look through on the list.
  1505. * @lruvec: The LRU vector to pull pages from.
  1506. * @dst: The temp list to put pages on to.
  1507. * @nr_scanned: The number of pages that were scanned.
  1508. * @sc: The scan_control struct for this reclaim session
  1509. * @lru: LRU list id for isolating
  1510. *
  1511. * returns how many pages were moved onto *@dst.
  1512. */
  1513. static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
  1514. struct lruvec *lruvec, struct list_head *dst,
  1515. unsigned long *nr_scanned, struct scan_control *sc,
  1516. enum lru_list lru)
  1517. {
  1518. struct list_head *src = &lruvec->lists[lru];
  1519. unsigned long nr_taken = 0;
  1520. unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
  1521. unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
  1522. unsigned long skipped = 0, total_scan = 0, scan = 0;
  1523. unsigned long nr_pages;
  1524. unsigned long max_nr_skipped = 0;
  1525. LIST_HEAD(folios_skipped);
  1526. while (scan < nr_to_scan && !list_empty(src)) {
  1527. struct list_head *move_to = src;
  1528. struct folio *folio;
  1529. folio = lru_to_folio(src);
  1530. prefetchw_prev_lru_folio(folio, src, flags);
  1531. nr_pages = folio_nr_pages(folio);
  1532. total_scan += nr_pages;
  1533. /* Using max_nr_skipped to prevent hard LOCKUP*/
  1534. if (max_nr_skipped < SWAP_CLUSTER_MAX_SKIPPED &&
  1535. (folio_zonenum(folio) > sc->reclaim_idx)) {
  1536. nr_skipped[folio_zonenum(folio)] += nr_pages;
  1537. move_to = &folios_skipped;
  1538. max_nr_skipped++;
  1539. goto move;
  1540. }
  1541. /*
  1542. * Do not count skipped folios because that makes the function
  1543. * return with no isolated folios if the LRU mostly contains
  1544. * ineligible folios. This causes the VM to not reclaim any
  1545. * folios, triggering a premature OOM.
  1546. * Account all pages in a folio.
  1547. */
  1548. scan += nr_pages;
  1549. if (!folio_test_lru(folio))
  1550. goto move;
  1551. if (!sc->may_unmap && folio_mapped(folio))
  1552. goto move;
  1553. /*
  1554. * Be careful not to clear the lru flag until after we're
  1555. * sure the folio is not being freed elsewhere -- the
  1556. * folio release code relies on it.
  1557. */
  1558. if (unlikely(!folio_try_get(folio)))
  1559. goto move;
  1560. if (!folio_test_clear_lru(folio)) {
  1561. /* Another thread is already isolating this folio */
  1562. folio_put(folio);
  1563. goto move;
  1564. }
  1565. nr_taken += nr_pages;
  1566. nr_zone_taken[folio_zonenum(folio)] += nr_pages;
  1567. move_to = dst;
  1568. move:
  1569. list_move(&folio->lru, move_to);
  1570. }
  1571. /*
  1572. * Splice any skipped folios to the start of the LRU list. Note that
  1573. * this disrupts the LRU order when reclaiming for lower zones but
  1574. * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
  1575. * scanning would soon rescan the same folios to skip and waste lots
  1576. * of cpu cycles.
  1577. */
  1578. if (!list_empty(&folios_skipped)) {
  1579. int zid;
  1580. list_splice(&folios_skipped, src);
  1581. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  1582. if (!nr_skipped[zid])
  1583. continue;
  1584. __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
  1585. skipped += nr_skipped[zid];
  1586. }
  1587. }
  1588. *nr_scanned = total_scan;
  1589. trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
  1590. total_scan, skipped, nr_taken, lru);
  1591. update_lru_sizes(lruvec, lru, nr_zone_taken);
  1592. return nr_taken;
  1593. }
  1594. /**
  1595. * folio_isolate_lru() - Try to isolate a folio from its LRU list.
  1596. * @folio: Folio to isolate from its LRU list.
  1597. *
  1598. * Isolate a @folio from an LRU list and adjust the vmstat statistic
  1599. * corresponding to whatever LRU list the folio was on.
  1600. *
  1601. * The folio will have its LRU flag cleared. If it was found on the
  1602. * active list, it will have the Active flag set. If it was found on the
  1603. * unevictable list, it will have the Unevictable flag set. These flags
  1604. * may need to be cleared by the caller before letting the page go.
  1605. *
  1606. * Context:
  1607. *
  1608. * (1) Must be called with an elevated refcount on the folio. This is a
  1609. * fundamental difference from isolate_lru_folios() (which is called
  1610. * without a stable reference).
  1611. * (2) The lru_lock must not be held.
  1612. * (3) Interrupts must be enabled.
  1613. *
  1614. * Return: true if the folio was removed from an LRU list.
  1615. * false if the folio was not on an LRU list.
  1616. */
  1617. bool folio_isolate_lru(struct folio *folio)
  1618. {
  1619. bool ret = false;
  1620. VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
  1621. if (folio_test_clear_lru(folio)) {
  1622. struct lruvec *lruvec;
  1623. folio_get(folio);
  1624. lruvec = folio_lruvec_lock_irq(folio);
  1625. lruvec_del_folio(lruvec, folio);
  1626. unlock_page_lruvec_irq(lruvec);
  1627. ret = true;
  1628. }
  1629. return ret;
  1630. }
  1631. /*
  1632. * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
  1633. * then get rescheduled. When there are massive number of tasks doing page
  1634. * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
  1635. * the LRU list will go small and be scanned faster than necessary, leading to
  1636. * unnecessary swapping, thrashing and OOM.
  1637. */
  1638. static bool too_many_isolated(struct pglist_data *pgdat, int file,
  1639. struct scan_control *sc)
  1640. {
  1641. unsigned long inactive, isolated;
  1642. bool too_many;
  1643. if (current_is_kswapd())
  1644. return false;
  1645. if (!writeback_throttling_sane(sc))
  1646. return false;
  1647. if (file) {
  1648. inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
  1649. isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
  1650. } else {
  1651. inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
  1652. isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
  1653. }
  1654. /*
  1655. * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
  1656. * won't get blocked by normal direct-reclaimers, forming a circular
  1657. * deadlock.
  1658. */
  1659. if (gfp_has_io_fs(sc->gfp_mask))
  1660. inactive >>= 3;
  1661. too_many = isolated > inactive;
  1662. /* Wake up tasks throttled due to too_many_isolated. */
  1663. if (!too_many)
  1664. wake_throttle_isolated(pgdat);
  1665. return too_many;
  1666. }
  1667. /*
  1668. * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
  1669. *
  1670. * Returns the number of pages moved to the given lruvec.
  1671. */
  1672. static unsigned int move_folios_to_lru(struct lruvec *lruvec,
  1673. struct list_head *list)
  1674. {
  1675. int nr_pages, nr_moved = 0;
  1676. struct folio_batch free_folios;
  1677. folio_batch_init(&free_folios);
  1678. while (!list_empty(list)) {
  1679. struct folio *folio = lru_to_folio(list);
  1680. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  1681. list_del(&folio->lru);
  1682. if (unlikely(!folio_evictable(folio))) {
  1683. spin_unlock_irq(&lruvec->lru_lock);
  1684. folio_putback_lru(folio);
  1685. spin_lock_irq(&lruvec->lru_lock);
  1686. continue;
  1687. }
  1688. /*
  1689. * The folio_set_lru needs to be kept here for list integrity.
  1690. * Otherwise:
  1691. * #0 move_folios_to_lru #1 release_pages
  1692. * if (!folio_put_testzero())
  1693. * if (folio_put_testzero())
  1694. * !lru //skip lru_lock
  1695. * folio_set_lru()
  1696. * list_add(&folio->lru,)
  1697. * list_add(&folio->lru,)
  1698. */
  1699. folio_set_lru(folio);
  1700. if (unlikely(folio_put_testzero(folio))) {
  1701. __folio_clear_lru_flags(folio);
  1702. folio_unqueue_deferred_split(folio);
  1703. if (folio_batch_add(&free_folios, folio) == 0) {
  1704. spin_unlock_irq(&lruvec->lru_lock);
  1705. mem_cgroup_uncharge_folios(&free_folios);
  1706. free_unref_folios(&free_folios);
  1707. spin_lock_irq(&lruvec->lru_lock);
  1708. }
  1709. continue;
  1710. }
  1711. /*
  1712. * All pages were isolated from the same lruvec (and isolation
  1713. * inhibits memcg migration).
  1714. */
  1715. VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
  1716. lruvec_add_folio(lruvec, folio);
  1717. nr_pages = folio_nr_pages(folio);
  1718. nr_moved += nr_pages;
  1719. if (folio_test_active(folio))
  1720. workingset_age_nonresident(lruvec, nr_pages);
  1721. }
  1722. if (free_folios.nr) {
  1723. spin_unlock_irq(&lruvec->lru_lock);
  1724. mem_cgroup_uncharge_folios(&free_folios);
  1725. free_unref_folios(&free_folios);
  1726. spin_lock_irq(&lruvec->lru_lock);
  1727. }
  1728. return nr_moved;
  1729. }
  1730. /*
  1731. * If a kernel thread (such as nfsd for loop-back mounts) services a backing
  1732. * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
  1733. * we should not throttle. Otherwise it is safe to do so.
  1734. */
  1735. static int current_may_throttle(void)
  1736. {
  1737. return !(current->flags & PF_LOCAL_THROTTLE);
  1738. }
  1739. /*
  1740. * shrink_inactive_list() is a helper for shrink_node(). It returns the number
  1741. * of reclaimed pages
  1742. */
  1743. static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
  1744. struct lruvec *lruvec, struct scan_control *sc,
  1745. enum lru_list lru)
  1746. {
  1747. LIST_HEAD(folio_list);
  1748. unsigned long nr_scanned;
  1749. unsigned int nr_reclaimed = 0;
  1750. unsigned long nr_taken;
  1751. struct reclaim_stat stat;
  1752. bool file = is_file_lru(lru);
  1753. enum vm_event_item item;
  1754. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  1755. bool stalled = false;
  1756. while (unlikely(too_many_isolated(pgdat, file, sc))) {
  1757. if (stalled)
  1758. return 0;
  1759. /* wait a bit for the reclaimer. */
  1760. stalled = true;
  1761. reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
  1762. /* We are about to die and free our memory. Return now. */
  1763. if (fatal_signal_pending(current))
  1764. return SWAP_CLUSTER_MAX;
  1765. }
  1766. lru_add_drain();
  1767. spin_lock_irq(&lruvec->lru_lock);
  1768. nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
  1769. &nr_scanned, sc, lru);
  1770. __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
  1771. item = PGSCAN_KSWAPD + reclaimer_offset(sc);
  1772. if (!cgroup_reclaim(sc))
  1773. __count_vm_events(item, nr_scanned);
  1774. count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
  1775. __count_vm_events(PGSCAN_ANON + file, nr_scanned);
  1776. spin_unlock_irq(&lruvec->lru_lock);
  1777. if (nr_taken == 0)
  1778. return 0;
  1779. nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false,
  1780. lruvec_memcg(lruvec));
  1781. spin_lock_irq(&lruvec->lru_lock);
  1782. move_folios_to_lru(lruvec, &folio_list);
  1783. mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
  1784. stat.nr_demoted);
  1785. __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
  1786. item = PGSTEAL_KSWAPD + reclaimer_offset(sc);
  1787. if (!cgroup_reclaim(sc))
  1788. __count_vm_events(item, nr_reclaimed);
  1789. count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
  1790. __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
  1791. lru_note_cost_unlock_irq(lruvec, file, stat.nr_pageout,
  1792. nr_scanned - nr_reclaimed);
  1793. /*
  1794. * If dirty folios are scanned that are not queued for IO, it
  1795. * implies that flushers are not doing their job. This can
  1796. * happen when memory pressure pushes dirty folios to the end of
  1797. * the LRU before the dirty limits are breached and the dirty
  1798. * data has expired. It can also happen when the proportion of
  1799. * dirty folios grows not through writes but through memory
  1800. * pressure reclaiming all the clean cache. And in some cases,
  1801. * the flushers simply cannot keep up with the allocation
  1802. * rate. Nudge the flusher threads in case they are asleep.
  1803. */
  1804. if (stat.nr_unqueued_dirty == nr_taken) {
  1805. wakeup_flusher_threads(WB_REASON_VMSCAN);
  1806. /*
  1807. * For cgroupv1 dirty throttling is achieved by waking up
  1808. * the kernel flusher here and later waiting on folios
  1809. * which are in writeback to finish (see shrink_folio_list()).
  1810. *
  1811. * Flusher may not be able to issue writeback quickly
  1812. * enough for cgroupv1 writeback throttling to work
  1813. * on a large system.
  1814. */
  1815. if (!writeback_throttling_sane(sc))
  1816. reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
  1817. }
  1818. sc->nr.dirty += stat.nr_dirty;
  1819. sc->nr.congested += stat.nr_congested;
  1820. sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
  1821. sc->nr.writeback += stat.nr_writeback;
  1822. sc->nr.immediate += stat.nr_immediate;
  1823. sc->nr.taken += nr_taken;
  1824. if (file)
  1825. sc->nr.file_taken += nr_taken;
  1826. trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
  1827. nr_scanned, nr_reclaimed, &stat, sc->priority, file);
  1828. return nr_reclaimed;
  1829. }
  1830. /*
  1831. * shrink_active_list() moves folios from the active LRU to the inactive LRU.
  1832. *
  1833. * We move them the other way if the folio is referenced by one or more
  1834. * processes.
  1835. *
  1836. * If the folios are mostly unmapped, the processing is fast and it is
  1837. * appropriate to hold lru_lock across the whole operation. But if
  1838. * the folios are mapped, the processing is slow (folio_referenced()), so
  1839. * we should drop lru_lock around each folio. It's impossible to balance
  1840. * this, so instead we remove the folios from the LRU while processing them.
  1841. * It is safe to rely on the active flag against the non-LRU folios in here
  1842. * because nobody will play with that bit on a non-LRU folio.
  1843. *
  1844. * The downside is that we have to touch folio->_refcount against each folio.
  1845. * But we had to alter folio->flags anyway.
  1846. */
  1847. static void shrink_active_list(unsigned long nr_to_scan,
  1848. struct lruvec *lruvec,
  1849. struct scan_control *sc,
  1850. enum lru_list lru)
  1851. {
  1852. unsigned long nr_taken;
  1853. unsigned long nr_scanned;
  1854. vm_flags_t vm_flags;
  1855. LIST_HEAD(l_hold); /* The folios which were snipped off */
  1856. LIST_HEAD(l_active);
  1857. LIST_HEAD(l_inactive);
  1858. unsigned nr_deactivate, nr_activate;
  1859. unsigned nr_rotated = 0;
  1860. bool file = is_file_lru(lru);
  1861. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  1862. lru_add_drain();
  1863. spin_lock_irq(&lruvec->lru_lock);
  1864. nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
  1865. &nr_scanned, sc, lru);
  1866. __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
  1867. if (!cgroup_reclaim(sc))
  1868. __count_vm_events(PGREFILL, nr_scanned);
  1869. count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
  1870. spin_unlock_irq(&lruvec->lru_lock);
  1871. while (!list_empty(&l_hold)) {
  1872. struct folio *folio;
  1873. cond_resched();
  1874. folio = lru_to_folio(&l_hold);
  1875. list_del(&folio->lru);
  1876. if (unlikely(!folio_evictable(folio))) {
  1877. folio_putback_lru(folio);
  1878. continue;
  1879. }
  1880. if (unlikely(buffer_heads_over_limit)) {
  1881. if (folio_needs_release(folio) &&
  1882. folio_trylock(folio)) {
  1883. filemap_release_folio(folio, 0);
  1884. folio_unlock(folio);
  1885. }
  1886. }
  1887. /* Referenced or rmap lock contention: rotate */
  1888. if (folio_referenced(folio, 0, sc->target_mem_cgroup,
  1889. &vm_flags) != 0) {
  1890. /*
  1891. * Identify referenced, file-backed active folios and
  1892. * give them one more trip around the active list. So
  1893. * that executable code get better chances to stay in
  1894. * memory under moderate memory pressure. Anon folios
  1895. * are not likely to be evicted by use-once streaming
  1896. * IO, plus JVM can create lots of anon VM_EXEC folios,
  1897. * so we ignore them here.
  1898. */
  1899. if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
  1900. nr_rotated += folio_nr_pages(folio);
  1901. list_add(&folio->lru, &l_active);
  1902. continue;
  1903. }
  1904. }
  1905. folio_clear_active(folio); /* we are de-activating */
  1906. folio_set_workingset(folio);
  1907. list_add(&folio->lru, &l_inactive);
  1908. }
  1909. /*
  1910. * Move folios back to the lru list.
  1911. */
  1912. spin_lock_irq(&lruvec->lru_lock);
  1913. nr_activate = move_folios_to_lru(lruvec, &l_active);
  1914. nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
  1915. __count_vm_events(PGDEACTIVATE, nr_deactivate);
  1916. count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
  1917. __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
  1918. lru_note_cost_unlock_irq(lruvec, file, 0, nr_rotated);
  1919. trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
  1920. nr_deactivate, nr_rotated, sc->priority, file);
  1921. }
  1922. static unsigned int reclaim_folio_list(struct list_head *folio_list,
  1923. struct pglist_data *pgdat)
  1924. {
  1925. struct reclaim_stat stat;
  1926. unsigned int nr_reclaimed;
  1927. struct folio *folio;
  1928. struct scan_control sc = {
  1929. .gfp_mask = GFP_KERNEL,
  1930. .may_writepage = 1,
  1931. .may_unmap = 1,
  1932. .may_swap = 1,
  1933. .no_demotion = 1,
  1934. };
  1935. nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &stat, true, NULL);
  1936. while (!list_empty(folio_list)) {
  1937. folio = lru_to_folio(folio_list);
  1938. list_del(&folio->lru);
  1939. folio_putback_lru(folio);
  1940. }
  1941. trace_mm_vmscan_reclaim_pages(pgdat->node_id, sc.nr_scanned, nr_reclaimed, &stat);
  1942. return nr_reclaimed;
  1943. }
  1944. unsigned long reclaim_pages(struct list_head *folio_list)
  1945. {
  1946. int nid;
  1947. unsigned int nr_reclaimed = 0;
  1948. LIST_HEAD(node_folio_list);
  1949. unsigned int noreclaim_flag;
  1950. if (list_empty(folio_list))
  1951. return nr_reclaimed;
  1952. noreclaim_flag = memalloc_noreclaim_save();
  1953. nid = folio_nid(lru_to_folio(folio_list));
  1954. do {
  1955. struct folio *folio = lru_to_folio(folio_list);
  1956. if (nid == folio_nid(folio)) {
  1957. folio_clear_active(folio);
  1958. list_move(&folio->lru, &node_folio_list);
  1959. continue;
  1960. }
  1961. nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
  1962. nid = folio_nid(lru_to_folio(folio_list));
  1963. } while (!list_empty(folio_list));
  1964. nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
  1965. memalloc_noreclaim_restore(noreclaim_flag);
  1966. return nr_reclaimed;
  1967. }
  1968. static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
  1969. struct lruvec *lruvec, struct scan_control *sc)
  1970. {
  1971. if (is_active_lru(lru)) {
  1972. if (sc->may_deactivate & (1 << is_file_lru(lru)))
  1973. shrink_active_list(nr_to_scan, lruvec, sc, lru);
  1974. else
  1975. sc->skipped_deactivate = 1;
  1976. return 0;
  1977. }
  1978. return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
  1979. }
  1980. /*
  1981. * The inactive anon list should be small enough that the VM never has
  1982. * to do too much work.
  1983. *
  1984. * The inactive file list should be small enough to leave most memory
  1985. * to the established workingset on the scan-resistant active list,
  1986. * but large enough to avoid thrashing the aggregate readahead window.
  1987. *
  1988. * Both inactive lists should also be large enough that each inactive
  1989. * folio has a chance to be referenced again before it is reclaimed.
  1990. *
  1991. * If that fails and refaulting is observed, the inactive list grows.
  1992. *
  1993. * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
  1994. * on this LRU, maintained by the pageout code. An inactive_ratio
  1995. * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
  1996. *
  1997. * total target max
  1998. * memory ratio inactive
  1999. * -------------------------------------
  2000. * 10MB 1 5MB
  2001. * 100MB 1 50MB
  2002. * 1GB 3 250MB
  2003. * 10GB 10 0.9GB
  2004. * 100GB 31 3GB
  2005. * 1TB 101 10GB
  2006. * 10TB 320 32GB
  2007. */
  2008. static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
  2009. {
  2010. enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
  2011. unsigned long inactive, active;
  2012. unsigned long inactive_ratio;
  2013. unsigned long gb;
  2014. inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
  2015. active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
  2016. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  2017. if (gb)
  2018. inactive_ratio = int_sqrt(10 * gb);
  2019. else
  2020. inactive_ratio = 1;
  2021. return inactive * inactive_ratio < active;
  2022. }
  2023. enum scan_balance {
  2024. SCAN_EQUAL,
  2025. SCAN_FRACT,
  2026. SCAN_ANON,
  2027. SCAN_FILE,
  2028. };
  2029. static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
  2030. {
  2031. unsigned long file;
  2032. struct lruvec *target_lruvec;
  2033. if (lru_gen_enabled())
  2034. return;
  2035. target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
  2036. /*
  2037. * Flush the memory cgroup stats in rate-limited way as we don't need
  2038. * most accurate stats here. We may switch to regular stats flushing
  2039. * in the future once it is cheap enough.
  2040. */
  2041. mem_cgroup_flush_stats_ratelimited(sc->target_mem_cgroup);
  2042. /*
  2043. * Determine the scan balance between anon and file LRUs.
  2044. */
  2045. spin_lock_irq(&target_lruvec->lru_lock);
  2046. sc->anon_cost = target_lruvec->anon_cost;
  2047. sc->file_cost = target_lruvec->file_cost;
  2048. spin_unlock_irq(&target_lruvec->lru_lock);
  2049. /*
  2050. * Target desirable inactive:active list ratios for the anon
  2051. * and file LRU lists.
  2052. */
  2053. if (!sc->force_deactivate) {
  2054. unsigned long refaults;
  2055. /*
  2056. * When refaults are being observed, it means a new
  2057. * workingset is being established. Deactivate to get
  2058. * rid of any stale active pages quickly.
  2059. */
  2060. refaults = lruvec_page_state(target_lruvec,
  2061. WORKINGSET_ACTIVATE_ANON);
  2062. if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
  2063. inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
  2064. sc->may_deactivate |= DEACTIVATE_ANON;
  2065. else
  2066. sc->may_deactivate &= ~DEACTIVATE_ANON;
  2067. refaults = lruvec_page_state(target_lruvec,
  2068. WORKINGSET_ACTIVATE_FILE);
  2069. if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
  2070. inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
  2071. sc->may_deactivate |= DEACTIVATE_FILE;
  2072. else
  2073. sc->may_deactivate &= ~DEACTIVATE_FILE;
  2074. } else
  2075. sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
  2076. /*
  2077. * If we have plenty of inactive file pages that aren't
  2078. * thrashing, try to reclaim those first before touching
  2079. * anonymous pages.
  2080. */
  2081. file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
  2082. if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE) &&
  2083. !sc->no_cache_trim_mode)
  2084. sc->cache_trim_mode = 1;
  2085. else
  2086. sc->cache_trim_mode = 0;
  2087. /*
  2088. * Prevent the reclaimer from falling into the cache trap: as
  2089. * cache pages start out inactive, every cache fault will tip
  2090. * the scan balance towards the file LRU. And as the file LRU
  2091. * shrinks, so does the window for rotation from references.
  2092. * This means we have a runaway feedback loop where a tiny
  2093. * thrashing file LRU becomes infinitely more attractive than
  2094. * anon pages. Try to detect this based on file LRU size.
  2095. */
  2096. if (!cgroup_reclaim(sc)) {
  2097. unsigned long total_high_wmark = 0;
  2098. unsigned long free, anon;
  2099. int z;
  2100. struct zone *zone;
  2101. free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
  2102. file = node_page_state(pgdat, NR_ACTIVE_FILE) +
  2103. node_page_state(pgdat, NR_INACTIVE_FILE);
  2104. for_each_managed_zone_pgdat(zone, pgdat, z, MAX_NR_ZONES - 1) {
  2105. total_high_wmark += high_wmark_pages(zone);
  2106. }
  2107. /*
  2108. * Consider anon: if that's low too, this isn't a
  2109. * runaway file reclaim problem, but rather just
  2110. * extreme pressure. Reclaim as per usual then.
  2111. */
  2112. anon = node_page_state(pgdat, NR_INACTIVE_ANON);
  2113. sc->file_is_tiny =
  2114. file + free <= total_high_wmark &&
  2115. !(sc->may_deactivate & DEACTIVATE_ANON) &&
  2116. anon >> sc->priority;
  2117. }
  2118. }
  2119. static inline void calculate_pressure_balance(struct scan_control *sc,
  2120. int swappiness, u64 *fraction, u64 *denominator)
  2121. {
  2122. unsigned long anon_cost, file_cost, total_cost;
  2123. unsigned long ap, fp;
  2124. /*
  2125. * Calculate the pressure balance between anon and file pages.
  2126. *
  2127. * The amount of pressure we put on each LRU is inversely
  2128. * proportional to the cost of reclaiming each list, as
  2129. * determined by the share of pages that are refaulting, times
  2130. * the relative IO cost of bringing back a swapped out
  2131. * anonymous page vs reloading a filesystem page (swappiness).
  2132. *
  2133. * Although we limit that influence to ensure no list gets
  2134. * left behind completely: at least a third of the pressure is
  2135. * applied, before swappiness.
  2136. *
  2137. * With swappiness at 100, anon and file have equal IO cost.
  2138. */
  2139. total_cost = sc->anon_cost + sc->file_cost;
  2140. anon_cost = total_cost + sc->anon_cost;
  2141. file_cost = total_cost + sc->file_cost;
  2142. total_cost = anon_cost + file_cost;
  2143. ap = swappiness * (total_cost + 1);
  2144. ap /= anon_cost + 1;
  2145. fp = (MAX_SWAPPINESS - swappiness) * (total_cost + 1);
  2146. fp /= file_cost + 1;
  2147. fraction[WORKINGSET_ANON] = ap;
  2148. fraction[WORKINGSET_FILE] = fp;
  2149. *denominator = ap + fp;
  2150. }
  2151. static unsigned long apply_proportional_protection(struct mem_cgroup *memcg,
  2152. struct scan_control *sc, unsigned long scan)
  2153. {
  2154. unsigned long min, low, usage;
  2155. mem_cgroup_protection(sc->target_mem_cgroup, memcg, &min, &low, &usage);
  2156. if (min || low) {
  2157. /*
  2158. * Scale a cgroup's reclaim pressure by proportioning
  2159. * its current usage to its memory.low or memory.min
  2160. * setting.
  2161. *
  2162. * This is important, as otherwise scanning aggression
  2163. * becomes extremely binary -- from nothing as we
  2164. * approach the memory protection threshold, to totally
  2165. * nominal as we exceed it. This results in requiring
  2166. * setting extremely liberal protection thresholds. It
  2167. * also means we simply get no protection at all if we
  2168. * set it too low, which is not ideal.
  2169. *
  2170. * If there is any protection in place, we reduce scan
  2171. * pressure by how much of the total memory used is
  2172. * within protection thresholds.
  2173. *
  2174. * There is one special case: in the first reclaim pass,
  2175. * we skip over all groups that are within their low
  2176. * protection. If that fails to reclaim enough pages to
  2177. * satisfy the reclaim goal, we come back and override
  2178. * the best-effort low protection. However, we still
  2179. * ideally want to honor how well-behaved groups are in
  2180. * that case instead of simply punishing them all
  2181. * equally. As such, we reclaim them based on how much
  2182. * memory they are using, reducing the scan pressure
  2183. * again by how much of the total memory used is under
  2184. * hard protection.
  2185. */
  2186. unsigned long protection;
  2187. /* memory.low scaling, make sure we retry before OOM */
  2188. if (!sc->memcg_low_reclaim && low > min) {
  2189. protection = low;
  2190. sc->memcg_low_skipped = 1;
  2191. } else {
  2192. protection = min;
  2193. }
  2194. /* Avoid TOCTOU with earlier protection check */
  2195. usage = max(usage, protection);
  2196. scan -= scan * protection / (usage + 1);
  2197. /*
  2198. * Minimally target SWAP_CLUSTER_MAX pages to keep
  2199. * reclaim moving forwards, avoiding decrementing
  2200. * sc->priority further than desirable.
  2201. */
  2202. scan = max(scan, SWAP_CLUSTER_MAX);
  2203. }
  2204. return scan;
  2205. }
  2206. /*
  2207. * Determine how aggressively the anon and file LRU lists should be
  2208. * scanned.
  2209. *
  2210. * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
  2211. * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
  2212. */
  2213. static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
  2214. unsigned long *nr)
  2215. {
  2216. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  2217. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  2218. int swappiness = sc_swappiness(sc, memcg);
  2219. u64 fraction[ANON_AND_FILE];
  2220. u64 denominator = 0; /* gcc */
  2221. enum scan_balance scan_balance;
  2222. enum lru_list lru;
  2223. /* If we have no swap space, do not bother scanning anon folios. */
  2224. if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
  2225. scan_balance = SCAN_FILE;
  2226. goto out;
  2227. }
  2228. /*
  2229. * Global reclaim will swap to prevent OOM even with no
  2230. * swappiness, but memcg users want to use this knob to
  2231. * disable swapping for individual groups completely when
  2232. * using the memory controller's swap limit feature would be
  2233. * too expensive.
  2234. */
  2235. if (cgroup_reclaim(sc) && !swappiness) {
  2236. scan_balance = SCAN_FILE;
  2237. goto out;
  2238. }
  2239. /* Proactive reclaim initiated by userspace for anonymous memory only */
  2240. if (swappiness == SWAPPINESS_ANON_ONLY) {
  2241. WARN_ON_ONCE(!sc->proactive);
  2242. scan_balance = SCAN_ANON;
  2243. goto out;
  2244. }
  2245. /*
  2246. * Do not apply any pressure balancing cleverness when the
  2247. * system is close to OOM, scan both anon and file equally
  2248. * (unless the swappiness setting disagrees with swapping).
  2249. */
  2250. if (!sc->priority && swappiness) {
  2251. scan_balance = SCAN_EQUAL;
  2252. goto out;
  2253. }
  2254. /*
  2255. * If the system is almost out of file pages, force-scan anon.
  2256. */
  2257. if (sc->file_is_tiny) {
  2258. scan_balance = SCAN_ANON;
  2259. goto out;
  2260. }
  2261. /*
  2262. * If there is enough inactive page cache, we do not reclaim
  2263. * anything from the anonymous working right now to make sure
  2264. * a streaming file access pattern doesn't cause swapping.
  2265. */
  2266. if (sc->cache_trim_mode) {
  2267. scan_balance = SCAN_FILE;
  2268. goto out;
  2269. }
  2270. scan_balance = SCAN_FRACT;
  2271. calculate_pressure_balance(sc, swappiness, fraction, &denominator);
  2272. out:
  2273. for_each_evictable_lru(lru) {
  2274. bool file = is_file_lru(lru);
  2275. unsigned long lruvec_size;
  2276. unsigned long scan;
  2277. lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
  2278. scan = apply_proportional_protection(memcg, sc, lruvec_size);
  2279. scan >>= sc->priority;
  2280. /*
  2281. * If the cgroup's already been deleted, make sure to
  2282. * scrape out the remaining cache.
  2283. */
  2284. if (!scan && !mem_cgroup_online(memcg))
  2285. scan = min(lruvec_size, SWAP_CLUSTER_MAX);
  2286. switch (scan_balance) {
  2287. case SCAN_EQUAL:
  2288. /* Scan lists relative to size */
  2289. break;
  2290. case SCAN_FRACT:
  2291. /*
  2292. * Scan types proportional to swappiness and
  2293. * their relative recent reclaim efficiency.
  2294. * Make sure we don't miss the last page on
  2295. * the offlined memory cgroups because of a
  2296. * round-off error.
  2297. */
  2298. scan = mem_cgroup_online(memcg) ?
  2299. div64_u64(scan * fraction[file], denominator) :
  2300. DIV64_U64_ROUND_UP(scan * fraction[file],
  2301. denominator);
  2302. break;
  2303. case SCAN_FILE:
  2304. case SCAN_ANON:
  2305. /* Scan one type exclusively */
  2306. if ((scan_balance == SCAN_FILE) != file)
  2307. scan = 0;
  2308. break;
  2309. default:
  2310. /* Look ma, no brain */
  2311. BUG();
  2312. }
  2313. nr[lru] = scan;
  2314. }
  2315. }
  2316. /*
  2317. * Anonymous LRU management is a waste if there is
  2318. * ultimately no way to reclaim the memory.
  2319. */
  2320. static bool can_age_anon_pages(struct lruvec *lruvec,
  2321. struct scan_control *sc)
  2322. {
  2323. /* Aging the anon LRU is valuable if swap is present: */
  2324. if (total_swap_pages > 0)
  2325. return true;
  2326. /* Also valuable if anon pages can be demoted: */
  2327. return can_demote(lruvec_pgdat(lruvec)->node_id, sc,
  2328. lruvec_memcg(lruvec));
  2329. }
  2330. #ifdef CONFIG_LRU_GEN
  2331. #ifdef CONFIG_LRU_GEN_ENABLED
  2332. DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
  2333. #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
  2334. #else
  2335. DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
  2336. #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
  2337. #endif
  2338. static bool should_walk_mmu(void)
  2339. {
  2340. return arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK);
  2341. }
  2342. static bool should_clear_pmd_young(void)
  2343. {
  2344. return arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG);
  2345. }
  2346. /******************************************************************************
  2347. * shorthand helpers
  2348. ******************************************************************************/
  2349. #define DEFINE_MAX_SEQ(lruvec) \
  2350. unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
  2351. #define DEFINE_MIN_SEQ(lruvec) \
  2352. unsigned long min_seq[ANON_AND_FILE] = { \
  2353. READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
  2354. READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
  2355. }
  2356. /* Get the min/max evictable type based on swappiness */
  2357. #define min_type(swappiness) (!(swappiness))
  2358. #define max_type(swappiness) ((swappiness) < SWAPPINESS_ANON_ONLY)
  2359. #define evictable_min_seq(min_seq, swappiness) \
  2360. min((min_seq)[min_type(swappiness)], (min_seq)[max_type(swappiness)])
  2361. #define for_each_gen_type_zone(gen, type, zone) \
  2362. for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
  2363. for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
  2364. for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
  2365. #define for_each_evictable_type(type, swappiness) \
  2366. for ((type) = min_type(swappiness); (type) <= max_type(swappiness); (type)++)
  2367. #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
  2368. #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
  2369. static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
  2370. {
  2371. struct pglist_data *pgdat = NODE_DATA(nid);
  2372. #ifdef CONFIG_MEMCG
  2373. if (memcg) {
  2374. struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
  2375. /* see the comment in mem_cgroup_lruvec() */
  2376. if (!lruvec->pgdat)
  2377. lruvec->pgdat = pgdat;
  2378. return lruvec;
  2379. }
  2380. #endif
  2381. VM_WARN_ON_ONCE(!mem_cgroup_disabled());
  2382. return &pgdat->__lruvec;
  2383. }
  2384. static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
  2385. {
  2386. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  2387. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  2388. if (!sc->may_swap)
  2389. return 0;
  2390. if (!can_demote(pgdat->node_id, sc, memcg) &&
  2391. mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
  2392. return 0;
  2393. return sc_swappiness(sc, memcg);
  2394. }
  2395. static int get_nr_gens(struct lruvec *lruvec, int type)
  2396. {
  2397. return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
  2398. }
  2399. static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
  2400. {
  2401. int type;
  2402. for (type = 0; type < ANON_AND_FILE; type++) {
  2403. int n = get_nr_gens(lruvec, type);
  2404. if (n < MIN_NR_GENS || n > MAX_NR_GENS)
  2405. return false;
  2406. }
  2407. return true;
  2408. }
  2409. /******************************************************************************
  2410. * Bloom filters
  2411. ******************************************************************************/
  2412. /*
  2413. * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
  2414. * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
  2415. * bits in a bitmap, k is the number of hash functions and n is the number of
  2416. * inserted items.
  2417. *
  2418. * Page table walkers use one of the two filters to reduce their search space.
  2419. * To get rid of non-leaf entries that no longer have enough leaf entries, the
  2420. * aging uses the double-buffering technique to flip to the other filter each
  2421. * time it produces a new generation. For non-leaf entries that have enough
  2422. * leaf entries, the aging carries them over to the next generation in
  2423. * walk_pmd_range(); the eviction also report them when walking the rmap
  2424. * in lru_gen_look_around().
  2425. *
  2426. * For future optimizations:
  2427. * 1. It's not necessary to keep both filters all the time. The spare one can be
  2428. * freed after the RCU grace period and reallocated if needed again.
  2429. * 2. And when reallocating, it's worth scaling its size according to the number
  2430. * of inserted entries in the other filter, to reduce the memory overhead on
  2431. * small systems and false positives on large systems.
  2432. * 3. Jenkins' hash function is an alternative to Knuth's.
  2433. */
  2434. #define BLOOM_FILTER_SHIFT 15
  2435. static inline int filter_gen_from_seq(unsigned long seq)
  2436. {
  2437. return seq % NR_BLOOM_FILTERS;
  2438. }
  2439. static void get_item_key(void *item, int *key)
  2440. {
  2441. u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
  2442. BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
  2443. key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
  2444. key[1] = hash >> BLOOM_FILTER_SHIFT;
  2445. }
  2446. static bool test_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
  2447. void *item)
  2448. {
  2449. int key[2];
  2450. unsigned long *filter;
  2451. int gen = filter_gen_from_seq(seq);
  2452. filter = READ_ONCE(mm_state->filters[gen]);
  2453. if (!filter)
  2454. return true;
  2455. get_item_key(item, key);
  2456. return test_bit(key[0], filter) && test_bit(key[1], filter);
  2457. }
  2458. static void update_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq,
  2459. void *item)
  2460. {
  2461. int key[2];
  2462. unsigned long *filter;
  2463. int gen = filter_gen_from_seq(seq);
  2464. filter = READ_ONCE(mm_state->filters[gen]);
  2465. if (!filter)
  2466. return;
  2467. get_item_key(item, key);
  2468. if (!test_bit(key[0], filter))
  2469. set_bit(key[0], filter);
  2470. if (!test_bit(key[1], filter))
  2471. set_bit(key[1], filter);
  2472. }
  2473. static void reset_bloom_filter(struct lru_gen_mm_state *mm_state, unsigned long seq)
  2474. {
  2475. unsigned long *filter;
  2476. int gen = filter_gen_from_seq(seq);
  2477. filter = mm_state->filters[gen];
  2478. if (filter) {
  2479. bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
  2480. return;
  2481. }
  2482. filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
  2483. __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
  2484. WRITE_ONCE(mm_state->filters[gen], filter);
  2485. }
  2486. /******************************************************************************
  2487. * mm_struct list
  2488. ******************************************************************************/
  2489. #ifdef CONFIG_LRU_GEN_WALKS_MMU
  2490. static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
  2491. {
  2492. static struct lru_gen_mm_list mm_list = {
  2493. .fifo = LIST_HEAD_INIT(mm_list.fifo),
  2494. .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
  2495. };
  2496. #ifdef CONFIG_MEMCG
  2497. if (memcg)
  2498. return &memcg->mm_list;
  2499. #endif
  2500. VM_WARN_ON_ONCE(!mem_cgroup_disabled());
  2501. return &mm_list;
  2502. }
  2503. static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
  2504. {
  2505. return &lruvec->mm_state;
  2506. }
  2507. static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
  2508. {
  2509. int key;
  2510. struct mm_struct *mm;
  2511. struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
  2512. struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
  2513. mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
  2514. key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
  2515. if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
  2516. return NULL;
  2517. clear_bit(key, &mm->lru_gen.bitmap);
  2518. return mmget_not_zero(mm) ? mm : NULL;
  2519. }
  2520. void lru_gen_add_mm(struct mm_struct *mm)
  2521. {
  2522. int nid;
  2523. struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
  2524. struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
  2525. VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
  2526. #ifdef CONFIG_MEMCG
  2527. VM_WARN_ON_ONCE(mm->lru_gen.memcg);
  2528. mm->lru_gen.memcg = memcg;
  2529. #endif
  2530. spin_lock(&mm_list->lock);
  2531. for_each_node_state(nid, N_MEMORY) {
  2532. struct lruvec *lruvec = get_lruvec(memcg, nid);
  2533. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  2534. /* the first addition since the last iteration */
  2535. if (mm_state->tail == &mm_list->fifo)
  2536. mm_state->tail = &mm->lru_gen.list;
  2537. }
  2538. list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
  2539. spin_unlock(&mm_list->lock);
  2540. }
  2541. void lru_gen_del_mm(struct mm_struct *mm)
  2542. {
  2543. int nid;
  2544. struct lru_gen_mm_list *mm_list;
  2545. struct mem_cgroup *memcg = NULL;
  2546. if (list_empty(&mm->lru_gen.list))
  2547. return;
  2548. #ifdef CONFIG_MEMCG
  2549. memcg = mm->lru_gen.memcg;
  2550. #endif
  2551. mm_list = get_mm_list(memcg);
  2552. spin_lock(&mm_list->lock);
  2553. for_each_node(nid) {
  2554. struct lruvec *lruvec = get_lruvec(memcg, nid);
  2555. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  2556. /* where the current iteration continues after */
  2557. if (mm_state->head == &mm->lru_gen.list)
  2558. mm_state->head = mm_state->head->prev;
  2559. /* where the last iteration ended before */
  2560. if (mm_state->tail == &mm->lru_gen.list)
  2561. mm_state->tail = mm_state->tail->next;
  2562. }
  2563. list_del_init(&mm->lru_gen.list);
  2564. spin_unlock(&mm_list->lock);
  2565. #ifdef CONFIG_MEMCG
  2566. mem_cgroup_put(mm->lru_gen.memcg);
  2567. mm->lru_gen.memcg = NULL;
  2568. #endif
  2569. }
  2570. #ifdef CONFIG_MEMCG
  2571. void lru_gen_migrate_mm(struct mm_struct *mm)
  2572. {
  2573. struct mem_cgroup *memcg;
  2574. struct task_struct *task = rcu_dereference_protected(mm->owner, true);
  2575. VM_WARN_ON_ONCE(task->mm != mm);
  2576. lockdep_assert_held(&task->alloc_lock);
  2577. /* for mm_update_next_owner() */
  2578. if (mem_cgroup_disabled())
  2579. return;
  2580. /* migration can happen before addition */
  2581. if (!mm->lru_gen.memcg)
  2582. return;
  2583. rcu_read_lock();
  2584. memcg = mem_cgroup_from_task(task);
  2585. rcu_read_unlock();
  2586. if (memcg == mm->lru_gen.memcg)
  2587. return;
  2588. VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
  2589. lru_gen_del_mm(mm);
  2590. lru_gen_add_mm(mm);
  2591. }
  2592. #endif
  2593. #else /* !CONFIG_LRU_GEN_WALKS_MMU */
  2594. static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
  2595. {
  2596. return NULL;
  2597. }
  2598. static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec)
  2599. {
  2600. return NULL;
  2601. }
  2602. static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk)
  2603. {
  2604. return NULL;
  2605. }
  2606. #endif
  2607. static void reset_mm_stats(struct lru_gen_mm_walk *walk, bool last)
  2608. {
  2609. int i;
  2610. int hist;
  2611. struct lruvec *lruvec = walk->lruvec;
  2612. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  2613. lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
  2614. hist = lru_hist_from_seq(walk->seq);
  2615. for (i = 0; i < NR_MM_STATS; i++) {
  2616. WRITE_ONCE(mm_state->stats[hist][i],
  2617. mm_state->stats[hist][i] + walk->mm_stats[i]);
  2618. walk->mm_stats[i] = 0;
  2619. }
  2620. if (NR_HIST_GENS > 1 && last) {
  2621. hist = lru_hist_from_seq(walk->seq + 1);
  2622. for (i = 0; i < NR_MM_STATS; i++)
  2623. WRITE_ONCE(mm_state->stats[hist][i], 0);
  2624. }
  2625. }
  2626. static bool iterate_mm_list(struct lru_gen_mm_walk *walk, struct mm_struct **iter)
  2627. {
  2628. bool first = false;
  2629. bool last = false;
  2630. struct mm_struct *mm = NULL;
  2631. struct lruvec *lruvec = walk->lruvec;
  2632. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  2633. struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
  2634. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  2635. /*
  2636. * mm_state->seq is incremented after each iteration of mm_list. There
  2637. * are three interesting cases for this page table walker:
  2638. * 1. It tries to start a new iteration with a stale max_seq: there is
  2639. * nothing left to do.
  2640. * 2. It started the next iteration: it needs to reset the Bloom filter
  2641. * so that a fresh set of PTE tables can be recorded.
  2642. * 3. It ended the current iteration: it needs to reset the mm stats
  2643. * counters and tell its caller to increment max_seq.
  2644. */
  2645. spin_lock(&mm_list->lock);
  2646. VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->seq);
  2647. if (walk->seq <= mm_state->seq)
  2648. goto done;
  2649. if (!mm_state->head)
  2650. mm_state->head = &mm_list->fifo;
  2651. if (mm_state->head == &mm_list->fifo)
  2652. first = true;
  2653. do {
  2654. mm_state->head = mm_state->head->next;
  2655. if (mm_state->head == &mm_list->fifo) {
  2656. WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
  2657. last = true;
  2658. break;
  2659. }
  2660. /* force scan for those added after the last iteration */
  2661. if (!mm_state->tail || mm_state->tail == mm_state->head) {
  2662. mm_state->tail = mm_state->head->next;
  2663. walk->force_scan = true;
  2664. }
  2665. } while (!(mm = get_next_mm(walk)));
  2666. done:
  2667. if (*iter || last)
  2668. reset_mm_stats(walk, last);
  2669. spin_unlock(&mm_list->lock);
  2670. if (mm && first)
  2671. reset_bloom_filter(mm_state, walk->seq + 1);
  2672. if (*iter)
  2673. mmput_async(*iter);
  2674. *iter = mm;
  2675. return last;
  2676. }
  2677. static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq)
  2678. {
  2679. bool success = false;
  2680. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  2681. struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
  2682. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  2683. spin_lock(&mm_list->lock);
  2684. VM_WARN_ON_ONCE(mm_state->seq + 1 < seq);
  2685. if (seq > mm_state->seq) {
  2686. mm_state->head = NULL;
  2687. mm_state->tail = NULL;
  2688. WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
  2689. success = true;
  2690. }
  2691. spin_unlock(&mm_list->lock);
  2692. return success;
  2693. }
  2694. /******************************************************************************
  2695. * PID controller
  2696. ******************************************************************************/
  2697. /*
  2698. * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
  2699. *
  2700. * The P term is refaulted/(evicted+protected) from a tier in the generation
  2701. * currently being evicted; the I term is the exponential moving average of the
  2702. * P term over the generations previously evicted, using the smoothing factor
  2703. * 1/2; the D term isn't supported.
  2704. *
  2705. * The setpoint (SP) is always the first tier of one type; the process variable
  2706. * (PV) is either any tier of the other type or any other tier of the same
  2707. * type.
  2708. *
  2709. * The error is the difference between the SP and the PV; the correction is to
  2710. * turn off protection when SP>PV or turn on protection when SP<PV.
  2711. *
  2712. * For future optimizations:
  2713. * 1. The D term may discount the other two terms over time so that long-lived
  2714. * generations can resist stale information.
  2715. */
  2716. struct ctrl_pos {
  2717. unsigned long refaulted;
  2718. unsigned long total;
  2719. int gain;
  2720. };
  2721. static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
  2722. struct ctrl_pos *pos)
  2723. {
  2724. int i;
  2725. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  2726. int hist = lru_hist_from_seq(lrugen->min_seq[type]);
  2727. pos->gain = gain;
  2728. pos->refaulted = pos->total = 0;
  2729. for (i = tier % MAX_NR_TIERS; i <= min(tier, MAX_NR_TIERS - 1); i++) {
  2730. pos->refaulted += lrugen->avg_refaulted[type][i] +
  2731. atomic_long_read(&lrugen->refaulted[hist][type][i]);
  2732. pos->total += lrugen->avg_total[type][i] +
  2733. lrugen->protected[hist][type][i] +
  2734. atomic_long_read(&lrugen->evicted[hist][type][i]);
  2735. }
  2736. }
  2737. static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
  2738. {
  2739. int hist, tier;
  2740. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  2741. bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
  2742. unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
  2743. lockdep_assert_held(&lruvec->lru_lock);
  2744. if (!carryover && !clear)
  2745. return;
  2746. hist = lru_hist_from_seq(seq);
  2747. for (tier = 0; tier < MAX_NR_TIERS; tier++) {
  2748. if (carryover) {
  2749. unsigned long sum;
  2750. sum = lrugen->avg_refaulted[type][tier] +
  2751. atomic_long_read(&lrugen->refaulted[hist][type][tier]);
  2752. WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
  2753. sum = lrugen->avg_total[type][tier] +
  2754. lrugen->protected[hist][type][tier] +
  2755. atomic_long_read(&lrugen->evicted[hist][type][tier]);
  2756. WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
  2757. }
  2758. if (clear) {
  2759. atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
  2760. atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
  2761. WRITE_ONCE(lrugen->protected[hist][type][tier], 0);
  2762. }
  2763. }
  2764. }
  2765. static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
  2766. {
  2767. /*
  2768. * Return true if the PV has a limited number of refaults or a lower
  2769. * refaulted/total than the SP.
  2770. */
  2771. return pv->refaulted < MIN_LRU_BATCH ||
  2772. pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
  2773. (sp->refaulted + 1) * pv->total * pv->gain;
  2774. }
  2775. /******************************************************************************
  2776. * the aging
  2777. ******************************************************************************/
  2778. /* promote pages accessed through page tables */
  2779. static int folio_update_gen(struct folio *folio, int gen)
  2780. {
  2781. unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f);
  2782. VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
  2783. /* see the comment on LRU_REFS_FLAGS */
  2784. if (!folio_test_referenced(folio) && !folio_test_workingset(folio)) {
  2785. set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced));
  2786. return -1;
  2787. }
  2788. do {
  2789. /* lru_gen_del_folio() has isolated this page? */
  2790. if (!(old_flags & LRU_GEN_MASK))
  2791. return -1;
  2792. new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS);
  2793. new_flags |= ((gen + 1UL) << LRU_GEN_PGOFF) | BIT(PG_workingset);
  2794. } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags));
  2795. return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
  2796. }
  2797. /* protect pages accessed multiple times through file descriptors */
  2798. static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
  2799. {
  2800. int type = folio_is_file_lru(folio);
  2801. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  2802. int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
  2803. unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f);
  2804. VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
  2805. do {
  2806. new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
  2807. /* folio_update_gen() has promoted this page? */
  2808. if (new_gen >= 0 && new_gen != old_gen)
  2809. return new_gen;
  2810. new_gen = (old_gen + 1) % MAX_NR_GENS;
  2811. new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS);
  2812. new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
  2813. /* for folio_end_writeback() */
  2814. if (reclaiming)
  2815. new_flags |= BIT(PG_reclaim);
  2816. } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags));
  2817. lru_gen_update_size(lruvec, folio, old_gen, new_gen);
  2818. return new_gen;
  2819. }
  2820. static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
  2821. int old_gen, int new_gen)
  2822. {
  2823. int type = folio_is_file_lru(folio);
  2824. int zone = folio_zonenum(folio);
  2825. int delta = folio_nr_pages(folio);
  2826. VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
  2827. VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
  2828. walk->batched++;
  2829. walk->nr_pages[old_gen][type][zone] -= delta;
  2830. walk->nr_pages[new_gen][type][zone] += delta;
  2831. }
  2832. static void reset_batch_size(struct lru_gen_mm_walk *walk)
  2833. {
  2834. int gen, type, zone;
  2835. struct lruvec *lruvec = walk->lruvec;
  2836. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  2837. walk->batched = 0;
  2838. for_each_gen_type_zone(gen, type, zone) {
  2839. enum lru_list lru = type * LRU_INACTIVE_FILE;
  2840. int delta = walk->nr_pages[gen][type][zone];
  2841. if (!delta)
  2842. continue;
  2843. walk->nr_pages[gen][type][zone] = 0;
  2844. WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
  2845. lrugen->nr_pages[gen][type][zone] + delta);
  2846. if (lru_gen_is_active(lruvec, gen))
  2847. lru += LRU_ACTIVE;
  2848. __update_lru_size(lruvec, lru, zone, delta);
  2849. }
  2850. }
  2851. static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
  2852. {
  2853. struct address_space *mapping;
  2854. struct vm_area_struct *vma = args->vma;
  2855. struct lru_gen_mm_walk *walk = args->private;
  2856. if (!vma_is_accessible(vma))
  2857. return true;
  2858. if (is_vm_hugetlb_page(vma))
  2859. return true;
  2860. if (!vma_has_recency(vma))
  2861. return true;
  2862. if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
  2863. return true;
  2864. if (vma == get_gate_vma(vma->vm_mm))
  2865. return true;
  2866. if (vma_is_anonymous(vma))
  2867. return !walk->swappiness;
  2868. if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
  2869. return true;
  2870. mapping = vma->vm_file->f_mapping;
  2871. if (mapping_unevictable(mapping))
  2872. return true;
  2873. if (shmem_mapping(mapping))
  2874. return !walk->swappiness;
  2875. if (walk->swappiness > MAX_SWAPPINESS)
  2876. return true;
  2877. /* to exclude special mappings like dax, etc. */
  2878. return !mapping->a_ops->read_folio;
  2879. }
  2880. /*
  2881. * Some userspace memory allocators map many single-page VMAs. Instead of
  2882. * returning back to the PGD table for each of such VMAs, finish an entire PMD
  2883. * table to reduce zigzags and improve cache performance.
  2884. */
  2885. static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
  2886. unsigned long *vm_start, unsigned long *vm_end)
  2887. {
  2888. unsigned long start = round_up(*vm_end, size);
  2889. unsigned long end = (start | ~mask) + 1;
  2890. VMA_ITERATOR(vmi, args->mm, start);
  2891. VM_WARN_ON_ONCE(mask & size);
  2892. VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
  2893. for_each_vma(vmi, args->vma) {
  2894. if (end && end <= args->vma->vm_start)
  2895. return false;
  2896. if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
  2897. continue;
  2898. *vm_start = max(start, args->vma->vm_start);
  2899. *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
  2900. return true;
  2901. }
  2902. return false;
  2903. }
  2904. static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr,
  2905. struct pglist_data *pgdat)
  2906. {
  2907. unsigned long pfn = pte_pfn(pte);
  2908. VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
  2909. if (!pte_present(pte) || is_zero_pfn(pfn))
  2910. return -1;
  2911. if (WARN_ON_ONCE(pte_special(pte)))
  2912. return -1;
  2913. if (!pte_young(pte) && !mm_has_notifiers(vma->vm_mm))
  2914. return -1;
  2915. if (WARN_ON_ONCE(!pfn_valid(pfn)))
  2916. return -1;
  2917. if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
  2918. return -1;
  2919. return pfn;
  2920. }
  2921. static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr,
  2922. struct pglist_data *pgdat)
  2923. {
  2924. unsigned long pfn = pmd_pfn(pmd);
  2925. VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
  2926. if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
  2927. return -1;
  2928. if (!pmd_young(pmd) && !mm_has_notifiers(vma->vm_mm))
  2929. return -1;
  2930. if (WARN_ON_ONCE(!pfn_valid(pfn)))
  2931. return -1;
  2932. if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
  2933. return -1;
  2934. return pfn;
  2935. }
  2936. static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
  2937. struct pglist_data *pgdat)
  2938. {
  2939. struct folio *folio = pfn_folio(pfn);
  2940. if (folio_lru_gen(folio) < 0)
  2941. return NULL;
  2942. if (folio_nid(folio) != pgdat->node_id)
  2943. return NULL;
  2944. if (folio_memcg(folio) != memcg)
  2945. return NULL;
  2946. return folio;
  2947. }
  2948. static bool suitable_to_scan(int total, int young)
  2949. {
  2950. int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
  2951. /* suitable if the average number of young PTEs per cacheline is >=1 */
  2952. return young * n >= total;
  2953. }
  2954. static void walk_update_folio(struct lru_gen_mm_walk *walk, struct folio *folio,
  2955. int new_gen, bool dirty)
  2956. {
  2957. int old_gen;
  2958. if (!folio)
  2959. return;
  2960. if (dirty && !folio_test_dirty(folio) &&
  2961. !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
  2962. !folio_test_swapcache(folio)))
  2963. folio_mark_dirty(folio);
  2964. if (walk) {
  2965. old_gen = folio_update_gen(folio, new_gen);
  2966. if (old_gen >= 0 && old_gen != new_gen)
  2967. update_batch_size(walk, folio, old_gen, new_gen);
  2968. } else if (lru_gen_set_refs(folio)) {
  2969. old_gen = folio_lru_gen(folio);
  2970. if (old_gen >= 0 && old_gen != new_gen)
  2971. folio_activate(folio);
  2972. }
  2973. }
  2974. static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
  2975. struct mm_walk *args)
  2976. {
  2977. int i;
  2978. bool dirty;
  2979. pte_t *pte;
  2980. spinlock_t *ptl;
  2981. unsigned long addr;
  2982. int total = 0;
  2983. int young = 0;
  2984. struct folio *last = NULL;
  2985. struct lru_gen_mm_walk *walk = args->private;
  2986. struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
  2987. struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
  2988. DEFINE_MAX_SEQ(walk->lruvec);
  2989. int gen = lru_gen_from_seq(max_seq);
  2990. pmd_t pmdval;
  2991. pte = pte_offset_map_rw_nolock(args->mm, pmd, start & PMD_MASK, &pmdval, &ptl);
  2992. if (!pte)
  2993. return false;
  2994. if (!spin_trylock(ptl)) {
  2995. pte_unmap(pte);
  2996. return true;
  2997. }
  2998. if (unlikely(!pmd_same(pmdval, pmdp_get_lockless(pmd)))) {
  2999. pte_unmap_unlock(pte, ptl);
  3000. return false;
  3001. }
  3002. lazy_mmu_mode_enable();
  3003. restart:
  3004. for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
  3005. unsigned long pfn;
  3006. struct folio *folio;
  3007. pte_t ptent = ptep_get(pte + i);
  3008. total++;
  3009. walk->mm_stats[MM_LEAF_TOTAL]++;
  3010. pfn = get_pte_pfn(ptent, args->vma, addr, pgdat);
  3011. if (pfn == -1)
  3012. continue;
  3013. folio = get_pfn_folio(pfn, memcg, pgdat);
  3014. if (!folio)
  3015. continue;
  3016. if (!ptep_clear_young_notify(args->vma, addr, pte + i))
  3017. continue;
  3018. if (last != folio) {
  3019. walk_update_folio(walk, last, gen, dirty);
  3020. last = folio;
  3021. dirty = false;
  3022. }
  3023. if (pte_dirty(ptent))
  3024. dirty = true;
  3025. young++;
  3026. walk->mm_stats[MM_LEAF_YOUNG]++;
  3027. }
  3028. walk_update_folio(walk, last, gen, dirty);
  3029. last = NULL;
  3030. if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
  3031. goto restart;
  3032. lazy_mmu_mode_disable();
  3033. pte_unmap_unlock(pte, ptl);
  3034. return suitable_to_scan(total, young);
  3035. }
  3036. static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
  3037. struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
  3038. {
  3039. int i;
  3040. bool dirty;
  3041. pmd_t *pmd;
  3042. spinlock_t *ptl;
  3043. struct folio *last = NULL;
  3044. struct lru_gen_mm_walk *walk = args->private;
  3045. struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
  3046. struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
  3047. DEFINE_MAX_SEQ(walk->lruvec);
  3048. int gen = lru_gen_from_seq(max_seq);
  3049. VM_WARN_ON_ONCE(pud_leaf(*pud));
  3050. /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
  3051. if (*first == -1) {
  3052. *first = addr;
  3053. bitmap_zero(bitmap, MIN_LRU_BATCH);
  3054. return;
  3055. }
  3056. i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
  3057. if (i && i <= MIN_LRU_BATCH) {
  3058. __set_bit(i - 1, bitmap);
  3059. return;
  3060. }
  3061. pmd = pmd_offset(pud, *first);
  3062. ptl = pmd_lockptr(args->mm, pmd);
  3063. if (!spin_trylock(ptl))
  3064. goto done;
  3065. lazy_mmu_mode_enable();
  3066. do {
  3067. unsigned long pfn;
  3068. struct folio *folio;
  3069. /* don't round down the first address */
  3070. addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
  3071. if (!pmd_present(pmd[i]))
  3072. goto next;
  3073. if (!pmd_trans_huge(pmd[i])) {
  3074. if (!walk->force_scan && should_clear_pmd_young() &&
  3075. !mm_has_notifiers(args->mm))
  3076. pmdp_test_and_clear_young(vma, addr, pmd + i);
  3077. goto next;
  3078. }
  3079. pfn = get_pmd_pfn(pmd[i], vma, addr, pgdat);
  3080. if (pfn == -1)
  3081. goto next;
  3082. folio = get_pfn_folio(pfn, memcg, pgdat);
  3083. if (!folio)
  3084. goto next;
  3085. if (!pmdp_clear_young_notify(vma, addr, pmd + i))
  3086. goto next;
  3087. if (last != folio) {
  3088. walk_update_folio(walk, last, gen, dirty);
  3089. last = folio;
  3090. dirty = false;
  3091. }
  3092. if (pmd_dirty(pmd[i]))
  3093. dirty = true;
  3094. walk->mm_stats[MM_LEAF_YOUNG]++;
  3095. next:
  3096. i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
  3097. } while (i <= MIN_LRU_BATCH);
  3098. walk_update_folio(walk, last, gen, dirty);
  3099. lazy_mmu_mode_disable();
  3100. spin_unlock(ptl);
  3101. done:
  3102. *first = -1;
  3103. }
  3104. static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
  3105. struct mm_walk *args)
  3106. {
  3107. int i;
  3108. pmd_t *pmd;
  3109. unsigned long next;
  3110. unsigned long addr;
  3111. struct vm_area_struct *vma;
  3112. DECLARE_BITMAP(bitmap, MIN_LRU_BATCH);
  3113. unsigned long first = -1;
  3114. struct lru_gen_mm_walk *walk = args->private;
  3115. struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec);
  3116. VM_WARN_ON_ONCE(pud_leaf(*pud));
  3117. /*
  3118. * Finish an entire PMD in two passes: the first only reaches to PTE
  3119. * tables to avoid taking the PMD lock; the second, if necessary, takes
  3120. * the PMD lock to clear the accessed bit in PMD entries.
  3121. */
  3122. pmd = pmd_offset(pud, start & PUD_MASK);
  3123. restart:
  3124. /* walk_pte_range() may call get_next_vma() */
  3125. vma = args->vma;
  3126. for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
  3127. pmd_t val = pmdp_get_lockless(pmd + i);
  3128. next = pmd_addr_end(addr, end);
  3129. if (!pmd_present(val) || is_huge_zero_pmd(val)) {
  3130. walk->mm_stats[MM_LEAF_TOTAL]++;
  3131. continue;
  3132. }
  3133. if (pmd_trans_huge(val)) {
  3134. struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
  3135. unsigned long pfn = get_pmd_pfn(val, vma, addr, pgdat);
  3136. walk->mm_stats[MM_LEAF_TOTAL]++;
  3137. if (pfn != -1)
  3138. walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
  3139. continue;
  3140. }
  3141. if (!walk->force_scan && should_clear_pmd_young() &&
  3142. !mm_has_notifiers(args->mm)) {
  3143. if (!pmd_young(val))
  3144. continue;
  3145. walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
  3146. }
  3147. if (!walk->force_scan && !test_bloom_filter(mm_state, walk->seq, pmd + i))
  3148. continue;
  3149. walk->mm_stats[MM_NONLEAF_FOUND]++;
  3150. if (!walk_pte_range(&val, addr, next, args))
  3151. continue;
  3152. walk->mm_stats[MM_NONLEAF_ADDED]++;
  3153. /* carry over to the next generation */
  3154. update_bloom_filter(mm_state, walk->seq + 1, pmd + i);
  3155. }
  3156. walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
  3157. if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
  3158. goto restart;
  3159. }
  3160. static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
  3161. struct mm_walk *args)
  3162. {
  3163. int i;
  3164. pud_t *pud;
  3165. unsigned long addr;
  3166. unsigned long next;
  3167. struct lru_gen_mm_walk *walk = args->private;
  3168. VM_WARN_ON_ONCE(p4d_leaf(*p4d));
  3169. pud = pud_offset(p4d, start & P4D_MASK);
  3170. restart:
  3171. for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
  3172. pud_t val = pudp_get(pud + i);
  3173. next = pud_addr_end(addr, end);
  3174. if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
  3175. continue;
  3176. walk_pmd_range(&val, addr, next, args);
  3177. if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
  3178. end = (addr | ~PUD_MASK) + 1;
  3179. goto done;
  3180. }
  3181. }
  3182. if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
  3183. goto restart;
  3184. end = round_up(end, P4D_SIZE);
  3185. done:
  3186. if (!end || !args->vma)
  3187. return 1;
  3188. walk->next_addr = max(end, args->vma->vm_start);
  3189. return -EAGAIN;
  3190. }
  3191. static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
  3192. {
  3193. static const struct mm_walk_ops mm_walk_ops = {
  3194. .test_walk = should_skip_vma,
  3195. .p4d_entry = walk_pud_range,
  3196. .walk_lock = PGWALK_RDLOCK,
  3197. };
  3198. int err;
  3199. struct lruvec *lruvec = walk->lruvec;
  3200. walk->next_addr = FIRST_USER_ADDRESS;
  3201. do {
  3202. DEFINE_MAX_SEQ(lruvec);
  3203. err = -EBUSY;
  3204. /* another thread might have called inc_max_seq() */
  3205. if (walk->seq != max_seq)
  3206. break;
  3207. /* the caller might be holding the lock for write */
  3208. if (mmap_read_trylock(mm)) {
  3209. err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
  3210. mmap_read_unlock(mm);
  3211. }
  3212. if (walk->batched) {
  3213. spin_lock_irq(&lruvec->lru_lock);
  3214. reset_batch_size(walk);
  3215. spin_unlock_irq(&lruvec->lru_lock);
  3216. }
  3217. cond_resched();
  3218. } while (err == -EAGAIN);
  3219. }
  3220. static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
  3221. {
  3222. struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
  3223. if (pgdat && current_is_kswapd()) {
  3224. VM_WARN_ON_ONCE(walk);
  3225. walk = &pgdat->mm_walk;
  3226. } else if (!walk && force_alloc) {
  3227. VM_WARN_ON_ONCE(current_is_kswapd());
  3228. walk = kzalloc_obj(*walk,
  3229. __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
  3230. }
  3231. current->reclaim_state->mm_walk = walk;
  3232. return walk;
  3233. }
  3234. static void clear_mm_walk(void)
  3235. {
  3236. struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
  3237. VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
  3238. VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
  3239. current->reclaim_state->mm_walk = NULL;
  3240. if (!current_is_kswapd())
  3241. kfree(walk);
  3242. }
  3243. static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness)
  3244. {
  3245. int zone;
  3246. int remaining = MAX_LRU_BATCH;
  3247. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3248. int hist = lru_hist_from_seq(lrugen->min_seq[type]);
  3249. int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
  3250. /* For file type, skip the check if swappiness is anon only */
  3251. if (type && (swappiness == SWAPPINESS_ANON_ONLY))
  3252. goto done;
  3253. /* For anon type, skip the check if swappiness is zero (file only) */
  3254. if (!type && !swappiness)
  3255. goto done;
  3256. /* prevent cold/hot inversion if the type is evictable */
  3257. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3258. struct list_head *head = &lrugen->folios[old_gen][type][zone];
  3259. while (!list_empty(head)) {
  3260. struct folio *folio = lru_to_folio(head);
  3261. int refs = folio_lru_refs(folio);
  3262. bool workingset = folio_test_workingset(folio);
  3263. VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
  3264. VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
  3265. VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
  3266. VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
  3267. new_gen = folio_inc_gen(lruvec, folio, false);
  3268. list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
  3269. /* don't count the workingset being lazily promoted */
  3270. if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) {
  3271. int tier = lru_tier_from_refs(refs, workingset);
  3272. int delta = folio_nr_pages(folio);
  3273. WRITE_ONCE(lrugen->protected[hist][type][tier],
  3274. lrugen->protected[hist][type][tier] + delta);
  3275. }
  3276. if (!--remaining)
  3277. return false;
  3278. }
  3279. }
  3280. done:
  3281. reset_ctrl_pos(lruvec, type, true);
  3282. WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
  3283. return true;
  3284. }
  3285. static bool try_to_inc_min_seq(struct lruvec *lruvec, int swappiness)
  3286. {
  3287. int gen, type, zone;
  3288. bool success = false;
  3289. bool seq_inc_flag = false;
  3290. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3291. DEFINE_MIN_SEQ(lruvec);
  3292. VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
  3293. /* find the oldest populated generation */
  3294. for_each_evictable_type(type, swappiness) {
  3295. while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
  3296. gen = lru_gen_from_seq(min_seq[type]);
  3297. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3298. if (!list_empty(&lrugen->folios[gen][type][zone]))
  3299. goto next;
  3300. }
  3301. min_seq[type]++;
  3302. seq_inc_flag = true;
  3303. }
  3304. next:
  3305. ;
  3306. }
  3307. /*
  3308. * If min_seq[type] of both anonymous and file is not increased,
  3309. * we can directly return false to avoid unnecessary checking
  3310. * overhead later.
  3311. */
  3312. if (!seq_inc_flag)
  3313. return success;
  3314. /* see the comment on lru_gen_folio */
  3315. if (swappiness && swappiness <= MAX_SWAPPINESS) {
  3316. unsigned long seq = lrugen->max_seq - MIN_NR_GENS;
  3317. if (min_seq[LRU_GEN_ANON] > seq && min_seq[LRU_GEN_FILE] < seq)
  3318. min_seq[LRU_GEN_ANON] = seq;
  3319. else if (min_seq[LRU_GEN_FILE] > seq && min_seq[LRU_GEN_ANON] < seq)
  3320. min_seq[LRU_GEN_FILE] = seq;
  3321. }
  3322. for_each_evictable_type(type, swappiness) {
  3323. if (min_seq[type] <= lrugen->min_seq[type])
  3324. continue;
  3325. reset_ctrl_pos(lruvec, type, true);
  3326. WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
  3327. success = true;
  3328. }
  3329. return success;
  3330. }
  3331. static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness)
  3332. {
  3333. bool success;
  3334. int prev, next;
  3335. int type, zone;
  3336. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3337. restart:
  3338. if (seq < READ_ONCE(lrugen->max_seq))
  3339. return false;
  3340. spin_lock_irq(&lruvec->lru_lock);
  3341. VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
  3342. success = seq == lrugen->max_seq;
  3343. if (!success)
  3344. goto unlock;
  3345. for (type = 0; type < ANON_AND_FILE; type++) {
  3346. if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
  3347. continue;
  3348. if (inc_min_seq(lruvec, type, swappiness))
  3349. continue;
  3350. spin_unlock_irq(&lruvec->lru_lock);
  3351. cond_resched();
  3352. goto restart;
  3353. }
  3354. /*
  3355. * Update the active/inactive LRU sizes for compatibility. Both sides of
  3356. * the current max_seq need to be covered, since max_seq+1 can overlap
  3357. * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
  3358. * overlap, cold/hot inversion happens.
  3359. */
  3360. prev = lru_gen_from_seq(lrugen->max_seq - 1);
  3361. next = lru_gen_from_seq(lrugen->max_seq + 1);
  3362. for (type = 0; type < ANON_AND_FILE; type++) {
  3363. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3364. enum lru_list lru = type * LRU_INACTIVE_FILE;
  3365. long delta = lrugen->nr_pages[prev][type][zone] -
  3366. lrugen->nr_pages[next][type][zone];
  3367. if (!delta)
  3368. continue;
  3369. __update_lru_size(lruvec, lru, zone, delta);
  3370. __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
  3371. }
  3372. }
  3373. for (type = 0; type < ANON_AND_FILE; type++)
  3374. reset_ctrl_pos(lruvec, type, false);
  3375. WRITE_ONCE(lrugen->timestamps[next], jiffies);
  3376. /* make sure preceding modifications appear */
  3377. smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
  3378. unlock:
  3379. spin_unlock_irq(&lruvec->lru_lock);
  3380. return success;
  3381. }
  3382. static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq,
  3383. int swappiness, bool force_scan)
  3384. {
  3385. bool success;
  3386. struct lru_gen_mm_walk *walk;
  3387. struct mm_struct *mm = NULL;
  3388. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3389. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  3390. VM_WARN_ON_ONCE(seq > READ_ONCE(lrugen->max_seq));
  3391. if (!mm_state)
  3392. return inc_max_seq(lruvec, seq, swappiness);
  3393. /* see the comment in iterate_mm_list() */
  3394. if (seq <= READ_ONCE(mm_state->seq))
  3395. return false;
  3396. /*
  3397. * If the hardware doesn't automatically set the accessed bit, fallback
  3398. * to lru_gen_look_around(), which only clears the accessed bit in a
  3399. * handful of PTEs. Spreading the work out over a period of time usually
  3400. * is less efficient, but it avoids bursty page faults.
  3401. */
  3402. if (!should_walk_mmu()) {
  3403. success = iterate_mm_list_nowalk(lruvec, seq);
  3404. goto done;
  3405. }
  3406. walk = set_mm_walk(NULL, true);
  3407. if (!walk) {
  3408. success = iterate_mm_list_nowalk(lruvec, seq);
  3409. goto done;
  3410. }
  3411. walk->lruvec = lruvec;
  3412. walk->seq = seq;
  3413. walk->swappiness = swappiness;
  3414. walk->force_scan = force_scan;
  3415. do {
  3416. success = iterate_mm_list(walk, &mm);
  3417. if (mm)
  3418. walk_mm(mm, walk);
  3419. } while (mm);
  3420. done:
  3421. if (success) {
  3422. success = inc_max_seq(lruvec, seq, swappiness);
  3423. WARN_ON_ONCE(!success);
  3424. }
  3425. return success;
  3426. }
  3427. /******************************************************************************
  3428. * working set protection
  3429. ******************************************************************************/
  3430. static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
  3431. {
  3432. int priority;
  3433. unsigned long reclaimable;
  3434. if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
  3435. return;
  3436. /*
  3437. * Determine the initial priority based on
  3438. * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim,
  3439. * where reclaimed_to_scanned_ratio = inactive / total.
  3440. */
  3441. reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
  3442. if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
  3443. reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
  3444. /* round down reclaimable and round up sc->nr_to_reclaim */
  3445. priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
  3446. /*
  3447. * The estimation is based on LRU pages only, so cap it to prevent
  3448. * overshoots of shrinker objects by large margins.
  3449. */
  3450. sc->priority = clamp(priority, DEF_PRIORITY / 2, DEF_PRIORITY);
  3451. }
  3452. static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
  3453. {
  3454. int gen, type, zone;
  3455. unsigned long total = 0;
  3456. int swappiness = get_swappiness(lruvec, sc);
  3457. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3458. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  3459. DEFINE_MAX_SEQ(lruvec);
  3460. DEFINE_MIN_SEQ(lruvec);
  3461. for_each_evictable_type(type, swappiness) {
  3462. unsigned long seq;
  3463. for (seq = min_seq[type]; seq <= max_seq; seq++) {
  3464. gen = lru_gen_from_seq(seq);
  3465. for (zone = 0; zone < MAX_NR_ZONES; zone++)
  3466. total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
  3467. }
  3468. }
  3469. /* whether the size is big enough to be helpful */
  3470. return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
  3471. }
  3472. static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
  3473. unsigned long min_ttl)
  3474. {
  3475. int gen;
  3476. unsigned long birth;
  3477. int swappiness = get_swappiness(lruvec, sc);
  3478. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  3479. DEFINE_MIN_SEQ(lruvec);
  3480. if (mem_cgroup_below_min(NULL, memcg))
  3481. return false;
  3482. if (!lruvec_is_sizable(lruvec, sc))
  3483. return false;
  3484. gen = lru_gen_from_seq(evictable_min_seq(min_seq, swappiness));
  3485. birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
  3486. return time_is_before_jiffies(birth + min_ttl);
  3487. }
  3488. /* to protect the working set of the last N jiffies */
  3489. static unsigned long lru_gen_min_ttl __read_mostly;
  3490. static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
  3491. {
  3492. struct mem_cgroup *memcg;
  3493. unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
  3494. bool reclaimable = !min_ttl;
  3495. VM_WARN_ON_ONCE(!current_is_kswapd());
  3496. set_initial_priority(pgdat, sc);
  3497. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  3498. do {
  3499. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  3500. mem_cgroup_calculate_protection(NULL, memcg);
  3501. if (!reclaimable)
  3502. reclaimable = lruvec_is_reclaimable(lruvec, sc, min_ttl);
  3503. } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
  3504. /*
  3505. * The main goal is to OOM kill if every generation from all memcgs is
  3506. * younger than min_ttl. However, another possibility is all memcgs are
  3507. * either too small or below min.
  3508. */
  3509. if (!reclaimable && mutex_trylock(&oom_lock)) {
  3510. struct oom_control oc = {
  3511. .gfp_mask = sc->gfp_mask,
  3512. };
  3513. out_of_memory(&oc);
  3514. mutex_unlock(&oom_lock);
  3515. }
  3516. }
  3517. /******************************************************************************
  3518. * rmap/PT walk feedback
  3519. ******************************************************************************/
  3520. /*
  3521. * This function exploits spatial locality when shrink_folio_list() walks the
  3522. * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
  3523. * the scan was done cacheline efficiently, it adds the PMD entry pointing to
  3524. * the PTE table to the Bloom filter. This forms a feedback loop between the
  3525. * eviction and the aging.
  3526. */
  3527. bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
  3528. {
  3529. int i;
  3530. bool dirty;
  3531. unsigned long start;
  3532. unsigned long end;
  3533. struct lru_gen_mm_walk *walk;
  3534. struct folio *last = NULL;
  3535. int young = 1;
  3536. pte_t *pte = pvmw->pte;
  3537. unsigned long addr = pvmw->address;
  3538. struct vm_area_struct *vma = pvmw->vma;
  3539. struct folio *folio = pfn_folio(pvmw->pfn);
  3540. struct mem_cgroup *memcg = folio_memcg(folio);
  3541. struct pglist_data *pgdat = folio_pgdat(folio);
  3542. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  3543. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  3544. DEFINE_MAX_SEQ(lruvec);
  3545. int gen = lru_gen_from_seq(max_seq);
  3546. lockdep_assert_held(pvmw->ptl);
  3547. VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
  3548. if (!ptep_clear_young_notify(vma, addr, pte))
  3549. return false;
  3550. if (spin_is_contended(pvmw->ptl))
  3551. return true;
  3552. /* exclude special VMAs containing anon pages from COW */
  3553. if (vma->vm_flags & VM_SPECIAL)
  3554. return true;
  3555. /* avoid taking the LRU lock under the PTL when possible */
  3556. walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
  3557. start = max(addr & PMD_MASK, vma->vm_start);
  3558. end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1;
  3559. if (end - start == PAGE_SIZE)
  3560. return true;
  3561. if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
  3562. if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
  3563. end = start + MIN_LRU_BATCH * PAGE_SIZE;
  3564. else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
  3565. start = end - MIN_LRU_BATCH * PAGE_SIZE;
  3566. else {
  3567. start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
  3568. end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
  3569. }
  3570. }
  3571. lazy_mmu_mode_enable();
  3572. pte -= (addr - start) / PAGE_SIZE;
  3573. for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
  3574. unsigned long pfn;
  3575. pte_t ptent = ptep_get(pte + i);
  3576. pfn = get_pte_pfn(ptent, vma, addr, pgdat);
  3577. if (pfn == -1)
  3578. continue;
  3579. folio = get_pfn_folio(pfn, memcg, pgdat);
  3580. if (!folio)
  3581. continue;
  3582. if (!ptep_clear_young_notify(vma, addr, pte + i))
  3583. continue;
  3584. if (last != folio) {
  3585. walk_update_folio(walk, last, gen, dirty);
  3586. last = folio;
  3587. dirty = false;
  3588. }
  3589. if (pte_dirty(ptent))
  3590. dirty = true;
  3591. young++;
  3592. }
  3593. walk_update_folio(walk, last, gen, dirty);
  3594. lazy_mmu_mode_disable();
  3595. /* feedback from rmap walkers to page table walkers */
  3596. if (mm_state && suitable_to_scan(i, young))
  3597. update_bloom_filter(mm_state, max_seq, pvmw->pmd);
  3598. return true;
  3599. }
  3600. /******************************************************************************
  3601. * memcg LRU
  3602. ******************************************************************************/
  3603. /* see the comment on MEMCG_NR_GENS */
  3604. enum {
  3605. MEMCG_LRU_NOP,
  3606. MEMCG_LRU_HEAD,
  3607. MEMCG_LRU_TAIL,
  3608. MEMCG_LRU_OLD,
  3609. MEMCG_LRU_YOUNG,
  3610. };
  3611. static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
  3612. {
  3613. int seg;
  3614. int old, new;
  3615. unsigned long flags;
  3616. int bin = get_random_u32_below(MEMCG_NR_BINS);
  3617. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  3618. spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
  3619. VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
  3620. seg = 0;
  3621. new = old = lruvec->lrugen.gen;
  3622. /* see the comment on MEMCG_NR_GENS */
  3623. if (op == MEMCG_LRU_HEAD)
  3624. seg = MEMCG_LRU_HEAD;
  3625. else if (op == MEMCG_LRU_TAIL)
  3626. seg = MEMCG_LRU_TAIL;
  3627. else if (op == MEMCG_LRU_OLD)
  3628. new = get_memcg_gen(pgdat->memcg_lru.seq);
  3629. else if (op == MEMCG_LRU_YOUNG)
  3630. new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
  3631. else
  3632. VM_WARN_ON_ONCE(true);
  3633. WRITE_ONCE(lruvec->lrugen.seg, seg);
  3634. WRITE_ONCE(lruvec->lrugen.gen, new);
  3635. hlist_nulls_del_rcu(&lruvec->lrugen.list);
  3636. if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
  3637. hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
  3638. else
  3639. hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
  3640. pgdat->memcg_lru.nr_memcgs[old]--;
  3641. pgdat->memcg_lru.nr_memcgs[new]++;
  3642. if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
  3643. WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
  3644. spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
  3645. }
  3646. #ifdef CONFIG_MEMCG
  3647. void lru_gen_online_memcg(struct mem_cgroup *memcg)
  3648. {
  3649. int gen;
  3650. int nid;
  3651. int bin = get_random_u32_below(MEMCG_NR_BINS);
  3652. for_each_node(nid) {
  3653. struct pglist_data *pgdat = NODE_DATA(nid);
  3654. struct lruvec *lruvec = get_lruvec(memcg, nid);
  3655. spin_lock_irq(&pgdat->memcg_lru.lock);
  3656. VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
  3657. gen = get_memcg_gen(pgdat->memcg_lru.seq);
  3658. lruvec->lrugen.gen = gen;
  3659. hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
  3660. pgdat->memcg_lru.nr_memcgs[gen]++;
  3661. spin_unlock_irq(&pgdat->memcg_lru.lock);
  3662. }
  3663. }
  3664. void lru_gen_offline_memcg(struct mem_cgroup *memcg)
  3665. {
  3666. int nid;
  3667. for_each_node(nid) {
  3668. struct lruvec *lruvec = get_lruvec(memcg, nid);
  3669. lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
  3670. }
  3671. }
  3672. void lru_gen_release_memcg(struct mem_cgroup *memcg)
  3673. {
  3674. int gen;
  3675. int nid;
  3676. for_each_node(nid) {
  3677. struct pglist_data *pgdat = NODE_DATA(nid);
  3678. struct lruvec *lruvec = get_lruvec(memcg, nid);
  3679. spin_lock_irq(&pgdat->memcg_lru.lock);
  3680. if (hlist_nulls_unhashed(&lruvec->lrugen.list))
  3681. goto unlock;
  3682. gen = lruvec->lrugen.gen;
  3683. hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
  3684. pgdat->memcg_lru.nr_memcgs[gen]--;
  3685. if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
  3686. WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
  3687. unlock:
  3688. spin_unlock_irq(&pgdat->memcg_lru.lock);
  3689. }
  3690. }
  3691. void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
  3692. {
  3693. struct lruvec *lruvec = get_lruvec(memcg, nid);
  3694. /* see the comment on MEMCG_NR_GENS */
  3695. if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_HEAD)
  3696. lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
  3697. }
  3698. #endif /* CONFIG_MEMCG */
  3699. /******************************************************************************
  3700. * the eviction
  3701. ******************************************************************************/
  3702. static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc,
  3703. int tier_idx)
  3704. {
  3705. bool success;
  3706. bool dirty, writeback;
  3707. int gen = folio_lru_gen(folio);
  3708. int type = folio_is_file_lru(folio);
  3709. int zone = folio_zonenum(folio);
  3710. int delta = folio_nr_pages(folio);
  3711. int refs = folio_lru_refs(folio);
  3712. bool workingset = folio_test_workingset(folio);
  3713. int tier = lru_tier_from_refs(refs, workingset);
  3714. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3715. VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
  3716. /* unevictable */
  3717. if (!folio_evictable(folio)) {
  3718. success = lru_gen_del_folio(lruvec, folio, true);
  3719. VM_WARN_ON_ONCE_FOLIO(!success, folio);
  3720. folio_set_unevictable(folio);
  3721. lruvec_add_folio(lruvec, folio);
  3722. __count_vm_events(UNEVICTABLE_PGCULLED, delta);
  3723. return true;
  3724. }
  3725. /* promoted */
  3726. if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
  3727. list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
  3728. return true;
  3729. }
  3730. /* protected */
  3731. if (tier > tier_idx || refs + workingset == BIT(LRU_REFS_WIDTH) + 1) {
  3732. gen = folio_inc_gen(lruvec, folio, false);
  3733. list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
  3734. /* don't count the workingset being lazily promoted */
  3735. if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) {
  3736. int hist = lru_hist_from_seq(lrugen->min_seq[type]);
  3737. WRITE_ONCE(lrugen->protected[hist][type][tier],
  3738. lrugen->protected[hist][type][tier] + delta);
  3739. }
  3740. return true;
  3741. }
  3742. /* ineligible */
  3743. if (zone > sc->reclaim_idx) {
  3744. gen = folio_inc_gen(lruvec, folio, false);
  3745. list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
  3746. return true;
  3747. }
  3748. dirty = folio_test_dirty(folio);
  3749. writeback = folio_test_writeback(folio);
  3750. if (type == LRU_GEN_FILE && dirty) {
  3751. sc->nr.file_taken += delta;
  3752. if (!writeback)
  3753. sc->nr.unqueued_dirty += delta;
  3754. }
  3755. /* waiting for writeback */
  3756. if (writeback || (type == LRU_GEN_FILE && dirty)) {
  3757. gen = folio_inc_gen(lruvec, folio, true);
  3758. list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
  3759. return true;
  3760. }
  3761. return false;
  3762. }
  3763. static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
  3764. {
  3765. bool success;
  3766. /* swap constrained */
  3767. if (!(sc->gfp_mask & __GFP_IO) &&
  3768. (folio_test_dirty(folio) ||
  3769. (folio_test_anon(folio) && !folio_test_swapcache(folio))))
  3770. return false;
  3771. /* raced with release_pages() */
  3772. if (!folio_try_get(folio))
  3773. return false;
  3774. /* raced with another isolation */
  3775. if (!folio_test_clear_lru(folio)) {
  3776. folio_put(folio);
  3777. return false;
  3778. }
  3779. /* see the comment on LRU_REFS_FLAGS */
  3780. if (!folio_test_referenced(folio))
  3781. set_mask_bits(&folio->flags.f, LRU_REFS_MASK, 0);
  3782. /* for shrink_folio_list() */
  3783. folio_clear_reclaim(folio);
  3784. success = lru_gen_del_folio(lruvec, folio, true);
  3785. VM_WARN_ON_ONCE_FOLIO(!success, folio);
  3786. return true;
  3787. }
  3788. static int scan_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
  3789. struct scan_control *sc, int type, int tier,
  3790. struct list_head *list)
  3791. {
  3792. int i;
  3793. int gen;
  3794. enum vm_event_item item;
  3795. int sorted = 0;
  3796. int scanned = 0;
  3797. int isolated = 0;
  3798. int skipped = 0;
  3799. int scan_batch = min(nr_to_scan, MAX_LRU_BATCH);
  3800. int remaining = scan_batch;
  3801. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3802. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  3803. VM_WARN_ON_ONCE(!list_empty(list));
  3804. if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
  3805. return 0;
  3806. gen = lru_gen_from_seq(lrugen->min_seq[type]);
  3807. for (i = MAX_NR_ZONES; i > 0; i--) {
  3808. LIST_HEAD(moved);
  3809. int skipped_zone = 0;
  3810. int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
  3811. struct list_head *head = &lrugen->folios[gen][type][zone];
  3812. while (!list_empty(head)) {
  3813. struct folio *folio = lru_to_folio(head);
  3814. int delta = folio_nr_pages(folio);
  3815. VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
  3816. VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
  3817. VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
  3818. VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
  3819. scanned += delta;
  3820. if (sort_folio(lruvec, folio, sc, tier))
  3821. sorted += delta;
  3822. else if (isolate_folio(lruvec, folio, sc)) {
  3823. list_add(&folio->lru, list);
  3824. isolated += delta;
  3825. } else {
  3826. list_move(&folio->lru, &moved);
  3827. skipped_zone += delta;
  3828. }
  3829. if (!--remaining || max(isolated, skipped_zone) >= MIN_LRU_BATCH)
  3830. break;
  3831. }
  3832. if (skipped_zone) {
  3833. list_splice(&moved, head);
  3834. __count_zid_vm_events(PGSCAN_SKIP, zone, skipped_zone);
  3835. skipped += skipped_zone;
  3836. }
  3837. if (!remaining || isolated >= MIN_LRU_BATCH)
  3838. break;
  3839. }
  3840. item = PGSCAN_KSWAPD + reclaimer_offset(sc);
  3841. if (!cgroup_reclaim(sc)) {
  3842. __count_vm_events(item, isolated);
  3843. __count_vm_events(PGREFILL, sorted);
  3844. }
  3845. count_memcg_events(memcg, item, isolated);
  3846. count_memcg_events(memcg, PGREFILL, sorted);
  3847. __count_vm_events(PGSCAN_ANON + type, isolated);
  3848. trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, scan_batch,
  3849. scanned, skipped, isolated,
  3850. type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
  3851. if (type == LRU_GEN_FILE)
  3852. sc->nr.file_taken += isolated;
  3853. /*
  3854. * There might not be eligible folios due to reclaim_idx. Check the
  3855. * remaining to prevent livelock if it's not making progress.
  3856. */
  3857. return isolated || !remaining ? scanned : 0;
  3858. }
  3859. static int get_tier_idx(struct lruvec *lruvec, int type)
  3860. {
  3861. int tier;
  3862. struct ctrl_pos sp, pv;
  3863. /*
  3864. * To leave a margin for fluctuations, use a larger gain factor (2:3).
  3865. * This value is chosen because any other tier would have at least twice
  3866. * as many refaults as the first tier.
  3867. */
  3868. read_ctrl_pos(lruvec, type, 0, 2, &sp);
  3869. for (tier = 1; tier < MAX_NR_TIERS; tier++) {
  3870. read_ctrl_pos(lruvec, type, tier, 3, &pv);
  3871. if (!positive_ctrl_err(&sp, &pv))
  3872. break;
  3873. }
  3874. return tier - 1;
  3875. }
  3876. static int get_type_to_scan(struct lruvec *lruvec, int swappiness)
  3877. {
  3878. struct ctrl_pos sp, pv;
  3879. if (swappiness <= MIN_SWAPPINESS + 1)
  3880. return LRU_GEN_FILE;
  3881. if (swappiness >= MAX_SWAPPINESS)
  3882. return LRU_GEN_ANON;
  3883. /*
  3884. * Compare the sum of all tiers of anon with that of file to determine
  3885. * which type to scan.
  3886. */
  3887. read_ctrl_pos(lruvec, LRU_GEN_ANON, MAX_NR_TIERS, swappiness, &sp);
  3888. read_ctrl_pos(lruvec, LRU_GEN_FILE, MAX_NR_TIERS, MAX_SWAPPINESS - swappiness, &pv);
  3889. return positive_ctrl_err(&sp, &pv);
  3890. }
  3891. static int isolate_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
  3892. struct scan_control *sc, int swappiness,
  3893. int *type_scanned, struct list_head *list)
  3894. {
  3895. int i;
  3896. int type = get_type_to_scan(lruvec, swappiness);
  3897. for_each_evictable_type(i, swappiness) {
  3898. int scanned;
  3899. int tier = get_tier_idx(lruvec, type);
  3900. *type_scanned = type;
  3901. scanned = scan_folios(nr_to_scan, lruvec, sc, type, tier, list);
  3902. if (scanned)
  3903. return scanned;
  3904. type = !type;
  3905. }
  3906. return 0;
  3907. }
  3908. static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec,
  3909. struct scan_control *sc, int swappiness)
  3910. {
  3911. int type;
  3912. int scanned;
  3913. int reclaimed;
  3914. LIST_HEAD(list);
  3915. LIST_HEAD(clean);
  3916. struct folio *folio;
  3917. struct folio *next;
  3918. enum vm_event_item item;
  3919. struct reclaim_stat stat;
  3920. struct lru_gen_mm_walk *walk;
  3921. bool skip_retry = false;
  3922. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3923. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  3924. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  3925. spin_lock_irq(&lruvec->lru_lock);
  3926. scanned = isolate_folios(nr_to_scan, lruvec, sc, swappiness, &type, &list);
  3927. scanned += try_to_inc_min_seq(lruvec, swappiness);
  3928. if (evictable_min_seq(lrugen->min_seq, swappiness) + MIN_NR_GENS > lrugen->max_seq)
  3929. scanned = 0;
  3930. spin_unlock_irq(&lruvec->lru_lock);
  3931. if (list_empty(&list))
  3932. return scanned;
  3933. retry:
  3934. reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false, memcg);
  3935. sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
  3936. sc->nr_reclaimed += reclaimed;
  3937. trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
  3938. scanned, reclaimed, &stat, sc->priority,
  3939. type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON);
  3940. list_for_each_entry_safe_reverse(folio, next, &list, lru) {
  3941. DEFINE_MIN_SEQ(lruvec);
  3942. if (!folio_evictable(folio)) {
  3943. list_del(&folio->lru);
  3944. folio_putback_lru(folio);
  3945. continue;
  3946. }
  3947. /* retry folios that may have missed folio_rotate_reclaimable() */
  3948. if (!skip_retry && !folio_test_active(folio) && !folio_mapped(folio) &&
  3949. !folio_test_dirty(folio) && !folio_test_writeback(folio)) {
  3950. list_move(&folio->lru, &clean);
  3951. continue;
  3952. }
  3953. /* don't add rejected folios to the oldest generation */
  3954. if (lru_gen_folio_seq(lruvec, folio, false) == min_seq[type])
  3955. set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active));
  3956. }
  3957. spin_lock_irq(&lruvec->lru_lock);
  3958. move_folios_to_lru(lruvec, &list);
  3959. walk = current->reclaim_state->mm_walk;
  3960. if (walk && walk->batched) {
  3961. walk->lruvec = lruvec;
  3962. reset_batch_size(walk);
  3963. }
  3964. mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc),
  3965. stat.nr_demoted);
  3966. item = PGSTEAL_KSWAPD + reclaimer_offset(sc);
  3967. if (!cgroup_reclaim(sc))
  3968. __count_vm_events(item, reclaimed);
  3969. count_memcg_events(memcg, item, reclaimed);
  3970. __count_vm_events(PGSTEAL_ANON + type, reclaimed);
  3971. spin_unlock_irq(&lruvec->lru_lock);
  3972. list_splice_init(&clean, &list);
  3973. if (!list_empty(&list)) {
  3974. skip_retry = true;
  3975. goto retry;
  3976. }
  3977. return scanned;
  3978. }
  3979. static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
  3980. int swappiness, unsigned long *nr_to_scan)
  3981. {
  3982. int gen, type, zone;
  3983. unsigned long size = 0;
  3984. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  3985. DEFINE_MIN_SEQ(lruvec);
  3986. *nr_to_scan = 0;
  3987. /* have to run aging, since eviction is not possible anymore */
  3988. if (evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS > max_seq)
  3989. return true;
  3990. for_each_evictable_type(type, swappiness) {
  3991. unsigned long seq;
  3992. for (seq = min_seq[type]; seq <= max_seq; seq++) {
  3993. gen = lru_gen_from_seq(seq);
  3994. for (zone = 0; zone < MAX_NR_ZONES; zone++)
  3995. size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
  3996. }
  3997. }
  3998. *nr_to_scan = size;
  3999. /* better to run aging even though eviction is still possible */
  4000. return evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS == max_seq;
  4001. }
  4002. /*
  4003. * For future optimizations:
  4004. * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
  4005. * reclaim.
  4006. */
  4007. static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
  4008. {
  4009. bool success;
  4010. unsigned long nr_to_scan;
  4011. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  4012. DEFINE_MAX_SEQ(lruvec);
  4013. if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
  4014. return -1;
  4015. success = should_run_aging(lruvec, max_seq, swappiness, &nr_to_scan);
  4016. /* try to scrape all its memory if this memcg was deleted */
  4017. if (nr_to_scan && !mem_cgroup_online(memcg))
  4018. return nr_to_scan;
  4019. nr_to_scan = apply_proportional_protection(memcg, sc, nr_to_scan);
  4020. /* try to get away with not aging at the default priority */
  4021. if (!success || sc->priority == DEF_PRIORITY)
  4022. return nr_to_scan >> sc->priority;
  4023. /* stop scanning this lruvec as it's low on cold folios */
  4024. return try_to_inc_max_seq(lruvec, max_seq, swappiness, false) ? -1 : 0;
  4025. }
  4026. static bool should_abort_scan(struct lruvec *lruvec, struct scan_control *sc)
  4027. {
  4028. int i;
  4029. enum zone_watermarks mark;
  4030. /* don't abort memcg reclaim to ensure fairness */
  4031. if (!root_reclaim(sc))
  4032. return false;
  4033. if (sc->nr_reclaimed >= max(sc->nr_to_reclaim, compact_gap(sc->order)))
  4034. return true;
  4035. /* check the order to exclude compaction-induced reclaim */
  4036. if (!current_is_kswapd() || sc->order)
  4037. return false;
  4038. mark = sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ?
  4039. WMARK_PROMO : WMARK_HIGH;
  4040. for (i = 0; i <= sc->reclaim_idx; i++) {
  4041. struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
  4042. unsigned long size = wmark_pages(zone, mark) + MIN_LRU_BATCH;
  4043. if (managed_zone(zone) && !zone_watermark_ok(zone, 0, size, sc->reclaim_idx, 0))
  4044. return false;
  4045. }
  4046. /* kswapd should abort if all eligible zones are safe */
  4047. return true;
  4048. }
  4049. static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
  4050. {
  4051. long nr_to_scan;
  4052. unsigned long scanned = 0;
  4053. int swappiness = get_swappiness(lruvec, sc);
  4054. while (true) {
  4055. int delta;
  4056. nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
  4057. if (nr_to_scan <= 0)
  4058. break;
  4059. delta = evict_folios(nr_to_scan, lruvec, sc, swappiness);
  4060. if (!delta)
  4061. break;
  4062. scanned += delta;
  4063. if (scanned >= nr_to_scan)
  4064. break;
  4065. if (should_abort_scan(lruvec, sc))
  4066. break;
  4067. cond_resched();
  4068. }
  4069. /*
  4070. * If too many file cache in the coldest generation can't be evicted
  4071. * due to being dirty, wake up the flusher.
  4072. */
  4073. if (sc->nr.unqueued_dirty && sc->nr.unqueued_dirty == sc->nr.file_taken)
  4074. wakeup_flusher_threads(WB_REASON_VMSCAN);
  4075. /* whether this lruvec should be rotated */
  4076. return nr_to_scan < 0;
  4077. }
  4078. static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
  4079. {
  4080. bool success;
  4081. unsigned long scanned = sc->nr_scanned;
  4082. unsigned long reclaimed = sc->nr_reclaimed;
  4083. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  4084. struct pglist_data *pgdat = lruvec_pgdat(lruvec);
  4085. /* lru_gen_age_node() called mem_cgroup_calculate_protection() */
  4086. if (mem_cgroup_below_min(NULL, memcg))
  4087. return MEMCG_LRU_YOUNG;
  4088. if (mem_cgroup_below_low(NULL, memcg)) {
  4089. /* see the comment on MEMCG_NR_GENS */
  4090. if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL)
  4091. return MEMCG_LRU_TAIL;
  4092. memcg_memory_event(memcg, MEMCG_LOW);
  4093. }
  4094. success = try_to_shrink_lruvec(lruvec, sc);
  4095. shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
  4096. if (!sc->proactive)
  4097. vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
  4098. sc->nr_reclaimed - reclaimed);
  4099. flush_reclaim_state(sc);
  4100. if (success && mem_cgroup_online(memcg))
  4101. return MEMCG_LRU_YOUNG;
  4102. if (!success && lruvec_is_sizable(lruvec, sc))
  4103. return 0;
  4104. /* one retry if offlined or too small */
  4105. return READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL ?
  4106. MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
  4107. }
  4108. static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
  4109. {
  4110. int op;
  4111. int gen;
  4112. int bin;
  4113. int first_bin;
  4114. struct lruvec *lruvec;
  4115. struct lru_gen_folio *lrugen;
  4116. struct mem_cgroup *memcg;
  4117. struct hlist_nulls_node *pos;
  4118. gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
  4119. bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
  4120. restart:
  4121. op = 0;
  4122. memcg = NULL;
  4123. rcu_read_lock();
  4124. hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
  4125. if (op) {
  4126. lru_gen_rotate_memcg(lruvec, op);
  4127. op = 0;
  4128. }
  4129. mem_cgroup_put(memcg);
  4130. memcg = NULL;
  4131. if (gen != READ_ONCE(lrugen->gen))
  4132. continue;
  4133. lruvec = container_of(lrugen, struct lruvec, lrugen);
  4134. memcg = lruvec_memcg(lruvec);
  4135. if (!mem_cgroup_tryget(memcg)) {
  4136. lru_gen_release_memcg(memcg);
  4137. memcg = NULL;
  4138. continue;
  4139. }
  4140. rcu_read_unlock();
  4141. op = shrink_one(lruvec, sc);
  4142. rcu_read_lock();
  4143. if (should_abort_scan(lruvec, sc))
  4144. break;
  4145. }
  4146. rcu_read_unlock();
  4147. if (op)
  4148. lru_gen_rotate_memcg(lruvec, op);
  4149. mem_cgroup_put(memcg);
  4150. if (!is_a_nulls(pos))
  4151. return;
  4152. /* restart if raced with lru_gen_rotate_memcg() */
  4153. if (gen != get_nulls_value(pos))
  4154. goto restart;
  4155. /* try the rest of the bins of the current generation */
  4156. bin = get_memcg_bin(bin + 1);
  4157. if (bin != first_bin)
  4158. goto restart;
  4159. }
  4160. static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
  4161. {
  4162. struct blk_plug plug;
  4163. VM_WARN_ON_ONCE(root_reclaim(sc));
  4164. VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
  4165. lru_add_drain();
  4166. blk_start_plug(&plug);
  4167. set_mm_walk(NULL, sc->proactive);
  4168. if (try_to_shrink_lruvec(lruvec, sc))
  4169. lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
  4170. clear_mm_walk();
  4171. blk_finish_plug(&plug);
  4172. }
  4173. static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
  4174. {
  4175. struct blk_plug plug;
  4176. unsigned long reclaimed = sc->nr_reclaimed;
  4177. VM_WARN_ON_ONCE(!root_reclaim(sc));
  4178. /*
  4179. * Unmapped clean folios are already prioritized. Scanning for more of
  4180. * them is likely futile and can cause high reclaim latency when there
  4181. * is a large number of memcgs.
  4182. */
  4183. if (!sc->may_writepage || !sc->may_unmap)
  4184. goto done;
  4185. lru_add_drain();
  4186. blk_start_plug(&plug);
  4187. set_mm_walk(pgdat, sc->proactive);
  4188. set_initial_priority(pgdat, sc);
  4189. if (current_is_kswapd())
  4190. sc->nr_reclaimed = 0;
  4191. if (mem_cgroup_disabled())
  4192. shrink_one(&pgdat->__lruvec, sc);
  4193. else
  4194. shrink_many(pgdat, sc);
  4195. if (current_is_kswapd())
  4196. sc->nr_reclaimed += reclaimed;
  4197. clear_mm_walk();
  4198. blk_finish_plug(&plug);
  4199. done:
  4200. if (sc->nr_reclaimed > reclaimed)
  4201. kswapd_try_clear_hopeless(pgdat, sc->order, sc->reclaim_idx);
  4202. }
  4203. /******************************************************************************
  4204. * state change
  4205. ******************************************************************************/
  4206. static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
  4207. {
  4208. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  4209. if (lrugen->enabled) {
  4210. enum lru_list lru;
  4211. for_each_evictable_lru(lru) {
  4212. if (!list_empty(&lruvec->lists[lru]))
  4213. return false;
  4214. }
  4215. } else {
  4216. int gen, type, zone;
  4217. for_each_gen_type_zone(gen, type, zone) {
  4218. if (!list_empty(&lrugen->folios[gen][type][zone]))
  4219. return false;
  4220. }
  4221. }
  4222. return true;
  4223. }
  4224. static bool fill_evictable(struct lruvec *lruvec)
  4225. {
  4226. enum lru_list lru;
  4227. int remaining = MAX_LRU_BATCH;
  4228. for_each_evictable_lru(lru) {
  4229. int type = is_file_lru(lru);
  4230. bool active = is_active_lru(lru);
  4231. struct list_head *head = &lruvec->lists[lru];
  4232. while (!list_empty(head)) {
  4233. bool success;
  4234. struct folio *folio = lru_to_folio(head);
  4235. VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
  4236. VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
  4237. VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
  4238. VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
  4239. lruvec_del_folio(lruvec, folio);
  4240. success = lru_gen_add_folio(lruvec, folio, false);
  4241. VM_WARN_ON_ONCE(!success);
  4242. if (!--remaining)
  4243. return false;
  4244. }
  4245. }
  4246. return true;
  4247. }
  4248. static bool drain_evictable(struct lruvec *lruvec)
  4249. {
  4250. int gen, type, zone;
  4251. int remaining = MAX_LRU_BATCH;
  4252. for_each_gen_type_zone(gen, type, zone) {
  4253. struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
  4254. while (!list_empty(head)) {
  4255. bool success;
  4256. struct folio *folio = lru_to_folio(head);
  4257. VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
  4258. VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
  4259. VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
  4260. VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
  4261. success = lru_gen_del_folio(lruvec, folio, false);
  4262. VM_WARN_ON_ONCE(!success);
  4263. lruvec_add_folio(lruvec, folio);
  4264. if (!--remaining)
  4265. return false;
  4266. }
  4267. }
  4268. return true;
  4269. }
  4270. static void lru_gen_change_state(bool enabled)
  4271. {
  4272. static DEFINE_MUTEX(state_mutex);
  4273. struct mem_cgroup *memcg;
  4274. cgroup_lock();
  4275. cpus_read_lock();
  4276. get_online_mems();
  4277. mutex_lock(&state_mutex);
  4278. if (enabled == lru_gen_enabled())
  4279. goto unlock;
  4280. if (enabled)
  4281. static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
  4282. else
  4283. static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
  4284. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  4285. do {
  4286. int nid;
  4287. for_each_node(nid) {
  4288. struct lruvec *lruvec = get_lruvec(memcg, nid);
  4289. spin_lock_irq(&lruvec->lru_lock);
  4290. VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
  4291. VM_WARN_ON_ONCE(!state_is_valid(lruvec));
  4292. lruvec->lrugen.enabled = enabled;
  4293. while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
  4294. spin_unlock_irq(&lruvec->lru_lock);
  4295. cond_resched();
  4296. spin_lock_irq(&lruvec->lru_lock);
  4297. }
  4298. spin_unlock_irq(&lruvec->lru_lock);
  4299. }
  4300. cond_resched();
  4301. } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
  4302. unlock:
  4303. mutex_unlock(&state_mutex);
  4304. put_online_mems();
  4305. cpus_read_unlock();
  4306. cgroup_unlock();
  4307. }
  4308. /******************************************************************************
  4309. * sysfs interface
  4310. ******************************************************************************/
  4311. static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
  4312. {
  4313. return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
  4314. }
  4315. /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
  4316. static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
  4317. const char *buf, size_t len)
  4318. {
  4319. unsigned int msecs;
  4320. if (kstrtouint(buf, 0, &msecs))
  4321. return -EINVAL;
  4322. WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
  4323. return len;
  4324. }
  4325. static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
  4326. static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
  4327. {
  4328. unsigned int caps = 0;
  4329. if (get_cap(LRU_GEN_CORE))
  4330. caps |= BIT(LRU_GEN_CORE);
  4331. if (should_walk_mmu())
  4332. caps |= BIT(LRU_GEN_MM_WALK);
  4333. if (should_clear_pmd_young())
  4334. caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
  4335. return sysfs_emit(buf, "0x%04x\n", caps);
  4336. }
  4337. /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
  4338. static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
  4339. const char *buf, size_t len)
  4340. {
  4341. int i;
  4342. unsigned int caps;
  4343. if (tolower(*buf) == 'n')
  4344. caps = 0;
  4345. else if (tolower(*buf) == 'y')
  4346. caps = -1;
  4347. else if (kstrtouint(buf, 0, &caps))
  4348. return -EINVAL;
  4349. for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
  4350. bool enabled = caps & BIT(i);
  4351. if (i == LRU_GEN_CORE)
  4352. lru_gen_change_state(enabled);
  4353. else if (enabled)
  4354. static_branch_enable(&lru_gen_caps[i]);
  4355. else
  4356. static_branch_disable(&lru_gen_caps[i]);
  4357. }
  4358. return len;
  4359. }
  4360. static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
  4361. static struct attribute *lru_gen_attrs[] = {
  4362. &lru_gen_min_ttl_attr.attr,
  4363. &lru_gen_enabled_attr.attr,
  4364. NULL
  4365. };
  4366. static const struct attribute_group lru_gen_attr_group = {
  4367. .name = "lru_gen",
  4368. .attrs = lru_gen_attrs,
  4369. };
  4370. /******************************************************************************
  4371. * debugfs interface
  4372. ******************************************************************************/
  4373. static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
  4374. {
  4375. struct mem_cgroup *memcg;
  4376. loff_t nr_to_skip = *pos;
  4377. m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
  4378. if (!m->private)
  4379. return ERR_PTR(-ENOMEM);
  4380. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  4381. do {
  4382. int nid;
  4383. for_each_node_state(nid, N_MEMORY) {
  4384. if (!nr_to_skip--)
  4385. return get_lruvec(memcg, nid);
  4386. }
  4387. } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
  4388. return NULL;
  4389. }
  4390. static void lru_gen_seq_stop(struct seq_file *m, void *v)
  4391. {
  4392. if (!IS_ERR_OR_NULL(v))
  4393. mem_cgroup_iter_break(NULL, lruvec_memcg(v));
  4394. kvfree(m->private);
  4395. m->private = NULL;
  4396. }
  4397. static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
  4398. {
  4399. int nid = lruvec_pgdat(v)->node_id;
  4400. struct mem_cgroup *memcg = lruvec_memcg(v);
  4401. ++*pos;
  4402. nid = next_memory_node(nid);
  4403. if (nid == MAX_NUMNODES) {
  4404. memcg = mem_cgroup_iter(NULL, memcg, NULL);
  4405. if (!memcg)
  4406. return NULL;
  4407. nid = first_memory_node;
  4408. }
  4409. return get_lruvec(memcg, nid);
  4410. }
  4411. static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
  4412. unsigned long max_seq, unsigned long *min_seq,
  4413. unsigned long seq)
  4414. {
  4415. int i;
  4416. int type, tier;
  4417. int hist = lru_hist_from_seq(seq);
  4418. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  4419. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  4420. for (tier = 0; tier < MAX_NR_TIERS; tier++) {
  4421. seq_printf(m, " %10d", tier);
  4422. for (type = 0; type < ANON_AND_FILE; type++) {
  4423. const char *s = "xxx";
  4424. unsigned long n[3] = {};
  4425. if (seq == max_seq) {
  4426. s = "RTx";
  4427. n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
  4428. n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
  4429. } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
  4430. s = "rep";
  4431. n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
  4432. n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
  4433. n[2] = READ_ONCE(lrugen->protected[hist][type][tier]);
  4434. }
  4435. for (i = 0; i < 3; i++)
  4436. seq_printf(m, " %10lu%c", n[i], s[i]);
  4437. }
  4438. seq_putc(m, '\n');
  4439. }
  4440. if (!mm_state)
  4441. return;
  4442. seq_puts(m, " ");
  4443. for (i = 0; i < NR_MM_STATS; i++) {
  4444. const char *s = "xxxx";
  4445. unsigned long n = 0;
  4446. if (seq == max_seq && NR_HIST_GENS == 1) {
  4447. s = "TYFA";
  4448. n = READ_ONCE(mm_state->stats[hist][i]);
  4449. } else if (seq != max_seq && NR_HIST_GENS > 1) {
  4450. s = "tyfa";
  4451. n = READ_ONCE(mm_state->stats[hist][i]);
  4452. }
  4453. seq_printf(m, " %10lu%c", n, s[i]);
  4454. }
  4455. seq_putc(m, '\n');
  4456. }
  4457. /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
  4458. static int lru_gen_seq_show(struct seq_file *m, void *v)
  4459. {
  4460. unsigned long seq;
  4461. bool full = debugfs_get_aux_num(m->file);
  4462. struct lruvec *lruvec = v;
  4463. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  4464. int nid = lruvec_pgdat(lruvec)->node_id;
  4465. struct mem_cgroup *memcg = lruvec_memcg(lruvec);
  4466. DEFINE_MAX_SEQ(lruvec);
  4467. DEFINE_MIN_SEQ(lruvec);
  4468. if (nid == first_memory_node) {
  4469. const char *path = memcg ? m->private : "";
  4470. #ifdef CONFIG_MEMCG
  4471. if (memcg)
  4472. cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
  4473. #endif
  4474. seq_printf(m, "memcg %llu %s\n", mem_cgroup_id(memcg), path);
  4475. }
  4476. seq_printf(m, " node %5d\n", nid);
  4477. if (!full)
  4478. seq = evictable_min_seq(min_seq, MAX_SWAPPINESS / 2);
  4479. else if (max_seq >= MAX_NR_GENS)
  4480. seq = max_seq - MAX_NR_GENS + 1;
  4481. else
  4482. seq = 0;
  4483. for (; seq <= max_seq; seq++) {
  4484. int type, zone;
  4485. int gen = lru_gen_from_seq(seq);
  4486. unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
  4487. seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
  4488. for (type = 0; type < ANON_AND_FILE; type++) {
  4489. unsigned long size = 0;
  4490. char mark = full && seq < min_seq[type] ? 'x' : ' ';
  4491. for (zone = 0; zone < MAX_NR_ZONES; zone++)
  4492. size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
  4493. seq_printf(m, " %10lu%c", size, mark);
  4494. }
  4495. seq_putc(m, '\n');
  4496. if (full)
  4497. lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
  4498. }
  4499. return 0;
  4500. }
  4501. static const struct seq_operations lru_gen_seq_ops = {
  4502. .start = lru_gen_seq_start,
  4503. .stop = lru_gen_seq_stop,
  4504. .next = lru_gen_seq_next,
  4505. .show = lru_gen_seq_show,
  4506. };
  4507. static int run_aging(struct lruvec *lruvec, unsigned long seq,
  4508. int swappiness, bool force_scan)
  4509. {
  4510. DEFINE_MAX_SEQ(lruvec);
  4511. if (seq > max_seq)
  4512. return -EINVAL;
  4513. return try_to_inc_max_seq(lruvec, max_seq, swappiness, force_scan) ? 0 : -EEXIST;
  4514. }
  4515. static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
  4516. int swappiness, unsigned long nr_to_reclaim)
  4517. {
  4518. DEFINE_MAX_SEQ(lruvec);
  4519. if (seq + MIN_NR_GENS > max_seq)
  4520. return -EINVAL;
  4521. sc->nr_reclaimed = 0;
  4522. while (!signal_pending(current)) {
  4523. DEFINE_MIN_SEQ(lruvec);
  4524. if (seq < evictable_min_seq(min_seq, swappiness))
  4525. return 0;
  4526. if (sc->nr_reclaimed >= nr_to_reclaim)
  4527. return 0;
  4528. if (!evict_folios(nr_to_reclaim - sc->nr_reclaimed, lruvec, sc,
  4529. swappiness))
  4530. return 0;
  4531. cond_resched();
  4532. }
  4533. return -EINTR;
  4534. }
  4535. static int run_cmd(char cmd, u64 memcg_id, int nid, unsigned long seq,
  4536. struct scan_control *sc, int swappiness, unsigned long opt)
  4537. {
  4538. struct lruvec *lruvec;
  4539. int err = -EINVAL;
  4540. struct mem_cgroup *memcg = NULL;
  4541. if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
  4542. return -EINVAL;
  4543. if (!mem_cgroup_disabled()) {
  4544. memcg = mem_cgroup_get_from_id(memcg_id);
  4545. if (!memcg)
  4546. return -EINVAL;
  4547. }
  4548. if (memcg_id != mem_cgroup_id(memcg))
  4549. goto done;
  4550. sc->target_mem_cgroup = memcg;
  4551. lruvec = get_lruvec(memcg, nid);
  4552. if (swappiness < MIN_SWAPPINESS)
  4553. swappiness = get_swappiness(lruvec, sc);
  4554. else if (swappiness > SWAPPINESS_ANON_ONLY)
  4555. goto done;
  4556. switch (cmd) {
  4557. case '+':
  4558. err = run_aging(lruvec, seq, swappiness, opt);
  4559. break;
  4560. case '-':
  4561. err = run_eviction(lruvec, seq, sc, swappiness, opt);
  4562. break;
  4563. }
  4564. done:
  4565. mem_cgroup_put(memcg);
  4566. return err;
  4567. }
  4568. /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
  4569. static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
  4570. size_t len, loff_t *pos)
  4571. {
  4572. void *buf;
  4573. char *cur, *next;
  4574. unsigned int flags;
  4575. struct blk_plug plug;
  4576. int err = -EINVAL;
  4577. struct scan_control sc = {
  4578. .may_writepage = true,
  4579. .may_unmap = true,
  4580. .may_swap = true,
  4581. .reclaim_idx = MAX_NR_ZONES - 1,
  4582. .gfp_mask = GFP_KERNEL,
  4583. .proactive = true,
  4584. };
  4585. buf = kvmalloc(len + 1, GFP_KERNEL);
  4586. if (!buf)
  4587. return -ENOMEM;
  4588. if (copy_from_user(buf, src, len)) {
  4589. kvfree(buf);
  4590. return -EFAULT;
  4591. }
  4592. set_task_reclaim_state(current, &sc.reclaim_state);
  4593. flags = memalloc_noreclaim_save();
  4594. blk_start_plug(&plug);
  4595. if (!set_mm_walk(NULL, true)) {
  4596. err = -ENOMEM;
  4597. goto done;
  4598. }
  4599. next = buf;
  4600. next[len] = '\0';
  4601. while ((cur = strsep(&next, ",;\n"))) {
  4602. int n;
  4603. int end;
  4604. char cmd, swap_string[5];
  4605. u64 memcg_id;
  4606. unsigned int nid;
  4607. unsigned long seq;
  4608. unsigned int swappiness;
  4609. unsigned long opt = -1;
  4610. cur = skip_spaces(cur);
  4611. if (!*cur)
  4612. continue;
  4613. n = sscanf(cur, "%c %llu %u %lu %n %4s %n %lu %n", &cmd, &memcg_id, &nid,
  4614. &seq, &end, swap_string, &end, &opt, &end);
  4615. if (n < 4 || cur[end]) {
  4616. err = -EINVAL;
  4617. break;
  4618. }
  4619. if (n == 4) {
  4620. swappiness = -1;
  4621. } else if (!strcmp("max", swap_string)) {
  4622. /* set by userspace for anonymous memory only */
  4623. swappiness = SWAPPINESS_ANON_ONLY;
  4624. } else {
  4625. err = kstrtouint(swap_string, 0, &swappiness);
  4626. if (err)
  4627. break;
  4628. }
  4629. err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
  4630. if (err)
  4631. break;
  4632. }
  4633. done:
  4634. clear_mm_walk();
  4635. blk_finish_plug(&plug);
  4636. memalloc_noreclaim_restore(flags);
  4637. set_task_reclaim_state(current, NULL);
  4638. kvfree(buf);
  4639. return err ? : len;
  4640. }
  4641. static int lru_gen_seq_open(struct inode *inode, struct file *file)
  4642. {
  4643. return seq_open(file, &lru_gen_seq_ops);
  4644. }
  4645. static const struct file_operations lru_gen_rw_fops = {
  4646. .open = lru_gen_seq_open,
  4647. .read = seq_read,
  4648. .write = lru_gen_seq_write,
  4649. .llseek = seq_lseek,
  4650. .release = seq_release,
  4651. };
  4652. static const struct file_operations lru_gen_ro_fops = {
  4653. .open = lru_gen_seq_open,
  4654. .read = seq_read,
  4655. .llseek = seq_lseek,
  4656. .release = seq_release,
  4657. };
  4658. /******************************************************************************
  4659. * initialization
  4660. ******************************************************************************/
  4661. void lru_gen_init_pgdat(struct pglist_data *pgdat)
  4662. {
  4663. int i, j;
  4664. spin_lock_init(&pgdat->memcg_lru.lock);
  4665. for (i = 0; i < MEMCG_NR_GENS; i++) {
  4666. for (j = 0; j < MEMCG_NR_BINS; j++)
  4667. INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
  4668. }
  4669. }
  4670. void lru_gen_init_lruvec(struct lruvec *lruvec)
  4671. {
  4672. int i;
  4673. int gen, type, zone;
  4674. struct lru_gen_folio *lrugen = &lruvec->lrugen;
  4675. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  4676. lrugen->max_seq = MIN_NR_GENS + 1;
  4677. lrugen->enabled = lru_gen_enabled();
  4678. for (i = 0; i <= MIN_NR_GENS + 1; i++)
  4679. lrugen->timestamps[i] = jiffies;
  4680. for_each_gen_type_zone(gen, type, zone)
  4681. INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
  4682. if (mm_state)
  4683. mm_state->seq = MIN_NR_GENS;
  4684. }
  4685. #ifdef CONFIG_MEMCG
  4686. void lru_gen_init_memcg(struct mem_cgroup *memcg)
  4687. {
  4688. struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
  4689. if (!mm_list)
  4690. return;
  4691. INIT_LIST_HEAD(&mm_list->fifo);
  4692. spin_lock_init(&mm_list->lock);
  4693. }
  4694. void lru_gen_exit_memcg(struct mem_cgroup *memcg)
  4695. {
  4696. int i;
  4697. int nid;
  4698. struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
  4699. VM_WARN_ON_ONCE(mm_list && !list_empty(&mm_list->fifo));
  4700. for_each_node(nid) {
  4701. struct lruvec *lruvec = get_lruvec(memcg, nid);
  4702. struct lru_gen_mm_state *mm_state = get_mm_state(lruvec);
  4703. VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
  4704. sizeof(lruvec->lrugen.nr_pages)));
  4705. lruvec->lrugen.list.next = LIST_POISON1;
  4706. if (!mm_state)
  4707. continue;
  4708. for (i = 0; i < NR_BLOOM_FILTERS; i++) {
  4709. bitmap_free(mm_state->filters[i]);
  4710. mm_state->filters[i] = NULL;
  4711. }
  4712. }
  4713. }
  4714. #endif /* CONFIG_MEMCG */
  4715. static int __init init_lru_gen(void)
  4716. {
  4717. BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
  4718. BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
  4719. if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
  4720. pr_err("lru_gen: failed to create sysfs group\n");
  4721. debugfs_create_file_aux_num("lru_gen", 0644, NULL, NULL, false,
  4722. &lru_gen_rw_fops);
  4723. debugfs_create_file_aux_num("lru_gen_full", 0444, NULL, NULL, true,
  4724. &lru_gen_ro_fops);
  4725. return 0;
  4726. };
  4727. late_initcall(init_lru_gen);
  4728. #else /* !CONFIG_LRU_GEN */
  4729. static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
  4730. {
  4731. BUILD_BUG();
  4732. }
  4733. static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
  4734. {
  4735. BUILD_BUG();
  4736. }
  4737. static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
  4738. {
  4739. BUILD_BUG();
  4740. }
  4741. #endif /* CONFIG_LRU_GEN */
  4742. static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
  4743. {
  4744. unsigned long nr[NR_LRU_LISTS];
  4745. unsigned long targets[NR_LRU_LISTS];
  4746. unsigned long nr_to_scan;
  4747. enum lru_list lru;
  4748. unsigned long nr_reclaimed = 0;
  4749. unsigned long nr_to_reclaim = sc->nr_to_reclaim;
  4750. bool proportional_reclaim;
  4751. struct blk_plug plug;
  4752. if (lru_gen_enabled() && !root_reclaim(sc)) {
  4753. lru_gen_shrink_lruvec(lruvec, sc);
  4754. return;
  4755. }
  4756. get_scan_count(lruvec, sc, nr);
  4757. /* Record the original scan target for proportional adjustments later */
  4758. memcpy(targets, nr, sizeof(nr));
  4759. /*
  4760. * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
  4761. * event that can occur when there is little memory pressure e.g.
  4762. * multiple streaming readers/writers. Hence, we do not abort scanning
  4763. * when the requested number of pages are reclaimed when scanning at
  4764. * DEF_PRIORITY on the assumption that the fact we are direct
  4765. * reclaiming implies that kswapd is not keeping up and it is best to
  4766. * do a batch of work at once. For memcg reclaim one check is made to
  4767. * abort proportional reclaim if either the file or anon lru has already
  4768. * dropped to zero at the first pass.
  4769. */
  4770. proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
  4771. sc->priority == DEF_PRIORITY);
  4772. blk_start_plug(&plug);
  4773. while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
  4774. nr[LRU_INACTIVE_FILE]) {
  4775. unsigned long nr_anon, nr_file, percentage;
  4776. unsigned long nr_scanned;
  4777. for_each_evictable_lru(lru) {
  4778. if (nr[lru]) {
  4779. nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
  4780. nr[lru] -= nr_to_scan;
  4781. nr_reclaimed += shrink_list(lru, nr_to_scan,
  4782. lruvec, sc);
  4783. }
  4784. }
  4785. cond_resched();
  4786. if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
  4787. continue;
  4788. /*
  4789. * For kswapd and memcg, reclaim at least the number of pages
  4790. * requested. Ensure that the anon and file LRUs are scanned
  4791. * proportionally what was requested by get_scan_count(). We
  4792. * stop reclaiming one LRU and reduce the amount scanning
  4793. * proportional to the original scan target.
  4794. */
  4795. nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
  4796. nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
  4797. /*
  4798. * It's just vindictive to attack the larger once the smaller
  4799. * has gone to zero. And given the way we stop scanning the
  4800. * smaller below, this makes sure that we only make one nudge
  4801. * towards proportionality once we've got nr_to_reclaim.
  4802. */
  4803. if (!nr_file || !nr_anon)
  4804. break;
  4805. if (nr_file > nr_anon) {
  4806. unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
  4807. targets[LRU_ACTIVE_ANON] + 1;
  4808. lru = LRU_BASE;
  4809. percentage = nr_anon * 100 / scan_target;
  4810. } else {
  4811. unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
  4812. targets[LRU_ACTIVE_FILE] + 1;
  4813. lru = LRU_FILE;
  4814. percentage = nr_file * 100 / scan_target;
  4815. }
  4816. /* Stop scanning the smaller of the LRU */
  4817. nr[lru] = 0;
  4818. nr[lru + LRU_ACTIVE] = 0;
  4819. /*
  4820. * Recalculate the other LRU scan count based on its original
  4821. * scan target and the percentage scanning already complete
  4822. */
  4823. lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
  4824. nr_scanned = targets[lru] - nr[lru];
  4825. nr[lru] = targets[lru] * (100 - percentage) / 100;
  4826. nr[lru] -= min(nr[lru], nr_scanned);
  4827. lru += LRU_ACTIVE;
  4828. nr_scanned = targets[lru] - nr[lru];
  4829. nr[lru] = targets[lru] * (100 - percentage) / 100;
  4830. nr[lru] -= min(nr[lru], nr_scanned);
  4831. }
  4832. blk_finish_plug(&plug);
  4833. sc->nr_reclaimed += nr_reclaimed;
  4834. /*
  4835. * Even if we did not try to evict anon pages at all, we want to
  4836. * rebalance the anon lru active/inactive ratio.
  4837. */
  4838. if (can_age_anon_pages(lruvec, sc) &&
  4839. inactive_is_low(lruvec, LRU_INACTIVE_ANON))
  4840. shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
  4841. sc, LRU_ACTIVE_ANON);
  4842. }
  4843. /* Use reclaim/compaction for costly allocs or under memory pressure */
  4844. static bool in_reclaim_compaction(struct scan_control *sc)
  4845. {
  4846. if (gfp_compaction_allowed(sc->gfp_mask) && sc->order &&
  4847. (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
  4848. sc->priority < DEF_PRIORITY - 2))
  4849. return true;
  4850. return false;
  4851. }
  4852. /*
  4853. * Reclaim/compaction is used for high-order allocation requests. It reclaims
  4854. * order-0 pages before compacting the zone. should_continue_reclaim() returns
  4855. * true if more pages should be reclaimed such that when the page allocator
  4856. * calls try_to_compact_pages() that it will have enough free pages to succeed.
  4857. * It will give up earlier than that if there is difficulty reclaiming pages.
  4858. */
  4859. static inline bool should_continue_reclaim(struct pglist_data *pgdat,
  4860. unsigned long nr_reclaimed,
  4861. struct scan_control *sc)
  4862. {
  4863. unsigned long pages_for_compaction;
  4864. unsigned long inactive_lru_pages;
  4865. int z;
  4866. struct zone *zone;
  4867. /* If not in reclaim/compaction mode, stop */
  4868. if (!in_reclaim_compaction(sc))
  4869. return false;
  4870. /*
  4871. * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
  4872. * number of pages that were scanned. This will return to the caller
  4873. * with the risk reclaim/compaction and the resulting allocation attempt
  4874. * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
  4875. * allocations through requiring that the full LRU list has been scanned
  4876. * first, by assuming that zero delta of sc->nr_scanned means full LRU
  4877. * scan, but that approximation was wrong, and there were corner cases
  4878. * where always a non-zero amount of pages were scanned.
  4879. */
  4880. if (!nr_reclaimed)
  4881. return false;
  4882. /* If compaction would go ahead or the allocation would succeed, stop */
  4883. for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) {
  4884. unsigned long watermark = min_wmark_pages(zone);
  4885. /* Allocation can already succeed, nothing to do */
  4886. if (zone_watermark_ok(zone, sc->order, watermark,
  4887. sc->reclaim_idx, 0))
  4888. return false;
  4889. if (compaction_suitable(zone, sc->order, watermark,
  4890. sc->reclaim_idx))
  4891. return false;
  4892. }
  4893. /*
  4894. * If we have not reclaimed enough pages for compaction and the
  4895. * inactive lists are large enough, continue reclaiming
  4896. */
  4897. pages_for_compaction = compact_gap(sc->order);
  4898. inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
  4899. if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
  4900. inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
  4901. return inactive_lru_pages > pages_for_compaction;
  4902. }
  4903. static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
  4904. {
  4905. struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
  4906. struct mem_cgroup_reclaim_cookie reclaim = {
  4907. .pgdat = pgdat,
  4908. };
  4909. struct mem_cgroup_reclaim_cookie *partial = &reclaim;
  4910. struct mem_cgroup *memcg;
  4911. /*
  4912. * In most cases, direct reclaimers can do partial walks
  4913. * through the cgroup tree, using an iterator state that
  4914. * persists across invocations. This strikes a balance between
  4915. * fairness and allocation latency.
  4916. *
  4917. * For kswapd, reliable forward progress is more important
  4918. * than a quick return to idle. Always do full walks.
  4919. */
  4920. if (current_is_kswapd() || sc->memcg_full_walk)
  4921. partial = NULL;
  4922. memcg = mem_cgroup_iter(target_memcg, NULL, partial);
  4923. do {
  4924. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  4925. unsigned long reclaimed;
  4926. unsigned long scanned;
  4927. /*
  4928. * This loop can become CPU-bound when target memcgs
  4929. * aren't eligible for reclaim - either because they
  4930. * don't have any reclaimable pages, or because their
  4931. * memory is explicitly protected. Avoid soft lockups.
  4932. */
  4933. cond_resched();
  4934. mem_cgroup_calculate_protection(target_memcg, memcg);
  4935. if (mem_cgroup_below_min(target_memcg, memcg)) {
  4936. /*
  4937. * Hard protection.
  4938. * If there is no reclaimable memory, OOM.
  4939. */
  4940. continue;
  4941. } else if (mem_cgroup_below_low(target_memcg, memcg)) {
  4942. /*
  4943. * Soft protection.
  4944. * Respect the protection only as long as
  4945. * there is an unprotected supply
  4946. * of reclaimable memory from other cgroups.
  4947. */
  4948. if (!sc->memcg_low_reclaim) {
  4949. sc->memcg_low_skipped = 1;
  4950. continue;
  4951. }
  4952. memcg_memory_event(memcg, MEMCG_LOW);
  4953. }
  4954. reclaimed = sc->nr_reclaimed;
  4955. scanned = sc->nr_scanned;
  4956. shrink_lruvec(lruvec, sc);
  4957. shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
  4958. sc->priority);
  4959. /* Record the group's reclaim efficiency */
  4960. if (!sc->proactive)
  4961. vmpressure(sc->gfp_mask, memcg, false,
  4962. sc->nr_scanned - scanned,
  4963. sc->nr_reclaimed - reclaimed);
  4964. /* If partial walks are allowed, bail once goal is reached */
  4965. if (partial && sc->nr_reclaimed >= sc->nr_to_reclaim) {
  4966. mem_cgroup_iter_break(target_memcg, memcg);
  4967. break;
  4968. }
  4969. } while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial)));
  4970. }
  4971. static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
  4972. {
  4973. unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
  4974. struct lruvec *target_lruvec;
  4975. bool reclaimable = false;
  4976. if (lru_gen_enabled() && root_reclaim(sc)) {
  4977. memset(&sc->nr, 0, sizeof(sc->nr));
  4978. lru_gen_shrink_node(pgdat, sc);
  4979. return;
  4980. }
  4981. target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
  4982. again:
  4983. memset(&sc->nr, 0, sizeof(sc->nr));
  4984. nr_reclaimed = sc->nr_reclaimed;
  4985. nr_scanned = sc->nr_scanned;
  4986. prepare_scan_control(pgdat, sc);
  4987. shrink_node_memcgs(pgdat, sc);
  4988. flush_reclaim_state(sc);
  4989. nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
  4990. /* Record the subtree's reclaim efficiency */
  4991. if (!sc->proactive)
  4992. vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
  4993. sc->nr_scanned - nr_scanned, nr_node_reclaimed);
  4994. if (nr_node_reclaimed)
  4995. reclaimable = true;
  4996. if (current_is_kswapd()) {
  4997. /*
  4998. * If reclaim is isolating dirty pages under writeback,
  4999. * it implies that the long-lived page allocation rate
  5000. * is exceeding the page laundering rate. Either the
  5001. * global limits are not being effective at throttling
  5002. * processes due to the page distribution throughout
  5003. * zones or there is heavy usage of a slow backing
  5004. * device. The only option is to throttle from reclaim
  5005. * context which is not ideal as there is no guarantee
  5006. * the dirtying process is throttled in the same way
  5007. * balance_dirty_pages() manages.
  5008. *
  5009. * Once a node is flagged PGDAT_WRITEBACK, kswapd will
  5010. * count the number of pages under pages flagged for
  5011. * immediate reclaim and stall if any are encountered
  5012. * in the nr_immediate check below.
  5013. */
  5014. if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
  5015. set_bit(PGDAT_WRITEBACK, &pgdat->flags);
  5016. /*
  5017. * If kswapd scans pages marked for immediate
  5018. * reclaim and under writeback (nr_immediate), it
  5019. * implies that pages are cycling through the LRU
  5020. * faster than they are written so forcibly stall
  5021. * until some pages complete writeback.
  5022. */
  5023. if (sc->nr.immediate)
  5024. reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
  5025. }
  5026. /*
  5027. * Tag a node/memcg as congested if all the dirty pages were marked
  5028. * for writeback and immediate reclaim (counted in nr.congested).
  5029. *
  5030. * Legacy memcg will stall in page writeback so avoid forcibly
  5031. * stalling in reclaim_throttle().
  5032. */
  5033. if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested) {
  5034. if (cgroup_reclaim(sc) && writeback_throttling_sane(sc))
  5035. set_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags);
  5036. if (current_is_kswapd())
  5037. set_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags);
  5038. }
  5039. /*
  5040. * Stall direct reclaim for IO completions if the lruvec is
  5041. * node is congested. Allow kswapd to continue until it
  5042. * starts encountering unqueued dirty pages or cycling through
  5043. * the LRU too quickly.
  5044. */
  5045. if (!current_is_kswapd() && current_may_throttle() &&
  5046. !sc->hibernation_mode &&
  5047. (test_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags) ||
  5048. test_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags)))
  5049. reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
  5050. if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
  5051. goto again;
  5052. /*
  5053. * Kswapd gives up on balancing particular nodes after too
  5054. * many failures to reclaim anything from them and goes to
  5055. * sleep. On reclaim progress, reset the failure counter. A
  5056. * successful direct reclaim run will revive a dormant kswapd.
  5057. */
  5058. if (reclaimable)
  5059. kswapd_try_clear_hopeless(pgdat, sc->order, sc->reclaim_idx);
  5060. else if (sc->cache_trim_mode)
  5061. sc->cache_trim_mode_failed = 1;
  5062. }
  5063. /*
  5064. * Returns true if compaction should go ahead for a costly-order request, or
  5065. * the allocation would already succeed without compaction. Return false if we
  5066. * should reclaim first.
  5067. */
  5068. static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
  5069. {
  5070. unsigned long watermark;
  5071. if (!gfp_compaction_allowed(sc->gfp_mask))
  5072. return false;
  5073. /* Allocation can already succeed, nothing to do */
  5074. if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone),
  5075. sc->reclaim_idx, 0))
  5076. return true;
  5077. /*
  5078. * Direct reclaim usually targets the min watermark, but compaction
  5079. * takes time to run and there are potentially other callers using the
  5080. * pages just freed. So target a higher buffer to give compaction a
  5081. * reasonable chance of completing and allocating the pages.
  5082. *
  5083. * Note that we won't actually reclaim the whole buffer in one attempt
  5084. * as the target watermark in should_continue_reclaim() is lower. But if
  5085. * we are already above the high+gap watermark, don't reclaim at all.
  5086. */
  5087. watermark = high_wmark_pages(zone);
  5088. if (compaction_suitable(zone, sc->order, watermark, sc->reclaim_idx))
  5089. return true;
  5090. return false;
  5091. }
  5092. static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
  5093. {
  5094. /*
  5095. * If reclaim is making progress greater than 12% efficiency then
  5096. * wake all the NOPROGRESS throttled tasks.
  5097. */
  5098. if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
  5099. wait_queue_head_t *wqh;
  5100. wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
  5101. if (waitqueue_active(wqh))
  5102. wake_up(wqh);
  5103. return;
  5104. }
  5105. /*
  5106. * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
  5107. * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
  5108. * under writeback and marked for immediate reclaim at the tail of the
  5109. * LRU.
  5110. */
  5111. if (current_is_kswapd() || cgroup_reclaim(sc))
  5112. return;
  5113. /* Throttle if making no progress at high prioities. */
  5114. if (sc->priority == 1 && !sc->nr_reclaimed)
  5115. reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
  5116. }
  5117. /*
  5118. * This is the direct reclaim path, for page-allocating processes. We only
  5119. * try to reclaim pages from zones which will satisfy the caller's allocation
  5120. * request.
  5121. *
  5122. * If a zone is deemed to be full of pinned pages then just give it a light
  5123. * scan then give up on it.
  5124. */
  5125. static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
  5126. {
  5127. struct zoneref *z;
  5128. struct zone *zone;
  5129. unsigned long nr_soft_reclaimed;
  5130. unsigned long nr_soft_scanned;
  5131. gfp_t orig_mask;
  5132. pg_data_t *last_pgdat = NULL;
  5133. pg_data_t *first_pgdat = NULL;
  5134. /*
  5135. * If the number of buffer_heads in the machine exceeds the maximum
  5136. * allowed level, force direct reclaim to scan the highmem zone as
  5137. * highmem pages could be pinning lowmem pages storing buffer_heads
  5138. */
  5139. orig_mask = sc->gfp_mask;
  5140. if (buffer_heads_over_limit) {
  5141. sc->gfp_mask |= __GFP_HIGHMEM;
  5142. sc->reclaim_idx = gfp_zone(sc->gfp_mask);
  5143. }
  5144. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  5145. sc->reclaim_idx, sc->nodemask) {
  5146. /*
  5147. * Take care memory controller reclaiming has small influence
  5148. * to global LRU.
  5149. */
  5150. if (!cgroup_reclaim(sc)) {
  5151. if (!cpuset_zone_allowed(zone,
  5152. GFP_KERNEL | __GFP_HARDWALL))
  5153. continue;
  5154. /*
  5155. * If we already have plenty of memory free for
  5156. * compaction in this zone, don't free any more.
  5157. * Even though compaction is invoked for any
  5158. * non-zero order, only frequent costly order
  5159. * reclamation is disruptive enough to become a
  5160. * noticeable problem, like transparent huge
  5161. * page allocations.
  5162. */
  5163. if (IS_ENABLED(CONFIG_COMPACTION) &&
  5164. sc->order > PAGE_ALLOC_COSTLY_ORDER &&
  5165. compaction_ready(zone, sc)) {
  5166. sc->compaction_ready = true;
  5167. continue;
  5168. }
  5169. /*
  5170. * Shrink each node in the zonelist once. If the
  5171. * zonelist is ordered by zone (not the default) then a
  5172. * node may be shrunk multiple times but in that case
  5173. * the user prefers lower zones being preserved.
  5174. */
  5175. if (zone->zone_pgdat == last_pgdat)
  5176. continue;
  5177. /*
  5178. * This steals pages from memory cgroups over softlimit
  5179. * and returns the number of reclaimed pages and
  5180. * scanned pages. This works for global memory pressure
  5181. * and balancing, not for a memcg's limit.
  5182. */
  5183. nr_soft_scanned = 0;
  5184. nr_soft_reclaimed = memcg1_soft_limit_reclaim(zone->zone_pgdat,
  5185. sc->order, sc->gfp_mask,
  5186. &nr_soft_scanned);
  5187. sc->nr_reclaimed += nr_soft_reclaimed;
  5188. sc->nr_scanned += nr_soft_scanned;
  5189. /* need some check for avoid more shrink_zone() */
  5190. }
  5191. if (!first_pgdat)
  5192. first_pgdat = zone->zone_pgdat;
  5193. /* See comment about same check for global reclaim above */
  5194. if (zone->zone_pgdat == last_pgdat)
  5195. continue;
  5196. last_pgdat = zone->zone_pgdat;
  5197. shrink_node(zone->zone_pgdat, sc);
  5198. }
  5199. if (first_pgdat)
  5200. consider_reclaim_throttle(first_pgdat, sc);
  5201. /*
  5202. * Restore to original mask to avoid the impact on the caller if we
  5203. * promoted it to __GFP_HIGHMEM.
  5204. */
  5205. sc->gfp_mask = orig_mask;
  5206. }
  5207. static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
  5208. {
  5209. struct lruvec *target_lruvec;
  5210. unsigned long refaults;
  5211. if (lru_gen_enabled())
  5212. return;
  5213. target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
  5214. refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
  5215. target_lruvec->refaults[WORKINGSET_ANON] = refaults;
  5216. refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
  5217. target_lruvec->refaults[WORKINGSET_FILE] = refaults;
  5218. }
  5219. /*
  5220. * This is the main entry point to direct page reclaim.
  5221. *
  5222. * If a full scan of the inactive list fails to free enough memory then we
  5223. * are "out of memory" and something needs to be killed.
  5224. *
  5225. * If the caller is !__GFP_FS then the probability of a failure is reasonably
  5226. * high - the zone may be full of dirty or under-writeback pages, which this
  5227. * caller can't do much about. We kick the writeback threads and take explicit
  5228. * naps in the hope that some of these pages can be written. But if the
  5229. * allocating task holds filesystem locks which prevent writeout this might not
  5230. * work, and the allocation attempt will fail.
  5231. *
  5232. * returns: 0, if no pages reclaimed
  5233. * else, the number of pages reclaimed
  5234. */
  5235. static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
  5236. struct scan_control *sc)
  5237. {
  5238. int initial_priority = sc->priority;
  5239. pg_data_t *last_pgdat;
  5240. struct zoneref *z;
  5241. struct zone *zone;
  5242. retry:
  5243. delayacct_freepages_start();
  5244. if (!cgroup_reclaim(sc))
  5245. __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
  5246. do {
  5247. if (!sc->proactive)
  5248. vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
  5249. sc->priority);
  5250. sc->nr_scanned = 0;
  5251. shrink_zones(zonelist, sc);
  5252. if (sc->nr_reclaimed >= sc->nr_to_reclaim)
  5253. break;
  5254. if (sc->compaction_ready)
  5255. break;
  5256. } while (--sc->priority >= 0);
  5257. last_pgdat = NULL;
  5258. for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
  5259. sc->nodemask) {
  5260. if (zone->zone_pgdat == last_pgdat)
  5261. continue;
  5262. last_pgdat = zone->zone_pgdat;
  5263. snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
  5264. if (cgroup_reclaim(sc)) {
  5265. struct lruvec *lruvec;
  5266. lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
  5267. zone->zone_pgdat);
  5268. clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
  5269. }
  5270. }
  5271. delayacct_freepages_end();
  5272. if (sc->nr_reclaimed)
  5273. return sc->nr_reclaimed;
  5274. /* Aborted reclaim to try compaction? don't OOM, then */
  5275. if (sc->compaction_ready)
  5276. return 1;
  5277. /*
  5278. * In most cases, direct reclaimers can do partial walks
  5279. * through the cgroup tree to meet the reclaim goal while
  5280. * keeping latency low. Since the iterator state is shared
  5281. * among all direct reclaim invocations (to retain fairness
  5282. * among cgroups), though, high concurrency can result in
  5283. * individual threads not seeing enough cgroups to make
  5284. * meaningful forward progress. Avoid false OOMs in this case.
  5285. */
  5286. if (!sc->memcg_full_walk) {
  5287. sc->priority = initial_priority;
  5288. sc->memcg_full_walk = 1;
  5289. goto retry;
  5290. }
  5291. /*
  5292. * We make inactive:active ratio decisions based on the node's
  5293. * composition of memory, but a restrictive reclaim_idx or a
  5294. * memory.low cgroup setting can exempt large amounts of
  5295. * memory from reclaim. Neither of which are very common, so
  5296. * instead of doing costly eligibility calculations of the
  5297. * entire cgroup subtree up front, we assume the estimates are
  5298. * good, and retry with forcible deactivation if that fails.
  5299. */
  5300. if (sc->skipped_deactivate) {
  5301. sc->priority = initial_priority;
  5302. sc->force_deactivate = 1;
  5303. sc->skipped_deactivate = 0;
  5304. goto retry;
  5305. }
  5306. /* Untapped cgroup reserves? Don't OOM, retry. */
  5307. if (sc->memcg_low_skipped) {
  5308. sc->priority = initial_priority;
  5309. sc->force_deactivate = 0;
  5310. sc->memcg_low_reclaim = 1;
  5311. sc->memcg_low_skipped = 0;
  5312. goto retry;
  5313. }
  5314. return 0;
  5315. }
  5316. static bool allow_direct_reclaim(pg_data_t *pgdat)
  5317. {
  5318. struct zone *zone;
  5319. unsigned long pfmemalloc_reserve = 0;
  5320. unsigned long free_pages = 0;
  5321. int i;
  5322. bool wmark_ok;
  5323. if (kswapd_test_hopeless(pgdat))
  5324. return true;
  5325. for_each_managed_zone_pgdat(zone, pgdat, i, ZONE_NORMAL) {
  5326. if (!zone_reclaimable_pages(zone) && zone_page_state_snapshot(zone, NR_FREE_PAGES))
  5327. continue;
  5328. pfmemalloc_reserve += min_wmark_pages(zone);
  5329. free_pages += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  5330. }
  5331. /* If there are no reserves (unexpected config) then do not throttle */
  5332. if (!pfmemalloc_reserve)
  5333. return true;
  5334. wmark_ok = free_pages > pfmemalloc_reserve / 2;
  5335. /* kswapd must be awake if processes are being throttled */
  5336. if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
  5337. if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
  5338. WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
  5339. wake_up_interruptible(&pgdat->kswapd_wait);
  5340. }
  5341. return wmark_ok;
  5342. }
  5343. /*
  5344. * Throttle direct reclaimers if backing storage is backed by the network
  5345. * and the PFMEMALLOC reserve for the preferred node is getting dangerously
  5346. * depleted. kswapd will continue to make progress and wake the processes
  5347. * when the low watermark is reached.
  5348. *
  5349. * Returns true if a fatal signal was delivered during throttling. If this
  5350. * happens, the page allocator should not consider triggering the OOM killer.
  5351. */
  5352. static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
  5353. nodemask_t *nodemask)
  5354. {
  5355. struct zoneref *z;
  5356. struct zone *zone;
  5357. pg_data_t *pgdat = NULL;
  5358. /*
  5359. * Kernel threads should not be throttled as they may be indirectly
  5360. * responsible for cleaning pages necessary for reclaim to make forward
  5361. * progress. kjournald for example may enter direct reclaim while
  5362. * committing a transaction where throttling it could forcing other
  5363. * processes to block on log_wait_commit().
  5364. */
  5365. if (current->flags & PF_KTHREAD)
  5366. goto out;
  5367. /*
  5368. * If a fatal signal is pending, this process should not throttle.
  5369. * It should return quickly so it can exit and free its memory
  5370. */
  5371. if (fatal_signal_pending(current))
  5372. goto out;
  5373. /*
  5374. * Check if the pfmemalloc reserves are ok by finding the first node
  5375. * with a usable ZONE_NORMAL or lower zone. The expectation is that
  5376. * GFP_KERNEL will be required for allocating network buffers when
  5377. * swapping over the network so ZONE_HIGHMEM is unusable.
  5378. *
  5379. * Throttling is based on the first usable node and throttled processes
  5380. * wait on a queue until kswapd makes progress and wakes them. There
  5381. * is an affinity then between processes waking up and where reclaim
  5382. * progress has been made assuming the process wakes on the same node.
  5383. * More importantly, processes running on remote nodes will not compete
  5384. * for remote pfmemalloc reserves and processes on different nodes
  5385. * should make reasonable progress.
  5386. */
  5387. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  5388. gfp_zone(gfp_mask), nodemask) {
  5389. if (zone_idx(zone) > ZONE_NORMAL)
  5390. continue;
  5391. /* Throttle based on the first usable node */
  5392. pgdat = zone->zone_pgdat;
  5393. if (allow_direct_reclaim(pgdat))
  5394. goto out;
  5395. break;
  5396. }
  5397. /* If no zone was usable by the allocation flags then do not throttle */
  5398. if (!pgdat)
  5399. goto out;
  5400. /* Account for the throttling */
  5401. count_vm_event(PGSCAN_DIRECT_THROTTLE);
  5402. /*
  5403. * If the caller cannot enter the filesystem, it's possible that it
  5404. * is due to the caller holding an FS lock or performing a journal
  5405. * transaction in the case of a filesystem like ext[3|4]. In this case,
  5406. * it is not safe to block on pfmemalloc_wait as kswapd could be
  5407. * blocked waiting on the same lock. Instead, throttle for up to a
  5408. * second before continuing.
  5409. */
  5410. if (!(gfp_mask & __GFP_FS))
  5411. wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
  5412. allow_direct_reclaim(pgdat), HZ);
  5413. else
  5414. /* Throttle until kswapd wakes the process */
  5415. wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
  5416. allow_direct_reclaim(pgdat));
  5417. if (fatal_signal_pending(current))
  5418. return true;
  5419. out:
  5420. return false;
  5421. }
  5422. unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
  5423. gfp_t gfp_mask, nodemask_t *nodemask)
  5424. {
  5425. unsigned long nr_reclaimed;
  5426. struct scan_control sc = {
  5427. .nr_to_reclaim = SWAP_CLUSTER_MAX,
  5428. .gfp_mask = current_gfp_context(gfp_mask),
  5429. .reclaim_idx = gfp_zone(gfp_mask),
  5430. .order = order,
  5431. .nodemask = nodemask,
  5432. .priority = DEF_PRIORITY,
  5433. .may_writepage = 1,
  5434. .may_unmap = 1,
  5435. .may_swap = 1,
  5436. };
  5437. /*
  5438. * scan_control uses s8 fields for order, priority, and reclaim_idx.
  5439. * Confirm they are large enough for max values.
  5440. */
  5441. BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX);
  5442. BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
  5443. BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
  5444. /*
  5445. * Do not enter reclaim if fatal signal was delivered while throttled.
  5446. * 1 is returned so that the page allocator does not OOM kill at this
  5447. * point.
  5448. */
  5449. if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
  5450. return 1;
  5451. set_task_reclaim_state(current, &sc.reclaim_state);
  5452. trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
  5453. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  5454. trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
  5455. set_task_reclaim_state(current, NULL);
  5456. return nr_reclaimed;
  5457. }
  5458. #ifdef CONFIG_MEMCG
  5459. /* Only used by soft limit reclaim. Do not reuse for anything else. */
  5460. unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
  5461. gfp_t gfp_mask, bool noswap,
  5462. pg_data_t *pgdat,
  5463. unsigned long *nr_scanned)
  5464. {
  5465. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
  5466. struct scan_control sc = {
  5467. .nr_to_reclaim = SWAP_CLUSTER_MAX,
  5468. .target_mem_cgroup = memcg,
  5469. .may_writepage = 1,
  5470. .may_unmap = 1,
  5471. .reclaim_idx = MAX_NR_ZONES - 1,
  5472. .may_swap = !noswap,
  5473. };
  5474. WARN_ON_ONCE(!current->reclaim_state);
  5475. sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
  5476. (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
  5477. trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
  5478. sc.gfp_mask);
  5479. /*
  5480. * NOTE: Although we can get the priority field, using it
  5481. * here is not a good idea, since it limits the pages we can scan.
  5482. * if we don't reclaim here, the shrink_node from balance_pgdat
  5483. * will pick up pages from other mem cgroup's as well. We hack
  5484. * the priority and make it zero.
  5485. */
  5486. shrink_lruvec(lruvec, &sc);
  5487. trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
  5488. *nr_scanned = sc.nr_scanned;
  5489. return sc.nr_reclaimed;
  5490. }
  5491. unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
  5492. unsigned long nr_pages,
  5493. gfp_t gfp_mask,
  5494. unsigned int reclaim_options,
  5495. int *swappiness)
  5496. {
  5497. unsigned long nr_reclaimed;
  5498. unsigned int noreclaim_flag;
  5499. struct scan_control sc = {
  5500. .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
  5501. .proactive_swappiness = swappiness,
  5502. .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
  5503. (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
  5504. .reclaim_idx = MAX_NR_ZONES - 1,
  5505. .target_mem_cgroup = memcg,
  5506. .priority = DEF_PRIORITY,
  5507. .may_writepage = 1,
  5508. .may_unmap = 1,
  5509. .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
  5510. .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
  5511. };
  5512. /*
  5513. * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
  5514. * equal pressure on all the nodes. This is based on the assumption that
  5515. * the reclaim does not bail out early.
  5516. */
  5517. struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
  5518. set_task_reclaim_state(current, &sc.reclaim_state);
  5519. trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
  5520. noreclaim_flag = memalloc_noreclaim_save();
  5521. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  5522. memalloc_noreclaim_restore(noreclaim_flag);
  5523. trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
  5524. set_task_reclaim_state(current, NULL);
  5525. return nr_reclaimed;
  5526. }
  5527. #else
  5528. unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
  5529. unsigned long nr_pages,
  5530. gfp_t gfp_mask,
  5531. unsigned int reclaim_options,
  5532. int *swappiness)
  5533. {
  5534. return 0;
  5535. }
  5536. #endif
  5537. static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
  5538. {
  5539. struct mem_cgroup *memcg;
  5540. struct lruvec *lruvec;
  5541. if (lru_gen_enabled()) {
  5542. lru_gen_age_node(pgdat, sc);
  5543. return;
  5544. }
  5545. lruvec = mem_cgroup_lruvec(NULL, pgdat);
  5546. if (!can_age_anon_pages(lruvec, sc))
  5547. return;
  5548. if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
  5549. return;
  5550. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  5551. do {
  5552. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  5553. shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
  5554. sc, LRU_ACTIVE_ANON);
  5555. memcg = mem_cgroup_iter(NULL, memcg, NULL);
  5556. } while (memcg);
  5557. }
  5558. static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
  5559. {
  5560. int i;
  5561. struct zone *zone;
  5562. /*
  5563. * Check for watermark boosts top-down as the higher zones
  5564. * are more likely to be boosted. Both watermarks and boosts
  5565. * should not be checked at the same time as reclaim would
  5566. * start prematurely when there is no boosting and a lower
  5567. * zone is balanced.
  5568. */
  5569. for (i = highest_zoneidx; i >= 0; i--) {
  5570. zone = pgdat->node_zones + i;
  5571. if (!managed_zone(zone))
  5572. continue;
  5573. if (zone->watermark_boost)
  5574. return true;
  5575. }
  5576. return false;
  5577. }
  5578. /*
  5579. * Returns true if there is an eligible zone balanced for the request order
  5580. * and highest_zoneidx
  5581. */
  5582. static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
  5583. {
  5584. int i;
  5585. unsigned long mark = -1;
  5586. struct zone *zone;
  5587. /*
  5588. * Check watermarks bottom-up as lower zones are more likely to
  5589. * meet watermarks.
  5590. */
  5591. for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) {
  5592. enum zone_stat_item item;
  5593. unsigned long free_pages;
  5594. if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
  5595. mark = promo_wmark_pages(zone);
  5596. else
  5597. mark = high_wmark_pages(zone);
  5598. /*
  5599. * In defrag_mode, watermarks must be met in whole
  5600. * blocks to avoid polluting allocator fallbacks.
  5601. *
  5602. * However, kswapd usually cannot accomplish this on
  5603. * its own and needs kcompactd support. Once it's
  5604. * reclaimed a compaction gap, and kswapd_shrink_node
  5605. * has dropped order, simply ensure there are enough
  5606. * base pages for compaction, wake kcompactd & sleep.
  5607. */
  5608. if (defrag_mode && order)
  5609. item = NR_FREE_PAGES_BLOCKS;
  5610. else
  5611. item = NR_FREE_PAGES;
  5612. /*
  5613. * When there is a high number of CPUs in the system,
  5614. * the cumulative error from the vmstat per-cpu cache
  5615. * can blur the line between the watermarks. In that
  5616. * case, be safe and get an accurate snapshot.
  5617. *
  5618. * TODO: NR_FREE_PAGES_BLOCKS moves in steps of
  5619. * pageblock_nr_pages, while the vmstat pcp threshold
  5620. * is limited to 125. On many configurations that
  5621. * counter won't actually be per-cpu cached. But keep
  5622. * things simple for now; revisit when somebody cares.
  5623. */
  5624. free_pages = zone_page_state(zone, item);
  5625. if (zone->percpu_drift_mark && free_pages < zone->percpu_drift_mark)
  5626. free_pages = zone_page_state_snapshot(zone, item);
  5627. if (__zone_watermark_ok(zone, order, mark, highest_zoneidx,
  5628. 0, free_pages))
  5629. return true;
  5630. }
  5631. /*
  5632. * If a node has no managed zone within highest_zoneidx, it does not
  5633. * need balancing by definition. This can happen if a zone-restricted
  5634. * allocation tries to wake a remote kswapd.
  5635. */
  5636. if (mark == -1)
  5637. return true;
  5638. return false;
  5639. }
  5640. /* Clear pgdat state for congested, dirty or under writeback. */
  5641. static void clear_pgdat_congested(pg_data_t *pgdat)
  5642. {
  5643. struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
  5644. clear_bit(LRUVEC_NODE_CONGESTED, &lruvec->flags);
  5645. clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags);
  5646. clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
  5647. }
  5648. /*
  5649. * Prepare kswapd for sleeping. This verifies that there are no processes
  5650. * waiting in throttle_direct_reclaim() and that watermarks have been met.
  5651. *
  5652. * Returns true if kswapd is ready to sleep
  5653. */
  5654. static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
  5655. int highest_zoneidx)
  5656. {
  5657. /*
  5658. * The throttled processes are normally woken up in balance_pgdat() as
  5659. * soon as allow_direct_reclaim() is true. But there is a potential
  5660. * race between when kswapd checks the watermarks and a process gets
  5661. * throttled. There is also a potential race if processes get
  5662. * throttled, kswapd wakes, a large process exits thereby balancing the
  5663. * zones, which causes kswapd to exit balance_pgdat() before reaching
  5664. * the wake up checks. If kswapd is going to sleep, no process should
  5665. * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
  5666. * the wake up is premature, processes will wake kswapd and get
  5667. * throttled again. The difference from wake ups in balance_pgdat() is
  5668. * that here we are under prepare_to_wait().
  5669. */
  5670. if (waitqueue_active(&pgdat->pfmemalloc_wait))
  5671. wake_up_all(&pgdat->pfmemalloc_wait);
  5672. /* Hopeless node, leave it to direct reclaim */
  5673. if (kswapd_test_hopeless(pgdat))
  5674. return true;
  5675. if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
  5676. clear_pgdat_congested(pgdat);
  5677. return true;
  5678. }
  5679. return false;
  5680. }
  5681. /*
  5682. * kswapd shrinks a node of pages that are at or below the highest usable
  5683. * zone that is currently unbalanced.
  5684. *
  5685. * Returns true if kswapd scanned at least the requested number of pages to
  5686. * reclaim or if the lack of progress was due to pages under writeback.
  5687. * This is used to determine if the scanning priority needs to be raised.
  5688. */
  5689. static bool kswapd_shrink_node(pg_data_t *pgdat,
  5690. struct scan_control *sc)
  5691. {
  5692. struct zone *zone;
  5693. int z;
  5694. unsigned long nr_reclaimed = sc->nr_reclaimed;
  5695. /* Reclaim a number of pages proportional to the number of zones */
  5696. sc->nr_to_reclaim = 0;
  5697. for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) {
  5698. sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
  5699. }
  5700. /*
  5701. * Historically care was taken to put equal pressure on all zones but
  5702. * now pressure is applied based on node LRU order.
  5703. */
  5704. shrink_node(pgdat, sc);
  5705. /*
  5706. * Fragmentation may mean that the system cannot be rebalanced for
  5707. * high-order allocations. If twice the allocation size has been
  5708. * reclaimed then recheck watermarks only at order-0 to prevent
  5709. * excessive reclaim. Assume that a process requested a high-order
  5710. * can direct reclaim/compact.
  5711. */
  5712. if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
  5713. sc->order = 0;
  5714. /* account for progress from mm_account_reclaimed_pages() */
  5715. return max(sc->nr_scanned, sc->nr_reclaimed - nr_reclaimed) >= sc->nr_to_reclaim;
  5716. }
  5717. /* Page allocator PCP high watermark is lowered if reclaim is active. */
  5718. static inline void
  5719. update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
  5720. {
  5721. int i;
  5722. struct zone *zone;
  5723. for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) {
  5724. if (active)
  5725. set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
  5726. else
  5727. clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
  5728. }
  5729. }
  5730. static inline void
  5731. set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
  5732. {
  5733. update_reclaim_active(pgdat, highest_zoneidx, true);
  5734. }
  5735. static inline void
  5736. clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
  5737. {
  5738. update_reclaim_active(pgdat, highest_zoneidx, false);
  5739. }
  5740. /*
  5741. * For kswapd, balance_pgdat() will reclaim pages across a node from zones
  5742. * that are eligible for use by the caller until at least one zone is
  5743. * balanced.
  5744. *
  5745. * Returns the order kswapd finished reclaiming at.
  5746. *
  5747. * kswapd scans the zones in the highmem->normal->dma direction. It skips
  5748. * zones which have free_pages > high_wmark_pages(zone), but once a zone is
  5749. * found to have free_pages <= high_wmark_pages(zone), any page in that zone
  5750. * or lower is eligible for reclaim until at least one usable zone is
  5751. * balanced.
  5752. */
  5753. static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
  5754. {
  5755. int i;
  5756. unsigned long nr_soft_reclaimed;
  5757. unsigned long nr_soft_scanned;
  5758. unsigned long pflags;
  5759. unsigned long nr_boost_reclaim;
  5760. unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
  5761. bool boosted;
  5762. struct zone *zone;
  5763. struct scan_control sc = {
  5764. .gfp_mask = GFP_KERNEL,
  5765. .order = order,
  5766. .may_unmap = 1,
  5767. };
  5768. set_task_reclaim_state(current, &sc.reclaim_state);
  5769. psi_memstall_enter(&pflags);
  5770. __fs_reclaim_acquire(_THIS_IP_);
  5771. count_vm_event(PAGEOUTRUN);
  5772. /*
  5773. * Account for the reclaim boost. Note that the zone boost is left in
  5774. * place so that parallel allocations that are near the watermark will
  5775. * stall or direct reclaim until kswapd is finished.
  5776. */
  5777. nr_boost_reclaim = 0;
  5778. for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) {
  5779. nr_boost_reclaim += zone->watermark_boost;
  5780. zone_boosts[i] = zone->watermark_boost;
  5781. }
  5782. boosted = nr_boost_reclaim;
  5783. restart:
  5784. set_reclaim_active(pgdat, highest_zoneidx);
  5785. sc.priority = DEF_PRIORITY;
  5786. do {
  5787. unsigned long nr_reclaimed = sc.nr_reclaimed;
  5788. bool raise_priority = true;
  5789. bool balanced;
  5790. bool ret;
  5791. bool was_frozen;
  5792. sc.reclaim_idx = highest_zoneidx;
  5793. /*
  5794. * If the number of buffer_heads exceeds the maximum allowed
  5795. * then consider reclaiming from all zones. This has a dual
  5796. * purpose -- on 64-bit systems it is expected that
  5797. * buffer_heads are stripped during active rotation. On 32-bit
  5798. * systems, highmem pages can pin lowmem memory and shrinking
  5799. * buffers can relieve lowmem pressure. Reclaim may still not
  5800. * go ahead if all eligible zones for the original allocation
  5801. * request are balanced to avoid excessive reclaim from kswapd.
  5802. */
  5803. if (buffer_heads_over_limit) {
  5804. for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
  5805. zone = pgdat->node_zones + i;
  5806. if (!managed_zone(zone))
  5807. continue;
  5808. sc.reclaim_idx = i;
  5809. break;
  5810. }
  5811. }
  5812. /*
  5813. * If the pgdat is imbalanced then ignore boosting and preserve
  5814. * the watermarks for a later time and restart. Note that the
  5815. * zone watermarks will be still reset at the end of balancing
  5816. * on the grounds that the normal reclaim should be enough to
  5817. * re-evaluate if boosting is required when kswapd next wakes.
  5818. */
  5819. balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
  5820. if (!balanced && nr_boost_reclaim) {
  5821. nr_boost_reclaim = 0;
  5822. goto restart;
  5823. }
  5824. /*
  5825. * If boosting is not active then only reclaim if there are no
  5826. * eligible zones. Note that sc.reclaim_idx is not used as
  5827. * buffer_heads_over_limit may have adjusted it.
  5828. */
  5829. if (!nr_boost_reclaim && balanced)
  5830. goto out;
  5831. /* Limit the priority of boosting to avoid reclaim writeback */
  5832. if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
  5833. raise_priority = false;
  5834. /*
  5835. * Do not writeback or swap pages for boosted reclaim. The
  5836. * intent is to relieve pressure not issue sub-optimal IO
  5837. * from reclaim context. If no pages are reclaimed, the
  5838. * reclaim will be aborted.
  5839. */
  5840. sc.may_writepage = !nr_boost_reclaim;
  5841. sc.may_swap = !nr_boost_reclaim;
  5842. /*
  5843. * Do some background aging, to give pages a chance to be
  5844. * referenced before reclaiming. All pages are rotated
  5845. * regardless of classzone as this is about consistent aging.
  5846. */
  5847. kswapd_age_node(pgdat, &sc);
  5848. /* Call soft limit reclaim before calling shrink_node. */
  5849. sc.nr_scanned = 0;
  5850. nr_soft_scanned = 0;
  5851. nr_soft_reclaimed = memcg1_soft_limit_reclaim(pgdat, sc.order,
  5852. sc.gfp_mask, &nr_soft_scanned);
  5853. sc.nr_reclaimed += nr_soft_reclaimed;
  5854. /*
  5855. * There should be no need to raise the scanning priority if
  5856. * enough pages are already being scanned that that high
  5857. * watermark would be met at 100% efficiency.
  5858. */
  5859. if (kswapd_shrink_node(pgdat, &sc))
  5860. raise_priority = false;
  5861. /*
  5862. * If the low watermark is met there is no need for processes
  5863. * to be throttled on pfmemalloc_wait as they should not be
  5864. * able to safely make forward progress. Wake them
  5865. */
  5866. if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
  5867. allow_direct_reclaim(pgdat))
  5868. wake_up_all(&pgdat->pfmemalloc_wait);
  5869. /* Check if kswapd should be suspending */
  5870. __fs_reclaim_release(_THIS_IP_);
  5871. ret = kthread_freezable_should_stop(&was_frozen);
  5872. __fs_reclaim_acquire(_THIS_IP_);
  5873. if (was_frozen || ret)
  5874. break;
  5875. /*
  5876. * Raise priority if scanning rate is too low or there was no
  5877. * progress in reclaiming pages
  5878. */
  5879. nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
  5880. nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
  5881. /*
  5882. * If reclaim made no progress for a boost, stop reclaim as
  5883. * IO cannot be queued and it could be an infinite loop in
  5884. * extreme circumstances.
  5885. */
  5886. if (nr_boost_reclaim && !nr_reclaimed)
  5887. break;
  5888. if (raise_priority || !nr_reclaimed)
  5889. sc.priority--;
  5890. } while (sc.priority >= 1);
  5891. /*
  5892. * Restart only if it went through the priority loop all the way,
  5893. * but cache_trim_mode didn't work.
  5894. */
  5895. if (!sc.nr_reclaimed && sc.priority < 1 &&
  5896. !sc.no_cache_trim_mode && sc.cache_trim_mode_failed) {
  5897. sc.no_cache_trim_mode = 1;
  5898. goto restart;
  5899. }
  5900. /*
  5901. * If the reclaim was boosted, we might still be far from the
  5902. * watermark_high at this point. We need to avoid increasing the
  5903. * failure count to prevent the kswapd thread from stopping.
  5904. */
  5905. if (!sc.nr_reclaimed && !boosted) {
  5906. int fail_cnt = atomic_inc_return(&pgdat->kswapd_failures);
  5907. /* kswapd context, low overhead to trace every failure */
  5908. trace_mm_vmscan_kswapd_reclaim_fail(pgdat->node_id, fail_cnt);
  5909. }
  5910. out:
  5911. clear_reclaim_active(pgdat, highest_zoneidx);
  5912. /* If reclaim was boosted, account for the reclaim done in this pass */
  5913. if (boosted) {
  5914. unsigned long flags;
  5915. for (i = 0; i <= highest_zoneidx; i++) {
  5916. if (!zone_boosts[i])
  5917. continue;
  5918. /* Increments are under the zone lock */
  5919. zone = pgdat->node_zones + i;
  5920. spin_lock_irqsave(&zone->lock, flags);
  5921. zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
  5922. spin_unlock_irqrestore(&zone->lock, flags);
  5923. }
  5924. /*
  5925. * As there is now likely space, wakeup kcompact to defragment
  5926. * pageblocks.
  5927. */
  5928. wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
  5929. }
  5930. snapshot_refaults(NULL, pgdat);
  5931. __fs_reclaim_release(_THIS_IP_);
  5932. psi_memstall_leave(&pflags);
  5933. set_task_reclaim_state(current, NULL);
  5934. /*
  5935. * Return the order kswapd stopped reclaiming at as
  5936. * prepare_kswapd_sleep() takes it into account. If another caller
  5937. * entered the allocator slow path while kswapd was awake, order will
  5938. * remain at the higher level.
  5939. */
  5940. return sc.order;
  5941. }
  5942. /*
  5943. * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
  5944. * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
  5945. * not a valid index then either kswapd runs for first time or kswapd couldn't
  5946. * sleep after previous reclaim attempt (node is still unbalanced). In that
  5947. * case return the zone index of the previous kswapd reclaim cycle.
  5948. */
  5949. static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
  5950. enum zone_type prev_highest_zoneidx)
  5951. {
  5952. enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
  5953. return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
  5954. }
  5955. static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
  5956. unsigned int highest_zoneidx)
  5957. {
  5958. long remaining = 0;
  5959. DEFINE_WAIT(wait);
  5960. if (freezing(current) || kthread_should_stop())
  5961. return;
  5962. prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
  5963. /*
  5964. * Try to sleep for a short interval. Note that kcompactd will only be
  5965. * woken if it is possible to sleep for a short interval. This is
  5966. * deliberate on the assumption that if reclaim cannot keep an
  5967. * eligible zone balanced that it's also unlikely that compaction will
  5968. * succeed.
  5969. */
  5970. if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
  5971. /*
  5972. * Compaction records what page blocks it recently failed to
  5973. * isolate pages from and skips them in the future scanning.
  5974. * When kswapd is going to sleep, it is reasonable to assume
  5975. * that pages and compaction may succeed so reset the cache.
  5976. */
  5977. reset_isolation_suitable(pgdat);
  5978. /*
  5979. * We have freed the memory, now we should compact it to make
  5980. * allocation of the requested order possible.
  5981. */
  5982. wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
  5983. remaining = schedule_timeout(HZ/10);
  5984. /*
  5985. * If woken prematurely then reset kswapd_highest_zoneidx and
  5986. * order. The values will either be from a wakeup request or
  5987. * the previous request that slept prematurely.
  5988. */
  5989. if (remaining) {
  5990. WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
  5991. kswapd_highest_zoneidx(pgdat,
  5992. highest_zoneidx));
  5993. if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
  5994. WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
  5995. }
  5996. finish_wait(&pgdat->kswapd_wait, &wait);
  5997. prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
  5998. }
  5999. /*
  6000. * After a short sleep, check if it was a premature sleep. If not, then
  6001. * go fully to sleep until explicitly woken up.
  6002. */
  6003. if (!remaining &&
  6004. prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
  6005. trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
  6006. /*
  6007. * vmstat counters are not perfectly accurate and the estimated
  6008. * value for counters such as NR_FREE_PAGES can deviate from the
  6009. * true value by nr_online_cpus * threshold. To avoid the zone
  6010. * watermarks being breached while under pressure, we reduce the
  6011. * per-cpu vmstat threshold while kswapd is awake and restore
  6012. * them before going back to sleep.
  6013. */
  6014. set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
  6015. if (!kthread_should_stop())
  6016. schedule();
  6017. set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
  6018. } else {
  6019. if (remaining)
  6020. count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
  6021. else
  6022. count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
  6023. }
  6024. finish_wait(&pgdat->kswapd_wait, &wait);
  6025. }
  6026. /*
  6027. * The background pageout daemon, started as a kernel thread
  6028. * from the init process.
  6029. *
  6030. * This basically trickles out pages so that we have _some_
  6031. * free memory available even if there is no other activity
  6032. * that frees anything up. This is needed for things like routing
  6033. * etc, where we otherwise might have all activity going on in
  6034. * asynchronous contexts that cannot page things out.
  6035. *
  6036. * If there are applications that are active memory-allocators
  6037. * (most normal use), this basically shouldn't matter.
  6038. */
  6039. static int kswapd(void *p)
  6040. {
  6041. unsigned int alloc_order, reclaim_order;
  6042. unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
  6043. pg_data_t *pgdat = (pg_data_t *)p;
  6044. struct task_struct *tsk = current;
  6045. /*
  6046. * Tell the memory management that we're a "memory allocator",
  6047. * and that if we need more memory we should get access to it
  6048. * regardless (see "__alloc_pages()"). "kswapd" should
  6049. * never get caught in the normal page freeing logic.
  6050. *
  6051. * (Kswapd normally doesn't need memory anyway, but sometimes
  6052. * you need a small amount of memory in order to be able to
  6053. * page out something else, and this flag essentially protects
  6054. * us from recursively trying to free more memory as we're
  6055. * trying to free the first piece of memory in the first place).
  6056. */
  6057. tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
  6058. set_freezable();
  6059. WRITE_ONCE(pgdat->kswapd_order, 0);
  6060. WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
  6061. atomic_set(&pgdat->nr_writeback_throttled, 0);
  6062. for ( ; ; ) {
  6063. bool was_frozen;
  6064. alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
  6065. highest_zoneidx = kswapd_highest_zoneidx(pgdat,
  6066. highest_zoneidx);
  6067. kswapd_try_sleep:
  6068. kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
  6069. highest_zoneidx);
  6070. /* Read the new order and highest_zoneidx */
  6071. alloc_order = READ_ONCE(pgdat->kswapd_order);
  6072. highest_zoneidx = kswapd_highest_zoneidx(pgdat,
  6073. highest_zoneidx);
  6074. WRITE_ONCE(pgdat->kswapd_order, 0);
  6075. WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
  6076. if (kthread_freezable_should_stop(&was_frozen))
  6077. break;
  6078. /*
  6079. * We can speed up thawing tasks if we don't call balance_pgdat
  6080. * after returning from the refrigerator
  6081. */
  6082. if (was_frozen)
  6083. continue;
  6084. /*
  6085. * Reclaim begins at the requested order but if a high-order
  6086. * reclaim fails then kswapd falls back to reclaiming for
  6087. * order-0. If that happens, kswapd will consider sleeping
  6088. * for the order it finished reclaiming at (reclaim_order)
  6089. * but kcompactd is woken to compact for the original
  6090. * request (alloc_order).
  6091. */
  6092. trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
  6093. alloc_order);
  6094. reclaim_order = balance_pgdat(pgdat, alloc_order,
  6095. highest_zoneidx);
  6096. if (reclaim_order < alloc_order)
  6097. goto kswapd_try_sleep;
  6098. }
  6099. tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
  6100. return 0;
  6101. }
  6102. /*
  6103. * A zone is low on free memory or too fragmented for high-order memory. If
  6104. * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
  6105. * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
  6106. * has failed or is not needed, still wake up kcompactd if only compaction is
  6107. * needed.
  6108. */
  6109. void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
  6110. enum zone_type highest_zoneidx)
  6111. {
  6112. pg_data_t *pgdat;
  6113. enum zone_type curr_idx;
  6114. if (!managed_zone(zone))
  6115. return;
  6116. if (!cpuset_zone_allowed(zone, gfp_flags))
  6117. return;
  6118. pgdat = zone->zone_pgdat;
  6119. curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
  6120. if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
  6121. WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
  6122. if (READ_ONCE(pgdat->kswapd_order) < order)
  6123. WRITE_ONCE(pgdat->kswapd_order, order);
  6124. if (!waitqueue_active(&pgdat->kswapd_wait))
  6125. return;
  6126. /* Hopeless node, leave it to direct reclaim if possible */
  6127. if (kswapd_test_hopeless(pgdat) ||
  6128. (pgdat_balanced(pgdat, order, highest_zoneidx) &&
  6129. !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
  6130. /*
  6131. * There may be plenty of free memory available, but it's too
  6132. * fragmented for high-order allocations. Wake up kcompactd
  6133. * and rely on compaction_suitable() to determine if it's
  6134. * needed. If it fails, it will defer subsequent attempts to
  6135. * ratelimit its work.
  6136. */
  6137. if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
  6138. wakeup_kcompactd(pgdat, order, highest_zoneidx);
  6139. return;
  6140. }
  6141. trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
  6142. gfp_flags);
  6143. wake_up_interruptible(&pgdat->kswapd_wait);
  6144. }
  6145. void kswapd_clear_hopeless(pg_data_t *pgdat, enum kswapd_clear_hopeless_reason reason)
  6146. {
  6147. /* Only trace actual resets, not redundant zero-to-zero */
  6148. if (atomic_xchg(&pgdat->kswapd_failures, 0))
  6149. trace_mm_vmscan_kswapd_clear_hopeless(pgdat->node_id, reason);
  6150. }
  6151. /*
  6152. * Reset kswapd_failures only when the node is balanced. Without this
  6153. * check, successful direct reclaim (e.g., from cgroup memory.high
  6154. * throttling) can keep resetting kswapd_failures even when the node
  6155. * cannot be balanced, causing kswapd to run endlessly.
  6156. */
  6157. void kswapd_try_clear_hopeless(struct pglist_data *pgdat,
  6158. unsigned int order, int highest_zoneidx)
  6159. {
  6160. if (pgdat_balanced(pgdat, order, highest_zoneidx))
  6161. kswapd_clear_hopeless(pgdat, current_is_kswapd() ?
  6162. KSWAPD_CLEAR_HOPELESS_KSWAPD : KSWAPD_CLEAR_HOPELESS_DIRECT);
  6163. }
  6164. bool kswapd_test_hopeless(pg_data_t *pgdat)
  6165. {
  6166. return atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES;
  6167. }
  6168. #ifdef CONFIG_HIBERNATION
  6169. /*
  6170. * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
  6171. * freed pages.
  6172. *
  6173. * Rather than trying to age LRUs the aim is to preserve the overall
  6174. * LRU order by reclaiming preferentially
  6175. * inactive > active > active referenced > active mapped
  6176. */
  6177. unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
  6178. {
  6179. struct scan_control sc = {
  6180. .nr_to_reclaim = nr_to_reclaim,
  6181. .gfp_mask = GFP_HIGHUSER_MOVABLE,
  6182. .reclaim_idx = MAX_NR_ZONES - 1,
  6183. .priority = DEF_PRIORITY,
  6184. .may_writepage = 1,
  6185. .may_unmap = 1,
  6186. .may_swap = 1,
  6187. .hibernation_mode = 1,
  6188. };
  6189. struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
  6190. unsigned long nr_reclaimed;
  6191. unsigned int noreclaim_flag;
  6192. fs_reclaim_acquire(sc.gfp_mask);
  6193. noreclaim_flag = memalloc_noreclaim_save();
  6194. set_task_reclaim_state(current, &sc.reclaim_state);
  6195. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  6196. set_task_reclaim_state(current, NULL);
  6197. memalloc_noreclaim_restore(noreclaim_flag);
  6198. fs_reclaim_release(sc.gfp_mask);
  6199. return nr_reclaimed;
  6200. }
  6201. #endif /* CONFIG_HIBERNATION */
  6202. /*
  6203. * This kswapd start function will be called by init and node-hot-add.
  6204. */
  6205. void __meminit kswapd_run(int nid)
  6206. {
  6207. pg_data_t *pgdat = NODE_DATA(nid);
  6208. pgdat_kswapd_lock(pgdat);
  6209. if (!pgdat->kswapd) {
  6210. pgdat->kswapd = kthread_create_on_node(kswapd, pgdat, nid, "kswapd%d", nid);
  6211. if (IS_ERR(pgdat->kswapd)) {
  6212. /* failure at boot is fatal */
  6213. pr_err("Failed to start kswapd on node %d, ret=%pe\n",
  6214. nid, pgdat->kswapd);
  6215. BUG_ON(system_state < SYSTEM_RUNNING);
  6216. pgdat->kswapd = NULL;
  6217. } else {
  6218. wake_up_process(pgdat->kswapd);
  6219. }
  6220. }
  6221. pgdat_kswapd_unlock(pgdat);
  6222. }
  6223. /*
  6224. * Called by memory hotplug when all memory in a node is offlined. Caller must
  6225. * be holding mem_hotplug_begin/done().
  6226. */
  6227. void __meminit kswapd_stop(int nid)
  6228. {
  6229. pg_data_t *pgdat = NODE_DATA(nid);
  6230. struct task_struct *kswapd;
  6231. pgdat_kswapd_lock(pgdat);
  6232. kswapd = pgdat->kswapd;
  6233. if (kswapd) {
  6234. kthread_stop(kswapd);
  6235. pgdat->kswapd = NULL;
  6236. }
  6237. pgdat_kswapd_unlock(pgdat);
  6238. }
  6239. static const struct ctl_table vmscan_sysctl_table[] = {
  6240. {
  6241. .procname = "swappiness",
  6242. .data = &vm_swappiness,
  6243. .maxlen = sizeof(vm_swappiness),
  6244. .mode = 0644,
  6245. .proc_handler = proc_dointvec_minmax,
  6246. .extra1 = SYSCTL_ZERO,
  6247. .extra2 = SYSCTL_TWO_HUNDRED,
  6248. },
  6249. #ifdef CONFIG_NUMA
  6250. {
  6251. .procname = "zone_reclaim_mode",
  6252. .data = &node_reclaim_mode,
  6253. .maxlen = sizeof(node_reclaim_mode),
  6254. .mode = 0644,
  6255. .proc_handler = proc_dointvec_minmax,
  6256. .extra1 = SYSCTL_ZERO,
  6257. }
  6258. #endif
  6259. };
  6260. static int __init kswapd_init(void)
  6261. {
  6262. int nid;
  6263. swap_setup();
  6264. for_each_node_state(nid, N_MEMORY)
  6265. kswapd_run(nid);
  6266. register_sysctl_init("vm", vmscan_sysctl_table);
  6267. return 0;
  6268. }
  6269. module_init(kswapd_init)
  6270. #ifdef CONFIG_NUMA
  6271. /*
  6272. * Node reclaim mode
  6273. *
  6274. * If non-zero call node_reclaim when the number of free pages falls below
  6275. * the watermarks.
  6276. */
  6277. int node_reclaim_mode __read_mostly;
  6278. /*
  6279. * Priority for NODE_RECLAIM. This determines the fraction of pages
  6280. * of a node considered for each zone_reclaim. 4 scans 1/16th of
  6281. * a zone.
  6282. */
  6283. #define NODE_RECLAIM_PRIORITY 4
  6284. /*
  6285. * Percentage of pages in a zone that must be unmapped for node_reclaim to
  6286. * occur.
  6287. */
  6288. int sysctl_min_unmapped_ratio = 1;
  6289. /*
  6290. * If the number of slab pages in a zone grows beyond this percentage then
  6291. * slab reclaim needs to occur.
  6292. */
  6293. int sysctl_min_slab_ratio = 5;
  6294. static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
  6295. {
  6296. unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
  6297. unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
  6298. node_page_state(pgdat, NR_ACTIVE_FILE);
  6299. /*
  6300. * It's possible for there to be more file mapped pages than
  6301. * accounted for by the pages on the file LRU lists because
  6302. * tmpfs pages accounted for as ANON can also be FILE_MAPPED
  6303. */
  6304. return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
  6305. }
  6306. /* Work out how many page cache pages we can reclaim in this reclaim_mode */
  6307. static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
  6308. {
  6309. unsigned long nr_pagecache_reclaimable;
  6310. unsigned long delta = 0;
  6311. /*
  6312. * If RECLAIM_UNMAP is set, then all file pages are considered
  6313. * potentially reclaimable. Otherwise, we have to worry about
  6314. * pages like swapcache and node_unmapped_file_pages() provides
  6315. * a better estimate
  6316. */
  6317. if (node_reclaim_mode & RECLAIM_UNMAP)
  6318. nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
  6319. else
  6320. nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
  6321. /*
  6322. * Since we can't clean folios through reclaim, remove dirty file
  6323. * folios from consideration.
  6324. */
  6325. delta += node_page_state(pgdat, NR_FILE_DIRTY);
  6326. /* Watch for any possible underflows due to delta */
  6327. if (unlikely(delta > nr_pagecache_reclaimable))
  6328. delta = nr_pagecache_reclaimable;
  6329. return nr_pagecache_reclaimable - delta;
  6330. }
  6331. /*
  6332. * Try to free up some pages from this node through reclaim.
  6333. */
  6334. static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask,
  6335. unsigned long nr_pages,
  6336. struct scan_control *sc)
  6337. {
  6338. struct task_struct *p = current;
  6339. unsigned int noreclaim_flag;
  6340. unsigned long pflags;
  6341. trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, sc->order,
  6342. sc->gfp_mask);
  6343. cond_resched();
  6344. psi_memstall_enter(&pflags);
  6345. delayacct_freepages_start();
  6346. fs_reclaim_acquire(sc->gfp_mask);
  6347. /*
  6348. * We need to be able to allocate from the reserves for RECLAIM_UNMAP
  6349. */
  6350. noreclaim_flag = memalloc_noreclaim_save();
  6351. set_task_reclaim_state(p, &sc->reclaim_state);
  6352. if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
  6353. node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
  6354. /*
  6355. * Free memory by calling shrink node with increasing
  6356. * priorities until we have enough memory freed.
  6357. */
  6358. do {
  6359. shrink_node(pgdat, sc);
  6360. } while (sc->nr_reclaimed < nr_pages && --sc->priority >= 0);
  6361. }
  6362. set_task_reclaim_state(p, NULL);
  6363. memalloc_noreclaim_restore(noreclaim_flag);
  6364. fs_reclaim_release(sc->gfp_mask);
  6365. delayacct_freepages_end();
  6366. psi_memstall_leave(&pflags);
  6367. trace_mm_vmscan_node_reclaim_end(sc->nr_reclaimed);
  6368. return sc->nr_reclaimed;
  6369. }
  6370. int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
  6371. {
  6372. int ret;
  6373. /* Minimum pages needed in order to stay on node */
  6374. const unsigned long nr_pages = 1 << order;
  6375. struct scan_control sc = {
  6376. .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
  6377. .gfp_mask = current_gfp_context(gfp_mask),
  6378. .order = order,
  6379. .priority = NODE_RECLAIM_PRIORITY,
  6380. .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
  6381. .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
  6382. .may_swap = 1,
  6383. .reclaim_idx = gfp_zone(gfp_mask),
  6384. };
  6385. /*
  6386. * Node reclaim reclaims unmapped file backed pages and
  6387. * slab pages if we are over the defined limits.
  6388. *
  6389. * A small portion of unmapped file backed pages is needed for
  6390. * file I/O otherwise pages read by file I/O will be immediately
  6391. * thrown out if the node is overallocated. So we do not reclaim
  6392. * if less than a specified percentage of the node is used by
  6393. * unmapped file backed pages.
  6394. */
  6395. if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
  6396. node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
  6397. pgdat->min_slab_pages)
  6398. return NODE_RECLAIM_FULL;
  6399. /*
  6400. * Do not scan if the allocation should not be delayed.
  6401. */
  6402. if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
  6403. return NODE_RECLAIM_NOSCAN;
  6404. /*
  6405. * Only run node reclaim on the local node or on nodes that do not
  6406. * have associated processors. This will favor the local processor
  6407. * over remote processors and spread off node memory allocations
  6408. * as wide as possible.
  6409. */
  6410. if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
  6411. return NODE_RECLAIM_NOSCAN;
  6412. if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
  6413. return NODE_RECLAIM_NOSCAN;
  6414. ret = __node_reclaim(pgdat, gfp_mask, nr_pages, &sc) >= nr_pages;
  6415. clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
  6416. if (ret)
  6417. count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS);
  6418. else
  6419. count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
  6420. return ret;
  6421. }
  6422. #else
  6423. static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask,
  6424. unsigned long nr_pages,
  6425. struct scan_control *sc)
  6426. {
  6427. return 0;
  6428. }
  6429. #endif
  6430. enum {
  6431. MEMORY_RECLAIM_SWAPPINESS = 0,
  6432. MEMORY_RECLAIM_SWAPPINESS_MAX,
  6433. MEMORY_RECLAIM_NULL,
  6434. };
  6435. static const match_table_t tokens = {
  6436. { MEMORY_RECLAIM_SWAPPINESS, "swappiness=%d"},
  6437. { MEMORY_RECLAIM_SWAPPINESS_MAX, "swappiness=max"},
  6438. { MEMORY_RECLAIM_NULL, NULL },
  6439. };
  6440. int user_proactive_reclaim(char *buf,
  6441. struct mem_cgroup *memcg, pg_data_t *pgdat)
  6442. {
  6443. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  6444. unsigned long nr_to_reclaim, nr_reclaimed = 0;
  6445. int swappiness = -1;
  6446. char *old_buf, *start;
  6447. substring_t args[MAX_OPT_ARGS];
  6448. gfp_t gfp_mask = GFP_KERNEL;
  6449. if (!buf || (!memcg && !pgdat) || (memcg && pgdat))
  6450. return -EINVAL;
  6451. buf = strstrip(buf);
  6452. old_buf = buf;
  6453. nr_to_reclaim = memparse(buf, &buf) / PAGE_SIZE;
  6454. if (buf == old_buf)
  6455. return -EINVAL;
  6456. buf = strstrip(buf);
  6457. while ((start = strsep(&buf, " ")) != NULL) {
  6458. if (!strlen(start))
  6459. continue;
  6460. switch (match_token(start, tokens, args)) {
  6461. case MEMORY_RECLAIM_SWAPPINESS:
  6462. if (match_int(&args[0], &swappiness))
  6463. return -EINVAL;
  6464. if (swappiness < MIN_SWAPPINESS ||
  6465. swappiness > MAX_SWAPPINESS)
  6466. return -EINVAL;
  6467. break;
  6468. case MEMORY_RECLAIM_SWAPPINESS_MAX:
  6469. swappiness = SWAPPINESS_ANON_ONLY;
  6470. break;
  6471. default:
  6472. return -EINVAL;
  6473. }
  6474. }
  6475. while (nr_reclaimed < nr_to_reclaim) {
  6476. /* Will converge on zero, but reclaim enforces a minimum */
  6477. unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
  6478. unsigned long reclaimed;
  6479. if (signal_pending(current))
  6480. return -EINTR;
  6481. /*
  6482. * This is the final attempt, drain percpu lru caches in the
  6483. * hope of introducing more evictable pages.
  6484. */
  6485. if (!nr_retries)
  6486. lru_add_drain_all();
  6487. if (memcg) {
  6488. unsigned int reclaim_options;
  6489. reclaim_options = MEMCG_RECLAIM_MAY_SWAP |
  6490. MEMCG_RECLAIM_PROACTIVE;
  6491. reclaimed = try_to_free_mem_cgroup_pages(memcg,
  6492. batch_size, gfp_mask,
  6493. reclaim_options,
  6494. swappiness == -1 ? NULL : &swappiness);
  6495. } else {
  6496. struct scan_control sc = {
  6497. .gfp_mask = current_gfp_context(gfp_mask),
  6498. .reclaim_idx = gfp_zone(gfp_mask),
  6499. .proactive_swappiness = swappiness == -1 ? NULL : &swappiness,
  6500. .priority = DEF_PRIORITY,
  6501. .may_writepage = 1,
  6502. .nr_to_reclaim = max(batch_size, SWAP_CLUSTER_MAX),
  6503. .may_unmap = 1,
  6504. .may_swap = 1,
  6505. .proactive = 1,
  6506. };
  6507. if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED,
  6508. &pgdat->flags))
  6509. return -EBUSY;
  6510. reclaimed = __node_reclaim(pgdat, gfp_mask,
  6511. batch_size, &sc);
  6512. clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
  6513. }
  6514. if (!reclaimed && !nr_retries--)
  6515. return -EAGAIN;
  6516. nr_reclaimed += reclaimed;
  6517. }
  6518. return 0;
  6519. }
  6520. /**
  6521. * check_move_unevictable_folios - Move evictable folios to appropriate zone
  6522. * lru list
  6523. * @fbatch: Batch of lru folios to check.
  6524. *
  6525. * Checks folios for evictability, if an evictable folio is in the unevictable
  6526. * lru list, moves it to the appropriate evictable lru list. This function
  6527. * should be only used for lru folios.
  6528. */
  6529. void check_move_unevictable_folios(struct folio_batch *fbatch)
  6530. {
  6531. struct lruvec *lruvec = NULL;
  6532. int pgscanned = 0;
  6533. int pgrescued = 0;
  6534. int i;
  6535. for (i = 0; i < fbatch->nr; i++) {
  6536. struct folio *folio = fbatch->folios[i];
  6537. int nr_pages = folio_nr_pages(folio);
  6538. pgscanned += nr_pages;
  6539. /* block memcg migration while the folio moves between lrus */
  6540. if (!folio_test_clear_lru(folio))
  6541. continue;
  6542. lruvec = folio_lruvec_relock_irq(folio, lruvec);
  6543. if (folio_evictable(folio) && folio_test_unevictable(folio)) {
  6544. lruvec_del_folio(lruvec, folio);
  6545. folio_clear_unevictable(folio);
  6546. lruvec_add_folio(lruvec, folio);
  6547. pgrescued += nr_pages;
  6548. }
  6549. folio_set_lru(folio);
  6550. }
  6551. if (lruvec) {
  6552. __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
  6553. __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
  6554. unlock_page_lruvec_irq(lruvec);
  6555. } else if (pgscanned) {
  6556. count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
  6557. }
  6558. }
  6559. EXPORT_SYMBOL_GPL(check_move_unevictable_folios);
  6560. #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
  6561. static ssize_t reclaim_store(struct device *dev,
  6562. struct device_attribute *attr,
  6563. const char *buf, size_t count)
  6564. {
  6565. int ret, nid = dev->id;
  6566. ret = user_proactive_reclaim((char *)buf, NULL, NODE_DATA(nid));
  6567. return ret ? -EAGAIN : count;
  6568. }
  6569. static DEVICE_ATTR_WO(reclaim);
  6570. int reclaim_register_node(struct node *node)
  6571. {
  6572. return device_create_file(&node->dev, &dev_attr_reclaim);
  6573. }
  6574. void reclaim_unregister_node(struct node *node)
  6575. {
  6576. return device_remove_file(&node->dev, &dev_attr_reclaim);
  6577. }
  6578. #endif