vmscan.c 211 KB

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