page_alloc.c 198 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/page_alloc.c
  4. *
  5. * Manages the free list, the system allocates free pages here.
  6. * Note that kmalloc() lives in slab.c
  7. *
  8. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  9. * Swap reorganised 29.12.95, Stephen Tweedie
  10. * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
  11. * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
  12. * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
  13. * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
  14. * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
  15. * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
  16. */
  17. #include <linux/stddef.h>
  18. #include <linux/mm.h>
  19. #include <linux/highmem.h>
  20. #include <linux/interrupt.h>
  21. #include <linux/jiffies.h>
  22. #include <linux/compiler.h>
  23. #include <linux/kernel.h>
  24. #include <linux/kasan.h>
  25. #include <linux/kmsan.h>
  26. #include <linux/module.h>
  27. #include <linux/suspend.h>
  28. #include <linux/ratelimit.h>
  29. #include <linux/oom.h>
  30. #include <linux/topology.h>
  31. #include <linux/sysctl.h>
  32. #include <linux/cpu.h>
  33. #include <linux/cpuset.h>
  34. #include <linux/pagevec.h>
  35. #include <linux/memory_hotplug.h>
  36. #include <linux/nodemask.h>
  37. #include <linux/vmstat.h>
  38. #include <linux/fault-inject.h>
  39. #include <linux/compaction.h>
  40. #include <trace/events/kmem.h>
  41. #include <trace/events/oom.h>
  42. #include <linux/prefetch.h>
  43. #include <linux/mm_inline.h>
  44. #include <linux/mmu_notifier.h>
  45. #include <linux/migrate.h>
  46. #include <linux/sched/mm.h>
  47. #include <linux/page_owner.h>
  48. #include <linux/page_table_check.h>
  49. #include <linux/memcontrol.h>
  50. #include <linux/ftrace.h>
  51. #include <linux/lockdep.h>
  52. #include <linux/psi.h>
  53. #include <linux/khugepaged.h>
  54. #include <linux/delayacct.h>
  55. #include <linux/cacheinfo.h>
  56. #include <linux/pgalloc_tag.h>
  57. #include <asm/div64.h>
  58. #include "internal.h"
  59. #include "shuffle.h"
  60. #include "page_reporting.h"
  61. /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
  62. typedef int __bitwise fpi_t;
  63. /* No special request */
  64. #define FPI_NONE ((__force fpi_t)0)
  65. /*
  66. * Skip free page reporting notification for the (possibly merged) page.
  67. * This does not hinder free page reporting from grabbing the page,
  68. * reporting it and marking it "reported" - it only skips notifying
  69. * the free page reporting infrastructure about a newly freed page. For
  70. * example, used when temporarily pulling a page from a freelist and
  71. * putting it back unmodified.
  72. */
  73. #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
  74. /*
  75. * Place the (possibly merged) page to the tail of the freelist. Will ignore
  76. * page shuffling (relevant code - e.g., memory onlining - is expected to
  77. * shuffle the whole zone).
  78. *
  79. * Note: No code should rely on this flag for correctness - it's purely
  80. * to allow for optimizations when handing back either fresh pages
  81. * (memory onlining) or untouched pages (page isolation, free page
  82. * reporting).
  83. */
  84. #define FPI_TO_TAIL ((__force fpi_t)BIT(1))
  85. /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
  86. static DEFINE_MUTEX(pcp_batch_high_lock);
  87. #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8)
  88. #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT)
  89. /*
  90. * On SMP, spin_trylock is sufficient protection.
  91. * On PREEMPT_RT, spin_trylock is equivalent on both SMP and UP.
  92. */
  93. #define pcp_trylock_prepare(flags) do { } while (0)
  94. #define pcp_trylock_finish(flag) do { } while (0)
  95. #else
  96. /* UP spin_trylock always succeeds so disable IRQs to prevent re-entrancy. */
  97. #define pcp_trylock_prepare(flags) local_irq_save(flags)
  98. #define pcp_trylock_finish(flags) local_irq_restore(flags)
  99. #endif
  100. /*
  101. * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid
  102. * a migration causing the wrong PCP to be locked and remote memory being
  103. * potentially allocated, pin the task to the CPU for the lookup+lock.
  104. * preempt_disable is used on !RT because it is faster than migrate_disable.
  105. * migrate_disable is used on RT because otherwise RT spinlock usage is
  106. * interfered with and a high priority task cannot preempt the allocator.
  107. */
  108. #ifndef CONFIG_PREEMPT_RT
  109. #define pcpu_task_pin() preempt_disable()
  110. #define pcpu_task_unpin() preempt_enable()
  111. #else
  112. #define pcpu_task_pin() migrate_disable()
  113. #define pcpu_task_unpin() migrate_enable()
  114. #endif
  115. /*
  116. * Generic helper to lookup and a per-cpu variable with an embedded spinlock.
  117. * Return value should be used with equivalent unlock helper.
  118. */
  119. #define pcpu_spin_lock(type, member, ptr) \
  120. ({ \
  121. type *_ret; \
  122. pcpu_task_pin(); \
  123. _ret = this_cpu_ptr(ptr); \
  124. spin_lock(&_ret->member); \
  125. _ret; \
  126. })
  127. #define pcpu_spin_trylock(type, member, ptr) \
  128. ({ \
  129. type *_ret; \
  130. pcpu_task_pin(); \
  131. _ret = this_cpu_ptr(ptr); \
  132. if (!spin_trylock(&_ret->member)) { \
  133. pcpu_task_unpin(); \
  134. _ret = NULL; \
  135. } \
  136. _ret; \
  137. })
  138. #define pcpu_spin_unlock(member, ptr) \
  139. ({ \
  140. spin_unlock(&ptr->member); \
  141. pcpu_task_unpin(); \
  142. })
  143. /* struct per_cpu_pages specific helpers. */
  144. #define pcp_spin_lock(ptr) \
  145. pcpu_spin_lock(struct per_cpu_pages, lock, ptr)
  146. #define pcp_spin_trylock(ptr) \
  147. pcpu_spin_trylock(struct per_cpu_pages, lock, ptr)
  148. #define pcp_spin_unlock(ptr) \
  149. pcpu_spin_unlock(lock, ptr)
  150. #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
  151. DEFINE_PER_CPU(int, numa_node);
  152. EXPORT_PER_CPU_SYMBOL(numa_node);
  153. #endif
  154. DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
  155. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  156. /*
  157. * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
  158. * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
  159. * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
  160. * defined in <linux/topology.h>.
  161. */
  162. DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
  163. EXPORT_PER_CPU_SYMBOL(_numa_mem_);
  164. #endif
  165. static DEFINE_MUTEX(pcpu_drain_mutex);
  166. #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
  167. volatile unsigned long latent_entropy __latent_entropy;
  168. EXPORT_SYMBOL(latent_entropy);
  169. #endif
  170. /*
  171. * Array of node states.
  172. */
  173. nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
  174. [N_POSSIBLE] = NODE_MASK_ALL,
  175. [N_ONLINE] = { { [0] = 1UL } },
  176. #ifndef CONFIG_NUMA
  177. [N_NORMAL_MEMORY] = { { [0] = 1UL } },
  178. #ifdef CONFIG_HIGHMEM
  179. [N_HIGH_MEMORY] = { { [0] = 1UL } },
  180. #endif
  181. [N_MEMORY] = { { [0] = 1UL } },
  182. [N_CPU] = { { [0] = 1UL } },
  183. #endif /* NUMA */
  184. };
  185. EXPORT_SYMBOL(node_states);
  186. gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
  187. #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
  188. unsigned int pageblock_order __read_mostly;
  189. #endif
  190. static void __free_pages_ok(struct page *page, unsigned int order,
  191. fpi_t fpi_flags);
  192. /*
  193. * results with 256, 32 in the lowmem_reserve sysctl:
  194. * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
  195. * 1G machine -> (16M dma, 784M normal, 224M high)
  196. * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
  197. * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
  198. * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
  199. *
  200. * TBD: should special case ZONE_DMA32 machines here - in those we normally
  201. * don't need any ZONE_NORMAL reservation
  202. */
  203. static int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
  204. #ifdef CONFIG_ZONE_DMA
  205. [ZONE_DMA] = 256,
  206. #endif
  207. #ifdef CONFIG_ZONE_DMA32
  208. [ZONE_DMA32] = 256,
  209. #endif
  210. [ZONE_NORMAL] = 32,
  211. #ifdef CONFIG_HIGHMEM
  212. [ZONE_HIGHMEM] = 0,
  213. #endif
  214. [ZONE_MOVABLE] = 0,
  215. };
  216. char * const zone_names[MAX_NR_ZONES] = {
  217. #ifdef CONFIG_ZONE_DMA
  218. "DMA",
  219. #endif
  220. #ifdef CONFIG_ZONE_DMA32
  221. "DMA32",
  222. #endif
  223. "Normal",
  224. #ifdef CONFIG_HIGHMEM
  225. "HighMem",
  226. #endif
  227. "Movable",
  228. #ifdef CONFIG_ZONE_DEVICE
  229. "Device",
  230. #endif
  231. };
  232. const char * const migratetype_names[MIGRATE_TYPES] = {
  233. "Unmovable",
  234. "Movable",
  235. "Reclaimable",
  236. "HighAtomic",
  237. #ifdef CONFIG_CMA
  238. "CMA",
  239. #endif
  240. #ifdef CONFIG_MEMORY_ISOLATION
  241. "Isolate",
  242. #endif
  243. };
  244. int min_free_kbytes = 1024;
  245. int user_min_free_kbytes = -1;
  246. static int watermark_boost_factor __read_mostly = 15000;
  247. static int watermark_scale_factor = 10;
  248. /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
  249. int movable_zone;
  250. EXPORT_SYMBOL(movable_zone);
  251. #if MAX_NUMNODES > 1
  252. unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
  253. unsigned int nr_online_nodes __read_mostly = 1;
  254. EXPORT_SYMBOL(nr_node_ids);
  255. EXPORT_SYMBOL(nr_online_nodes);
  256. #endif
  257. static bool page_contains_unaccepted(struct page *page, unsigned int order);
  258. static bool cond_accept_memory(struct zone *zone, unsigned int order);
  259. static bool __free_unaccepted(struct page *page);
  260. int page_group_by_mobility_disabled __read_mostly;
  261. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  262. /*
  263. * During boot we initialize deferred pages on-demand, as needed, but once
  264. * page_alloc_init_late() has finished, the deferred pages are all initialized,
  265. * and we can permanently disable that path.
  266. */
  267. DEFINE_STATIC_KEY_TRUE(deferred_pages);
  268. static inline bool deferred_pages_enabled(void)
  269. {
  270. return static_branch_unlikely(&deferred_pages);
  271. }
  272. /*
  273. * deferred_grow_zone() is __init, but it is called from
  274. * get_page_from_freelist() during early boot until deferred_pages permanently
  275. * disables this call. This is why we have refdata wrapper to avoid warning,
  276. * and to ensure that the function body gets unloaded.
  277. */
  278. static bool __ref
  279. _deferred_grow_zone(struct zone *zone, unsigned int order)
  280. {
  281. return deferred_grow_zone(zone, order);
  282. }
  283. #else
  284. static inline bool deferred_pages_enabled(void)
  285. {
  286. return false;
  287. }
  288. static inline bool _deferred_grow_zone(struct zone *zone, unsigned int order)
  289. {
  290. return false;
  291. }
  292. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  293. /* Return a pointer to the bitmap storing bits affecting a block of pages */
  294. static inline unsigned long *get_pageblock_bitmap(const struct page *page,
  295. unsigned long pfn)
  296. {
  297. #ifdef CONFIG_SPARSEMEM
  298. return section_to_usemap(__pfn_to_section(pfn));
  299. #else
  300. return page_zone(page)->pageblock_flags;
  301. #endif /* CONFIG_SPARSEMEM */
  302. }
  303. static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
  304. {
  305. #ifdef CONFIG_SPARSEMEM
  306. pfn &= (PAGES_PER_SECTION-1);
  307. #else
  308. pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn);
  309. #endif /* CONFIG_SPARSEMEM */
  310. return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
  311. }
  312. /**
  313. * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
  314. * @page: The page within the block of interest
  315. * @pfn: The target page frame number
  316. * @mask: mask of bits that the caller is interested in
  317. *
  318. * Return: pageblock_bits flags
  319. */
  320. unsigned long get_pfnblock_flags_mask(const struct page *page,
  321. unsigned long pfn, unsigned long mask)
  322. {
  323. unsigned long *bitmap;
  324. unsigned long bitidx, word_bitidx;
  325. unsigned long word;
  326. bitmap = get_pageblock_bitmap(page, pfn);
  327. bitidx = pfn_to_bitidx(page, pfn);
  328. word_bitidx = bitidx / BITS_PER_LONG;
  329. bitidx &= (BITS_PER_LONG-1);
  330. /*
  331. * This races, without locks, with set_pfnblock_flags_mask(). Ensure
  332. * a consistent read of the memory array, so that results, even though
  333. * racy, are not corrupted.
  334. */
  335. word = READ_ONCE(bitmap[word_bitidx]);
  336. return (word >> bitidx) & mask;
  337. }
  338. static __always_inline int get_pfnblock_migratetype(const struct page *page,
  339. unsigned long pfn)
  340. {
  341. return get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK);
  342. }
  343. /**
  344. * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
  345. * @page: The page within the block of interest
  346. * @flags: The flags to set
  347. * @pfn: The target page frame number
  348. * @mask: mask of bits that the caller is interested in
  349. */
  350. void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
  351. unsigned long pfn,
  352. unsigned long mask)
  353. {
  354. unsigned long *bitmap;
  355. unsigned long bitidx, word_bitidx;
  356. unsigned long word;
  357. BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
  358. BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
  359. bitmap = get_pageblock_bitmap(page, pfn);
  360. bitidx = pfn_to_bitidx(page, pfn);
  361. word_bitidx = bitidx / BITS_PER_LONG;
  362. bitidx &= (BITS_PER_LONG-1);
  363. VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
  364. mask <<= bitidx;
  365. flags <<= bitidx;
  366. word = READ_ONCE(bitmap[word_bitidx]);
  367. do {
  368. } while (!try_cmpxchg(&bitmap[word_bitidx], &word, (word & ~mask) | flags));
  369. }
  370. void set_pageblock_migratetype(struct page *page, int migratetype)
  371. {
  372. if (unlikely(page_group_by_mobility_disabled &&
  373. migratetype < MIGRATE_PCPTYPES))
  374. migratetype = MIGRATE_UNMOVABLE;
  375. set_pfnblock_flags_mask(page, (unsigned long)migratetype,
  376. page_to_pfn(page), MIGRATETYPE_MASK);
  377. }
  378. #ifdef CONFIG_DEBUG_VM
  379. static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
  380. {
  381. int ret;
  382. unsigned seq;
  383. unsigned long pfn = page_to_pfn(page);
  384. unsigned long sp, start_pfn;
  385. do {
  386. seq = zone_span_seqbegin(zone);
  387. start_pfn = zone->zone_start_pfn;
  388. sp = zone->spanned_pages;
  389. ret = !zone_spans_pfn(zone, pfn);
  390. } while (zone_span_seqretry(zone, seq));
  391. if (ret)
  392. pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
  393. pfn, zone_to_nid(zone), zone->name,
  394. start_pfn, start_pfn + sp);
  395. return ret;
  396. }
  397. /*
  398. * Temporary debugging check for pages not lying within a given zone.
  399. */
  400. static bool __maybe_unused bad_range(struct zone *zone, struct page *page)
  401. {
  402. if (page_outside_zone_boundaries(zone, page))
  403. return true;
  404. if (zone != page_zone(page))
  405. return true;
  406. return false;
  407. }
  408. #else
  409. static inline bool __maybe_unused bad_range(struct zone *zone, struct page *page)
  410. {
  411. return false;
  412. }
  413. #endif
  414. static void bad_page(struct page *page, const char *reason)
  415. {
  416. static unsigned long resume;
  417. static unsigned long nr_shown;
  418. static unsigned long nr_unshown;
  419. /*
  420. * Allow a burst of 60 reports, then keep quiet for that minute;
  421. * or allow a steady drip of one report per second.
  422. */
  423. if (nr_shown == 60) {
  424. if (time_before(jiffies, resume)) {
  425. nr_unshown++;
  426. goto out;
  427. }
  428. if (nr_unshown) {
  429. pr_alert(
  430. "BUG: Bad page state: %lu messages suppressed\n",
  431. nr_unshown);
  432. nr_unshown = 0;
  433. }
  434. nr_shown = 0;
  435. }
  436. if (nr_shown++ == 0)
  437. resume = jiffies + 60 * HZ;
  438. pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
  439. current->comm, page_to_pfn(page));
  440. dump_page(page, reason);
  441. print_modules();
  442. dump_stack();
  443. out:
  444. /* Leave bad fields for debug, except PageBuddy could make trouble */
  445. if (PageBuddy(page))
  446. __ClearPageBuddy(page);
  447. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  448. }
  449. static inline unsigned int order_to_pindex(int migratetype, int order)
  450. {
  451. bool __maybe_unused movable;
  452. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  453. if (order > PAGE_ALLOC_COSTLY_ORDER) {
  454. VM_BUG_ON(order != HPAGE_PMD_ORDER);
  455. movable = migratetype == MIGRATE_MOVABLE;
  456. return NR_LOWORDER_PCP_LISTS + movable;
  457. }
  458. #else
  459. VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
  460. #endif
  461. return (MIGRATE_PCPTYPES * order) + migratetype;
  462. }
  463. static inline int pindex_to_order(unsigned int pindex)
  464. {
  465. int order = pindex / MIGRATE_PCPTYPES;
  466. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  467. if (pindex >= NR_LOWORDER_PCP_LISTS)
  468. order = HPAGE_PMD_ORDER;
  469. #else
  470. VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
  471. #endif
  472. return order;
  473. }
  474. static inline bool pcp_allowed_order(unsigned int order)
  475. {
  476. if (order <= PAGE_ALLOC_COSTLY_ORDER)
  477. return true;
  478. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  479. if (order == HPAGE_PMD_ORDER)
  480. return true;
  481. #endif
  482. return false;
  483. }
  484. /*
  485. * Higher-order pages are called "compound pages". They are structured thusly:
  486. *
  487. * The first PAGE_SIZE page is called the "head page" and have PG_head set.
  488. *
  489. * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
  490. * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
  491. *
  492. * The first tail page's ->compound_order holds the order of allocation.
  493. * This usage means that zero-order pages may not be compound.
  494. */
  495. void prep_compound_page(struct page *page, unsigned int order)
  496. {
  497. int i;
  498. int nr_pages = 1 << order;
  499. __SetPageHead(page);
  500. for (i = 1; i < nr_pages; i++)
  501. prep_compound_tail(page, i);
  502. prep_compound_head(page, order);
  503. }
  504. static inline void set_buddy_order(struct page *page, unsigned int order)
  505. {
  506. set_page_private(page, order);
  507. __SetPageBuddy(page);
  508. }
  509. #ifdef CONFIG_COMPACTION
  510. static inline struct capture_control *task_capc(struct zone *zone)
  511. {
  512. struct capture_control *capc = current->capture_control;
  513. return unlikely(capc) &&
  514. !(current->flags & PF_KTHREAD) &&
  515. !capc->page &&
  516. capc->cc->zone == zone ? capc : NULL;
  517. }
  518. static inline bool
  519. compaction_capture(struct capture_control *capc, struct page *page,
  520. int order, int migratetype)
  521. {
  522. if (!capc || order != capc->cc->order)
  523. return false;
  524. /* Do not accidentally pollute CMA or isolated regions*/
  525. if (is_migrate_cma(migratetype) ||
  526. is_migrate_isolate(migratetype))
  527. return false;
  528. /*
  529. * Do not let lower order allocations pollute a movable pageblock
  530. * unless compaction is also requesting movable pages.
  531. * This might let an unmovable request use a reclaimable pageblock
  532. * and vice-versa but no more than normal fallback logic which can
  533. * have trouble finding a high-order free page.
  534. */
  535. if (order < pageblock_order && migratetype == MIGRATE_MOVABLE &&
  536. capc->cc->migratetype != MIGRATE_MOVABLE)
  537. return false;
  538. capc->page = page;
  539. return true;
  540. }
  541. #else
  542. static inline struct capture_control *task_capc(struct zone *zone)
  543. {
  544. return NULL;
  545. }
  546. static inline bool
  547. compaction_capture(struct capture_control *capc, struct page *page,
  548. int order, int migratetype)
  549. {
  550. return false;
  551. }
  552. #endif /* CONFIG_COMPACTION */
  553. static inline void account_freepages(struct zone *zone, int nr_pages,
  554. int migratetype)
  555. {
  556. lockdep_assert_held(&zone->lock);
  557. if (is_migrate_isolate(migratetype))
  558. return;
  559. __mod_zone_page_state(zone, NR_FREE_PAGES, nr_pages);
  560. if (is_migrate_cma(migratetype))
  561. __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, nr_pages);
  562. else if (is_migrate_highatomic(migratetype))
  563. WRITE_ONCE(zone->nr_free_highatomic,
  564. zone->nr_free_highatomic + nr_pages);
  565. }
  566. /* Used for pages not on another list */
  567. static inline void __add_to_free_list(struct page *page, struct zone *zone,
  568. unsigned int order, int migratetype,
  569. bool tail)
  570. {
  571. struct free_area *area = &zone->free_area[order];
  572. VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
  573. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  574. get_pageblock_migratetype(page), migratetype, 1 << order);
  575. if (tail)
  576. list_add_tail(&page->buddy_list, &area->free_list[migratetype]);
  577. else
  578. list_add(&page->buddy_list, &area->free_list[migratetype]);
  579. area->nr_free++;
  580. }
  581. /*
  582. * Used for pages which are on another list. Move the pages to the tail
  583. * of the list - so the moved pages won't immediately be considered for
  584. * allocation again (e.g., optimization for memory onlining).
  585. */
  586. static inline void move_to_free_list(struct page *page, struct zone *zone,
  587. unsigned int order, int old_mt, int new_mt)
  588. {
  589. struct free_area *area = &zone->free_area[order];
  590. /* Free page moving can fail, so it happens before the type update */
  591. VM_WARN_ONCE(get_pageblock_migratetype(page) != old_mt,
  592. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  593. get_pageblock_migratetype(page), old_mt, 1 << order);
  594. list_move_tail(&page->buddy_list, &area->free_list[new_mt]);
  595. account_freepages(zone, -(1 << order), old_mt);
  596. account_freepages(zone, 1 << order, new_mt);
  597. }
  598. static inline void __del_page_from_free_list(struct page *page, struct zone *zone,
  599. unsigned int order, int migratetype)
  600. {
  601. VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
  602. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  603. get_pageblock_migratetype(page), migratetype, 1 << order);
  604. /* clear reported state and update reported page count */
  605. if (page_reported(page))
  606. __ClearPageReported(page);
  607. list_del(&page->buddy_list);
  608. __ClearPageBuddy(page);
  609. set_page_private(page, 0);
  610. zone->free_area[order].nr_free--;
  611. }
  612. static inline void del_page_from_free_list(struct page *page, struct zone *zone,
  613. unsigned int order, int migratetype)
  614. {
  615. __del_page_from_free_list(page, zone, order, migratetype);
  616. account_freepages(zone, -(1 << order), migratetype);
  617. }
  618. static inline struct page *get_page_from_free_area(struct free_area *area,
  619. int migratetype)
  620. {
  621. return list_first_entry_or_null(&area->free_list[migratetype],
  622. struct page, buddy_list);
  623. }
  624. /*
  625. * If this is less than the 2nd largest possible page, check if the buddy
  626. * of the next-higher order is free. If it is, it's possible
  627. * that pages are being freed that will coalesce soon. In case,
  628. * that is happening, add the free page to the tail of the list
  629. * so it's less likely to be used soon and more likely to be merged
  630. * as a 2-level higher order page
  631. */
  632. static inline bool
  633. buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
  634. struct page *page, unsigned int order)
  635. {
  636. unsigned long higher_page_pfn;
  637. struct page *higher_page;
  638. if (order >= MAX_PAGE_ORDER - 1)
  639. return false;
  640. higher_page_pfn = buddy_pfn & pfn;
  641. higher_page = page + (higher_page_pfn - pfn);
  642. return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1,
  643. NULL) != NULL;
  644. }
  645. /*
  646. * Freeing function for a buddy system allocator.
  647. *
  648. * The concept of a buddy system is to maintain direct-mapped table
  649. * (containing bit values) for memory blocks of various "orders".
  650. * The bottom level table contains the map for the smallest allocatable
  651. * units of memory (here, pages), and each level above it describes
  652. * pairs of units from the levels below, hence, "buddies".
  653. * At a high level, all that happens here is marking the table entry
  654. * at the bottom level available, and propagating the changes upward
  655. * as necessary, plus some accounting needed to play nicely with other
  656. * parts of the VM system.
  657. * At each level, we keep a list of pages, which are heads of continuous
  658. * free pages of length of (1 << order) and marked with PageBuddy.
  659. * Page's order is recorded in page_private(page) field.
  660. * So when we are allocating or freeing one, we can derive the state of the
  661. * other. That is, if we allocate a small block, and both were
  662. * free, the remainder of the region must be split into blocks.
  663. * If a block is freed, and its buddy is also free, then this
  664. * triggers coalescing into a block of larger size.
  665. *
  666. * -- nyc
  667. */
  668. static inline void __free_one_page(struct page *page,
  669. unsigned long pfn,
  670. struct zone *zone, unsigned int order,
  671. int migratetype, fpi_t fpi_flags)
  672. {
  673. struct capture_control *capc = task_capc(zone);
  674. unsigned long buddy_pfn = 0;
  675. unsigned long combined_pfn;
  676. struct page *buddy;
  677. bool to_tail;
  678. VM_BUG_ON(!zone_is_initialized(zone));
  679. VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
  680. VM_BUG_ON(migratetype == -1);
  681. VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
  682. VM_BUG_ON_PAGE(bad_range(zone, page), page);
  683. account_freepages(zone, 1 << order, migratetype);
  684. while (order < MAX_PAGE_ORDER) {
  685. int buddy_mt = migratetype;
  686. if (compaction_capture(capc, page, order, migratetype)) {
  687. account_freepages(zone, -(1 << order), migratetype);
  688. return;
  689. }
  690. buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn);
  691. if (!buddy)
  692. goto done_merging;
  693. if (unlikely(order >= pageblock_order)) {
  694. /*
  695. * We want to prevent merge between freepages on pageblock
  696. * without fallbacks and normal pageblock. Without this,
  697. * pageblock isolation could cause incorrect freepage or CMA
  698. * accounting or HIGHATOMIC accounting.
  699. */
  700. buddy_mt = get_pfnblock_migratetype(buddy, buddy_pfn);
  701. if (migratetype != buddy_mt &&
  702. (!migratetype_is_mergeable(migratetype) ||
  703. !migratetype_is_mergeable(buddy_mt)))
  704. goto done_merging;
  705. }
  706. /*
  707. * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
  708. * merge with it and move up one order.
  709. */
  710. if (page_is_guard(buddy))
  711. clear_page_guard(zone, buddy, order);
  712. else
  713. __del_page_from_free_list(buddy, zone, order, buddy_mt);
  714. if (unlikely(buddy_mt != migratetype)) {
  715. /*
  716. * Match buddy type. This ensures that an
  717. * expand() down the line puts the sub-blocks
  718. * on the right freelists.
  719. */
  720. set_pageblock_migratetype(buddy, migratetype);
  721. }
  722. combined_pfn = buddy_pfn & pfn;
  723. page = page + (combined_pfn - pfn);
  724. pfn = combined_pfn;
  725. order++;
  726. }
  727. done_merging:
  728. set_buddy_order(page, order);
  729. if (fpi_flags & FPI_TO_TAIL)
  730. to_tail = true;
  731. else if (is_shuffle_order(order))
  732. to_tail = shuffle_pick_tail();
  733. else
  734. to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
  735. __add_to_free_list(page, zone, order, migratetype, to_tail);
  736. /* Notify page reporting subsystem of freed page */
  737. if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
  738. page_reporting_notify_free(order);
  739. }
  740. /*
  741. * A bad page could be due to a number of fields. Instead of multiple branches,
  742. * try and check multiple fields with one check. The caller must do a detailed
  743. * check if necessary.
  744. */
  745. static inline bool page_expected_state(struct page *page,
  746. unsigned long check_flags)
  747. {
  748. if (unlikely(atomic_read(&page->_mapcount) != -1))
  749. return false;
  750. if (unlikely((unsigned long)page->mapping |
  751. page_ref_count(page) |
  752. #ifdef CONFIG_MEMCG
  753. page->memcg_data |
  754. #endif
  755. #ifdef CONFIG_PAGE_POOL
  756. ((page->pp_magic & ~0x3UL) == PP_SIGNATURE) |
  757. #endif
  758. (page->flags & check_flags)))
  759. return false;
  760. return true;
  761. }
  762. static const char *page_bad_reason(struct page *page, unsigned long flags)
  763. {
  764. const char *bad_reason = NULL;
  765. if (unlikely(atomic_read(&page->_mapcount) != -1))
  766. bad_reason = "nonzero mapcount";
  767. if (unlikely(page->mapping != NULL))
  768. bad_reason = "non-NULL mapping";
  769. if (unlikely(page_ref_count(page) != 0))
  770. bad_reason = "nonzero _refcount";
  771. if (unlikely(page->flags & flags)) {
  772. if (flags == PAGE_FLAGS_CHECK_AT_PREP)
  773. bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
  774. else
  775. bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
  776. }
  777. #ifdef CONFIG_MEMCG
  778. if (unlikely(page->memcg_data))
  779. bad_reason = "page still charged to cgroup";
  780. #endif
  781. #ifdef CONFIG_PAGE_POOL
  782. if (unlikely((page->pp_magic & ~0x3UL) == PP_SIGNATURE))
  783. bad_reason = "page_pool leak";
  784. #endif
  785. return bad_reason;
  786. }
  787. static void free_page_is_bad_report(struct page *page)
  788. {
  789. bad_page(page,
  790. page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
  791. }
  792. static inline bool free_page_is_bad(struct page *page)
  793. {
  794. if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
  795. return false;
  796. /* Something has gone sideways, find it */
  797. free_page_is_bad_report(page);
  798. return true;
  799. }
  800. static inline bool is_check_pages_enabled(void)
  801. {
  802. return static_branch_unlikely(&check_pages_enabled);
  803. }
  804. static int free_tail_page_prepare(struct page *head_page, struct page *page)
  805. {
  806. struct folio *folio = (struct folio *)head_page;
  807. int ret = 1;
  808. /*
  809. * We rely page->lru.next never has bit 0 set, unless the page
  810. * is PageTail(). Let's make sure that's true even for poisoned ->lru.
  811. */
  812. BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
  813. if (!is_check_pages_enabled()) {
  814. ret = 0;
  815. goto out;
  816. }
  817. switch (page - head_page) {
  818. case 1:
  819. /* the first tail page: these may be in place of ->mapping */
  820. if (unlikely(folio_entire_mapcount(folio))) {
  821. bad_page(page, "nonzero entire_mapcount");
  822. goto out;
  823. }
  824. if (unlikely(folio_large_mapcount(folio))) {
  825. bad_page(page, "nonzero large_mapcount");
  826. goto out;
  827. }
  828. if (unlikely(atomic_read(&folio->_nr_pages_mapped))) {
  829. bad_page(page, "nonzero nr_pages_mapped");
  830. goto out;
  831. }
  832. if (unlikely(atomic_read(&folio->_pincount))) {
  833. bad_page(page, "nonzero pincount");
  834. goto out;
  835. }
  836. break;
  837. case 2:
  838. /* the second tail page: deferred_list overlaps ->mapping */
  839. if (unlikely(!list_empty(&folio->_deferred_list))) {
  840. bad_page(page, "on deferred list");
  841. goto out;
  842. }
  843. break;
  844. default:
  845. if (page->mapping != TAIL_MAPPING) {
  846. bad_page(page, "corrupted mapping in tail page");
  847. goto out;
  848. }
  849. break;
  850. }
  851. if (unlikely(!PageTail(page))) {
  852. bad_page(page, "PageTail not set");
  853. goto out;
  854. }
  855. if (unlikely(compound_head(page) != head_page)) {
  856. bad_page(page, "compound_head not consistent");
  857. goto out;
  858. }
  859. ret = 0;
  860. out:
  861. page->mapping = NULL;
  862. clear_compound_head(page);
  863. return ret;
  864. }
  865. /*
  866. * Skip KASAN memory poisoning when either:
  867. *
  868. * 1. For generic KASAN: deferred memory initialization has not yet completed.
  869. * Tag-based KASAN modes skip pages freed via deferred memory initialization
  870. * using page tags instead (see below).
  871. * 2. For tag-based KASAN modes: the page has a match-all KASAN tag, indicating
  872. * that error detection is disabled for accesses via the page address.
  873. *
  874. * Pages will have match-all tags in the following circumstances:
  875. *
  876. * 1. Pages are being initialized for the first time, including during deferred
  877. * memory init; see the call to page_kasan_tag_reset in __init_single_page.
  878. * 2. The allocation was not unpoisoned due to __GFP_SKIP_KASAN, with the
  879. * exception of pages unpoisoned by kasan_unpoison_vmalloc.
  880. * 3. The allocation was excluded from being checked due to sampling,
  881. * see the call to kasan_unpoison_pages.
  882. *
  883. * Poisoning pages during deferred memory init will greatly lengthen the
  884. * process and cause problem in large memory systems as the deferred pages
  885. * initialization is done with interrupt disabled.
  886. *
  887. * Assuming that there will be no reference to those newly initialized
  888. * pages before they are ever allocated, this should have no effect on
  889. * KASAN memory tracking as the poison will be properly inserted at page
  890. * allocation time. The only corner case is when pages are allocated by
  891. * on-demand allocation and then freed again before the deferred pages
  892. * initialization is done, but this is not likely to happen.
  893. */
  894. static inline bool should_skip_kasan_poison(struct page *page)
  895. {
  896. if (IS_ENABLED(CONFIG_KASAN_GENERIC))
  897. return deferred_pages_enabled();
  898. return page_kasan_tag(page) == KASAN_TAG_KERNEL;
  899. }
  900. static void kernel_init_pages(struct page *page, int numpages)
  901. {
  902. int i;
  903. /* s390's use of memset() could override KASAN redzones. */
  904. kasan_disable_current();
  905. for (i = 0; i < numpages; i++)
  906. clear_highpage_kasan_tagged(page + i);
  907. kasan_enable_current();
  908. }
  909. __always_inline bool free_pages_prepare(struct page *page,
  910. unsigned int order)
  911. {
  912. int bad = 0;
  913. bool skip_kasan_poison = should_skip_kasan_poison(page);
  914. bool init = want_init_on_free();
  915. bool compound = PageCompound(page);
  916. struct folio *folio = page_folio(page);
  917. VM_BUG_ON_PAGE(PageTail(page), page);
  918. trace_mm_page_free(page, order);
  919. kmsan_free_page(page, order);
  920. if (memcg_kmem_online() && PageMemcgKmem(page))
  921. __memcg_kmem_uncharge_page(page, order);
  922. /*
  923. * In rare cases, when truncation or holepunching raced with
  924. * munlock after VM_LOCKED was cleared, Mlocked may still be
  925. * found set here. This does not indicate a problem, unless
  926. * "unevictable_pgs_cleared" appears worryingly large.
  927. */
  928. if (unlikely(folio_test_mlocked(folio))) {
  929. long nr_pages = folio_nr_pages(folio);
  930. __folio_clear_mlocked(folio);
  931. zone_stat_mod_folio(folio, NR_MLOCK, -nr_pages);
  932. count_vm_events(UNEVICTABLE_PGCLEARED, nr_pages);
  933. }
  934. if (unlikely(PageHWPoison(page)) && !order) {
  935. /* Do not let hwpoison pages hit pcplists/buddy */
  936. reset_page_owner(page, order);
  937. page_table_check_free(page, order);
  938. pgalloc_tag_sub(page, 1 << order);
  939. /*
  940. * The page is isolated and accounted for.
  941. * Mark the codetag as empty to avoid accounting error
  942. * when the page is freed by unpoison_memory().
  943. */
  944. clear_page_tag_ref(page);
  945. return false;
  946. }
  947. VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
  948. /*
  949. * Check tail pages before head page information is cleared to
  950. * avoid checking PageCompound for order-0 pages.
  951. */
  952. if (unlikely(order)) {
  953. int i;
  954. if (compound)
  955. page[1].flags &= ~PAGE_FLAGS_SECOND;
  956. for (i = 1; i < (1 << order); i++) {
  957. if (compound)
  958. bad += free_tail_page_prepare(page, page + i);
  959. if (is_check_pages_enabled()) {
  960. if (free_page_is_bad(page + i)) {
  961. bad++;
  962. continue;
  963. }
  964. }
  965. (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  966. }
  967. }
  968. if (PageMappingFlags(page)) {
  969. if (PageAnon(page))
  970. mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1);
  971. page->mapping = NULL;
  972. }
  973. if (is_check_pages_enabled()) {
  974. if (free_page_is_bad(page))
  975. bad++;
  976. if (bad)
  977. return false;
  978. }
  979. page_cpupid_reset_last(page);
  980. page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  981. reset_page_owner(page, order);
  982. page_table_check_free(page, order);
  983. pgalloc_tag_sub(page, 1 << order);
  984. if (!PageHighMem(page)) {
  985. debug_check_no_locks_freed(page_address(page),
  986. PAGE_SIZE << order);
  987. debug_check_no_obj_freed(page_address(page),
  988. PAGE_SIZE << order);
  989. }
  990. kernel_poison_pages(page, 1 << order);
  991. /*
  992. * As memory initialization might be integrated into KASAN,
  993. * KASAN poisoning and memory initialization code must be
  994. * kept together to avoid discrepancies in behavior.
  995. *
  996. * With hardware tag-based KASAN, memory tags must be set before the
  997. * page becomes unavailable via debug_pagealloc or arch_free_page.
  998. */
  999. if (!skip_kasan_poison) {
  1000. kasan_poison_pages(page, order, init);
  1001. /* Memory is already initialized if KASAN did it internally. */
  1002. if (kasan_has_integrated_init())
  1003. init = false;
  1004. }
  1005. if (init)
  1006. kernel_init_pages(page, 1 << order);
  1007. /*
  1008. * arch_free_page() can make the page's contents inaccessible. s390
  1009. * does this. So nothing which can access the page's contents should
  1010. * happen after this.
  1011. */
  1012. arch_free_page(page, order);
  1013. debug_pagealloc_unmap_pages(page, 1 << order);
  1014. return true;
  1015. }
  1016. /*
  1017. * Frees a number of pages from the PCP lists
  1018. * Assumes all pages on list are in same zone.
  1019. * count is the number of pages to free.
  1020. */
  1021. static void free_pcppages_bulk(struct zone *zone, int count,
  1022. struct per_cpu_pages *pcp,
  1023. int pindex)
  1024. {
  1025. unsigned long flags;
  1026. unsigned int order;
  1027. struct page *page;
  1028. /*
  1029. * Ensure proper count is passed which otherwise would stuck in the
  1030. * below while (list_empty(list)) loop.
  1031. */
  1032. count = min(pcp->count, count);
  1033. /* Ensure requested pindex is drained first. */
  1034. pindex = pindex - 1;
  1035. spin_lock_irqsave(&zone->lock, flags);
  1036. while (count > 0) {
  1037. struct list_head *list;
  1038. int nr_pages;
  1039. /* Remove pages from lists in a round-robin fashion. */
  1040. do {
  1041. if (++pindex > NR_PCP_LISTS - 1)
  1042. pindex = 0;
  1043. list = &pcp->lists[pindex];
  1044. } while (list_empty(list));
  1045. order = pindex_to_order(pindex);
  1046. nr_pages = 1 << order;
  1047. do {
  1048. unsigned long pfn;
  1049. int mt;
  1050. page = list_last_entry(list, struct page, pcp_list);
  1051. pfn = page_to_pfn(page);
  1052. mt = get_pfnblock_migratetype(page, pfn);
  1053. /* must delete to avoid corrupting pcp list */
  1054. list_del(&page->pcp_list);
  1055. count -= nr_pages;
  1056. pcp->count -= nr_pages;
  1057. __free_one_page(page, pfn, zone, order, mt, FPI_NONE);
  1058. trace_mm_page_pcpu_drain(page, order, mt);
  1059. } while (count > 0 && !list_empty(list));
  1060. }
  1061. spin_unlock_irqrestore(&zone->lock, flags);
  1062. }
  1063. /* Split a multi-block free page into its individual pageblocks. */
  1064. static void split_large_buddy(struct zone *zone, struct page *page,
  1065. unsigned long pfn, int order, fpi_t fpi)
  1066. {
  1067. unsigned long end = pfn + (1 << order);
  1068. VM_WARN_ON_ONCE(!IS_ALIGNED(pfn, 1 << order));
  1069. /* Caller removed page from freelist, buddy info cleared! */
  1070. VM_WARN_ON_ONCE(PageBuddy(page));
  1071. if (order > pageblock_order)
  1072. order = pageblock_order;
  1073. do {
  1074. int mt = get_pfnblock_migratetype(page, pfn);
  1075. __free_one_page(page, pfn, zone, order, mt, fpi);
  1076. pfn += 1 << order;
  1077. if (pfn == end)
  1078. break;
  1079. page = pfn_to_page(pfn);
  1080. } while (1);
  1081. }
  1082. static void free_one_page(struct zone *zone, struct page *page,
  1083. unsigned long pfn, unsigned int order,
  1084. fpi_t fpi_flags)
  1085. {
  1086. unsigned long flags;
  1087. spin_lock_irqsave(&zone->lock, flags);
  1088. split_large_buddy(zone, page, pfn, order, fpi_flags);
  1089. spin_unlock_irqrestore(&zone->lock, flags);
  1090. __count_vm_events(PGFREE, 1 << order);
  1091. }
  1092. static void __free_pages_ok(struct page *page, unsigned int order,
  1093. fpi_t fpi_flags)
  1094. {
  1095. unsigned long pfn = page_to_pfn(page);
  1096. struct zone *zone = page_zone(page);
  1097. if (free_pages_prepare(page, order))
  1098. free_one_page(zone, page, pfn, order, fpi_flags);
  1099. }
  1100. void __meminit __free_pages_core(struct page *page, unsigned int order,
  1101. enum meminit_context context)
  1102. {
  1103. unsigned int nr_pages = 1 << order;
  1104. struct page *p = page;
  1105. unsigned int loop;
  1106. /*
  1107. * When initializing the memmap, __init_single_page() sets the refcount
  1108. * of all pages to 1 ("allocated"/"not free"). We have to set the
  1109. * refcount of all involved pages to 0.
  1110. *
  1111. * Note that hotplugged memory pages are initialized to PageOffline().
  1112. * Pages freed from memblock might be marked as reserved.
  1113. */
  1114. if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG) &&
  1115. unlikely(context == MEMINIT_HOTPLUG)) {
  1116. for (loop = 0; loop < nr_pages; loop++, p++) {
  1117. VM_WARN_ON_ONCE(PageReserved(p));
  1118. __ClearPageOffline(p);
  1119. set_page_count(p, 0);
  1120. }
  1121. /*
  1122. * Freeing the page with debug_pagealloc enabled will try to
  1123. * unmap it; some archs don't like double-unmappings, so
  1124. * map it first.
  1125. */
  1126. debug_pagealloc_map_pages(page, nr_pages);
  1127. adjust_managed_page_count(page, nr_pages);
  1128. } else {
  1129. for (loop = 0; loop < nr_pages; loop++, p++) {
  1130. __ClearPageReserved(p);
  1131. set_page_count(p, 0);
  1132. }
  1133. /* memblock adjusts totalram_pages() manually. */
  1134. atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
  1135. }
  1136. if (page_contains_unaccepted(page, order)) {
  1137. if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
  1138. return;
  1139. accept_memory(page_to_phys(page), PAGE_SIZE << order);
  1140. }
  1141. /*
  1142. * Bypass PCP and place fresh pages right to the tail, primarily
  1143. * relevant for memory onlining.
  1144. */
  1145. __free_pages_ok(page, order, FPI_TO_TAIL);
  1146. }
  1147. /*
  1148. * Check that the whole (or subset of) a pageblock given by the interval of
  1149. * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
  1150. * with the migration of free compaction scanner.
  1151. *
  1152. * Return struct page pointer of start_pfn, or NULL if checks were not passed.
  1153. *
  1154. * It's possible on some configurations to have a setup like node0 node1 node0
  1155. * i.e. it's possible that all pages within a zones range of pages do not
  1156. * belong to a single zone. We assume that a border between node0 and node1
  1157. * can occur within a single pageblock, but not a node0 node1 node0
  1158. * interleaving within a single pageblock. It is therefore sufficient to check
  1159. * the first and last page of a pageblock and avoid checking each individual
  1160. * page in a pageblock.
  1161. *
  1162. * Note: the function may return non-NULL struct page even for a page block
  1163. * which contains a memory hole (i.e. there is no physical memory for a subset
  1164. * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
  1165. * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
  1166. * even though the start pfn is online and valid. This should be safe most of
  1167. * the time because struct pages are still initialized via init_unavailable_range()
  1168. * and pfn walkers shouldn't touch any physical memory range for which they do
  1169. * not recognize any specific metadata in struct pages.
  1170. */
  1171. struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
  1172. unsigned long end_pfn, struct zone *zone)
  1173. {
  1174. struct page *start_page;
  1175. struct page *end_page;
  1176. /* end_pfn is one past the range we are checking */
  1177. end_pfn--;
  1178. if (!pfn_valid(end_pfn))
  1179. return NULL;
  1180. start_page = pfn_to_online_page(start_pfn);
  1181. if (!start_page)
  1182. return NULL;
  1183. if (page_zone(start_page) != zone)
  1184. return NULL;
  1185. end_page = pfn_to_page(end_pfn);
  1186. /* This gives a shorter code than deriving page_zone(end_page) */
  1187. if (page_zone_id(start_page) != page_zone_id(end_page))
  1188. return NULL;
  1189. return start_page;
  1190. }
  1191. /*
  1192. * The order of subdivision here is critical for the IO subsystem.
  1193. * Please do not alter this order without good reasons and regression
  1194. * testing. Specifically, as large blocks of memory are subdivided,
  1195. * the order in which smaller blocks are delivered depends on the order
  1196. * they're subdivided in this function. This is the primary factor
  1197. * influencing the order in which pages are delivered to the IO
  1198. * subsystem according to empirical testing, and this is also justified
  1199. * by considering the behavior of a buddy system containing a single
  1200. * large block of memory acted on by a series of small allocations.
  1201. * This behavior is a critical factor in sglist merging's success.
  1202. *
  1203. * -- nyc
  1204. */
  1205. static inline unsigned int expand(struct zone *zone, struct page *page, int low,
  1206. int high, int migratetype)
  1207. {
  1208. unsigned int size = 1 << high;
  1209. unsigned int nr_added = 0;
  1210. while (high > low) {
  1211. high--;
  1212. size >>= 1;
  1213. VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
  1214. /*
  1215. * Mark as guard pages (or page), that will allow to
  1216. * merge back to allocator when buddy will be freed.
  1217. * Corresponding page table entries will not be touched,
  1218. * pages will stay not present in virtual address space
  1219. */
  1220. if (set_page_guard(zone, &page[size], high))
  1221. continue;
  1222. __add_to_free_list(&page[size], zone, high, migratetype, false);
  1223. set_buddy_order(&page[size], high);
  1224. nr_added += size;
  1225. }
  1226. return nr_added;
  1227. }
  1228. static __always_inline void page_del_and_expand(struct zone *zone,
  1229. struct page *page, int low,
  1230. int high, int migratetype)
  1231. {
  1232. int nr_pages = 1 << high;
  1233. __del_page_from_free_list(page, zone, high, migratetype);
  1234. nr_pages -= expand(zone, page, low, high, migratetype);
  1235. account_freepages(zone, -nr_pages, migratetype);
  1236. }
  1237. static void check_new_page_bad(struct page *page)
  1238. {
  1239. if (unlikely(page->flags & __PG_HWPOISON)) {
  1240. /* Don't complain about hwpoisoned pages */
  1241. if (PageBuddy(page))
  1242. __ClearPageBuddy(page);
  1243. return;
  1244. }
  1245. bad_page(page,
  1246. page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
  1247. }
  1248. /*
  1249. * This page is about to be returned from the page allocator
  1250. */
  1251. static bool check_new_page(struct page *page)
  1252. {
  1253. if (likely(page_expected_state(page,
  1254. PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
  1255. return false;
  1256. check_new_page_bad(page);
  1257. return true;
  1258. }
  1259. static inline bool check_new_pages(struct page *page, unsigned int order)
  1260. {
  1261. if (is_check_pages_enabled()) {
  1262. for (int i = 0; i < (1 << order); i++) {
  1263. struct page *p = page + i;
  1264. if (check_new_page(p))
  1265. return true;
  1266. }
  1267. }
  1268. return false;
  1269. }
  1270. static inline bool should_skip_kasan_unpoison(gfp_t flags)
  1271. {
  1272. /* Don't skip if a software KASAN mode is enabled. */
  1273. if (IS_ENABLED(CONFIG_KASAN_GENERIC) ||
  1274. IS_ENABLED(CONFIG_KASAN_SW_TAGS))
  1275. return false;
  1276. /* Skip, if hardware tag-based KASAN is not enabled. */
  1277. if (!kasan_hw_tags_enabled())
  1278. return true;
  1279. /*
  1280. * With hardware tag-based KASAN enabled, skip if this has been
  1281. * requested via __GFP_SKIP_KASAN.
  1282. */
  1283. return flags & __GFP_SKIP_KASAN;
  1284. }
  1285. static inline bool should_skip_init(gfp_t flags)
  1286. {
  1287. /* Don't skip, if hardware tag-based KASAN is not enabled. */
  1288. if (!kasan_hw_tags_enabled())
  1289. return false;
  1290. /* For hardware tag-based KASAN, skip if requested. */
  1291. return (flags & __GFP_SKIP_ZERO);
  1292. }
  1293. inline void post_alloc_hook(struct page *page, unsigned int order,
  1294. gfp_t gfp_flags)
  1295. {
  1296. bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) &&
  1297. !should_skip_init(gfp_flags);
  1298. bool zero_tags = init && (gfp_flags & __GFP_ZEROTAGS);
  1299. int i;
  1300. set_page_private(page, 0);
  1301. set_page_refcounted(page);
  1302. arch_alloc_page(page, order);
  1303. debug_pagealloc_map_pages(page, 1 << order);
  1304. /*
  1305. * Page unpoisoning must happen before memory initialization.
  1306. * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
  1307. * allocations and the page unpoisoning code will complain.
  1308. */
  1309. kernel_unpoison_pages(page, 1 << order);
  1310. /*
  1311. * As memory initialization might be integrated into KASAN,
  1312. * KASAN unpoisoning and memory initializion code must be
  1313. * kept together to avoid discrepancies in behavior.
  1314. */
  1315. /*
  1316. * If memory tags should be zeroed
  1317. * (which happens only when memory should be initialized as well).
  1318. */
  1319. if (zero_tags) {
  1320. /* Initialize both memory and memory tags. */
  1321. for (i = 0; i != 1 << order; ++i)
  1322. tag_clear_highpage(page + i);
  1323. /* Take note that memory was initialized by the loop above. */
  1324. init = false;
  1325. }
  1326. if (!should_skip_kasan_unpoison(gfp_flags) &&
  1327. kasan_unpoison_pages(page, order, init)) {
  1328. /* Take note that memory was initialized by KASAN. */
  1329. if (kasan_has_integrated_init())
  1330. init = false;
  1331. } else {
  1332. /*
  1333. * If memory tags have not been set by KASAN, reset the page
  1334. * tags to ensure page_address() dereferencing does not fault.
  1335. */
  1336. for (i = 0; i != 1 << order; ++i)
  1337. page_kasan_tag_reset(page + i);
  1338. }
  1339. /* If memory is still not initialized, initialize it now. */
  1340. if (init)
  1341. kernel_init_pages(page, 1 << order);
  1342. set_page_owner(page, order, gfp_flags);
  1343. page_table_check_alloc(page, order);
  1344. pgalloc_tag_add(page, current, 1 << order);
  1345. }
  1346. static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
  1347. unsigned int alloc_flags)
  1348. {
  1349. post_alloc_hook(page, order, gfp_flags);
  1350. if (order && (gfp_flags & __GFP_COMP))
  1351. prep_compound_page(page, order);
  1352. /*
  1353. * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
  1354. * allocate the page. The expectation is that the caller is taking
  1355. * steps that will free more memory. The caller should avoid the page
  1356. * being used for !PFMEMALLOC purposes.
  1357. */
  1358. if (alloc_flags & ALLOC_NO_WATERMARKS)
  1359. set_page_pfmemalloc(page);
  1360. else
  1361. clear_page_pfmemalloc(page);
  1362. }
  1363. /*
  1364. * Go through the free lists for the given migratetype and remove
  1365. * the smallest available page from the freelists
  1366. */
  1367. static __always_inline
  1368. struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
  1369. int migratetype)
  1370. {
  1371. unsigned int current_order;
  1372. struct free_area *area;
  1373. struct page *page;
  1374. /* Find a page of the appropriate size in the preferred list */
  1375. for (current_order = order; current_order < NR_PAGE_ORDERS; ++current_order) {
  1376. area = &(zone->free_area[current_order]);
  1377. page = get_page_from_free_area(area, migratetype);
  1378. if (!page)
  1379. continue;
  1380. page_del_and_expand(zone, page, order, current_order,
  1381. migratetype);
  1382. trace_mm_page_alloc_zone_locked(page, order, migratetype,
  1383. pcp_allowed_order(order) &&
  1384. migratetype < MIGRATE_PCPTYPES);
  1385. return page;
  1386. }
  1387. return NULL;
  1388. }
  1389. /*
  1390. * This array describes the order lists are fallen back to when
  1391. * the free lists for the desirable migrate type are depleted
  1392. *
  1393. * The other migratetypes do not have fallbacks.
  1394. */
  1395. static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = {
  1396. [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE },
  1397. [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE },
  1398. [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE },
  1399. };
  1400. #ifdef CONFIG_CMA
  1401. static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1402. unsigned int order)
  1403. {
  1404. return __rmqueue_smallest(zone, order, MIGRATE_CMA);
  1405. }
  1406. #else
  1407. static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1408. unsigned int order) { return NULL; }
  1409. #endif
  1410. /*
  1411. * Change the type of a block and move all its free pages to that
  1412. * type's freelist.
  1413. */
  1414. static int __move_freepages_block(struct zone *zone, unsigned long start_pfn,
  1415. int old_mt, int new_mt)
  1416. {
  1417. struct page *page;
  1418. unsigned long pfn, end_pfn;
  1419. unsigned int order;
  1420. int pages_moved = 0;
  1421. VM_WARN_ON(start_pfn & (pageblock_nr_pages - 1));
  1422. end_pfn = pageblock_end_pfn(start_pfn);
  1423. for (pfn = start_pfn; pfn < end_pfn;) {
  1424. page = pfn_to_page(pfn);
  1425. if (!PageBuddy(page)) {
  1426. pfn++;
  1427. continue;
  1428. }
  1429. /* Make sure we are not inadvertently changing nodes */
  1430. VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
  1431. VM_BUG_ON_PAGE(page_zone(page) != zone, page);
  1432. order = buddy_order(page);
  1433. move_to_free_list(page, zone, order, old_mt, new_mt);
  1434. pfn += 1 << order;
  1435. pages_moved += 1 << order;
  1436. }
  1437. set_pageblock_migratetype(pfn_to_page(start_pfn), new_mt);
  1438. return pages_moved;
  1439. }
  1440. static bool prep_move_freepages_block(struct zone *zone, struct page *page,
  1441. unsigned long *start_pfn,
  1442. int *num_free, int *num_movable)
  1443. {
  1444. unsigned long pfn, start, end;
  1445. pfn = page_to_pfn(page);
  1446. start = pageblock_start_pfn(pfn);
  1447. end = pageblock_end_pfn(pfn);
  1448. /*
  1449. * The caller only has the lock for @zone, don't touch ranges
  1450. * that straddle into other zones. While we could move part of
  1451. * the range that's inside the zone, this call is usually
  1452. * accompanied by other operations such as migratetype updates
  1453. * which also should be locked.
  1454. */
  1455. if (!zone_spans_pfn(zone, start))
  1456. return false;
  1457. if (!zone_spans_pfn(zone, end - 1))
  1458. return false;
  1459. *start_pfn = start;
  1460. if (num_free) {
  1461. *num_free = 0;
  1462. *num_movable = 0;
  1463. for (pfn = start; pfn < end;) {
  1464. page = pfn_to_page(pfn);
  1465. if (PageBuddy(page)) {
  1466. int nr = 1 << buddy_order(page);
  1467. *num_free += nr;
  1468. pfn += nr;
  1469. continue;
  1470. }
  1471. /*
  1472. * We assume that pages that could be isolated for
  1473. * migration are movable. But we don't actually try
  1474. * isolating, as that would be expensive.
  1475. */
  1476. if (PageLRU(page) || __PageMovable(page))
  1477. (*num_movable)++;
  1478. pfn++;
  1479. }
  1480. }
  1481. return true;
  1482. }
  1483. static int move_freepages_block(struct zone *zone, struct page *page,
  1484. int old_mt, int new_mt)
  1485. {
  1486. unsigned long start_pfn;
  1487. if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
  1488. return -1;
  1489. return __move_freepages_block(zone, start_pfn, old_mt, new_mt);
  1490. }
  1491. #ifdef CONFIG_MEMORY_ISOLATION
  1492. /* Look for a buddy that straddles start_pfn */
  1493. static unsigned long find_large_buddy(unsigned long start_pfn)
  1494. {
  1495. int order = 0;
  1496. struct page *page;
  1497. unsigned long pfn = start_pfn;
  1498. while (!PageBuddy(page = pfn_to_page(pfn))) {
  1499. /* Nothing found */
  1500. if (++order > MAX_PAGE_ORDER)
  1501. return start_pfn;
  1502. pfn &= ~0UL << order;
  1503. }
  1504. /*
  1505. * Found a preceding buddy, but does it straddle?
  1506. */
  1507. if (pfn + (1 << buddy_order(page)) > start_pfn)
  1508. return pfn;
  1509. /* Nothing found */
  1510. return start_pfn;
  1511. }
  1512. /**
  1513. * move_freepages_block_isolate - move free pages in block for page isolation
  1514. * @zone: the zone
  1515. * @page: the pageblock page
  1516. * @migratetype: migratetype to set on the pageblock
  1517. *
  1518. * This is similar to move_freepages_block(), but handles the special
  1519. * case encountered in page isolation, where the block of interest
  1520. * might be part of a larger buddy spanning multiple pageblocks.
  1521. *
  1522. * Unlike the regular page allocator path, which moves pages while
  1523. * stealing buddies off the freelist, page isolation is interested in
  1524. * arbitrary pfn ranges that may have overlapping buddies on both ends.
  1525. *
  1526. * This function handles that. Straddling buddies are split into
  1527. * individual pageblocks. Only the block of interest is moved.
  1528. *
  1529. * Returns %true if pages could be moved, %false otherwise.
  1530. */
  1531. bool move_freepages_block_isolate(struct zone *zone, struct page *page,
  1532. int migratetype)
  1533. {
  1534. unsigned long start_pfn, pfn;
  1535. if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
  1536. return false;
  1537. /* No splits needed if buddies can't span multiple blocks */
  1538. if (pageblock_order == MAX_PAGE_ORDER)
  1539. goto move;
  1540. /* We're a tail block in a larger buddy */
  1541. pfn = find_large_buddy(start_pfn);
  1542. if (pfn != start_pfn) {
  1543. struct page *buddy = pfn_to_page(pfn);
  1544. int order = buddy_order(buddy);
  1545. del_page_from_free_list(buddy, zone, order,
  1546. get_pfnblock_migratetype(buddy, pfn));
  1547. set_pageblock_migratetype(page, migratetype);
  1548. split_large_buddy(zone, buddy, pfn, order, FPI_NONE);
  1549. return true;
  1550. }
  1551. /* We're the starting block of a larger buddy */
  1552. if (PageBuddy(page) && buddy_order(page) > pageblock_order) {
  1553. int order = buddy_order(page);
  1554. del_page_from_free_list(page, zone, order,
  1555. get_pfnblock_migratetype(page, pfn));
  1556. set_pageblock_migratetype(page, migratetype);
  1557. split_large_buddy(zone, page, pfn, order, FPI_NONE);
  1558. return true;
  1559. }
  1560. move:
  1561. __move_freepages_block(zone, start_pfn,
  1562. get_pfnblock_migratetype(page, start_pfn),
  1563. migratetype);
  1564. return true;
  1565. }
  1566. #endif /* CONFIG_MEMORY_ISOLATION */
  1567. static void change_pageblock_range(struct page *pageblock_page,
  1568. int start_order, int migratetype)
  1569. {
  1570. int nr_pageblocks = 1 << (start_order - pageblock_order);
  1571. while (nr_pageblocks--) {
  1572. set_pageblock_migratetype(pageblock_page, migratetype);
  1573. pageblock_page += pageblock_nr_pages;
  1574. }
  1575. }
  1576. /*
  1577. * When we are falling back to another migratetype during allocation, try to
  1578. * steal extra free pages from the same pageblocks to satisfy further
  1579. * allocations, instead of polluting multiple pageblocks.
  1580. *
  1581. * If we are stealing a relatively large buddy page, it is likely there will
  1582. * be more free pages in the pageblock, so try to steal them all. For
  1583. * reclaimable and unmovable allocations, we steal regardless of page size,
  1584. * as fragmentation caused by those allocations polluting movable pageblocks
  1585. * is worse than movable allocations stealing from unmovable and reclaimable
  1586. * pageblocks.
  1587. */
  1588. static bool can_steal_fallback(unsigned int order, int start_mt)
  1589. {
  1590. /*
  1591. * Leaving this order check is intended, although there is
  1592. * relaxed order check in next check. The reason is that
  1593. * we can actually steal whole pageblock if this condition met,
  1594. * but, below check doesn't guarantee it and that is just heuristic
  1595. * so could be changed anytime.
  1596. */
  1597. if (order >= pageblock_order)
  1598. return true;
  1599. if (order >= pageblock_order / 2 ||
  1600. start_mt == MIGRATE_RECLAIMABLE ||
  1601. start_mt == MIGRATE_UNMOVABLE ||
  1602. page_group_by_mobility_disabled)
  1603. return true;
  1604. return false;
  1605. }
  1606. static inline bool boost_watermark(struct zone *zone)
  1607. {
  1608. unsigned long max_boost;
  1609. if (!watermark_boost_factor)
  1610. return false;
  1611. /*
  1612. * Don't bother in zones that are unlikely to produce results.
  1613. * On small machines, including kdump capture kernels running
  1614. * in a small area, boosting the watermark can cause an out of
  1615. * memory situation immediately.
  1616. */
  1617. if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
  1618. return false;
  1619. max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
  1620. watermark_boost_factor, 10000);
  1621. /*
  1622. * high watermark may be uninitialised if fragmentation occurs
  1623. * very early in boot so do not boost. We do not fall
  1624. * through and boost by pageblock_nr_pages as failing
  1625. * allocations that early means that reclaim is not going
  1626. * to help and it may even be impossible to reclaim the
  1627. * boosted watermark resulting in a hang.
  1628. */
  1629. if (!max_boost)
  1630. return false;
  1631. max_boost = max(pageblock_nr_pages, max_boost);
  1632. zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
  1633. max_boost);
  1634. return true;
  1635. }
  1636. /*
  1637. * This function implements actual steal behaviour. If order is large enough, we
  1638. * can claim the whole pageblock for the requested migratetype. If not, we check
  1639. * the pageblock for constituent pages; if at least half of the pages are free
  1640. * or compatible, we can still claim the whole block, so pages freed in the
  1641. * future will be put on the correct free list. Otherwise, we isolate exactly
  1642. * the order we need from the fallback block and leave its migratetype alone.
  1643. */
  1644. static struct page *
  1645. steal_suitable_fallback(struct zone *zone, struct page *page,
  1646. int current_order, int order, int start_type,
  1647. unsigned int alloc_flags, bool whole_block)
  1648. {
  1649. int free_pages, movable_pages, alike_pages;
  1650. unsigned long start_pfn;
  1651. int block_type;
  1652. block_type = get_pageblock_migratetype(page);
  1653. /*
  1654. * This can happen due to races and we want to prevent broken
  1655. * highatomic accounting.
  1656. */
  1657. if (is_migrate_highatomic(block_type))
  1658. goto single_page;
  1659. /* Take ownership for orders >= pageblock_order */
  1660. if (current_order >= pageblock_order) {
  1661. unsigned int nr_added;
  1662. del_page_from_free_list(page, zone, current_order, block_type);
  1663. change_pageblock_range(page, current_order, start_type);
  1664. nr_added = expand(zone, page, order, current_order, start_type);
  1665. account_freepages(zone, nr_added, start_type);
  1666. return page;
  1667. }
  1668. /*
  1669. * Boost watermarks to increase reclaim pressure to reduce the
  1670. * likelihood of future fallbacks. Wake kswapd now as the node
  1671. * may be balanced overall and kswapd will not wake naturally.
  1672. */
  1673. if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
  1674. set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
  1675. /* We are not allowed to try stealing from the whole block */
  1676. if (!whole_block)
  1677. goto single_page;
  1678. /* moving whole block can fail due to zone boundary conditions */
  1679. if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages,
  1680. &movable_pages))
  1681. goto single_page;
  1682. /*
  1683. * Determine how many pages are compatible with our allocation.
  1684. * For movable allocation, it's the number of movable pages which
  1685. * we just obtained. For other types it's a bit more tricky.
  1686. */
  1687. if (start_type == MIGRATE_MOVABLE) {
  1688. alike_pages = movable_pages;
  1689. } else {
  1690. /*
  1691. * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
  1692. * to MOVABLE pageblock, consider all non-movable pages as
  1693. * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
  1694. * vice versa, be conservative since we can't distinguish the
  1695. * exact migratetype of non-movable pages.
  1696. */
  1697. if (block_type == MIGRATE_MOVABLE)
  1698. alike_pages = pageblock_nr_pages
  1699. - (free_pages + movable_pages);
  1700. else
  1701. alike_pages = 0;
  1702. }
  1703. /*
  1704. * If a sufficient number of pages in the block are either free or of
  1705. * compatible migratability as our allocation, claim the whole block.
  1706. */
  1707. if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
  1708. page_group_by_mobility_disabled) {
  1709. __move_freepages_block(zone, start_pfn, block_type, start_type);
  1710. return __rmqueue_smallest(zone, order, start_type);
  1711. }
  1712. single_page:
  1713. page_del_and_expand(zone, page, order, current_order, block_type);
  1714. return page;
  1715. }
  1716. /*
  1717. * Check whether there is a suitable fallback freepage with requested order.
  1718. * If only_stealable is true, this function returns fallback_mt only if
  1719. * we can steal other freepages all together. This would help to reduce
  1720. * fragmentation due to mixed migratetype pages in one pageblock.
  1721. */
  1722. int find_suitable_fallback(struct free_area *area, unsigned int order,
  1723. int migratetype, bool only_stealable, bool *can_steal)
  1724. {
  1725. int i;
  1726. int fallback_mt;
  1727. if (area->nr_free == 0)
  1728. return -1;
  1729. *can_steal = false;
  1730. for (i = 0; i < MIGRATE_PCPTYPES - 1 ; i++) {
  1731. fallback_mt = fallbacks[migratetype][i];
  1732. if (free_area_empty(area, fallback_mt))
  1733. continue;
  1734. if (can_steal_fallback(order, migratetype))
  1735. *can_steal = true;
  1736. if (!only_stealable)
  1737. return fallback_mt;
  1738. if (*can_steal)
  1739. return fallback_mt;
  1740. }
  1741. return -1;
  1742. }
  1743. /*
  1744. * Reserve the pageblock(s) surrounding an allocation request for
  1745. * exclusive use of high-order atomic allocations if there are no
  1746. * empty page blocks that contain a page with a suitable order
  1747. */
  1748. static void reserve_highatomic_pageblock(struct page *page, int order,
  1749. struct zone *zone)
  1750. {
  1751. int mt;
  1752. unsigned long max_managed, flags;
  1753. /*
  1754. * The number reserved as: minimum is 1 pageblock, maximum is
  1755. * roughly 1% of a zone. But if 1% of a zone falls below a
  1756. * pageblock size, then don't reserve any pageblocks.
  1757. * Check is race-prone but harmless.
  1758. */
  1759. if ((zone_managed_pages(zone) / 100) < pageblock_nr_pages)
  1760. return;
  1761. max_managed = ALIGN((zone_managed_pages(zone) / 100), pageblock_nr_pages);
  1762. if (zone->nr_reserved_highatomic >= max_managed)
  1763. return;
  1764. spin_lock_irqsave(&zone->lock, flags);
  1765. /* Recheck the nr_reserved_highatomic limit under the lock */
  1766. if (zone->nr_reserved_highatomic >= max_managed)
  1767. goto out_unlock;
  1768. /* Yoink! */
  1769. mt = get_pageblock_migratetype(page);
  1770. /* Only reserve normal pageblocks (i.e., they can merge with others) */
  1771. if (!migratetype_is_mergeable(mt))
  1772. goto out_unlock;
  1773. if (order < pageblock_order) {
  1774. if (move_freepages_block(zone, page, mt, MIGRATE_HIGHATOMIC) == -1)
  1775. goto out_unlock;
  1776. zone->nr_reserved_highatomic += pageblock_nr_pages;
  1777. } else {
  1778. change_pageblock_range(page, order, MIGRATE_HIGHATOMIC);
  1779. zone->nr_reserved_highatomic += 1 << order;
  1780. }
  1781. out_unlock:
  1782. spin_unlock_irqrestore(&zone->lock, flags);
  1783. }
  1784. /*
  1785. * Used when an allocation is about to fail under memory pressure. This
  1786. * potentially hurts the reliability of high-order allocations when under
  1787. * intense memory pressure but failed atomic allocations should be easier
  1788. * to recover from than an OOM.
  1789. *
  1790. * If @force is true, try to unreserve pageblocks even though highatomic
  1791. * pageblock is exhausted.
  1792. */
  1793. static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
  1794. bool force)
  1795. {
  1796. struct zonelist *zonelist = ac->zonelist;
  1797. unsigned long flags;
  1798. struct zoneref *z;
  1799. struct zone *zone;
  1800. struct page *page;
  1801. int order;
  1802. int ret;
  1803. for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
  1804. ac->nodemask) {
  1805. /*
  1806. * Preserve at least one pageblock unless memory pressure
  1807. * is really high.
  1808. */
  1809. if (!force && zone->nr_reserved_highatomic <=
  1810. pageblock_nr_pages)
  1811. continue;
  1812. spin_lock_irqsave(&zone->lock, flags);
  1813. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  1814. struct free_area *area = &(zone->free_area[order]);
  1815. int mt;
  1816. page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
  1817. if (!page)
  1818. continue;
  1819. mt = get_pageblock_migratetype(page);
  1820. /*
  1821. * In page freeing path, migratetype change is racy so
  1822. * we can counter several free pages in a pageblock
  1823. * in this loop although we changed the pageblock type
  1824. * from highatomic to ac->migratetype. So we should
  1825. * adjust the count once.
  1826. */
  1827. if (is_migrate_highatomic(mt)) {
  1828. unsigned long size;
  1829. /*
  1830. * It should never happen but changes to
  1831. * locking could inadvertently allow a per-cpu
  1832. * drain to add pages to MIGRATE_HIGHATOMIC
  1833. * while unreserving so be safe and watch for
  1834. * underflows.
  1835. */
  1836. size = max(pageblock_nr_pages, 1UL << order);
  1837. size = min(size, zone->nr_reserved_highatomic);
  1838. zone->nr_reserved_highatomic -= size;
  1839. }
  1840. /*
  1841. * Convert to ac->migratetype and avoid the normal
  1842. * pageblock stealing heuristics. Minimally, the caller
  1843. * is doing the work and needs the pages. More
  1844. * importantly, if the block was always converted to
  1845. * MIGRATE_UNMOVABLE or another type then the number
  1846. * of pageblocks that cannot be completely freed
  1847. * may increase.
  1848. */
  1849. if (order < pageblock_order)
  1850. ret = move_freepages_block(zone, page, mt,
  1851. ac->migratetype);
  1852. else {
  1853. move_to_free_list(page, zone, order, mt,
  1854. ac->migratetype);
  1855. change_pageblock_range(page, order,
  1856. ac->migratetype);
  1857. ret = 1;
  1858. }
  1859. /*
  1860. * Reserving the block(s) already succeeded,
  1861. * so this should not fail on zone boundaries.
  1862. */
  1863. WARN_ON_ONCE(ret == -1);
  1864. if (ret > 0) {
  1865. spin_unlock_irqrestore(&zone->lock, flags);
  1866. return ret;
  1867. }
  1868. }
  1869. spin_unlock_irqrestore(&zone->lock, flags);
  1870. }
  1871. return false;
  1872. }
  1873. /*
  1874. * Try finding a free buddy page on the fallback list and put it on the free
  1875. * list of requested migratetype, possibly along with other pages from the same
  1876. * block, depending on fragmentation avoidance heuristics. Returns true if
  1877. * fallback was found so that __rmqueue_smallest() can grab it.
  1878. *
  1879. * The use of signed ints for order and current_order is a deliberate
  1880. * deviation from the rest of this file, to make the for loop
  1881. * condition simpler.
  1882. */
  1883. static __always_inline struct page *
  1884. __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
  1885. unsigned int alloc_flags)
  1886. {
  1887. struct free_area *area;
  1888. int current_order;
  1889. int min_order = order;
  1890. struct page *page;
  1891. int fallback_mt;
  1892. bool can_steal;
  1893. /*
  1894. * Do not steal pages from freelists belonging to other pageblocks
  1895. * i.e. orders < pageblock_order. If there are no local zones free,
  1896. * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
  1897. */
  1898. if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT)
  1899. min_order = pageblock_order;
  1900. /*
  1901. * Find the largest available free page in the other list. This roughly
  1902. * approximates finding the pageblock with the most free pages, which
  1903. * would be too costly to do exactly.
  1904. */
  1905. for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
  1906. --current_order) {
  1907. area = &(zone->free_area[current_order]);
  1908. fallback_mt = find_suitable_fallback(area, current_order,
  1909. start_migratetype, false, &can_steal);
  1910. if (fallback_mt == -1)
  1911. continue;
  1912. /*
  1913. * We cannot steal all free pages from the pageblock and the
  1914. * requested migratetype is movable. In that case it's better to
  1915. * steal and split the smallest available page instead of the
  1916. * largest available page, because even if the next movable
  1917. * allocation falls back into a different pageblock than this
  1918. * one, it won't cause permanent fragmentation.
  1919. */
  1920. if (!can_steal && start_migratetype == MIGRATE_MOVABLE
  1921. && current_order > order)
  1922. goto find_smallest;
  1923. goto do_steal;
  1924. }
  1925. return NULL;
  1926. find_smallest:
  1927. for (current_order = order; current_order < NR_PAGE_ORDERS; current_order++) {
  1928. area = &(zone->free_area[current_order]);
  1929. fallback_mt = find_suitable_fallback(area, current_order,
  1930. start_migratetype, false, &can_steal);
  1931. if (fallback_mt != -1)
  1932. break;
  1933. }
  1934. /*
  1935. * This should not happen - we already found a suitable fallback
  1936. * when looking for the largest page.
  1937. */
  1938. VM_BUG_ON(current_order > MAX_PAGE_ORDER);
  1939. do_steal:
  1940. page = get_page_from_free_area(area, fallback_mt);
  1941. /* take off list, maybe claim block, expand remainder */
  1942. page = steal_suitable_fallback(zone, page, current_order, order,
  1943. start_migratetype, alloc_flags, can_steal);
  1944. trace_mm_page_alloc_extfrag(page, order, current_order,
  1945. start_migratetype, fallback_mt);
  1946. return page;
  1947. }
  1948. /*
  1949. * Do the hard work of removing an element from the buddy allocator.
  1950. * Call me with the zone->lock already held.
  1951. */
  1952. static __always_inline struct page *
  1953. __rmqueue(struct zone *zone, unsigned int order, int migratetype,
  1954. unsigned int alloc_flags)
  1955. {
  1956. struct page *page;
  1957. if (IS_ENABLED(CONFIG_CMA)) {
  1958. /*
  1959. * Balance movable allocations between regular and CMA areas by
  1960. * allocating from CMA when over half of the zone's free memory
  1961. * is in the CMA area.
  1962. */
  1963. if (alloc_flags & ALLOC_CMA &&
  1964. zone_page_state(zone, NR_FREE_CMA_PAGES) >
  1965. zone_page_state(zone, NR_FREE_PAGES) / 2) {
  1966. page = __rmqueue_cma_fallback(zone, order);
  1967. if (page)
  1968. return page;
  1969. }
  1970. }
  1971. page = __rmqueue_smallest(zone, order, migratetype);
  1972. if (unlikely(!page)) {
  1973. if (alloc_flags & ALLOC_CMA)
  1974. page = __rmqueue_cma_fallback(zone, order);
  1975. if (!page)
  1976. page = __rmqueue_fallback(zone, order, migratetype,
  1977. alloc_flags);
  1978. }
  1979. return page;
  1980. }
  1981. /*
  1982. * Obtain a specified number of elements from the buddy allocator, all under
  1983. * a single hold of the lock, for efficiency. Add them to the supplied list.
  1984. * Returns the number of new pages which were placed at *list.
  1985. */
  1986. static int rmqueue_bulk(struct zone *zone, unsigned int order,
  1987. unsigned long count, struct list_head *list,
  1988. int migratetype, unsigned int alloc_flags)
  1989. {
  1990. unsigned long flags;
  1991. int i;
  1992. spin_lock_irqsave(&zone->lock, flags);
  1993. for (i = 0; i < count; ++i) {
  1994. struct page *page = __rmqueue(zone, order, migratetype,
  1995. alloc_flags);
  1996. if (unlikely(page == NULL))
  1997. break;
  1998. /*
  1999. * Split buddy pages returned by expand() are received here in
  2000. * physical page order. The page is added to the tail of
  2001. * caller's list. From the callers perspective, the linked list
  2002. * is ordered by page number under some conditions. This is
  2003. * useful for IO devices that can forward direction from the
  2004. * head, thus also in the physical page order. This is useful
  2005. * for IO devices that can merge IO requests if the physical
  2006. * pages are ordered properly.
  2007. */
  2008. list_add_tail(&page->pcp_list, list);
  2009. }
  2010. spin_unlock_irqrestore(&zone->lock, flags);
  2011. return i;
  2012. }
  2013. /*
  2014. * Called from the vmstat counter updater to decay the PCP high.
  2015. * Return whether there are addition works to do.
  2016. */
  2017. int decay_pcp_high(struct zone *zone, struct per_cpu_pages *pcp)
  2018. {
  2019. int high_min, to_drain, batch;
  2020. int todo = 0;
  2021. high_min = READ_ONCE(pcp->high_min);
  2022. batch = READ_ONCE(pcp->batch);
  2023. /*
  2024. * Decrease pcp->high periodically to try to free possible
  2025. * idle PCP pages. And, avoid to free too many pages to
  2026. * control latency. This caps pcp->high decrement too.
  2027. */
  2028. if (pcp->high > high_min) {
  2029. pcp->high = max3(pcp->count - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
  2030. pcp->high - (pcp->high >> 3), high_min);
  2031. if (pcp->high > high_min)
  2032. todo++;
  2033. }
  2034. to_drain = pcp->count - pcp->high;
  2035. if (to_drain > 0) {
  2036. spin_lock(&pcp->lock);
  2037. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2038. spin_unlock(&pcp->lock);
  2039. todo++;
  2040. }
  2041. return todo;
  2042. }
  2043. #ifdef CONFIG_NUMA
  2044. /*
  2045. * Called from the vmstat counter updater to drain pagesets of this
  2046. * currently executing processor on remote nodes after they have
  2047. * expired.
  2048. */
  2049. void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
  2050. {
  2051. int to_drain, batch;
  2052. batch = READ_ONCE(pcp->batch);
  2053. to_drain = min(pcp->count, batch);
  2054. if (to_drain > 0) {
  2055. spin_lock(&pcp->lock);
  2056. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2057. spin_unlock(&pcp->lock);
  2058. }
  2059. }
  2060. #endif
  2061. /*
  2062. * Drain pcplists of the indicated processor and zone.
  2063. */
  2064. static void drain_pages_zone(unsigned int cpu, struct zone *zone)
  2065. {
  2066. struct per_cpu_pages *pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  2067. int count;
  2068. do {
  2069. spin_lock(&pcp->lock);
  2070. count = pcp->count;
  2071. if (count) {
  2072. int to_drain = min(count,
  2073. pcp->batch << CONFIG_PCP_BATCH_SCALE_MAX);
  2074. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2075. count -= to_drain;
  2076. }
  2077. spin_unlock(&pcp->lock);
  2078. } while (count);
  2079. }
  2080. /*
  2081. * Drain pcplists of all zones on the indicated processor.
  2082. */
  2083. static void drain_pages(unsigned int cpu)
  2084. {
  2085. struct zone *zone;
  2086. for_each_populated_zone(zone) {
  2087. drain_pages_zone(cpu, zone);
  2088. }
  2089. }
  2090. /*
  2091. * Spill all of this CPU's per-cpu pages back into the buddy allocator.
  2092. */
  2093. void drain_local_pages(struct zone *zone)
  2094. {
  2095. int cpu = smp_processor_id();
  2096. if (zone)
  2097. drain_pages_zone(cpu, zone);
  2098. else
  2099. drain_pages(cpu);
  2100. }
  2101. /*
  2102. * The implementation of drain_all_pages(), exposing an extra parameter to
  2103. * drain on all cpus.
  2104. *
  2105. * drain_all_pages() is optimized to only execute on cpus where pcplists are
  2106. * not empty. The check for non-emptiness can however race with a free to
  2107. * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
  2108. * that need the guarantee that every CPU has drained can disable the
  2109. * optimizing racy check.
  2110. */
  2111. static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
  2112. {
  2113. int cpu;
  2114. /*
  2115. * Allocate in the BSS so we won't require allocation in
  2116. * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
  2117. */
  2118. static cpumask_t cpus_with_pcps;
  2119. /*
  2120. * Do not drain if one is already in progress unless it's specific to
  2121. * a zone. Such callers are primarily CMA and memory hotplug and need
  2122. * the drain to be complete when the call returns.
  2123. */
  2124. if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
  2125. if (!zone)
  2126. return;
  2127. mutex_lock(&pcpu_drain_mutex);
  2128. }
  2129. /*
  2130. * We don't care about racing with CPU hotplug event
  2131. * as offline notification will cause the notified
  2132. * cpu to drain that CPU pcps and on_each_cpu_mask
  2133. * disables preemption as part of its processing
  2134. */
  2135. for_each_online_cpu(cpu) {
  2136. struct per_cpu_pages *pcp;
  2137. struct zone *z;
  2138. bool has_pcps = false;
  2139. if (force_all_cpus) {
  2140. /*
  2141. * The pcp.count check is racy, some callers need a
  2142. * guarantee that no cpu is missed.
  2143. */
  2144. has_pcps = true;
  2145. } else if (zone) {
  2146. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  2147. if (pcp->count)
  2148. has_pcps = true;
  2149. } else {
  2150. for_each_populated_zone(z) {
  2151. pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
  2152. if (pcp->count) {
  2153. has_pcps = true;
  2154. break;
  2155. }
  2156. }
  2157. }
  2158. if (has_pcps)
  2159. cpumask_set_cpu(cpu, &cpus_with_pcps);
  2160. else
  2161. cpumask_clear_cpu(cpu, &cpus_with_pcps);
  2162. }
  2163. for_each_cpu(cpu, &cpus_with_pcps) {
  2164. if (zone)
  2165. drain_pages_zone(cpu, zone);
  2166. else
  2167. drain_pages(cpu);
  2168. }
  2169. mutex_unlock(&pcpu_drain_mutex);
  2170. }
  2171. /*
  2172. * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
  2173. *
  2174. * When zone parameter is non-NULL, spill just the single zone's pages.
  2175. */
  2176. void drain_all_pages(struct zone *zone)
  2177. {
  2178. __drain_all_pages(zone, false);
  2179. }
  2180. static int nr_pcp_free(struct per_cpu_pages *pcp, int batch, int high, bool free_high)
  2181. {
  2182. int min_nr_free, max_nr_free;
  2183. /* Free as much as possible if batch freeing high-order pages. */
  2184. if (unlikely(free_high))
  2185. return min(pcp->count, batch << CONFIG_PCP_BATCH_SCALE_MAX);
  2186. /* Check for PCP disabled or boot pageset */
  2187. if (unlikely(high < batch))
  2188. return 1;
  2189. /* Leave at least pcp->batch pages on the list */
  2190. min_nr_free = batch;
  2191. max_nr_free = high - batch;
  2192. /*
  2193. * Increase the batch number to the number of the consecutive
  2194. * freed pages to reduce zone lock contention.
  2195. */
  2196. batch = clamp_t(int, pcp->free_count, min_nr_free, max_nr_free);
  2197. return batch;
  2198. }
  2199. static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone,
  2200. int batch, bool free_high)
  2201. {
  2202. int high, high_min, high_max;
  2203. high_min = READ_ONCE(pcp->high_min);
  2204. high_max = READ_ONCE(pcp->high_max);
  2205. high = pcp->high = clamp(pcp->high, high_min, high_max);
  2206. if (unlikely(!high))
  2207. return 0;
  2208. if (unlikely(free_high)) {
  2209. pcp->high = max(high - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
  2210. high_min);
  2211. return 0;
  2212. }
  2213. /*
  2214. * If reclaim is active, limit the number of pages that can be
  2215. * stored on pcp lists
  2216. */
  2217. if (test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) {
  2218. int free_count = max_t(int, pcp->free_count, batch);
  2219. pcp->high = max(high - free_count, high_min);
  2220. return min(batch << 2, pcp->high);
  2221. }
  2222. if (high_min == high_max)
  2223. return high;
  2224. if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) {
  2225. int free_count = max_t(int, pcp->free_count, batch);
  2226. pcp->high = max(high - free_count, high_min);
  2227. high = max(pcp->count, high_min);
  2228. } else if (pcp->count >= high) {
  2229. int need_high = pcp->free_count + batch;
  2230. /* pcp->high should be large enough to hold batch freed pages */
  2231. if (pcp->high < need_high)
  2232. pcp->high = clamp(need_high, high_min, high_max);
  2233. }
  2234. return high;
  2235. }
  2236. static void free_unref_page_commit(struct zone *zone, struct per_cpu_pages *pcp,
  2237. struct page *page, int migratetype,
  2238. unsigned int order)
  2239. {
  2240. int high, batch;
  2241. int pindex;
  2242. bool free_high = false;
  2243. /*
  2244. * On freeing, reduce the number of pages that are batch allocated.
  2245. * See nr_pcp_alloc() where alloc_factor is increased for subsequent
  2246. * allocations.
  2247. */
  2248. pcp->alloc_factor >>= 1;
  2249. __count_vm_events(PGFREE, 1 << order);
  2250. pindex = order_to_pindex(migratetype, order);
  2251. list_add(&page->pcp_list, &pcp->lists[pindex]);
  2252. pcp->count += 1 << order;
  2253. batch = READ_ONCE(pcp->batch);
  2254. /*
  2255. * As high-order pages other than THP's stored on PCP can contribute
  2256. * to fragmentation, limit the number stored when PCP is heavily
  2257. * freeing without allocation. The remainder after bulk freeing
  2258. * stops will be drained from vmstat refresh context.
  2259. */
  2260. if (order && order <= PAGE_ALLOC_COSTLY_ORDER) {
  2261. free_high = (pcp->free_count >= batch &&
  2262. (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) &&
  2263. (!(pcp->flags & PCPF_FREE_HIGH_BATCH) ||
  2264. pcp->count >= READ_ONCE(batch)));
  2265. pcp->flags |= PCPF_PREV_FREE_HIGH_ORDER;
  2266. } else if (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) {
  2267. pcp->flags &= ~PCPF_PREV_FREE_HIGH_ORDER;
  2268. }
  2269. if (pcp->free_count < (batch << CONFIG_PCP_BATCH_SCALE_MAX))
  2270. pcp->free_count += (1 << order);
  2271. high = nr_pcp_high(pcp, zone, batch, free_high);
  2272. if (pcp->count >= high) {
  2273. free_pcppages_bulk(zone, nr_pcp_free(pcp, batch, high, free_high),
  2274. pcp, pindex);
  2275. if (test_bit(ZONE_BELOW_HIGH, &zone->flags) &&
  2276. zone_watermark_ok(zone, 0, high_wmark_pages(zone),
  2277. ZONE_MOVABLE, 0))
  2278. clear_bit(ZONE_BELOW_HIGH, &zone->flags);
  2279. }
  2280. }
  2281. /*
  2282. * Free a pcp page
  2283. */
  2284. void free_unref_page(struct page *page, unsigned int order)
  2285. {
  2286. unsigned long __maybe_unused UP_flags;
  2287. struct per_cpu_pages *pcp;
  2288. struct zone *zone;
  2289. unsigned long pfn = page_to_pfn(page);
  2290. int migratetype;
  2291. if (!pcp_allowed_order(order)) {
  2292. __free_pages_ok(page, order, FPI_NONE);
  2293. return;
  2294. }
  2295. if (!free_pages_prepare(page, order))
  2296. return;
  2297. /*
  2298. * We only track unmovable, reclaimable and movable on pcp lists.
  2299. * Place ISOLATE pages on the isolated list because they are being
  2300. * offlined but treat HIGHATOMIC and CMA as movable pages so we can
  2301. * get those areas back if necessary. Otherwise, we may have to free
  2302. * excessively into the page allocator
  2303. */
  2304. migratetype = get_pfnblock_migratetype(page, pfn);
  2305. if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
  2306. if (unlikely(is_migrate_isolate(migratetype))) {
  2307. free_one_page(page_zone(page), page, pfn, order, FPI_NONE);
  2308. return;
  2309. }
  2310. migratetype = MIGRATE_MOVABLE;
  2311. }
  2312. zone = page_zone(page);
  2313. pcp_trylock_prepare(UP_flags);
  2314. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2315. if (pcp) {
  2316. free_unref_page_commit(zone, pcp, page, migratetype, order);
  2317. pcp_spin_unlock(pcp);
  2318. } else {
  2319. free_one_page(zone, page, pfn, order, FPI_NONE);
  2320. }
  2321. pcp_trylock_finish(UP_flags);
  2322. }
  2323. /*
  2324. * Free a batch of folios
  2325. */
  2326. void free_unref_folios(struct folio_batch *folios)
  2327. {
  2328. unsigned long __maybe_unused UP_flags;
  2329. struct per_cpu_pages *pcp = NULL;
  2330. struct zone *locked_zone = NULL;
  2331. int i, j;
  2332. /* Prepare folios for freeing */
  2333. for (i = 0, j = 0; i < folios->nr; i++) {
  2334. struct folio *folio = folios->folios[i];
  2335. unsigned long pfn = folio_pfn(folio);
  2336. unsigned int order = folio_order(folio);
  2337. if (!free_pages_prepare(&folio->page, order))
  2338. continue;
  2339. /*
  2340. * Free orders not handled on the PCP directly to the
  2341. * allocator.
  2342. */
  2343. if (!pcp_allowed_order(order)) {
  2344. free_one_page(folio_zone(folio), &folio->page,
  2345. pfn, order, FPI_NONE);
  2346. continue;
  2347. }
  2348. folio->private = (void *)(unsigned long)order;
  2349. if (j != i)
  2350. folios->folios[j] = folio;
  2351. j++;
  2352. }
  2353. folios->nr = j;
  2354. for (i = 0; i < folios->nr; i++) {
  2355. struct folio *folio = folios->folios[i];
  2356. struct zone *zone = folio_zone(folio);
  2357. unsigned long pfn = folio_pfn(folio);
  2358. unsigned int order = (unsigned long)folio->private;
  2359. int migratetype;
  2360. folio->private = NULL;
  2361. migratetype = get_pfnblock_migratetype(&folio->page, pfn);
  2362. /* Different zone requires a different pcp lock */
  2363. if (zone != locked_zone ||
  2364. is_migrate_isolate(migratetype)) {
  2365. if (pcp) {
  2366. pcp_spin_unlock(pcp);
  2367. pcp_trylock_finish(UP_flags);
  2368. locked_zone = NULL;
  2369. pcp = NULL;
  2370. }
  2371. /*
  2372. * Free isolated pages directly to the
  2373. * allocator, see comment in free_unref_page.
  2374. */
  2375. if (is_migrate_isolate(migratetype)) {
  2376. free_one_page(zone, &folio->page, pfn,
  2377. order, FPI_NONE);
  2378. continue;
  2379. }
  2380. /*
  2381. * trylock is necessary as folios may be getting freed
  2382. * from IRQ or SoftIRQ context after an IO completion.
  2383. */
  2384. pcp_trylock_prepare(UP_flags);
  2385. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2386. if (unlikely(!pcp)) {
  2387. pcp_trylock_finish(UP_flags);
  2388. free_one_page(zone, &folio->page, pfn,
  2389. order, FPI_NONE);
  2390. continue;
  2391. }
  2392. locked_zone = zone;
  2393. }
  2394. /*
  2395. * Non-isolated types over MIGRATE_PCPTYPES get added
  2396. * to the MIGRATE_MOVABLE pcp list.
  2397. */
  2398. if (unlikely(migratetype >= MIGRATE_PCPTYPES))
  2399. migratetype = MIGRATE_MOVABLE;
  2400. trace_mm_page_free_batched(&folio->page);
  2401. free_unref_page_commit(zone, pcp, &folio->page, migratetype,
  2402. order);
  2403. }
  2404. if (pcp) {
  2405. pcp_spin_unlock(pcp);
  2406. pcp_trylock_finish(UP_flags);
  2407. }
  2408. folio_batch_reinit(folios);
  2409. }
  2410. /*
  2411. * split_page takes a non-compound higher-order page, and splits it into
  2412. * n (1<<order) sub-pages: page[0..n]
  2413. * Each sub-page must be freed individually.
  2414. *
  2415. * Note: this is probably too low level an operation for use in drivers.
  2416. * Please consult with lkml before using this in your driver.
  2417. */
  2418. void split_page(struct page *page, unsigned int order)
  2419. {
  2420. int i;
  2421. VM_BUG_ON_PAGE(PageCompound(page), page);
  2422. VM_BUG_ON_PAGE(!page_count(page), page);
  2423. for (i = 1; i < (1 << order); i++)
  2424. set_page_refcounted(page + i);
  2425. split_page_owner(page, order, 0);
  2426. pgalloc_tag_split(page_folio(page), order, 0);
  2427. split_page_memcg(page, order, 0);
  2428. }
  2429. EXPORT_SYMBOL_GPL(split_page);
  2430. int __isolate_free_page(struct page *page, unsigned int order)
  2431. {
  2432. struct zone *zone = page_zone(page);
  2433. int mt = get_pageblock_migratetype(page);
  2434. if (!is_migrate_isolate(mt)) {
  2435. unsigned long watermark;
  2436. /*
  2437. * Obey watermarks as if the page was being allocated. We can
  2438. * emulate a high-order watermark check with a raised order-0
  2439. * watermark, because we already know our high-order page
  2440. * exists.
  2441. */
  2442. watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
  2443. if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
  2444. return 0;
  2445. }
  2446. del_page_from_free_list(page, zone, order, mt);
  2447. /*
  2448. * Set the pageblock if the isolated page is at least half of a
  2449. * pageblock
  2450. */
  2451. if (order >= pageblock_order - 1) {
  2452. struct page *endpage = page + (1 << order) - 1;
  2453. for (; page < endpage; page += pageblock_nr_pages) {
  2454. int mt = get_pageblock_migratetype(page);
  2455. /*
  2456. * Only change normal pageblocks (i.e., they can merge
  2457. * with others)
  2458. */
  2459. if (migratetype_is_mergeable(mt))
  2460. move_freepages_block(zone, page, mt,
  2461. MIGRATE_MOVABLE);
  2462. }
  2463. }
  2464. return 1UL << order;
  2465. }
  2466. /**
  2467. * __putback_isolated_page - Return a now-isolated page back where we got it
  2468. * @page: Page that was isolated
  2469. * @order: Order of the isolated page
  2470. * @mt: The page's pageblock's migratetype
  2471. *
  2472. * This function is meant to return a page pulled from the free lists via
  2473. * __isolate_free_page back to the free lists they were pulled from.
  2474. */
  2475. void __putback_isolated_page(struct page *page, unsigned int order, int mt)
  2476. {
  2477. struct zone *zone = page_zone(page);
  2478. /* zone lock should be held when this function is called */
  2479. lockdep_assert_held(&zone->lock);
  2480. /* Return isolated page to tail of freelist. */
  2481. __free_one_page(page, page_to_pfn(page), zone, order, mt,
  2482. FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
  2483. }
  2484. /*
  2485. * Update NUMA hit/miss statistics
  2486. */
  2487. static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
  2488. long nr_account)
  2489. {
  2490. #ifdef CONFIG_NUMA
  2491. enum numa_stat_item local_stat = NUMA_LOCAL;
  2492. /* skip numa counters update if numa stats is disabled */
  2493. if (!static_branch_likely(&vm_numa_stat_key))
  2494. return;
  2495. if (zone_to_nid(z) != numa_node_id())
  2496. local_stat = NUMA_OTHER;
  2497. if (zone_to_nid(z) == zone_to_nid(preferred_zone))
  2498. __count_numa_events(z, NUMA_HIT, nr_account);
  2499. else {
  2500. __count_numa_events(z, NUMA_MISS, nr_account);
  2501. __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
  2502. }
  2503. __count_numa_events(z, local_stat, nr_account);
  2504. #endif
  2505. }
  2506. static __always_inline
  2507. struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,
  2508. unsigned int order, unsigned int alloc_flags,
  2509. int migratetype)
  2510. {
  2511. struct page *page;
  2512. unsigned long flags;
  2513. do {
  2514. page = NULL;
  2515. spin_lock_irqsave(&zone->lock, flags);
  2516. if (alloc_flags & ALLOC_HIGHATOMIC)
  2517. page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
  2518. if (!page) {
  2519. page = __rmqueue(zone, order, migratetype, alloc_flags);
  2520. /*
  2521. * If the allocation fails, allow OOM handling and
  2522. * order-0 (atomic) allocs access to HIGHATOMIC
  2523. * reserves as failing now is worse than failing a
  2524. * high-order atomic allocation in the future.
  2525. */
  2526. if (!page && (alloc_flags & (ALLOC_OOM|ALLOC_NON_BLOCK)))
  2527. page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
  2528. if (!page) {
  2529. spin_unlock_irqrestore(&zone->lock, flags);
  2530. return NULL;
  2531. }
  2532. }
  2533. spin_unlock_irqrestore(&zone->lock, flags);
  2534. } while (check_new_pages(page, order));
  2535. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2536. zone_statistics(preferred_zone, zone, 1);
  2537. return page;
  2538. }
  2539. static int nr_pcp_alloc(struct per_cpu_pages *pcp, struct zone *zone, int order)
  2540. {
  2541. int high, base_batch, batch, max_nr_alloc;
  2542. int high_max, high_min;
  2543. base_batch = READ_ONCE(pcp->batch);
  2544. high_min = READ_ONCE(pcp->high_min);
  2545. high_max = READ_ONCE(pcp->high_max);
  2546. high = pcp->high = clamp(pcp->high, high_min, high_max);
  2547. /* Check for PCP disabled or boot pageset */
  2548. if (unlikely(high < base_batch))
  2549. return 1;
  2550. if (order)
  2551. batch = base_batch;
  2552. else
  2553. batch = (base_batch << pcp->alloc_factor);
  2554. /*
  2555. * If we had larger pcp->high, we could avoid to allocate from
  2556. * zone.
  2557. */
  2558. if (high_min != high_max && !test_bit(ZONE_BELOW_HIGH, &zone->flags))
  2559. high = pcp->high = min(high + batch, high_max);
  2560. if (!order) {
  2561. max_nr_alloc = max(high - pcp->count - base_batch, base_batch);
  2562. /*
  2563. * Double the number of pages allocated each time there is
  2564. * subsequent allocation of order-0 pages without any freeing.
  2565. */
  2566. if (batch <= max_nr_alloc &&
  2567. pcp->alloc_factor < CONFIG_PCP_BATCH_SCALE_MAX)
  2568. pcp->alloc_factor++;
  2569. batch = min(batch, max_nr_alloc);
  2570. }
  2571. /*
  2572. * Scale batch relative to order if batch implies free pages
  2573. * can be stored on the PCP. Batch can be 1 for small zones or
  2574. * for boot pagesets which should never store free pages as
  2575. * the pages may belong to arbitrary zones.
  2576. */
  2577. if (batch > 1)
  2578. batch = max(batch >> order, 2);
  2579. return batch;
  2580. }
  2581. /* Remove page from the per-cpu list, caller must protect the list */
  2582. static inline
  2583. struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order,
  2584. int migratetype,
  2585. unsigned int alloc_flags,
  2586. struct per_cpu_pages *pcp,
  2587. struct list_head *list)
  2588. {
  2589. struct page *page;
  2590. do {
  2591. if (list_empty(list)) {
  2592. int batch = nr_pcp_alloc(pcp, zone, order);
  2593. int alloced;
  2594. alloced = rmqueue_bulk(zone, order,
  2595. batch, list,
  2596. migratetype, alloc_flags);
  2597. pcp->count += alloced << order;
  2598. if (unlikely(list_empty(list)))
  2599. return NULL;
  2600. }
  2601. page = list_first_entry(list, struct page, pcp_list);
  2602. list_del(&page->pcp_list);
  2603. pcp->count -= 1 << order;
  2604. } while (check_new_pages(page, order));
  2605. return page;
  2606. }
  2607. /* Lock and remove page from the per-cpu list */
  2608. static struct page *rmqueue_pcplist(struct zone *preferred_zone,
  2609. struct zone *zone, unsigned int order,
  2610. int migratetype, unsigned int alloc_flags)
  2611. {
  2612. struct per_cpu_pages *pcp;
  2613. struct list_head *list;
  2614. struct page *page;
  2615. unsigned long __maybe_unused UP_flags;
  2616. /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
  2617. pcp_trylock_prepare(UP_flags);
  2618. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2619. if (!pcp) {
  2620. pcp_trylock_finish(UP_flags);
  2621. return NULL;
  2622. }
  2623. /*
  2624. * On allocation, reduce the number of pages that are batch freed.
  2625. * See nr_pcp_free() where free_factor is increased for subsequent
  2626. * frees.
  2627. */
  2628. pcp->free_count >>= 1;
  2629. list = &pcp->lists[order_to_pindex(migratetype, order)];
  2630. page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list);
  2631. pcp_spin_unlock(pcp);
  2632. pcp_trylock_finish(UP_flags);
  2633. if (page) {
  2634. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2635. zone_statistics(preferred_zone, zone, 1);
  2636. }
  2637. return page;
  2638. }
  2639. /*
  2640. * Allocate a page from the given zone.
  2641. * Use pcplists for THP or "cheap" high-order allocations.
  2642. */
  2643. /*
  2644. * Do not instrument rmqueue() with KMSAN. This function may call
  2645. * __msan_poison_alloca() through a call to set_pfnblock_flags_mask().
  2646. * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it
  2647. * may call rmqueue() again, which will result in a deadlock.
  2648. */
  2649. __no_sanitize_memory
  2650. static inline
  2651. struct page *rmqueue(struct zone *preferred_zone,
  2652. struct zone *zone, unsigned int order,
  2653. gfp_t gfp_flags, unsigned int alloc_flags,
  2654. int migratetype)
  2655. {
  2656. struct page *page;
  2657. if (likely(pcp_allowed_order(order))) {
  2658. page = rmqueue_pcplist(preferred_zone, zone, order,
  2659. migratetype, alloc_flags);
  2660. if (likely(page))
  2661. goto out;
  2662. }
  2663. page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags,
  2664. migratetype);
  2665. out:
  2666. /* Separate test+clear to avoid unnecessary atomics */
  2667. if ((alloc_flags & ALLOC_KSWAPD) &&
  2668. unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) {
  2669. clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
  2670. wakeup_kswapd(zone, 0, 0, zone_idx(zone));
  2671. }
  2672. VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
  2673. return page;
  2674. }
  2675. static inline long __zone_watermark_unusable_free(struct zone *z,
  2676. unsigned int order, unsigned int alloc_flags)
  2677. {
  2678. long unusable_free = (1 << order) - 1;
  2679. /*
  2680. * If the caller does not have rights to reserves below the min
  2681. * watermark then subtract the free pages reserved for highatomic.
  2682. */
  2683. if (likely(!(alloc_flags & ALLOC_RESERVES)))
  2684. unusable_free += READ_ONCE(z->nr_free_highatomic);
  2685. #ifdef CONFIG_CMA
  2686. /* If allocation can't use CMA areas don't use free CMA pages */
  2687. if (!(alloc_flags & ALLOC_CMA))
  2688. unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
  2689. #endif
  2690. return unusable_free;
  2691. }
  2692. /*
  2693. * Return true if free base pages are above 'mark'. For high-order checks it
  2694. * will return true of the order-0 watermark is reached and there is at least
  2695. * one free page of a suitable size. Checking now avoids taking the zone lock
  2696. * to check in the allocation paths if no pages are free.
  2697. */
  2698. bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2699. int highest_zoneidx, unsigned int alloc_flags,
  2700. long free_pages)
  2701. {
  2702. long min = mark;
  2703. int o;
  2704. /* free_pages may go negative - that's OK */
  2705. free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
  2706. if (unlikely(alloc_flags & ALLOC_RESERVES)) {
  2707. /*
  2708. * __GFP_HIGH allows access to 50% of the min reserve as well
  2709. * as OOM.
  2710. */
  2711. if (alloc_flags & ALLOC_MIN_RESERVE) {
  2712. min -= min / 2;
  2713. /*
  2714. * Non-blocking allocations (e.g. GFP_ATOMIC) can
  2715. * access more reserves than just __GFP_HIGH. Other
  2716. * non-blocking allocations requests such as GFP_NOWAIT
  2717. * or (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) do not get
  2718. * access to the min reserve.
  2719. */
  2720. if (alloc_flags & ALLOC_NON_BLOCK)
  2721. min -= min / 4;
  2722. }
  2723. /*
  2724. * OOM victims can try even harder than the normal reserve
  2725. * users on the grounds that it's definitely going to be in
  2726. * the exit path shortly and free memory. Any allocation it
  2727. * makes during the free path will be small and short-lived.
  2728. */
  2729. if (alloc_flags & ALLOC_OOM)
  2730. min -= min / 2;
  2731. }
  2732. /*
  2733. * Check watermarks for an order-0 allocation request. If these
  2734. * are not met, then a high-order request also cannot go ahead
  2735. * even if a suitable page happened to be free.
  2736. */
  2737. if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
  2738. return false;
  2739. /* If this is an order-0 request then the watermark is fine */
  2740. if (!order)
  2741. return true;
  2742. /* For a high-order request, check at least one suitable page is free */
  2743. for (o = order; o < NR_PAGE_ORDERS; o++) {
  2744. struct free_area *area = &z->free_area[o];
  2745. int mt;
  2746. if (!area->nr_free)
  2747. continue;
  2748. for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
  2749. if (!free_area_empty(area, mt))
  2750. return true;
  2751. }
  2752. #ifdef CONFIG_CMA
  2753. if ((alloc_flags & ALLOC_CMA) &&
  2754. !free_area_empty(area, MIGRATE_CMA)) {
  2755. return true;
  2756. }
  2757. #endif
  2758. if ((alloc_flags & (ALLOC_HIGHATOMIC|ALLOC_OOM)) &&
  2759. !free_area_empty(area, MIGRATE_HIGHATOMIC)) {
  2760. return true;
  2761. }
  2762. }
  2763. return false;
  2764. }
  2765. bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2766. int highest_zoneidx, unsigned int alloc_flags)
  2767. {
  2768. return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
  2769. zone_page_state(z, NR_FREE_PAGES));
  2770. }
  2771. static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
  2772. unsigned long mark, int highest_zoneidx,
  2773. unsigned int alloc_flags, gfp_t gfp_mask)
  2774. {
  2775. long free_pages;
  2776. free_pages = zone_page_state(z, NR_FREE_PAGES);
  2777. /*
  2778. * Fast check for order-0 only. If this fails then the reserves
  2779. * need to be calculated.
  2780. */
  2781. if (!order) {
  2782. long usable_free;
  2783. long reserved;
  2784. usable_free = free_pages;
  2785. reserved = __zone_watermark_unusable_free(z, 0, alloc_flags);
  2786. /* reserved may over estimate high-atomic reserves. */
  2787. usable_free -= min(usable_free, reserved);
  2788. if (usable_free > mark + z->lowmem_reserve[highest_zoneidx])
  2789. return true;
  2790. }
  2791. if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
  2792. free_pages))
  2793. return true;
  2794. /*
  2795. * Ignore watermark boosting for __GFP_HIGH order-0 allocations
  2796. * when checking the min watermark. The min watermark is the
  2797. * point where boosting is ignored so that kswapd is woken up
  2798. * when below the low watermark.
  2799. */
  2800. if (unlikely(!order && (alloc_flags & ALLOC_MIN_RESERVE) && z->watermark_boost
  2801. && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
  2802. mark = z->_watermark[WMARK_MIN];
  2803. return __zone_watermark_ok(z, order, mark, highest_zoneidx,
  2804. alloc_flags, free_pages);
  2805. }
  2806. return false;
  2807. }
  2808. bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
  2809. unsigned long mark, int highest_zoneidx)
  2810. {
  2811. long free_pages = zone_page_state(z, NR_FREE_PAGES);
  2812. if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
  2813. free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
  2814. return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
  2815. free_pages);
  2816. }
  2817. #ifdef CONFIG_NUMA
  2818. int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
  2819. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2820. {
  2821. return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
  2822. node_reclaim_distance;
  2823. }
  2824. #else /* CONFIG_NUMA */
  2825. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2826. {
  2827. return true;
  2828. }
  2829. #endif /* CONFIG_NUMA */
  2830. /*
  2831. * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
  2832. * fragmentation is subtle. If the preferred zone was HIGHMEM then
  2833. * premature use of a lower zone may cause lowmem pressure problems that
  2834. * are worse than fragmentation. If the next zone is ZONE_DMA then it is
  2835. * probably too small. It only makes sense to spread allocations to avoid
  2836. * fragmentation between the Normal and DMA32 zones.
  2837. */
  2838. static inline unsigned int
  2839. alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
  2840. {
  2841. unsigned int alloc_flags;
  2842. /*
  2843. * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
  2844. * to save a branch.
  2845. */
  2846. alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
  2847. #ifdef CONFIG_ZONE_DMA32
  2848. if (!zone)
  2849. return alloc_flags;
  2850. if (zone_idx(zone) != ZONE_NORMAL)
  2851. return alloc_flags;
  2852. /*
  2853. * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
  2854. * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
  2855. * on UMA that if Normal is populated then so is DMA32.
  2856. */
  2857. BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
  2858. if (nr_online_nodes > 1 && !populated_zone(--zone))
  2859. return alloc_flags;
  2860. alloc_flags |= ALLOC_NOFRAGMENT;
  2861. #endif /* CONFIG_ZONE_DMA32 */
  2862. return alloc_flags;
  2863. }
  2864. /* Must be called after current_gfp_context() which can change gfp_mask */
  2865. static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
  2866. unsigned int alloc_flags)
  2867. {
  2868. #ifdef CONFIG_CMA
  2869. if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
  2870. alloc_flags |= ALLOC_CMA;
  2871. #endif
  2872. return alloc_flags;
  2873. }
  2874. /*
  2875. * get_page_from_freelist goes through the zonelist trying to allocate
  2876. * a page.
  2877. */
  2878. static struct page *
  2879. get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
  2880. const struct alloc_context *ac)
  2881. {
  2882. struct zoneref *z;
  2883. struct zone *zone;
  2884. struct pglist_data *last_pgdat = NULL;
  2885. bool last_pgdat_dirty_ok = false;
  2886. bool no_fallback;
  2887. retry:
  2888. /*
  2889. * Scan zonelist, looking for a zone with enough free.
  2890. * See also cpuset_node_allowed() comment in kernel/cgroup/cpuset.c.
  2891. */
  2892. no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
  2893. z = ac->preferred_zoneref;
  2894. for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
  2895. ac->nodemask) {
  2896. struct page *page;
  2897. unsigned long mark;
  2898. if (cpusets_enabled() &&
  2899. (alloc_flags & ALLOC_CPUSET) &&
  2900. !__cpuset_zone_allowed(zone, gfp_mask))
  2901. continue;
  2902. /*
  2903. * When allocating a page cache page for writing, we
  2904. * want to get it from a node that is within its dirty
  2905. * limit, such that no single node holds more than its
  2906. * proportional share of globally allowed dirty pages.
  2907. * The dirty limits take into account the node's
  2908. * lowmem reserves and high watermark so that kswapd
  2909. * should be able to balance it without having to
  2910. * write pages from its LRU list.
  2911. *
  2912. * XXX: For now, allow allocations to potentially
  2913. * exceed the per-node dirty limit in the slowpath
  2914. * (spread_dirty_pages unset) before going into reclaim,
  2915. * which is important when on a NUMA setup the allowed
  2916. * nodes are together not big enough to reach the
  2917. * global limit. The proper fix for these situations
  2918. * will require awareness of nodes in the
  2919. * dirty-throttling and the flusher threads.
  2920. */
  2921. if (ac->spread_dirty_pages) {
  2922. if (last_pgdat != zone->zone_pgdat) {
  2923. last_pgdat = zone->zone_pgdat;
  2924. last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
  2925. }
  2926. if (!last_pgdat_dirty_ok)
  2927. continue;
  2928. }
  2929. if (no_fallback && nr_online_nodes > 1 &&
  2930. zone != zonelist_zone(ac->preferred_zoneref)) {
  2931. int local_nid;
  2932. /*
  2933. * If moving to a remote node, retry but allow
  2934. * fragmenting fallbacks. Locality is more important
  2935. * than fragmentation avoidance.
  2936. */
  2937. local_nid = zonelist_node_idx(ac->preferred_zoneref);
  2938. if (zone_to_nid(zone) != local_nid) {
  2939. alloc_flags &= ~ALLOC_NOFRAGMENT;
  2940. goto retry;
  2941. }
  2942. }
  2943. cond_accept_memory(zone, order);
  2944. /*
  2945. * Detect whether the number of free pages is below high
  2946. * watermark. If so, we will decrease pcp->high and free
  2947. * PCP pages in free path to reduce the possibility of
  2948. * premature page reclaiming. Detection is done here to
  2949. * avoid to do that in hotter free path.
  2950. */
  2951. if (test_bit(ZONE_BELOW_HIGH, &zone->flags))
  2952. goto check_alloc_wmark;
  2953. mark = high_wmark_pages(zone);
  2954. if (zone_watermark_fast(zone, order, mark,
  2955. ac->highest_zoneidx, alloc_flags,
  2956. gfp_mask))
  2957. goto try_this_zone;
  2958. else
  2959. set_bit(ZONE_BELOW_HIGH, &zone->flags);
  2960. check_alloc_wmark:
  2961. mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
  2962. if (!zone_watermark_fast(zone, order, mark,
  2963. ac->highest_zoneidx, alloc_flags,
  2964. gfp_mask)) {
  2965. int ret;
  2966. if (cond_accept_memory(zone, order))
  2967. goto try_this_zone;
  2968. /*
  2969. * Watermark failed for this zone, but see if we can
  2970. * grow this zone if it contains deferred pages.
  2971. */
  2972. if (deferred_pages_enabled()) {
  2973. if (_deferred_grow_zone(zone, order))
  2974. goto try_this_zone;
  2975. }
  2976. /* Checked here to keep the fast path fast */
  2977. BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
  2978. if (alloc_flags & ALLOC_NO_WATERMARKS)
  2979. goto try_this_zone;
  2980. if (!node_reclaim_enabled() ||
  2981. !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
  2982. continue;
  2983. ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
  2984. switch (ret) {
  2985. case NODE_RECLAIM_NOSCAN:
  2986. /* did not scan */
  2987. continue;
  2988. case NODE_RECLAIM_FULL:
  2989. /* scanned but unreclaimable */
  2990. continue;
  2991. default:
  2992. /* did we reclaim enough */
  2993. if (zone_watermark_ok(zone, order, mark,
  2994. ac->highest_zoneidx, alloc_flags))
  2995. goto try_this_zone;
  2996. continue;
  2997. }
  2998. }
  2999. try_this_zone:
  3000. page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
  3001. gfp_mask, alloc_flags, ac->migratetype);
  3002. if (page) {
  3003. prep_new_page(page, order, gfp_mask, alloc_flags);
  3004. /*
  3005. * If this is a high-order atomic allocation then check
  3006. * if the pageblock should be reserved for the future
  3007. */
  3008. if (unlikely(alloc_flags & ALLOC_HIGHATOMIC))
  3009. reserve_highatomic_pageblock(page, order, zone);
  3010. return page;
  3011. } else {
  3012. if (cond_accept_memory(zone, order))
  3013. goto try_this_zone;
  3014. /* Try again if zone has deferred pages */
  3015. if (deferred_pages_enabled()) {
  3016. if (_deferred_grow_zone(zone, order))
  3017. goto try_this_zone;
  3018. }
  3019. }
  3020. }
  3021. /*
  3022. * It's possible on a UMA machine to get through all zones that are
  3023. * fragmented. If avoiding fragmentation, reset and try again.
  3024. */
  3025. if (no_fallback) {
  3026. alloc_flags &= ~ALLOC_NOFRAGMENT;
  3027. goto retry;
  3028. }
  3029. return NULL;
  3030. }
  3031. static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
  3032. {
  3033. unsigned int filter = SHOW_MEM_FILTER_NODES;
  3034. /*
  3035. * This documents exceptions given to allocations in certain
  3036. * contexts that are allowed to allocate outside current's set
  3037. * of allowed nodes.
  3038. */
  3039. if (!(gfp_mask & __GFP_NOMEMALLOC))
  3040. if (tsk_is_oom_victim(current) ||
  3041. (current->flags & (PF_MEMALLOC | PF_EXITING)))
  3042. filter &= ~SHOW_MEM_FILTER_NODES;
  3043. if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
  3044. filter &= ~SHOW_MEM_FILTER_NODES;
  3045. __show_mem(filter, nodemask, gfp_zone(gfp_mask));
  3046. }
  3047. void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
  3048. {
  3049. struct va_format vaf;
  3050. va_list args;
  3051. static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
  3052. if ((gfp_mask & __GFP_NOWARN) ||
  3053. !__ratelimit(&nopage_rs) ||
  3054. ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
  3055. return;
  3056. va_start(args, fmt);
  3057. vaf.fmt = fmt;
  3058. vaf.va = &args;
  3059. pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
  3060. current->comm, &vaf, gfp_mask, &gfp_mask,
  3061. nodemask_pr_args(nodemask));
  3062. va_end(args);
  3063. cpuset_print_current_mems_allowed();
  3064. pr_cont("\n");
  3065. dump_stack();
  3066. warn_alloc_show_mem(gfp_mask, nodemask);
  3067. }
  3068. static inline struct page *
  3069. __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
  3070. unsigned int alloc_flags,
  3071. const struct alloc_context *ac)
  3072. {
  3073. struct page *page;
  3074. page = get_page_from_freelist(gfp_mask, order,
  3075. alloc_flags|ALLOC_CPUSET, ac);
  3076. /*
  3077. * fallback to ignore cpuset restriction if our nodes
  3078. * are depleted
  3079. */
  3080. if (!page)
  3081. page = get_page_from_freelist(gfp_mask, order,
  3082. alloc_flags, ac);
  3083. return page;
  3084. }
  3085. static inline struct page *
  3086. __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
  3087. const struct alloc_context *ac, unsigned long *did_some_progress)
  3088. {
  3089. struct oom_control oc = {
  3090. .zonelist = ac->zonelist,
  3091. .nodemask = ac->nodemask,
  3092. .memcg = NULL,
  3093. .gfp_mask = gfp_mask,
  3094. .order = order,
  3095. };
  3096. struct page *page;
  3097. *did_some_progress = 0;
  3098. /*
  3099. * Acquire the oom lock. If that fails, somebody else is
  3100. * making progress for us.
  3101. */
  3102. if (!mutex_trylock(&oom_lock)) {
  3103. *did_some_progress = 1;
  3104. schedule_timeout_uninterruptible(1);
  3105. return NULL;
  3106. }
  3107. /*
  3108. * Go through the zonelist yet one more time, keep very high watermark
  3109. * here, this is only to catch a parallel oom killing, we must fail if
  3110. * we're still under heavy pressure. But make sure that this reclaim
  3111. * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
  3112. * allocation which will never fail due to oom_lock already held.
  3113. */
  3114. page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
  3115. ~__GFP_DIRECT_RECLAIM, order,
  3116. ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
  3117. if (page)
  3118. goto out;
  3119. /* Coredumps can quickly deplete all memory reserves */
  3120. if (current->flags & PF_DUMPCORE)
  3121. goto out;
  3122. /* The OOM killer will not help higher order allocs */
  3123. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3124. goto out;
  3125. /*
  3126. * We have already exhausted all our reclaim opportunities without any
  3127. * success so it is time to admit defeat. We will skip the OOM killer
  3128. * because it is very likely that the caller has a more reasonable
  3129. * fallback than shooting a random task.
  3130. *
  3131. * The OOM killer may not free memory on a specific node.
  3132. */
  3133. if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
  3134. goto out;
  3135. /* The OOM killer does not needlessly kill tasks for lowmem */
  3136. if (ac->highest_zoneidx < ZONE_NORMAL)
  3137. goto out;
  3138. if (pm_suspended_storage())
  3139. goto out;
  3140. /*
  3141. * XXX: GFP_NOFS allocations should rather fail than rely on
  3142. * other request to make a forward progress.
  3143. * We are in an unfortunate situation where out_of_memory cannot
  3144. * do much for this context but let's try it to at least get
  3145. * access to memory reserved if the current task is killed (see
  3146. * out_of_memory). Once filesystems are ready to handle allocation
  3147. * failures more gracefully we should just bail out here.
  3148. */
  3149. /* Exhausted what can be done so it's blame time */
  3150. if (out_of_memory(&oc) ||
  3151. WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) {
  3152. *did_some_progress = 1;
  3153. /*
  3154. * Help non-failing allocations by giving them access to memory
  3155. * reserves
  3156. */
  3157. if (gfp_mask & __GFP_NOFAIL)
  3158. page = __alloc_pages_cpuset_fallback(gfp_mask, order,
  3159. ALLOC_NO_WATERMARKS, ac);
  3160. }
  3161. out:
  3162. mutex_unlock(&oom_lock);
  3163. return page;
  3164. }
  3165. /*
  3166. * Maximum number of compaction retries with a progress before OOM
  3167. * killer is consider as the only way to move forward.
  3168. */
  3169. #define MAX_COMPACT_RETRIES 16
  3170. #ifdef CONFIG_COMPACTION
  3171. /* Try memory compaction for high-order allocations before reclaim */
  3172. static struct page *
  3173. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3174. unsigned int alloc_flags, const struct alloc_context *ac,
  3175. enum compact_priority prio, enum compact_result *compact_result)
  3176. {
  3177. struct page *page = NULL;
  3178. unsigned long pflags;
  3179. unsigned int noreclaim_flag;
  3180. if (!order)
  3181. return NULL;
  3182. psi_memstall_enter(&pflags);
  3183. delayacct_compact_start();
  3184. noreclaim_flag = memalloc_noreclaim_save();
  3185. *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
  3186. prio, &page);
  3187. memalloc_noreclaim_restore(noreclaim_flag);
  3188. psi_memstall_leave(&pflags);
  3189. delayacct_compact_end();
  3190. if (*compact_result == COMPACT_SKIPPED)
  3191. return NULL;
  3192. /*
  3193. * At least in one zone compaction wasn't deferred or skipped, so let's
  3194. * count a compaction stall
  3195. */
  3196. count_vm_event(COMPACTSTALL);
  3197. /* Prep a captured page if available */
  3198. if (page)
  3199. prep_new_page(page, order, gfp_mask, alloc_flags);
  3200. /* Try get a page from the freelist if available */
  3201. if (!page)
  3202. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3203. if (page) {
  3204. struct zone *zone = page_zone(page);
  3205. zone->compact_blockskip_flush = false;
  3206. compaction_defer_reset(zone, order, true);
  3207. count_vm_event(COMPACTSUCCESS);
  3208. return page;
  3209. }
  3210. /*
  3211. * It's bad if compaction run occurs and fails. The most likely reason
  3212. * is that pages exist, but not enough to satisfy watermarks.
  3213. */
  3214. count_vm_event(COMPACTFAIL);
  3215. cond_resched();
  3216. return NULL;
  3217. }
  3218. static inline bool
  3219. should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
  3220. enum compact_result compact_result,
  3221. enum compact_priority *compact_priority,
  3222. int *compaction_retries)
  3223. {
  3224. int max_retries = MAX_COMPACT_RETRIES;
  3225. int min_priority;
  3226. bool ret = false;
  3227. int retries = *compaction_retries;
  3228. enum compact_priority priority = *compact_priority;
  3229. if (!order)
  3230. return false;
  3231. if (fatal_signal_pending(current))
  3232. return false;
  3233. /*
  3234. * Compaction was skipped due to a lack of free order-0
  3235. * migration targets. Continue if reclaim can help.
  3236. */
  3237. if (compact_result == COMPACT_SKIPPED) {
  3238. ret = compaction_zonelist_suitable(ac, order, alloc_flags);
  3239. goto out;
  3240. }
  3241. /*
  3242. * Compaction managed to coalesce some page blocks, but the
  3243. * allocation failed presumably due to a race. Retry some.
  3244. */
  3245. if (compact_result == COMPACT_SUCCESS) {
  3246. /*
  3247. * !costly requests are much more important than
  3248. * __GFP_RETRY_MAYFAIL costly ones because they are de
  3249. * facto nofail and invoke OOM killer to move on while
  3250. * costly can fail and users are ready to cope with
  3251. * that. 1/4 retries is rather arbitrary but we would
  3252. * need much more detailed feedback from compaction to
  3253. * make a better decision.
  3254. */
  3255. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3256. max_retries /= 4;
  3257. if (++(*compaction_retries) <= max_retries) {
  3258. ret = true;
  3259. goto out;
  3260. }
  3261. }
  3262. /*
  3263. * Compaction failed. Retry with increasing priority.
  3264. */
  3265. min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
  3266. MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
  3267. if (*compact_priority > min_priority) {
  3268. (*compact_priority)--;
  3269. *compaction_retries = 0;
  3270. ret = true;
  3271. }
  3272. out:
  3273. trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
  3274. return ret;
  3275. }
  3276. #else
  3277. static inline struct page *
  3278. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3279. unsigned int alloc_flags, const struct alloc_context *ac,
  3280. enum compact_priority prio, enum compact_result *compact_result)
  3281. {
  3282. *compact_result = COMPACT_SKIPPED;
  3283. return NULL;
  3284. }
  3285. static inline bool
  3286. should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
  3287. enum compact_result compact_result,
  3288. enum compact_priority *compact_priority,
  3289. int *compaction_retries)
  3290. {
  3291. struct zone *zone;
  3292. struct zoneref *z;
  3293. if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
  3294. return false;
  3295. /*
  3296. * There are setups with compaction disabled which would prefer to loop
  3297. * inside the allocator rather than hit the oom killer prematurely.
  3298. * Let's give them a good hope and keep retrying while the order-0
  3299. * watermarks are OK.
  3300. */
  3301. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  3302. ac->highest_zoneidx, ac->nodemask) {
  3303. if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
  3304. ac->highest_zoneidx, alloc_flags))
  3305. return true;
  3306. }
  3307. return false;
  3308. }
  3309. #endif /* CONFIG_COMPACTION */
  3310. #ifdef CONFIG_LOCKDEP
  3311. static struct lockdep_map __fs_reclaim_map =
  3312. STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
  3313. static bool __need_reclaim(gfp_t gfp_mask)
  3314. {
  3315. /* no reclaim without waiting on it */
  3316. if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
  3317. return false;
  3318. /* this guy won't enter reclaim */
  3319. if (current->flags & PF_MEMALLOC)
  3320. return false;
  3321. if (gfp_mask & __GFP_NOLOCKDEP)
  3322. return false;
  3323. return true;
  3324. }
  3325. void __fs_reclaim_acquire(unsigned long ip)
  3326. {
  3327. lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
  3328. }
  3329. void __fs_reclaim_release(unsigned long ip)
  3330. {
  3331. lock_release(&__fs_reclaim_map, ip);
  3332. }
  3333. void fs_reclaim_acquire(gfp_t gfp_mask)
  3334. {
  3335. gfp_mask = current_gfp_context(gfp_mask);
  3336. if (__need_reclaim(gfp_mask)) {
  3337. if (gfp_mask & __GFP_FS)
  3338. __fs_reclaim_acquire(_RET_IP_);
  3339. #ifdef CONFIG_MMU_NOTIFIER
  3340. lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
  3341. lock_map_release(&__mmu_notifier_invalidate_range_start_map);
  3342. #endif
  3343. }
  3344. }
  3345. EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
  3346. void fs_reclaim_release(gfp_t gfp_mask)
  3347. {
  3348. gfp_mask = current_gfp_context(gfp_mask);
  3349. if (__need_reclaim(gfp_mask)) {
  3350. if (gfp_mask & __GFP_FS)
  3351. __fs_reclaim_release(_RET_IP_);
  3352. }
  3353. }
  3354. EXPORT_SYMBOL_GPL(fs_reclaim_release);
  3355. #endif
  3356. /*
  3357. * Zonelists may change due to hotplug during allocation. Detect when zonelists
  3358. * have been rebuilt so allocation retries. Reader side does not lock and
  3359. * retries the allocation if zonelist changes. Writer side is protected by the
  3360. * embedded spin_lock.
  3361. */
  3362. static DEFINE_SEQLOCK(zonelist_update_seq);
  3363. static unsigned int zonelist_iter_begin(void)
  3364. {
  3365. if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
  3366. return read_seqbegin(&zonelist_update_seq);
  3367. return 0;
  3368. }
  3369. static unsigned int check_retry_zonelist(unsigned int seq)
  3370. {
  3371. if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
  3372. return read_seqretry(&zonelist_update_seq, seq);
  3373. return seq;
  3374. }
  3375. /* Perform direct synchronous page reclaim */
  3376. static unsigned long
  3377. __perform_reclaim(gfp_t gfp_mask, unsigned int order,
  3378. const struct alloc_context *ac)
  3379. {
  3380. unsigned int noreclaim_flag;
  3381. unsigned long progress;
  3382. cond_resched();
  3383. /* We now go into synchronous reclaim */
  3384. cpuset_memory_pressure_bump();
  3385. fs_reclaim_acquire(gfp_mask);
  3386. noreclaim_flag = memalloc_noreclaim_save();
  3387. progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
  3388. ac->nodemask);
  3389. memalloc_noreclaim_restore(noreclaim_flag);
  3390. fs_reclaim_release(gfp_mask);
  3391. cond_resched();
  3392. return progress;
  3393. }
  3394. /* The really slow allocator path where we enter direct reclaim */
  3395. static inline struct page *
  3396. __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
  3397. unsigned int alloc_flags, const struct alloc_context *ac,
  3398. unsigned long *did_some_progress)
  3399. {
  3400. struct page *page = NULL;
  3401. unsigned long pflags;
  3402. bool drained = false;
  3403. psi_memstall_enter(&pflags);
  3404. *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
  3405. if (unlikely(!(*did_some_progress)))
  3406. goto out;
  3407. retry:
  3408. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3409. /*
  3410. * If an allocation failed after direct reclaim, it could be because
  3411. * pages are pinned on the per-cpu lists or in high alloc reserves.
  3412. * Shrink them and try again
  3413. */
  3414. if (!page && !drained) {
  3415. unreserve_highatomic_pageblock(ac, false);
  3416. drain_all_pages(NULL);
  3417. drained = true;
  3418. goto retry;
  3419. }
  3420. out:
  3421. psi_memstall_leave(&pflags);
  3422. return page;
  3423. }
  3424. static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
  3425. const struct alloc_context *ac)
  3426. {
  3427. struct zoneref *z;
  3428. struct zone *zone;
  3429. pg_data_t *last_pgdat = NULL;
  3430. enum zone_type highest_zoneidx = ac->highest_zoneidx;
  3431. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
  3432. ac->nodemask) {
  3433. if (!managed_zone(zone))
  3434. continue;
  3435. if (last_pgdat != zone->zone_pgdat) {
  3436. wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
  3437. last_pgdat = zone->zone_pgdat;
  3438. }
  3439. }
  3440. }
  3441. static inline unsigned int
  3442. gfp_to_alloc_flags(gfp_t gfp_mask, unsigned int order)
  3443. {
  3444. unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
  3445. /*
  3446. * __GFP_HIGH is assumed to be the same as ALLOC_MIN_RESERVE
  3447. * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
  3448. * to save two branches.
  3449. */
  3450. BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_MIN_RESERVE);
  3451. BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
  3452. /*
  3453. * The caller may dip into page reserves a bit more if the caller
  3454. * cannot run direct reclaim, or if the caller has realtime scheduling
  3455. * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
  3456. * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH).
  3457. */
  3458. alloc_flags |= (__force int)
  3459. (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
  3460. if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
  3461. /*
  3462. * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
  3463. * if it can't schedule.
  3464. */
  3465. if (!(gfp_mask & __GFP_NOMEMALLOC)) {
  3466. alloc_flags |= ALLOC_NON_BLOCK;
  3467. if (order > 0)
  3468. alloc_flags |= ALLOC_HIGHATOMIC;
  3469. }
  3470. /*
  3471. * Ignore cpuset mems for non-blocking __GFP_HIGH (probably
  3472. * GFP_ATOMIC) rather than fail, see the comment for
  3473. * cpuset_node_allowed().
  3474. */
  3475. if (alloc_flags & ALLOC_MIN_RESERVE)
  3476. alloc_flags &= ~ALLOC_CPUSET;
  3477. } else if (unlikely(rt_or_dl_task(current)) && in_task())
  3478. alloc_flags |= ALLOC_MIN_RESERVE;
  3479. alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
  3480. return alloc_flags;
  3481. }
  3482. static bool oom_reserves_allowed(struct task_struct *tsk)
  3483. {
  3484. if (!tsk_is_oom_victim(tsk))
  3485. return false;
  3486. /*
  3487. * !MMU doesn't have oom reaper so give access to memory reserves
  3488. * only to the thread with TIF_MEMDIE set
  3489. */
  3490. if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
  3491. return false;
  3492. return true;
  3493. }
  3494. /*
  3495. * Distinguish requests which really need access to full memory
  3496. * reserves from oom victims which can live with a portion of it
  3497. */
  3498. static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
  3499. {
  3500. if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
  3501. return 0;
  3502. if (gfp_mask & __GFP_MEMALLOC)
  3503. return ALLOC_NO_WATERMARKS;
  3504. if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
  3505. return ALLOC_NO_WATERMARKS;
  3506. if (!in_interrupt()) {
  3507. if (current->flags & PF_MEMALLOC)
  3508. return ALLOC_NO_WATERMARKS;
  3509. else if (oom_reserves_allowed(current))
  3510. return ALLOC_OOM;
  3511. }
  3512. return 0;
  3513. }
  3514. bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
  3515. {
  3516. return !!__gfp_pfmemalloc_flags(gfp_mask);
  3517. }
  3518. /*
  3519. * Checks whether it makes sense to retry the reclaim to make a forward progress
  3520. * for the given allocation request.
  3521. *
  3522. * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
  3523. * without success, or when we couldn't even meet the watermark if we
  3524. * reclaimed all remaining pages on the LRU lists.
  3525. *
  3526. * Returns true if a retry is viable or false to enter the oom path.
  3527. */
  3528. static inline bool
  3529. should_reclaim_retry(gfp_t gfp_mask, unsigned order,
  3530. struct alloc_context *ac, int alloc_flags,
  3531. bool did_some_progress, int *no_progress_loops)
  3532. {
  3533. struct zone *zone;
  3534. struct zoneref *z;
  3535. bool ret = false;
  3536. /*
  3537. * Costly allocations might have made a progress but this doesn't mean
  3538. * their order will become available due to high fragmentation so
  3539. * always increment the no progress counter for them
  3540. */
  3541. if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
  3542. *no_progress_loops = 0;
  3543. else
  3544. (*no_progress_loops)++;
  3545. if (*no_progress_loops > MAX_RECLAIM_RETRIES)
  3546. goto out;
  3547. /*
  3548. * Keep reclaiming pages while there is a chance this will lead
  3549. * somewhere. If none of the target zones can satisfy our allocation
  3550. * request even if all reclaimable pages are considered then we are
  3551. * screwed and have to go OOM.
  3552. */
  3553. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  3554. ac->highest_zoneidx, ac->nodemask) {
  3555. unsigned long available;
  3556. unsigned long reclaimable;
  3557. unsigned long min_wmark = min_wmark_pages(zone);
  3558. bool wmark;
  3559. if (cpusets_enabled() &&
  3560. (alloc_flags & ALLOC_CPUSET) &&
  3561. !__cpuset_zone_allowed(zone, gfp_mask))
  3562. continue;
  3563. available = reclaimable = zone_reclaimable_pages(zone);
  3564. available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  3565. /*
  3566. * Would the allocation succeed if we reclaimed all
  3567. * reclaimable pages?
  3568. */
  3569. wmark = __zone_watermark_ok(zone, order, min_wmark,
  3570. ac->highest_zoneidx, alloc_flags, available);
  3571. trace_reclaim_retry_zone(z, order, reclaimable,
  3572. available, min_wmark, *no_progress_loops, wmark);
  3573. if (wmark) {
  3574. ret = true;
  3575. break;
  3576. }
  3577. }
  3578. /*
  3579. * Memory allocation/reclaim might be called from a WQ context and the
  3580. * current implementation of the WQ concurrency control doesn't
  3581. * recognize that a particular WQ is congested if the worker thread is
  3582. * looping without ever sleeping. Therefore we have to do a short sleep
  3583. * here rather than calling cond_resched().
  3584. */
  3585. if (current->flags & PF_WQ_WORKER)
  3586. schedule_timeout_uninterruptible(1);
  3587. else
  3588. cond_resched();
  3589. out:
  3590. /* Before OOM, exhaust highatomic_reserve */
  3591. if (!ret)
  3592. return unreserve_highatomic_pageblock(ac, true);
  3593. return ret;
  3594. }
  3595. static inline bool
  3596. check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
  3597. {
  3598. /*
  3599. * It's possible that cpuset's mems_allowed and the nodemask from
  3600. * mempolicy don't intersect. This should be normally dealt with by
  3601. * policy_nodemask(), but it's possible to race with cpuset update in
  3602. * such a way the check therein was true, and then it became false
  3603. * before we got our cpuset_mems_cookie here.
  3604. * This assumes that for all allocations, ac->nodemask can come only
  3605. * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
  3606. * when it does not intersect with the cpuset restrictions) or the
  3607. * caller can deal with a violated nodemask.
  3608. */
  3609. if (cpusets_enabled() && ac->nodemask &&
  3610. !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
  3611. ac->nodemask = NULL;
  3612. return true;
  3613. }
  3614. /*
  3615. * When updating a task's mems_allowed or mempolicy nodemask, it is
  3616. * possible to race with parallel threads in such a way that our
  3617. * allocation can fail while the mask is being updated. If we are about
  3618. * to fail, check if the cpuset changed during allocation and if so,
  3619. * retry.
  3620. */
  3621. if (read_mems_allowed_retry(cpuset_mems_cookie))
  3622. return true;
  3623. return false;
  3624. }
  3625. static inline struct page *
  3626. __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
  3627. struct alloc_context *ac)
  3628. {
  3629. bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
  3630. bool can_compact = gfp_compaction_allowed(gfp_mask);
  3631. bool nofail = gfp_mask & __GFP_NOFAIL;
  3632. const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
  3633. struct page *page = NULL;
  3634. unsigned int alloc_flags;
  3635. unsigned long did_some_progress;
  3636. enum compact_priority compact_priority;
  3637. enum compact_result compact_result;
  3638. int compaction_retries;
  3639. int no_progress_loops;
  3640. unsigned int cpuset_mems_cookie;
  3641. unsigned int zonelist_iter_cookie;
  3642. int reserve_flags;
  3643. if (unlikely(nofail)) {
  3644. /*
  3645. * We most definitely don't want callers attempting to
  3646. * allocate greater than order-1 page units with __GFP_NOFAIL.
  3647. */
  3648. WARN_ON_ONCE(order > 1);
  3649. /*
  3650. * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM,
  3651. * otherwise, we may result in lockup.
  3652. */
  3653. WARN_ON_ONCE(!can_direct_reclaim);
  3654. /*
  3655. * PF_MEMALLOC request from this context is rather bizarre
  3656. * because we cannot reclaim anything and only can loop waiting
  3657. * for somebody to do a work for us.
  3658. */
  3659. WARN_ON_ONCE(current->flags & PF_MEMALLOC);
  3660. }
  3661. restart:
  3662. compaction_retries = 0;
  3663. no_progress_loops = 0;
  3664. compact_priority = DEF_COMPACT_PRIORITY;
  3665. cpuset_mems_cookie = read_mems_allowed_begin();
  3666. zonelist_iter_cookie = zonelist_iter_begin();
  3667. /*
  3668. * The fast path uses conservative alloc_flags to succeed only until
  3669. * kswapd needs to be woken up, and to avoid the cost of setting up
  3670. * alloc_flags precisely. So we do that now.
  3671. */
  3672. alloc_flags = gfp_to_alloc_flags(gfp_mask, order);
  3673. /*
  3674. * We need to recalculate the starting point for the zonelist iterator
  3675. * because we might have used different nodemask in the fast path, or
  3676. * there was a cpuset modification and we are retrying - otherwise we
  3677. * could end up iterating over non-eligible zones endlessly.
  3678. */
  3679. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3680. ac->highest_zoneidx, ac->nodemask);
  3681. if (!zonelist_zone(ac->preferred_zoneref))
  3682. goto nopage;
  3683. /*
  3684. * Check for insane configurations where the cpuset doesn't contain
  3685. * any suitable zone to satisfy the request - e.g. non-movable
  3686. * GFP_HIGHUSER allocations from MOVABLE nodes only.
  3687. */
  3688. if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
  3689. struct zoneref *z = first_zones_zonelist(ac->zonelist,
  3690. ac->highest_zoneidx,
  3691. &cpuset_current_mems_allowed);
  3692. if (!zonelist_zone(z))
  3693. goto nopage;
  3694. }
  3695. if (alloc_flags & ALLOC_KSWAPD)
  3696. wake_all_kswapds(order, gfp_mask, ac);
  3697. /*
  3698. * The adjusted alloc_flags might result in immediate success, so try
  3699. * that first
  3700. */
  3701. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3702. if (page)
  3703. goto got_pg;
  3704. /*
  3705. * For costly allocations, try direct compaction first, as it's likely
  3706. * that we have enough base pages and don't need to reclaim. For non-
  3707. * movable high-order allocations, do that as well, as compaction will
  3708. * try prevent permanent fragmentation by migrating from blocks of the
  3709. * same migratetype.
  3710. * Don't try this for allocations that are allowed to ignore
  3711. * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
  3712. */
  3713. if (can_direct_reclaim && can_compact &&
  3714. (costly_order ||
  3715. (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
  3716. && !gfp_pfmemalloc_allowed(gfp_mask)) {
  3717. page = __alloc_pages_direct_compact(gfp_mask, order,
  3718. alloc_flags, ac,
  3719. INIT_COMPACT_PRIORITY,
  3720. &compact_result);
  3721. if (page)
  3722. goto got_pg;
  3723. /*
  3724. * Checks for costly allocations with __GFP_NORETRY, which
  3725. * includes some THP page fault allocations
  3726. */
  3727. if (costly_order && (gfp_mask & __GFP_NORETRY)) {
  3728. /*
  3729. * If allocating entire pageblock(s) and compaction
  3730. * failed because all zones are below low watermarks
  3731. * or is prohibited because it recently failed at this
  3732. * order, fail immediately unless the allocator has
  3733. * requested compaction and reclaim retry.
  3734. *
  3735. * Reclaim is
  3736. * - potentially very expensive because zones are far
  3737. * below their low watermarks or this is part of very
  3738. * bursty high order allocations,
  3739. * - not guaranteed to help because isolate_freepages()
  3740. * may not iterate over freed pages as part of its
  3741. * linear scan, and
  3742. * - unlikely to make entire pageblocks free on its
  3743. * own.
  3744. */
  3745. if (compact_result == COMPACT_SKIPPED ||
  3746. compact_result == COMPACT_DEFERRED)
  3747. goto nopage;
  3748. /*
  3749. * Looks like reclaim/compaction is worth trying, but
  3750. * sync compaction could be very expensive, so keep
  3751. * using async compaction.
  3752. */
  3753. compact_priority = INIT_COMPACT_PRIORITY;
  3754. }
  3755. }
  3756. retry:
  3757. /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
  3758. if (alloc_flags & ALLOC_KSWAPD)
  3759. wake_all_kswapds(order, gfp_mask, ac);
  3760. reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
  3761. if (reserve_flags)
  3762. alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) |
  3763. (alloc_flags & ALLOC_KSWAPD);
  3764. /*
  3765. * Reset the nodemask and zonelist iterators if memory policies can be
  3766. * ignored. These allocations are high priority and system rather than
  3767. * user oriented.
  3768. */
  3769. if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
  3770. ac->nodemask = NULL;
  3771. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3772. ac->highest_zoneidx, ac->nodemask);
  3773. }
  3774. /* Attempt with potentially adjusted zonelist and alloc_flags */
  3775. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3776. if (page)
  3777. goto got_pg;
  3778. /* Caller is not willing to reclaim, we can't balance anything */
  3779. if (!can_direct_reclaim)
  3780. goto nopage;
  3781. /* Avoid recursion of direct reclaim */
  3782. if (current->flags & PF_MEMALLOC)
  3783. goto nopage;
  3784. /* Try direct reclaim and then allocating */
  3785. page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
  3786. &did_some_progress);
  3787. if (page)
  3788. goto got_pg;
  3789. /* Try direct compaction and then allocating */
  3790. page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
  3791. compact_priority, &compact_result);
  3792. if (page)
  3793. goto got_pg;
  3794. /* Do not loop if specifically requested */
  3795. if (gfp_mask & __GFP_NORETRY)
  3796. goto nopage;
  3797. /*
  3798. * Do not retry costly high order allocations unless they are
  3799. * __GFP_RETRY_MAYFAIL and we can compact
  3800. */
  3801. if (costly_order && (!can_compact ||
  3802. !(gfp_mask & __GFP_RETRY_MAYFAIL)))
  3803. goto nopage;
  3804. if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
  3805. did_some_progress > 0, &no_progress_loops))
  3806. goto retry;
  3807. /*
  3808. * It doesn't make any sense to retry for the compaction if the order-0
  3809. * reclaim is not able to make any progress because the current
  3810. * implementation of the compaction depends on the sufficient amount
  3811. * of free memory (see __compaction_suitable)
  3812. */
  3813. if (did_some_progress > 0 && can_compact &&
  3814. should_compact_retry(ac, order, alloc_flags,
  3815. compact_result, &compact_priority,
  3816. &compaction_retries))
  3817. goto retry;
  3818. /*
  3819. * Deal with possible cpuset update races or zonelist updates to avoid
  3820. * a unnecessary OOM kill.
  3821. */
  3822. if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
  3823. check_retry_zonelist(zonelist_iter_cookie))
  3824. goto restart;
  3825. /* Reclaim has failed us, start killing things */
  3826. page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
  3827. if (page)
  3828. goto got_pg;
  3829. /* Avoid allocations with no watermarks from looping endlessly */
  3830. if (tsk_is_oom_victim(current) &&
  3831. (alloc_flags & ALLOC_OOM ||
  3832. (gfp_mask & __GFP_NOMEMALLOC)))
  3833. goto nopage;
  3834. /* Retry as long as the OOM killer is making progress */
  3835. if (did_some_progress) {
  3836. no_progress_loops = 0;
  3837. goto retry;
  3838. }
  3839. nopage:
  3840. /*
  3841. * Deal with possible cpuset update races or zonelist updates to avoid
  3842. * a unnecessary OOM kill.
  3843. */
  3844. if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
  3845. check_retry_zonelist(zonelist_iter_cookie))
  3846. goto restart;
  3847. /*
  3848. * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
  3849. * we always retry
  3850. */
  3851. if (unlikely(nofail)) {
  3852. /*
  3853. * Lacking direct_reclaim we can't do anything to reclaim memory,
  3854. * we disregard these unreasonable nofail requests and still
  3855. * return NULL
  3856. */
  3857. if (!can_direct_reclaim)
  3858. goto fail;
  3859. /*
  3860. * Help non-failing allocations by giving some access to memory
  3861. * reserves normally used for high priority non-blocking
  3862. * allocations but do not use ALLOC_NO_WATERMARKS because this
  3863. * could deplete whole memory reserves which would just make
  3864. * the situation worse.
  3865. */
  3866. page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac);
  3867. if (page)
  3868. goto got_pg;
  3869. cond_resched();
  3870. goto retry;
  3871. }
  3872. fail:
  3873. warn_alloc(gfp_mask, ac->nodemask,
  3874. "page allocation failure: order:%u", order);
  3875. got_pg:
  3876. return page;
  3877. }
  3878. static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
  3879. int preferred_nid, nodemask_t *nodemask,
  3880. struct alloc_context *ac, gfp_t *alloc_gfp,
  3881. unsigned int *alloc_flags)
  3882. {
  3883. ac->highest_zoneidx = gfp_zone(gfp_mask);
  3884. ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
  3885. ac->nodemask = nodemask;
  3886. ac->migratetype = gfp_migratetype(gfp_mask);
  3887. if (cpusets_enabled()) {
  3888. *alloc_gfp |= __GFP_HARDWALL;
  3889. /*
  3890. * When we are in the interrupt context, it is irrelevant
  3891. * to the current task context. It means that any node ok.
  3892. */
  3893. if (in_task() && !ac->nodemask)
  3894. ac->nodemask = &cpuset_current_mems_allowed;
  3895. else
  3896. *alloc_flags |= ALLOC_CPUSET;
  3897. }
  3898. might_alloc(gfp_mask);
  3899. if (should_fail_alloc_page(gfp_mask, order))
  3900. return false;
  3901. *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
  3902. /* Dirty zone balancing only done in the fast path */
  3903. ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
  3904. /*
  3905. * The preferred zone is used for statistics but crucially it is
  3906. * also used as the starting point for the zonelist iterator. It
  3907. * may get reset for allocations that ignore memory policies.
  3908. */
  3909. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3910. ac->highest_zoneidx, ac->nodemask);
  3911. return true;
  3912. }
  3913. /*
  3914. * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array
  3915. * @gfp: GFP flags for the allocation
  3916. * @preferred_nid: The preferred NUMA node ID to allocate from
  3917. * @nodemask: Set of nodes to allocate from, may be NULL
  3918. * @nr_pages: The number of pages desired on the list or array
  3919. * @page_list: Optional list to store the allocated pages
  3920. * @page_array: Optional array to store the pages
  3921. *
  3922. * This is a batched version of the page allocator that attempts to
  3923. * allocate nr_pages quickly. Pages are added to page_list if page_list
  3924. * is not NULL, otherwise it is assumed that the page_array is valid.
  3925. *
  3926. * For lists, nr_pages is the number of pages that should be allocated.
  3927. *
  3928. * For arrays, only NULL elements are populated with pages and nr_pages
  3929. * is the maximum number of pages that will be stored in the array.
  3930. *
  3931. * Returns the number of pages on the list or array.
  3932. */
  3933. unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
  3934. nodemask_t *nodemask, int nr_pages,
  3935. struct list_head *page_list,
  3936. struct page **page_array)
  3937. {
  3938. struct page *page;
  3939. unsigned long __maybe_unused UP_flags;
  3940. struct zone *zone;
  3941. struct zoneref *z;
  3942. struct per_cpu_pages *pcp;
  3943. struct list_head *pcp_list;
  3944. struct alloc_context ac;
  3945. gfp_t alloc_gfp;
  3946. unsigned int alloc_flags = ALLOC_WMARK_LOW;
  3947. int nr_populated = 0, nr_account = 0;
  3948. /*
  3949. * Skip populated array elements to determine if any pages need
  3950. * to be allocated before disabling IRQs.
  3951. */
  3952. while (page_array && nr_populated < nr_pages && page_array[nr_populated])
  3953. nr_populated++;
  3954. /* No pages requested? */
  3955. if (unlikely(nr_pages <= 0))
  3956. goto out;
  3957. /* Already populated array? */
  3958. if (unlikely(page_array && nr_pages - nr_populated == 0))
  3959. goto out;
  3960. /* Bulk allocator does not support memcg accounting. */
  3961. if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
  3962. goto failed;
  3963. /* Use the single page allocator for one page. */
  3964. if (nr_pages - nr_populated == 1)
  3965. goto failed;
  3966. #ifdef CONFIG_PAGE_OWNER
  3967. /*
  3968. * PAGE_OWNER may recurse into the allocator to allocate space to
  3969. * save the stack with pagesets.lock held. Releasing/reacquiring
  3970. * removes much of the performance benefit of bulk allocation so
  3971. * force the caller to allocate one page at a time as it'll have
  3972. * similar performance to added complexity to the bulk allocator.
  3973. */
  3974. if (static_branch_unlikely(&page_owner_inited))
  3975. goto failed;
  3976. #endif
  3977. /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
  3978. gfp &= gfp_allowed_mask;
  3979. alloc_gfp = gfp;
  3980. if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
  3981. goto out;
  3982. gfp = alloc_gfp;
  3983. /* Find an allowed local zone that meets the low watermark. */
  3984. z = ac.preferred_zoneref;
  3985. for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
  3986. unsigned long mark;
  3987. if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
  3988. !__cpuset_zone_allowed(zone, gfp)) {
  3989. continue;
  3990. }
  3991. if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
  3992. zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
  3993. goto failed;
  3994. }
  3995. cond_accept_memory(zone, 0);
  3996. retry_this_zone:
  3997. mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
  3998. if (zone_watermark_fast(zone, 0, mark,
  3999. zonelist_zone_idx(ac.preferred_zoneref),
  4000. alloc_flags, gfp)) {
  4001. break;
  4002. }
  4003. if (cond_accept_memory(zone, 0))
  4004. goto retry_this_zone;
  4005. /* Try again if zone has deferred pages */
  4006. if (deferred_pages_enabled()) {
  4007. if (_deferred_grow_zone(zone, 0))
  4008. goto retry_this_zone;
  4009. }
  4010. }
  4011. /*
  4012. * If there are no allowed local zones that meets the watermarks then
  4013. * try to allocate a single page and reclaim if necessary.
  4014. */
  4015. if (unlikely(!zone))
  4016. goto failed;
  4017. /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
  4018. pcp_trylock_prepare(UP_flags);
  4019. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  4020. if (!pcp)
  4021. goto failed_irq;
  4022. /* Attempt the batch allocation */
  4023. pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
  4024. while (nr_populated < nr_pages) {
  4025. /* Skip existing pages */
  4026. if (page_array && page_array[nr_populated]) {
  4027. nr_populated++;
  4028. continue;
  4029. }
  4030. page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
  4031. pcp, pcp_list);
  4032. if (unlikely(!page)) {
  4033. /* Try and allocate at least one page */
  4034. if (!nr_account) {
  4035. pcp_spin_unlock(pcp);
  4036. goto failed_irq;
  4037. }
  4038. break;
  4039. }
  4040. nr_account++;
  4041. prep_new_page(page, 0, gfp, 0);
  4042. if (page_list)
  4043. list_add(&page->lru, page_list);
  4044. else
  4045. page_array[nr_populated] = page;
  4046. nr_populated++;
  4047. }
  4048. pcp_spin_unlock(pcp);
  4049. pcp_trylock_finish(UP_flags);
  4050. __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
  4051. zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
  4052. out:
  4053. return nr_populated;
  4054. failed_irq:
  4055. pcp_trylock_finish(UP_flags);
  4056. failed:
  4057. page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask);
  4058. if (page) {
  4059. if (page_list)
  4060. list_add(&page->lru, page_list);
  4061. else
  4062. page_array[nr_populated] = page;
  4063. nr_populated++;
  4064. }
  4065. goto out;
  4066. }
  4067. EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof);
  4068. /*
  4069. * This is the 'heart' of the zoned buddy allocator.
  4070. */
  4071. struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
  4072. int preferred_nid, nodemask_t *nodemask)
  4073. {
  4074. struct page *page;
  4075. unsigned int alloc_flags = ALLOC_WMARK_LOW;
  4076. gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
  4077. struct alloc_context ac = { };
  4078. /*
  4079. * There are several places where we assume that the order value is sane
  4080. * so bail out early if the request is out of bound.
  4081. */
  4082. if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp))
  4083. return NULL;
  4084. gfp &= gfp_allowed_mask;
  4085. /*
  4086. * Apply scoped allocation constraints. This is mainly about GFP_NOFS
  4087. * resp. GFP_NOIO which has to be inherited for all allocation requests
  4088. * from a particular context which has been marked by
  4089. * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
  4090. * movable zones are not used during allocation.
  4091. */
  4092. gfp = current_gfp_context(gfp);
  4093. alloc_gfp = gfp;
  4094. if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
  4095. &alloc_gfp, &alloc_flags))
  4096. return NULL;
  4097. /*
  4098. * Forbid the first pass from falling back to types that fragment
  4099. * memory until all local zones are considered.
  4100. */
  4101. alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp);
  4102. /* First allocation attempt */
  4103. page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
  4104. if (likely(page))
  4105. goto out;
  4106. alloc_gfp = gfp;
  4107. ac.spread_dirty_pages = false;
  4108. /*
  4109. * Restore the original nodemask if it was potentially replaced with
  4110. * &cpuset_current_mems_allowed to optimize the fast-path attempt.
  4111. */
  4112. ac.nodemask = nodemask;
  4113. page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
  4114. out:
  4115. if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page &&
  4116. unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
  4117. __free_pages(page, order);
  4118. page = NULL;
  4119. }
  4120. trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
  4121. kmsan_alloc_page(page, order, alloc_gfp);
  4122. return page;
  4123. }
  4124. EXPORT_SYMBOL(__alloc_pages_noprof);
  4125. struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid,
  4126. nodemask_t *nodemask)
  4127. {
  4128. struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order,
  4129. preferred_nid, nodemask);
  4130. return page_rmappable_folio(page);
  4131. }
  4132. EXPORT_SYMBOL(__folio_alloc_noprof);
  4133. /*
  4134. * Common helper functions. Never use with __GFP_HIGHMEM because the returned
  4135. * address cannot represent highmem pages. Use alloc_pages and then kmap if
  4136. * you need to access high mem.
  4137. */
  4138. unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order)
  4139. {
  4140. struct page *page;
  4141. page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order);
  4142. if (!page)
  4143. return 0;
  4144. return (unsigned long) page_address(page);
  4145. }
  4146. EXPORT_SYMBOL(get_free_pages_noprof);
  4147. unsigned long get_zeroed_page_noprof(gfp_t gfp_mask)
  4148. {
  4149. return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0);
  4150. }
  4151. EXPORT_SYMBOL(get_zeroed_page_noprof);
  4152. /**
  4153. * __free_pages - Free pages allocated with alloc_pages().
  4154. * @page: The page pointer returned from alloc_pages().
  4155. * @order: The order of the allocation.
  4156. *
  4157. * This function can free multi-page allocations that are not compound
  4158. * pages. It does not check that the @order passed in matches that of
  4159. * the allocation, so it is easy to leak memory. Freeing more memory
  4160. * than was allocated will probably emit a warning.
  4161. *
  4162. * If the last reference to this page is speculative, it will be released
  4163. * by put_page() which only frees the first page of a non-compound
  4164. * allocation. To prevent the remaining pages from being leaked, we free
  4165. * the subsequent pages here. If you want to use the page's reference
  4166. * count to decide when to free the allocation, you should allocate a
  4167. * compound page, and use put_page() instead of __free_pages().
  4168. *
  4169. * Context: May be called in interrupt context or while holding a normal
  4170. * spinlock, but not in NMI context or while holding a raw spinlock.
  4171. */
  4172. void __free_pages(struct page *page, unsigned int order)
  4173. {
  4174. /* get PageHead before we drop reference */
  4175. int head = PageHead(page);
  4176. struct alloc_tag *tag = pgalloc_tag_get(page);
  4177. if (put_page_testzero(page))
  4178. free_unref_page(page, order);
  4179. else if (!head) {
  4180. pgalloc_tag_sub_pages(tag, (1 << order) - 1);
  4181. while (order-- > 0)
  4182. free_unref_page(page + (1 << order), order);
  4183. }
  4184. }
  4185. EXPORT_SYMBOL(__free_pages);
  4186. void free_pages(unsigned long addr, unsigned int order)
  4187. {
  4188. if (addr != 0) {
  4189. VM_BUG_ON(!virt_addr_valid((void *)addr));
  4190. __free_pages(virt_to_page((void *)addr), order);
  4191. }
  4192. }
  4193. EXPORT_SYMBOL(free_pages);
  4194. /*
  4195. * Page Fragment:
  4196. * An arbitrary-length arbitrary-offset area of memory which resides
  4197. * within a 0 or higher order page. Multiple fragments within that page
  4198. * are individually refcounted, in the page's reference counter.
  4199. *
  4200. * The page_frag functions below provide a simple allocation framework for
  4201. * page fragments. This is used by the network stack and network device
  4202. * drivers to provide a backing region of memory for use as either an
  4203. * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
  4204. */
  4205. static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
  4206. gfp_t gfp_mask)
  4207. {
  4208. struct page *page = NULL;
  4209. gfp_t gfp = gfp_mask;
  4210. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4211. gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP |
  4212. __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
  4213. page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
  4214. PAGE_FRAG_CACHE_MAX_ORDER);
  4215. nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
  4216. #endif
  4217. if (unlikely(!page))
  4218. page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
  4219. nc->va = page ? page_address(page) : NULL;
  4220. return page;
  4221. }
  4222. void page_frag_cache_drain(struct page_frag_cache *nc)
  4223. {
  4224. if (!nc->va)
  4225. return;
  4226. __page_frag_cache_drain(virt_to_head_page(nc->va), nc->pagecnt_bias);
  4227. nc->va = NULL;
  4228. }
  4229. EXPORT_SYMBOL(page_frag_cache_drain);
  4230. void __page_frag_cache_drain(struct page *page, unsigned int count)
  4231. {
  4232. VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
  4233. if (page_ref_sub_and_test(page, count))
  4234. free_unref_page(page, compound_order(page));
  4235. }
  4236. EXPORT_SYMBOL(__page_frag_cache_drain);
  4237. void *__page_frag_alloc_align(struct page_frag_cache *nc,
  4238. unsigned int fragsz, gfp_t gfp_mask,
  4239. unsigned int align_mask)
  4240. {
  4241. unsigned int size = PAGE_SIZE;
  4242. struct page *page;
  4243. int offset;
  4244. if (unlikely(!nc->va)) {
  4245. refill:
  4246. page = __page_frag_cache_refill(nc, gfp_mask);
  4247. if (!page)
  4248. return NULL;
  4249. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4250. /* if size can vary use size else just use PAGE_SIZE */
  4251. size = nc->size;
  4252. #endif
  4253. /* Even if we own the page, we do not use atomic_set().
  4254. * This would break get_page_unless_zero() users.
  4255. */
  4256. page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
  4257. /* reset page count bias and offset to start of new frag */
  4258. nc->pfmemalloc = page_is_pfmemalloc(page);
  4259. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  4260. nc->offset = size;
  4261. }
  4262. offset = nc->offset - fragsz;
  4263. if (unlikely(offset < 0)) {
  4264. page = virt_to_page(nc->va);
  4265. if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
  4266. goto refill;
  4267. if (unlikely(nc->pfmemalloc)) {
  4268. free_unref_page(page, compound_order(page));
  4269. goto refill;
  4270. }
  4271. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4272. /* if size can vary use size else just use PAGE_SIZE */
  4273. size = nc->size;
  4274. #endif
  4275. /* OK, page count is 0, we can safely set it */
  4276. set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
  4277. /* reset page count bias and offset to start of new frag */
  4278. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  4279. offset = size - fragsz;
  4280. if (unlikely(offset < 0)) {
  4281. /*
  4282. * The caller is trying to allocate a fragment
  4283. * with fragsz > PAGE_SIZE but the cache isn't big
  4284. * enough to satisfy the request, this may
  4285. * happen in low memory conditions.
  4286. * We don't release the cache page because
  4287. * it could make memory pressure worse
  4288. * so we simply return NULL here.
  4289. */
  4290. return NULL;
  4291. }
  4292. }
  4293. nc->pagecnt_bias--;
  4294. offset &= align_mask;
  4295. nc->offset = offset;
  4296. return nc->va + offset;
  4297. }
  4298. EXPORT_SYMBOL(__page_frag_alloc_align);
  4299. /*
  4300. * Frees a page fragment allocated out of either a compound or order 0 page.
  4301. */
  4302. void page_frag_free(void *addr)
  4303. {
  4304. struct page *page = virt_to_head_page(addr);
  4305. if (unlikely(put_page_testzero(page)))
  4306. free_unref_page(page, compound_order(page));
  4307. }
  4308. EXPORT_SYMBOL(page_frag_free);
  4309. static void *make_alloc_exact(unsigned long addr, unsigned int order,
  4310. size_t size)
  4311. {
  4312. if (addr) {
  4313. unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE);
  4314. struct page *page = virt_to_page((void *)addr);
  4315. struct page *last = page + nr;
  4316. split_page_owner(page, order, 0);
  4317. pgalloc_tag_split(page_folio(page), order, 0);
  4318. split_page_memcg(page, order, 0);
  4319. while (page < --last)
  4320. set_page_refcounted(last);
  4321. last = page + (1UL << order);
  4322. for (page += nr; page < last; page++)
  4323. __free_pages_ok(page, 0, FPI_TO_TAIL);
  4324. }
  4325. return (void *)addr;
  4326. }
  4327. /**
  4328. * alloc_pages_exact - allocate an exact number physically-contiguous pages.
  4329. * @size: the number of bytes to allocate
  4330. * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
  4331. *
  4332. * This function is similar to alloc_pages(), except that it allocates the
  4333. * minimum number of pages to satisfy the request. alloc_pages() can only
  4334. * allocate memory in power-of-two pages.
  4335. *
  4336. * This function is also limited by MAX_PAGE_ORDER.
  4337. *
  4338. * Memory allocated by this function must be released by free_pages_exact().
  4339. *
  4340. * Return: pointer to the allocated area or %NULL in case of error.
  4341. */
  4342. void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
  4343. {
  4344. unsigned int order = get_order(size);
  4345. unsigned long addr;
  4346. if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
  4347. gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
  4348. addr = get_free_pages_noprof(gfp_mask, order);
  4349. return make_alloc_exact(addr, order, size);
  4350. }
  4351. EXPORT_SYMBOL(alloc_pages_exact_noprof);
  4352. /**
  4353. * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
  4354. * pages on a node.
  4355. * @nid: the preferred node ID where memory should be allocated
  4356. * @size: the number of bytes to allocate
  4357. * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
  4358. *
  4359. * Like alloc_pages_exact(), but try to allocate on node nid first before falling
  4360. * back.
  4361. *
  4362. * Return: pointer to the allocated area or %NULL in case of error.
  4363. */
  4364. void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
  4365. {
  4366. unsigned int order = get_order(size);
  4367. struct page *p;
  4368. if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
  4369. gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
  4370. p = alloc_pages_node_noprof(nid, gfp_mask, order);
  4371. if (!p)
  4372. return NULL;
  4373. return make_alloc_exact((unsigned long)page_address(p), order, size);
  4374. }
  4375. /**
  4376. * free_pages_exact - release memory allocated via alloc_pages_exact()
  4377. * @virt: the value returned by alloc_pages_exact.
  4378. * @size: size of allocation, same value as passed to alloc_pages_exact().
  4379. *
  4380. * Release the memory allocated by a previous call to alloc_pages_exact.
  4381. */
  4382. void free_pages_exact(void *virt, size_t size)
  4383. {
  4384. unsigned long addr = (unsigned long)virt;
  4385. unsigned long end = addr + PAGE_ALIGN(size);
  4386. while (addr < end) {
  4387. free_page(addr);
  4388. addr += PAGE_SIZE;
  4389. }
  4390. }
  4391. EXPORT_SYMBOL(free_pages_exact);
  4392. /**
  4393. * nr_free_zone_pages - count number of pages beyond high watermark
  4394. * @offset: The zone index of the highest zone
  4395. *
  4396. * nr_free_zone_pages() counts the number of pages which are beyond the
  4397. * high watermark within all zones at or below a given zone index. For each
  4398. * zone, the number of pages is calculated as:
  4399. *
  4400. * nr_free_zone_pages = managed_pages - high_pages
  4401. *
  4402. * Return: number of pages beyond high watermark.
  4403. */
  4404. static unsigned long nr_free_zone_pages(int offset)
  4405. {
  4406. struct zoneref *z;
  4407. struct zone *zone;
  4408. /* Just pick one node, since fallback list is circular */
  4409. unsigned long sum = 0;
  4410. struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
  4411. for_each_zone_zonelist(zone, z, zonelist, offset) {
  4412. unsigned long size = zone_managed_pages(zone);
  4413. unsigned long high = high_wmark_pages(zone);
  4414. if (size > high)
  4415. sum += size - high;
  4416. }
  4417. return sum;
  4418. }
  4419. /**
  4420. * nr_free_buffer_pages - count number of pages beyond high watermark
  4421. *
  4422. * nr_free_buffer_pages() counts the number of pages which are beyond the high
  4423. * watermark within ZONE_DMA and ZONE_NORMAL.
  4424. *
  4425. * Return: number of pages beyond high watermark within ZONE_DMA and
  4426. * ZONE_NORMAL.
  4427. */
  4428. unsigned long nr_free_buffer_pages(void)
  4429. {
  4430. return nr_free_zone_pages(gfp_zone(GFP_USER));
  4431. }
  4432. EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
  4433. static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
  4434. {
  4435. zoneref->zone = zone;
  4436. zoneref->zone_idx = zone_idx(zone);
  4437. }
  4438. /*
  4439. * Builds allocation fallback zone lists.
  4440. *
  4441. * Add all populated zones of a node to the zonelist.
  4442. */
  4443. static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
  4444. {
  4445. struct zone *zone;
  4446. enum zone_type zone_type = MAX_NR_ZONES;
  4447. int nr_zones = 0;
  4448. do {
  4449. zone_type--;
  4450. zone = pgdat->node_zones + zone_type;
  4451. if (populated_zone(zone)) {
  4452. zoneref_set_zone(zone, &zonerefs[nr_zones++]);
  4453. check_highest_zone(zone_type);
  4454. }
  4455. } while (zone_type);
  4456. return nr_zones;
  4457. }
  4458. #ifdef CONFIG_NUMA
  4459. static int __parse_numa_zonelist_order(char *s)
  4460. {
  4461. /*
  4462. * We used to support different zonelists modes but they turned
  4463. * out to be just not useful. Let's keep the warning in place
  4464. * if somebody still use the cmd line parameter so that we do
  4465. * not fail it silently
  4466. */
  4467. if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
  4468. pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
  4469. return -EINVAL;
  4470. }
  4471. return 0;
  4472. }
  4473. static char numa_zonelist_order[] = "Node";
  4474. #define NUMA_ZONELIST_ORDER_LEN 16
  4475. /*
  4476. * sysctl handler for numa_zonelist_order
  4477. */
  4478. static int numa_zonelist_order_handler(const struct ctl_table *table, int write,
  4479. void *buffer, size_t *length, loff_t *ppos)
  4480. {
  4481. if (write)
  4482. return __parse_numa_zonelist_order(buffer);
  4483. return proc_dostring(table, write, buffer, length, ppos);
  4484. }
  4485. static int node_load[MAX_NUMNODES];
  4486. /**
  4487. * find_next_best_node - find the next node that should appear in a given node's fallback list
  4488. * @node: node whose fallback list we're appending
  4489. * @used_node_mask: nodemask_t of already used nodes
  4490. *
  4491. * We use a number of factors to determine which is the next node that should
  4492. * appear on a given node's fallback list. The node should not have appeared
  4493. * already in @node's fallback list, and it should be the next closest node
  4494. * according to the distance array (which contains arbitrary distance values
  4495. * from each node to each node in the system), and should also prefer nodes
  4496. * with no CPUs, since presumably they'll have very little allocation pressure
  4497. * on them otherwise.
  4498. *
  4499. * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
  4500. */
  4501. int find_next_best_node(int node, nodemask_t *used_node_mask)
  4502. {
  4503. int n, val;
  4504. int min_val = INT_MAX;
  4505. int best_node = NUMA_NO_NODE;
  4506. /*
  4507. * Use the local node if we haven't already, but for memoryless local
  4508. * node, we should skip it and fall back to other nodes.
  4509. */
  4510. if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) {
  4511. node_set(node, *used_node_mask);
  4512. return node;
  4513. }
  4514. for_each_node_state(n, N_MEMORY) {
  4515. /* Don't want a node to appear more than once */
  4516. if (node_isset(n, *used_node_mask))
  4517. continue;
  4518. /* Use the distance array to find the distance */
  4519. val = node_distance(node, n);
  4520. /* Penalize nodes under us ("prefer the next node") */
  4521. val += (n < node);
  4522. /* Give preference to headless and unused nodes */
  4523. if (!cpumask_empty(cpumask_of_node(n)))
  4524. val += PENALTY_FOR_NODE_WITH_CPUS;
  4525. /* Slight preference for less loaded node */
  4526. val *= MAX_NUMNODES;
  4527. val += node_load[n];
  4528. if (val < min_val) {
  4529. min_val = val;
  4530. best_node = n;
  4531. }
  4532. }
  4533. if (best_node >= 0)
  4534. node_set(best_node, *used_node_mask);
  4535. return best_node;
  4536. }
  4537. /*
  4538. * Build zonelists ordered by node and zones within node.
  4539. * This results in maximum locality--normal zone overflows into local
  4540. * DMA zone, if any--but risks exhausting DMA zone.
  4541. */
  4542. static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
  4543. unsigned nr_nodes)
  4544. {
  4545. struct zoneref *zonerefs;
  4546. int i;
  4547. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4548. for (i = 0; i < nr_nodes; i++) {
  4549. int nr_zones;
  4550. pg_data_t *node = NODE_DATA(node_order[i]);
  4551. nr_zones = build_zonerefs_node(node, zonerefs);
  4552. zonerefs += nr_zones;
  4553. }
  4554. zonerefs->zone = NULL;
  4555. zonerefs->zone_idx = 0;
  4556. }
  4557. /*
  4558. * Build __GFP_THISNODE zonelists
  4559. */
  4560. static void build_thisnode_zonelists(pg_data_t *pgdat)
  4561. {
  4562. struct zoneref *zonerefs;
  4563. int nr_zones;
  4564. zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
  4565. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4566. zonerefs += nr_zones;
  4567. zonerefs->zone = NULL;
  4568. zonerefs->zone_idx = 0;
  4569. }
  4570. /*
  4571. * Build zonelists ordered by zone and nodes within zones.
  4572. * This results in conserving DMA zone[s] until all Normal memory is
  4573. * exhausted, but results in overflowing to remote node while memory
  4574. * may still exist in local DMA zone.
  4575. */
  4576. static void build_zonelists(pg_data_t *pgdat)
  4577. {
  4578. static int node_order[MAX_NUMNODES];
  4579. int node, nr_nodes = 0;
  4580. nodemask_t used_mask = NODE_MASK_NONE;
  4581. int local_node, prev_node;
  4582. /* NUMA-aware ordering of nodes */
  4583. local_node = pgdat->node_id;
  4584. prev_node = local_node;
  4585. memset(node_order, 0, sizeof(node_order));
  4586. while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
  4587. /*
  4588. * We don't want to pressure a particular node.
  4589. * So adding penalty to the first node in same
  4590. * distance group to make it round-robin.
  4591. */
  4592. if (node_distance(local_node, node) !=
  4593. node_distance(local_node, prev_node))
  4594. node_load[node] += 1;
  4595. node_order[nr_nodes++] = node;
  4596. prev_node = node;
  4597. }
  4598. build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
  4599. build_thisnode_zonelists(pgdat);
  4600. pr_info("Fallback order for Node %d: ", local_node);
  4601. for (node = 0; node < nr_nodes; node++)
  4602. pr_cont("%d ", node_order[node]);
  4603. pr_cont("\n");
  4604. }
  4605. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4606. /*
  4607. * Return node id of node used for "local" allocations.
  4608. * I.e., first node id of first zone in arg node's generic zonelist.
  4609. * Used for initializing percpu 'numa_mem', which is used primarily
  4610. * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
  4611. */
  4612. int local_memory_node(int node)
  4613. {
  4614. struct zoneref *z;
  4615. z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
  4616. gfp_zone(GFP_KERNEL),
  4617. NULL);
  4618. return zonelist_node_idx(z);
  4619. }
  4620. #endif
  4621. static void setup_min_unmapped_ratio(void);
  4622. static void setup_min_slab_ratio(void);
  4623. #else /* CONFIG_NUMA */
  4624. static void build_zonelists(pg_data_t *pgdat)
  4625. {
  4626. struct zoneref *zonerefs;
  4627. int nr_zones;
  4628. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4629. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4630. zonerefs += nr_zones;
  4631. zonerefs->zone = NULL;
  4632. zonerefs->zone_idx = 0;
  4633. }
  4634. #endif /* CONFIG_NUMA */
  4635. /*
  4636. * Boot pageset table. One per cpu which is going to be used for all
  4637. * zones and all nodes. The parameters will be set in such a way
  4638. * that an item put on a list will immediately be handed over to
  4639. * the buddy list. This is safe since pageset manipulation is done
  4640. * with interrupts disabled.
  4641. *
  4642. * The boot_pagesets must be kept even after bootup is complete for
  4643. * unused processors and/or zones. They do play a role for bootstrapping
  4644. * hotplugged processors.
  4645. *
  4646. * zoneinfo_show() and maybe other functions do
  4647. * not check if the processor is online before following the pageset pointer.
  4648. * Other parts of the kernel may not check if the zone is available.
  4649. */
  4650. static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
  4651. /* These effectively disable the pcplists in the boot pageset completely */
  4652. #define BOOT_PAGESET_HIGH 0
  4653. #define BOOT_PAGESET_BATCH 1
  4654. static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
  4655. static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
  4656. static void __build_all_zonelists(void *data)
  4657. {
  4658. int nid;
  4659. int __maybe_unused cpu;
  4660. pg_data_t *self = data;
  4661. unsigned long flags;
  4662. /*
  4663. * The zonelist_update_seq must be acquired with irqsave because the
  4664. * reader can be invoked from IRQ with GFP_ATOMIC.
  4665. */
  4666. write_seqlock_irqsave(&zonelist_update_seq, flags);
  4667. /*
  4668. * Also disable synchronous printk() to prevent any printk() from
  4669. * trying to hold port->lock, for
  4670. * tty_insert_flip_string_and_push_buffer() on other CPU might be
  4671. * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held.
  4672. */
  4673. printk_deferred_enter();
  4674. #ifdef CONFIG_NUMA
  4675. memset(node_load, 0, sizeof(node_load));
  4676. #endif
  4677. /*
  4678. * This node is hotadded and no memory is yet present. So just
  4679. * building zonelists is fine - no need to touch other nodes.
  4680. */
  4681. if (self && !node_online(self->node_id)) {
  4682. build_zonelists(self);
  4683. } else {
  4684. /*
  4685. * All possible nodes have pgdat preallocated
  4686. * in free_area_init
  4687. */
  4688. for_each_node(nid) {
  4689. pg_data_t *pgdat = NODE_DATA(nid);
  4690. build_zonelists(pgdat);
  4691. }
  4692. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4693. /*
  4694. * We now know the "local memory node" for each node--
  4695. * i.e., the node of the first zone in the generic zonelist.
  4696. * Set up numa_mem percpu variable for on-line cpus. During
  4697. * boot, only the boot cpu should be on-line; we'll init the
  4698. * secondary cpus' numa_mem as they come on-line. During
  4699. * node/memory hotplug, we'll fixup all on-line cpus.
  4700. */
  4701. for_each_online_cpu(cpu)
  4702. set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
  4703. #endif
  4704. }
  4705. printk_deferred_exit();
  4706. write_sequnlock_irqrestore(&zonelist_update_seq, flags);
  4707. }
  4708. static noinline void __init
  4709. build_all_zonelists_init(void)
  4710. {
  4711. int cpu;
  4712. __build_all_zonelists(NULL);
  4713. /*
  4714. * Initialize the boot_pagesets that are going to be used
  4715. * for bootstrapping processors. The real pagesets for
  4716. * each zone will be allocated later when the per cpu
  4717. * allocator is available.
  4718. *
  4719. * boot_pagesets are used also for bootstrapping offline
  4720. * cpus if the system is already booted because the pagesets
  4721. * are needed to initialize allocators on a specific cpu too.
  4722. * F.e. the percpu allocator needs the page allocator which
  4723. * needs the percpu allocator in order to allocate its pagesets
  4724. * (a chicken-egg dilemma).
  4725. */
  4726. for_each_possible_cpu(cpu)
  4727. per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
  4728. mminit_verify_zonelist();
  4729. cpuset_init_current_mems_allowed();
  4730. }
  4731. /*
  4732. * unless system_state == SYSTEM_BOOTING.
  4733. *
  4734. * __ref due to call of __init annotated helper build_all_zonelists_init
  4735. * [protected by SYSTEM_BOOTING].
  4736. */
  4737. void __ref build_all_zonelists(pg_data_t *pgdat)
  4738. {
  4739. unsigned long vm_total_pages;
  4740. if (system_state == SYSTEM_BOOTING) {
  4741. build_all_zonelists_init();
  4742. } else {
  4743. __build_all_zonelists(pgdat);
  4744. /* cpuset refresh routine should be here */
  4745. }
  4746. /* Get the number of free pages beyond high watermark in all zones. */
  4747. vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
  4748. /*
  4749. * Disable grouping by mobility if the number of pages in the
  4750. * system is too low to allow the mechanism to work. It would be
  4751. * more accurate, but expensive to check per-zone. This check is
  4752. * made on memory-hotadd so a system can start with mobility
  4753. * disabled and enable it later
  4754. */
  4755. if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
  4756. page_group_by_mobility_disabled = 1;
  4757. else
  4758. page_group_by_mobility_disabled = 0;
  4759. pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
  4760. nr_online_nodes,
  4761. page_group_by_mobility_disabled ? "off" : "on",
  4762. vm_total_pages);
  4763. #ifdef CONFIG_NUMA
  4764. pr_info("Policy zone: %s\n", zone_names[policy_zone]);
  4765. #endif
  4766. }
  4767. static int zone_batchsize(struct zone *zone)
  4768. {
  4769. #ifdef CONFIG_MMU
  4770. int batch;
  4771. /*
  4772. * The number of pages to batch allocate is either ~0.1%
  4773. * of the zone or 1MB, whichever is smaller. The batch
  4774. * size is striking a balance between allocation latency
  4775. * and zone lock contention.
  4776. */
  4777. batch = min(zone_managed_pages(zone) >> 10, SZ_1M / PAGE_SIZE);
  4778. batch /= 4; /* We effectively *= 4 below */
  4779. if (batch < 1)
  4780. batch = 1;
  4781. /*
  4782. * Clamp the batch to a 2^n - 1 value. Having a power
  4783. * of 2 value was found to be more likely to have
  4784. * suboptimal cache aliasing properties in some cases.
  4785. *
  4786. * For example if 2 tasks are alternately allocating
  4787. * batches of pages, one task can end up with a lot
  4788. * of pages of one half of the possible page colors
  4789. * and the other with pages of the other colors.
  4790. */
  4791. batch = rounddown_pow_of_two(batch + batch/2) - 1;
  4792. return batch;
  4793. #else
  4794. /* The deferral and batching of frees should be suppressed under NOMMU
  4795. * conditions.
  4796. *
  4797. * The problem is that NOMMU needs to be able to allocate large chunks
  4798. * of contiguous memory as there's no hardware page translation to
  4799. * assemble apparent contiguous memory from discontiguous pages.
  4800. *
  4801. * Queueing large contiguous runs of pages for batching, however,
  4802. * causes the pages to actually be freed in smaller chunks. As there
  4803. * can be a significant delay between the individual batches being
  4804. * recycled, this leads to the once large chunks of space being
  4805. * fragmented and becoming unavailable for high-order allocations.
  4806. */
  4807. return 0;
  4808. #endif
  4809. }
  4810. static int percpu_pagelist_high_fraction;
  4811. static int zone_highsize(struct zone *zone, int batch, int cpu_online,
  4812. int high_fraction)
  4813. {
  4814. #ifdef CONFIG_MMU
  4815. int high;
  4816. int nr_split_cpus;
  4817. unsigned long total_pages;
  4818. if (!high_fraction) {
  4819. /*
  4820. * By default, the high value of the pcp is based on the zone
  4821. * low watermark so that if they are full then background
  4822. * reclaim will not be started prematurely.
  4823. */
  4824. total_pages = low_wmark_pages(zone);
  4825. } else {
  4826. /*
  4827. * If percpu_pagelist_high_fraction is configured, the high
  4828. * value is based on a fraction of the managed pages in the
  4829. * zone.
  4830. */
  4831. total_pages = zone_managed_pages(zone) / high_fraction;
  4832. }
  4833. /*
  4834. * Split the high value across all online CPUs local to the zone. Note
  4835. * that early in boot that CPUs may not be online yet and that during
  4836. * CPU hotplug that the cpumask is not yet updated when a CPU is being
  4837. * onlined. For memory nodes that have no CPUs, split the high value
  4838. * across all online CPUs to mitigate the risk that reclaim is triggered
  4839. * prematurely due to pages stored on pcp lists.
  4840. */
  4841. nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
  4842. if (!nr_split_cpus)
  4843. nr_split_cpus = num_online_cpus();
  4844. high = total_pages / nr_split_cpus;
  4845. /*
  4846. * Ensure high is at least batch*4. The multiple is based on the
  4847. * historical relationship between high and batch.
  4848. */
  4849. high = max(high, batch << 2);
  4850. return high;
  4851. #else
  4852. return 0;
  4853. #endif
  4854. }
  4855. /*
  4856. * pcp->high and pcp->batch values are related and generally batch is lower
  4857. * than high. They are also related to pcp->count such that count is lower
  4858. * than high, and as soon as it reaches high, the pcplist is flushed.
  4859. *
  4860. * However, guaranteeing these relations at all times would require e.g. write
  4861. * barriers here but also careful usage of read barriers at the read side, and
  4862. * thus be prone to error and bad for performance. Thus the update only prevents
  4863. * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max
  4864. * should ensure they can cope with those fields changing asynchronously, and
  4865. * fully trust only the pcp->count field on the local CPU with interrupts
  4866. * disabled.
  4867. *
  4868. * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
  4869. * outside of boot time (or some other assurance that no concurrent updaters
  4870. * exist).
  4871. */
  4872. static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min,
  4873. unsigned long high_max, unsigned long batch)
  4874. {
  4875. WRITE_ONCE(pcp->batch, batch);
  4876. WRITE_ONCE(pcp->high_min, high_min);
  4877. WRITE_ONCE(pcp->high_max, high_max);
  4878. }
  4879. static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
  4880. {
  4881. int pindex;
  4882. memset(pcp, 0, sizeof(*pcp));
  4883. memset(pzstats, 0, sizeof(*pzstats));
  4884. spin_lock_init(&pcp->lock);
  4885. for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
  4886. INIT_LIST_HEAD(&pcp->lists[pindex]);
  4887. /*
  4888. * Set batch and high values safe for a boot pageset. A true percpu
  4889. * pageset's initialization will update them subsequently. Here we don't
  4890. * need to be as careful as pageset_update() as nobody can access the
  4891. * pageset yet.
  4892. */
  4893. pcp->high_min = BOOT_PAGESET_HIGH;
  4894. pcp->high_max = BOOT_PAGESET_HIGH;
  4895. pcp->batch = BOOT_PAGESET_BATCH;
  4896. pcp->free_count = 0;
  4897. }
  4898. static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min,
  4899. unsigned long high_max, unsigned long batch)
  4900. {
  4901. struct per_cpu_pages *pcp;
  4902. int cpu;
  4903. for_each_possible_cpu(cpu) {
  4904. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  4905. pageset_update(pcp, high_min, high_max, batch);
  4906. }
  4907. }
  4908. /*
  4909. * Calculate and set new high and batch values for all per-cpu pagesets of a
  4910. * zone based on the zone's size.
  4911. */
  4912. static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
  4913. {
  4914. int new_high_min, new_high_max, new_batch;
  4915. new_batch = max(1, zone_batchsize(zone));
  4916. if (percpu_pagelist_high_fraction) {
  4917. new_high_min = zone_highsize(zone, new_batch, cpu_online,
  4918. percpu_pagelist_high_fraction);
  4919. /*
  4920. * PCP high is tuned manually, disable auto-tuning via
  4921. * setting high_min and high_max to the manual value.
  4922. */
  4923. new_high_max = new_high_min;
  4924. } else {
  4925. new_high_min = zone_highsize(zone, new_batch, cpu_online, 0);
  4926. new_high_max = zone_highsize(zone, new_batch, cpu_online,
  4927. MIN_PERCPU_PAGELIST_HIGH_FRACTION);
  4928. }
  4929. if (zone->pageset_high_min == new_high_min &&
  4930. zone->pageset_high_max == new_high_max &&
  4931. zone->pageset_batch == new_batch)
  4932. return;
  4933. zone->pageset_high_min = new_high_min;
  4934. zone->pageset_high_max = new_high_max;
  4935. zone->pageset_batch = new_batch;
  4936. __zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max,
  4937. new_batch);
  4938. }
  4939. void __meminit setup_zone_pageset(struct zone *zone)
  4940. {
  4941. int cpu;
  4942. /* Size may be 0 on !SMP && !NUMA */
  4943. if (sizeof(struct per_cpu_zonestat) > 0)
  4944. zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
  4945. zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
  4946. for_each_possible_cpu(cpu) {
  4947. struct per_cpu_pages *pcp;
  4948. struct per_cpu_zonestat *pzstats;
  4949. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  4950. pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
  4951. per_cpu_pages_init(pcp, pzstats);
  4952. }
  4953. zone_set_pageset_high_and_batch(zone, 0);
  4954. }
  4955. /*
  4956. * The zone indicated has a new number of managed_pages; batch sizes and percpu
  4957. * page high values need to be recalculated.
  4958. */
  4959. static void zone_pcp_update(struct zone *zone, int cpu_online)
  4960. {
  4961. mutex_lock(&pcp_batch_high_lock);
  4962. zone_set_pageset_high_and_batch(zone, cpu_online);
  4963. mutex_unlock(&pcp_batch_high_lock);
  4964. }
  4965. static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu)
  4966. {
  4967. struct per_cpu_pages *pcp;
  4968. struct cpu_cacheinfo *cci;
  4969. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  4970. cci = get_cpu_cacheinfo(cpu);
  4971. /*
  4972. * If data cache slice of CPU is large enough, "pcp->batch"
  4973. * pages can be preserved in PCP before draining PCP for
  4974. * consecutive high-order pages freeing without allocation.
  4975. * This can reduce zone lock contention without hurting
  4976. * cache-hot pages sharing.
  4977. */
  4978. spin_lock(&pcp->lock);
  4979. if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch)
  4980. pcp->flags |= PCPF_FREE_HIGH_BATCH;
  4981. else
  4982. pcp->flags &= ~PCPF_FREE_HIGH_BATCH;
  4983. spin_unlock(&pcp->lock);
  4984. }
  4985. void setup_pcp_cacheinfo(unsigned int cpu)
  4986. {
  4987. struct zone *zone;
  4988. for_each_populated_zone(zone)
  4989. zone_pcp_update_cacheinfo(zone, cpu);
  4990. }
  4991. /*
  4992. * Allocate per cpu pagesets and initialize them.
  4993. * Before this call only boot pagesets were available.
  4994. */
  4995. void __init setup_per_cpu_pageset(void)
  4996. {
  4997. struct pglist_data *pgdat;
  4998. struct zone *zone;
  4999. int __maybe_unused cpu;
  5000. for_each_populated_zone(zone)
  5001. setup_zone_pageset(zone);
  5002. #ifdef CONFIG_NUMA
  5003. /*
  5004. * Unpopulated zones continue using the boot pagesets.
  5005. * The numa stats for these pagesets need to be reset.
  5006. * Otherwise, they will end up skewing the stats of
  5007. * the nodes these zones are associated with.
  5008. */
  5009. for_each_possible_cpu(cpu) {
  5010. struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
  5011. memset(pzstats->vm_numa_event, 0,
  5012. sizeof(pzstats->vm_numa_event));
  5013. }
  5014. #endif
  5015. for_each_online_pgdat(pgdat)
  5016. pgdat->per_cpu_nodestats =
  5017. alloc_percpu(struct per_cpu_nodestat);
  5018. }
  5019. __meminit void zone_pcp_init(struct zone *zone)
  5020. {
  5021. /*
  5022. * per cpu subsystem is not up at this point. The following code
  5023. * relies on the ability of the linker to provide the
  5024. * offset of a (static) per cpu variable into the per cpu area.
  5025. */
  5026. zone->per_cpu_pageset = &boot_pageset;
  5027. zone->per_cpu_zonestats = &boot_zonestats;
  5028. zone->pageset_high_min = BOOT_PAGESET_HIGH;
  5029. zone->pageset_high_max = BOOT_PAGESET_HIGH;
  5030. zone->pageset_batch = BOOT_PAGESET_BATCH;
  5031. if (populated_zone(zone))
  5032. pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name,
  5033. zone->present_pages, zone_batchsize(zone));
  5034. }
  5035. void adjust_managed_page_count(struct page *page, long count)
  5036. {
  5037. atomic_long_add(count, &page_zone(page)->managed_pages);
  5038. totalram_pages_add(count);
  5039. }
  5040. EXPORT_SYMBOL(adjust_managed_page_count);
  5041. unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
  5042. {
  5043. void *pos;
  5044. unsigned long pages = 0;
  5045. start = (void *)PAGE_ALIGN((unsigned long)start);
  5046. end = (void *)((unsigned long)end & PAGE_MASK);
  5047. for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
  5048. struct page *page = virt_to_page(pos);
  5049. void *direct_map_addr;
  5050. /*
  5051. * 'direct_map_addr' might be different from 'pos'
  5052. * because some architectures' virt_to_page()
  5053. * work with aliases. Getting the direct map
  5054. * address ensures that we get a _writeable_
  5055. * alias for the memset().
  5056. */
  5057. direct_map_addr = page_address(page);
  5058. /*
  5059. * Perform a kasan-unchecked memset() since this memory
  5060. * has not been initialized.
  5061. */
  5062. direct_map_addr = kasan_reset_tag(direct_map_addr);
  5063. if ((unsigned int)poison <= 0xFF)
  5064. memset(direct_map_addr, poison, PAGE_SIZE);
  5065. free_reserved_page(page);
  5066. }
  5067. if (pages && s)
  5068. pr_info("Freeing %s memory: %ldK\n", s, K(pages));
  5069. return pages;
  5070. }
  5071. void free_reserved_page(struct page *page)
  5072. {
  5073. clear_page_tag_ref(page);
  5074. ClearPageReserved(page);
  5075. init_page_count(page);
  5076. __free_page(page);
  5077. adjust_managed_page_count(page, 1);
  5078. }
  5079. EXPORT_SYMBOL(free_reserved_page);
  5080. static int page_alloc_cpu_dead(unsigned int cpu)
  5081. {
  5082. struct zone *zone;
  5083. lru_add_drain_cpu(cpu);
  5084. mlock_drain_remote(cpu);
  5085. drain_pages(cpu);
  5086. /*
  5087. * Spill the event counters of the dead processor
  5088. * into the current processors event counters.
  5089. * This artificially elevates the count of the current
  5090. * processor.
  5091. */
  5092. vm_events_fold_cpu(cpu);
  5093. /*
  5094. * Zero the differential counters of the dead processor
  5095. * so that the vm statistics are consistent.
  5096. *
  5097. * This is only okay since the processor is dead and cannot
  5098. * race with what we are doing.
  5099. */
  5100. cpu_vm_stats_fold(cpu);
  5101. for_each_populated_zone(zone)
  5102. zone_pcp_update(zone, 0);
  5103. return 0;
  5104. }
  5105. static int page_alloc_cpu_online(unsigned int cpu)
  5106. {
  5107. struct zone *zone;
  5108. for_each_populated_zone(zone)
  5109. zone_pcp_update(zone, 1);
  5110. return 0;
  5111. }
  5112. void __init page_alloc_init_cpuhp(void)
  5113. {
  5114. int ret;
  5115. ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
  5116. "mm/page_alloc:pcp",
  5117. page_alloc_cpu_online,
  5118. page_alloc_cpu_dead);
  5119. WARN_ON(ret < 0);
  5120. }
  5121. /*
  5122. * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
  5123. * or min_free_kbytes changes.
  5124. */
  5125. static void calculate_totalreserve_pages(void)
  5126. {
  5127. struct pglist_data *pgdat;
  5128. unsigned long reserve_pages = 0;
  5129. enum zone_type i, j;
  5130. for_each_online_pgdat(pgdat) {
  5131. pgdat->totalreserve_pages = 0;
  5132. for (i = 0; i < MAX_NR_ZONES; i++) {
  5133. struct zone *zone = pgdat->node_zones + i;
  5134. long max = 0;
  5135. unsigned long managed_pages = zone_managed_pages(zone);
  5136. /* Find valid and maximum lowmem_reserve in the zone */
  5137. for (j = i; j < MAX_NR_ZONES; j++) {
  5138. if (zone->lowmem_reserve[j] > max)
  5139. max = zone->lowmem_reserve[j];
  5140. }
  5141. /* we treat the high watermark as reserved pages. */
  5142. max += high_wmark_pages(zone);
  5143. if (max > managed_pages)
  5144. max = managed_pages;
  5145. pgdat->totalreserve_pages += max;
  5146. reserve_pages += max;
  5147. }
  5148. }
  5149. totalreserve_pages = reserve_pages;
  5150. }
  5151. /*
  5152. * setup_per_zone_lowmem_reserve - called whenever
  5153. * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
  5154. * has a correct pages reserved value, so an adequate number of
  5155. * pages are left in the zone after a successful __alloc_pages().
  5156. */
  5157. static void setup_per_zone_lowmem_reserve(void)
  5158. {
  5159. struct pglist_data *pgdat;
  5160. enum zone_type i, j;
  5161. for_each_online_pgdat(pgdat) {
  5162. for (i = 0; i < MAX_NR_ZONES - 1; i++) {
  5163. struct zone *zone = &pgdat->node_zones[i];
  5164. int ratio = sysctl_lowmem_reserve_ratio[i];
  5165. bool clear = !ratio || !zone_managed_pages(zone);
  5166. unsigned long managed_pages = 0;
  5167. for (j = i + 1; j < MAX_NR_ZONES; j++) {
  5168. struct zone *upper_zone = &pgdat->node_zones[j];
  5169. bool empty = !zone_managed_pages(upper_zone);
  5170. managed_pages += zone_managed_pages(upper_zone);
  5171. if (clear || empty)
  5172. zone->lowmem_reserve[j] = 0;
  5173. else
  5174. zone->lowmem_reserve[j] = managed_pages / ratio;
  5175. }
  5176. }
  5177. }
  5178. /* update totalreserve_pages */
  5179. calculate_totalreserve_pages();
  5180. }
  5181. static void __setup_per_zone_wmarks(void)
  5182. {
  5183. unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
  5184. unsigned long lowmem_pages = 0;
  5185. struct zone *zone;
  5186. unsigned long flags;
  5187. /* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */
  5188. for_each_zone(zone) {
  5189. if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE)
  5190. lowmem_pages += zone_managed_pages(zone);
  5191. }
  5192. for_each_zone(zone) {
  5193. u64 tmp;
  5194. spin_lock_irqsave(&zone->lock, flags);
  5195. tmp = (u64)pages_min * zone_managed_pages(zone);
  5196. tmp = div64_ul(tmp, lowmem_pages);
  5197. if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) {
  5198. /*
  5199. * __GFP_HIGH and PF_MEMALLOC allocations usually don't
  5200. * need highmem and movable zones pages, so cap pages_min
  5201. * to a small value here.
  5202. *
  5203. * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
  5204. * deltas control async page reclaim, and so should
  5205. * not be capped for highmem and movable zones.
  5206. */
  5207. unsigned long min_pages;
  5208. min_pages = zone_managed_pages(zone) / 1024;
  5209. min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
  5210. zone->_watermark[WMARK_MIN] = min_pages;
  5211. } else {
  5212. /*
  5213. * If it's a lowmem zone, reserve a number of pages
  5214. * proportionate to the zone's size.
  5215. */
  5216. zone->_watermark[WMARK_MIN] = tmp;
  5217. }
  5218. /*
  5219. * Set the kswapd watermarks distance according to the
  5220. * scale factor in proportion to available memory, but
  5221. * ensure a minimum size on small systems.
  5222. */
  5223. tmp = max_t(u64, tmp >> 2,
  5224. mult_frac(zone_managed_pages(zone),
  5225. watermark_scale_factor, 10000));
  5226. zone->watermark_boost = 0;
  5227. zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
  5228. zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
  5229. zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
  5230. spin_unlock_irqrestore(&zone->lock, flags);
  5231. }
  5232. /* update totalreserve_pages */
  5233. calculate_totalreserve_pages();
  5234. }
  5235. /**
  5236. * setup_per_zone_wmarks - called when min_free_kbytes changes
  5237. * or when memory is hot-{added|removed}
  5238. *
  5239. * Ensures that the watermark[min,low,high] values for each zone are set
  5240. * correctly with respect to min_free_kbytes.
  5241. */
  5242. void setup_per_zone_wmarks(void)
  5243. {
  5244. struct zone *zone;
  5245. static DEFINE_SPINLOCK(lock);
  5246. spin_lock(&lock);
  5247. __setup_per_zone_wmarks();
  5248. spin_unlock(&lock);
  5249. /*
  5250. * The watermark size have changed so update the pcpu batch
  5251. * and high limits or the limits may be inappropriate.
  5252. */
  5253. for_each_zone(zone)
  5254. zone_pcp_update(zone, 0);
  5255. }
  5256. /*
  5257. * Initialise min_free_kbytes.
  5258. *
  5259. * For small machines we want it small (128k min). For large machines
  5260. * we want it large (256MB max). But it is not linear, because network
  5261. * bandwidth does not increase linearly with machine size. We use
  5262. *
  5263. * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
  5264. * min_free_kbytes = sqrt(lowmem_kbytes * 16)
  5265. *
  5266. * which yields
  5267. *
  5268. * 16MB: 512k
  5269. * 32MB: 724k
  5270. * 64MB: 1024k
  5271. * 128MB: 1448k
  5272. * 256MB: 2048k
  5273. * 512MB: 2896k
  5274. * 1024MB: 4096k
  5275. * 2048MB: 5792k
  5276. * 4096MB: 8192k
  5277. * 8192MB: 11584k
  5278. * 16384MB: 16384k
  5279. */
  5280. void calculate_min_free_kbytes(void)
  5281. {
  5282. unsigned long lowmem_kbytes;
  5283. int new_min_free_kbytes;
  5284. lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
  5285. new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
  5286. if (new_min_free_kbytes > user_min_free_kbytes)
  5287. min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
  5288. else
  5289. pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
  5290. new_min_free_kbytes, user_min_free_kbytes);
  5291. }
  5292. int __meminit init_per_zone_wmark_min(void)
  5293. {
  5294. calculate_min_free_kbytes();
  5295. setup_per_zone_wmarks();
  5296. refresh_zone_stat_thresholds();
  5297. setup_per_zone_lowmem_reserve();
  5298. #ifdef CONFIG_NUMA
  5299. setup_min_unmapped_ratio();
  5300. setup_min_slab_ratio();
  5301. #endif
  5302. khugepaged_min_free_kbytes_update();
  5303. return 0;
  5304. }
  5305. postcore_initcall(init_per_zone_wmark_min)
  5306. /*
  5307. * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
  5308. * that we can call two helper functions whenever min_free_kbytes
  5309. * changes.
  5310. */
  5311. static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write,
  5312. void *buffer, size_t *length, loff_t *ppos)
  5313. {
  5314. int rc;
  5315. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5316. if (rc)
  5317. return rc;
  5318. if (write) {
  5319. user_min_free_kbytes = min_free_kbytes;
  5320. setup_per_zone_wmarks();
  5321. }
  5322. return 0;
  5323. }
  5324. static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write,
  5325. void *buffer, size_t *length, loff_t *ppos)
  5326. {
  5327. int rc;
  5328. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5329. if (rc)
  5330. return rc;
  5331. if (write)
  5332. setup_per_zone_wmarks();
  5333. return 0;
  5334. }
  5335. #ifdef CONFIG_NUMA
  5336. static void setup_min_unmapped_ratio(void)
  5337. {
  5338. pg_data_t *pgdat;
  5339. struct zone *zone;
  5340. for_each_online_pgdat(pgdat)
  5341. pgdat->min_unmapped_pages = 0;
  5342. for_each_zone(zone)
  5343. zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
  5344. sysctl_min_unmapped_ratio) / 100;
  5345. }
  5346. static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write,
  5347. void *buffer, size_t *length, loff_t *ppos)
  5348. {
  5349. int rc;
  5350. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5351. if (rc)
  5352. return rc;
  5353. setup_min_unmapped_ratio();
  5354. return 0;
  5355. }
  5356. static void setup_min_slab_ratio(void)
  5357. {
  5358. pg_data_t *pgdat;
  5359. struct zone *zone;
  5360. for_each_online_pgdat(pgdat)
  5361. pgdat->min_slab_pages = 0;
  5362. for_each_zone(zone)
  5363. zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
  5364. sysctl_min_slab_ratio) / 100;
  5365. }
  5366. static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write,
  5367. void *buffer, size_t *length, loff_t *ppos)
  5368. {
  5369. int rc;
  5370. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5371. if (rc)
  5372. return rc;
  5373. setup_min_slab_ratio();
  5374. return 0;
  5375. }
  5376. #endif
  5377. /*
  5378. * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
  5379. * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
  5380. * whenever sysctl_lowmem_reserve_ratio changes.
  5381. *
  5382. * The reserve ratio obviously has absolutely no relation with the
  5383. * minimum watermarks. The lowmem reserve ratio can only make sense
  5384. * if in function of the boot time zone sizes.
  5385. */
  5386. static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table,
  5387. int write, void *buffer, size_t *length, loff_t *ppos)
  5388. {
  5389. int i;
  5390. proc_dointvec_minmax(table, write, buffer, length, ppos);
  5391. for (i = 0; i < MAX_NR_ZONES; i++) {
  5392. if (sysctl_lowmem_reserve_ratio[i] < 1)
  5393. sysctl_lowmem_reserve_ratio[i] = 0;
  5394. }
  5395. setup_per_zone_lowmem_reserve();
  5396. return 0;
  5397. }
  5398. /*
  5399. * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
  5400. * cpu. It is the fraction of total pages in each zone that a hot per cpu
  5401. * pagelist can have before it gets flushed back to buddy allocator.
  5402. */
  5403. static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table,
  5404. int write, void *buffer, size_t *length, loff_t *ppos)
  5405. {
  5406. struct zone *zone;
  5407. int old_percpu_pagelist_high_fraction;
  5408. int ret;
  5409. mutex_lock(&pcp_batch_high_lock);
  5410. old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
  5411. ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5412. if (!write || ret < 0)
  5413. goto out;
  5414. /* Sanity checking to avoid pcp imbalance */
  5415. if (percpu_pagelist_high_fraction &&
  5416. percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
  5417. percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
  5418. ret = -EINVAL;
  5419. goto out;
  5420. }
  5421. /* No change? */
  5422. if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
  5423. goto out;
  5424. for_each_populated_zone(zone)
  5425. zone_set_pageset_high_and_batch(zone, 0);
  5426. out:
  5427. mutex_unlock(&pcp_batch_high_lock);
  5428. return ret;
  5429. }
  5430. static struct ctl_table page_alloc_sysctl_table[] = {
  5431. {
  5432. .procname = "min_free_kbytes",
  5433. .data = &min_free_kbytes,
  5434. .maxlen = sizeof(min_free_kbytes),
  5435. .mode = 0644,
  5436. .proc_handler = min_free_kbytes_sysctl_handler,
  5437. .extra1 = SYSCTL_ZERO,
  5438. },
  5439. {
  5440. .procname = "watermark_boost_factor",
  5441. .data = &watermark_boost_factor,
  5442. .maxlen = sizeof(watermark_boost_factor),
  5443. .mode = 0644,
  5444. .proc_handler = proc_dointvec_minmax,
  5445. .extra1 = SYSCTL_ZERO,
  5446. },
  5447. {
  5448. .procname = "watermark_scale_factor",
  5449. .data = &watermark_scale_factor,
  5450. .maxlen = sizeof(watermark_scale_factor),
  5451. .mode = 0644,
  5452. .proc_handler = watermark_scale_factor_sysctl_handler,
  5453. .extra1 = SYSCTL_ONE,
  5454. .extra2 = SYSCTL_THREE_THOUSAND,
  5455. },
  5456. {
  5457. .procname = "percpu_pagelist_high_fraction",
  5458. .data = &percpu_pagelist_high_fraction,
  5459. .maxlen = sizeof(percpu_pagelist_high_fraction),
  5460. .mode = 0644,
  5461. .proc_handler = percpu_pagelist_high_fraction_sysctl_handler,
  5462. .extra1 = SYSCTL_ZERO,
  5463. },
  5464. {
  5465. .procname = "lowmem_reserve_ratio",
  5466. .data = &sysctl_lowmem_reserve_ratio,
  5467. .maxlen = sizeof(sysctl_lowmem_reserve_ratio),
  5468. .mode = 0644,
  5469. .proc_handler = lowmem_reserve_ratio_sysctl_handler,
  5470. },
  5471. #ifdef CONFIG_NUMA
  5472. {
  5473. .procname = "numa_zonelist_order",
  5474. .data = &numa_zonelist_order,
  5475. .maxlen = NUMA_ZONELIST_ORDER_LEN,
  5476. .mode = 0644,
  5477. .proc_handler = numa_zonelist_order_handler,
  5478. },
  5479. {
  5480. .procname = "min_unmapped_ratio",
  5481. .data = &sysctl_min_unmapped_ratio,
  5482. .maxlen = sizeof(sysctl_min_unmapped_ratio),
  5483. .mode = 0644,
  5484. .proc_handler = sysctl_min_unmapped_ratio_sysctl_handler,
  5485. .extra1 = SYSCTL_ZERO,
  5486. .extra2 = SYSCTL_ONE_HUNDRED,
  5487. },
  5488. {
  5489. .procname = "min_slab_ratio",
  5490. .data = &sysctl_min_slab_ratio,
  5491. .maxlen = sizeof(sysctl_min_slab_ratio),
  5492. .mode = 0644,
  5493. .proc_handler = sysctl_min_slab_ratio_sysctl_handler,
  5494. .extra1 = SYSCTL_ZERO,
  5495. .extra2 = SYSCTL_ONE_HUNDRED,
  5496. },
  5497. #endif
  5498. };
  5499. void __init page_alloc_sysctl_init(void)
  5500. {
  5501. register_sysctl_init("vm", page_alloc_sysctl_table);
  5502. }
  5503. #ifdef CONFIG_CONTIG_ALLOC
  5504. /* Usage: See admin-guide/dynamic-debug-howto.rst */
  5505. static void alloc_contig_dump_pages(struct list_head *page_list)
  5506. {
  5507. DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
  5508. if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
  5509. struct page *page;
  5510. dump_stack();
  5511. list_for_each_entry(page, page_list, lru)
  5512. dump_page(page, "migration failure");
  5513. }
  5514. }
  5515. /*
  5516. * [start, end) must belong to a single zone.
  5517. * @migratetype: using migratetype to filter the type of migration in
  5518. * trace_mm_alloc_contig_migrate_range_info.
  5519. */
  5520. int __alloc_contig_migrate_range(struct compact_control *cc,
  5521. unsigned long start, unsigned long end,
  5522. int migratetype)
  5523. {
  5524. /* This function is based on compact_zone() from compaction.c. */
  5525. unsigned int nr_reclaimed;
  5526. unsigned long pfn = start;
  5527. unsigned int tries = 0;
  5528. int ret = 0;
  5529. struct migration_target_control mtc = {
  5530. .nid = zone_to_nid(cc->zone),
  5531. .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
  5532. .reason = MR_CONTIG_RANGE,
  5533. };
  5534. struct page *page;
  5535. unsigned long total_mapped = 0;
  5536. unsigned long total_migrated = 0;
  5537. unsigned long total_reclaimed = 0;
  5538. lru_cache_disable();
  5539. while (pfn < end || !list_empty(&cc->migratepages)) {
  5540. if (fatal_signal_pending(current)) {
  5541. ret = -EINTR;
  5542. break;
  5543. }
  5544. if (list_empty(&cc->migratepages)) {
  5545. cc->nr_migratepages = 0;
  5546. ret = isolate_migratepages_range(cc, pfn, end);
  5547. if (ret && ret != -EAGAIN)
  5548. break;
  5549. pfn = cc->migrate_pfn;
  5550. tries = 0;
  5551. } else if (++tries == 5) {
  5552. ret = -EBUSY;
  5553. break;
  5554. }
  5555. nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
  5556. &cc->migratepages);
  5557. cc->nr_migratepages -= nr_reclaimed;
  5558. if (trace_mm_alloc_contig_migrate_range_info_enabled()) {
  5559. total_reclaimed += nr_reclaimed;
  5560. list_for_each_entry(page, &cc->migratepages, lru) {
  5561. struct folio *folio = page_folio(page);
  5562. total_mapped += folio_mapped(folio) *
  5563. folio_nr_pages(folio);
  5564. }
  5565. }
  5566. ret = migrate_pages(&cc->migratepages, alloc_migration_target,
  5567. NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
  5568. if (trace_mm_alloc_contig_migrate_range_info_enabled() && !ret)
  5569. total_migrated += cc->nr_migratepages;
  5570. /*
  5571. * On -ENOMEM, migrate_pages() bails out right away. It is pointless
  5572. * to retry again over this error, so do the same here.
  5573. */
  5574. if (ret == -ENOMEM)
  5575. break;
  5576. }
  5577. lru_cache_enable();
  5578. if (ret < 0) {
  5579. if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY)
  5580. alloc_contig_dump_pages(&cc->migratepages);
  5581. putback_movable_pages(&cc->migratepages);
  5582. }
  5583. trace_mm_alloc_contig_migrate_range_info(start, end, migratetype,
  5584. total_migrated,
  5585. total_reclaimed,
  5586. total_mapped);
  5587. return (ret < 0) ? ret : 0;
  5588. }
  5589. static void split_free_pages(struct list_head *list)
  5590. {
  5591. int order;
  5592. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  5593. struct page *page, *next;
  5594. int nr_pages = 1 << order;
  5595. list_for_each_entry_safe(page, next, &list[order], lru) {
  5596. int i;
  5597. post_alloc_hook(page, order, __GFP_MOVABLE);
  5598. if (!order)
  5599. continue;
  5600. split_page(page, order);
  5601. /* Add all subpages to the order-0 head, in sequence. */
  5602. list_del(&page->lru);
  5603. for (i = 0; i < nr_pages; i++)
  5604. list_add_tail(&page[i].lru, &list[0]);
  5605. }
  5606. }
  5607. }
  5608. /**
  5609. * alloc_contig_range() -- tries to allocate given range of pages
  5610. * @start: start PFN to allocate
  5611. * @end: one-past-the-last PFN to allocate
  5612. * @migratetype: migratetype of the underlying pageblocks (either
  5613. * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
  5614. * in range must have the same migratetype and it must
  5615. * be either of the two.
  5616. * @gfp_mask: GFP mask to use during compaction
  5617. *
  5618. * The PFN range does not have to be pageblock aligned. The PFN range must
  5619. * belong to a single zone.
  5620. *
  5621. * The first thing this routine does is attempt to MIGRATE_ISOLATE all
  5622. * pageblocks in the range. Once isolated, the pageblocks should not
  5623. * be modified by others.
  5624. *
  5625. * Return: zero on success or negative error code. On success all
  5626. * pages which PFN is in [start, end) are allocated for the caller and
  5627. * need to be freed with free_contig_range().
  5628. */
  5629. int alloc_contig_range_noprof(unsigned long start, unsigned long end,
  5630. unsigned migratetype, gfp_t gfp_mask)
  5631. {
  5632. unsigned long outer_start, outer_end;
  5633. int ret = 0;
  5634. struct compact_control cc = {
  5635. .nr_migratepages = 0,
  5636. .order = -1,
  5637. .zone = page_zone(pfn_to_page(start)),
  5638. .mode = MIGRATE_SYNC,
  5639. .ignore_skip_hint = true,
  5640. .no_set_skip_hint = true,
  5641. .gfp_mask = current_gfp_context(gfp_mask),
  5642. .alloc_contig = true,
  5643. };
  5644. INIT_LIST_HEAD(&cc.migratepages);
  5645. /*
  5646. * What we do here is we mark all pageblocks in range as
  5647. * MIGRATE_ISOLATE. Because pageblock and max order pages may
  5648. * have different sizes, and due to the way page allocator
  5649. * work, start_isolate_page_range() has special handlings for this.
  5650. *
  5651. * Once the pageblocks are marked as MIGRATE_ISOLATE, we
  5652. * migrate the pages from an unaligned range (ie. pages that
  5653. * we are interested in). This will put all the pages in
  5654. * range back to page allocator as MIGRATE_ISOLATE.
  5655. *
  5656. * When this is done, we take the pages in range from page
  5657. * allocator removing them from the buddy system. This way
  5658. * page allocator will never consider using them.
  5659. *
  5660. * This lets us mark the pageblocks back as
  5661. * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
  5662. * aligned range but not in the unaligned, original range are
  5663. * put back to page allocator so that buddy can use them.
  5664. */
  5665. ret = start_isolate_page_range(start, end, migratetype, 0, gfp_mask);
  5666. if (ret)
  5667. goto done;
  5668. drain_all_pages(cc.zone);
  5669. /*
  5670. * In case of -EBUSY, we'd like to know which page causes problem.
  5671. * So, just fall through. test_pages_isolated() has a tracepoint
  5672. * which will report the busy page.
  5673. *
  5674. * It is possible that busy pages could become available before
  5675. * the call to test_pages_isolated, and the range will actually be
  5676. * allocated. So, if we fall through be sure to clear ret so that
  5677. * -EBUSY is not accidentally used or returned to caller.
  5678. */
  5679. ret = __alloc_contig_migrate_range(&cc, start, end, migratetype);
  5680. if (ret && ret != -EBUSY)
  5681. goto done;
  5682. ret = 0;
  5683. /*
  5684. * Pages from [start, end) are within a pageblock_nr_pages
  5685. * aligned blocks that are marked as MIGRATE_ISOLATE. What's
  5686. * more, all pages in [start, end) are free in page allocator.
  5687. * What we are going to do is to allocate all pages from
  5688. * [start, end) (that is remove them from page allocator).
  5689. *
  5690. * The only problem is that pages at the beginning and at the
  5691. * end of interesting range may be not aligned with pages that
  5692. * page allocator holds, ie. they can be part of higher order
  5693. * pages. Because of this, we reserve the bigger range and
  5694. * once this is done free the pages we are not interested in.
  5695. *
  5696. * We don't have to hold zone->lock here because the pages are
  5697. * isolated thus they won't get removed from buddy.
  5698. */
  5699. outer_start = find_large_buddy(start);
  5700. /* Make sure the range is really isolated. */
  5701. if (test_pages_isolated(outer_start, end, 0)) {
  5702. ret = -EBUSY;
  5703. goto done;
  5704. }
  5705. /* Grab isolated pages from freelists. */
  5706. outer_end = isolate_freepages_range(&cc, outer_start, end);
  5707. if (!outer_end) {
  5708. ret = -EBUSY;
  5709. goto done;
  5710. }
  5711. if (!(gfp_mask & __GFP_COMP)) {
  5712. split_free_pages(cc.freepages);
  5713. /* Free head and tail (if any) */
  5714. if (start != outer_start)
  5715. free_contig_range(outer_start, start - outer_start);
  5716. if (end != outer_end)
  5717. free_contig_range(end, outer_end - end);
  5718. } else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) {
  5719. struct page *head = pfn_to_page(start);
  5720. int order = ilog2(end - start);
  5721. check_new_pages(head, order);
  5722. prep_new_page(head, order, gfp_mask, 0);
  5723. } else {
  5724. ret = -EINVAL;
  5725. WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n",
  5726. start, end, outer_start, outer_end);
  5727. }
  5728. done:
  5729. undo_isolate_page_range(start, end, migratetype);
  5730. return ret;
  5731. }
  5732. EXPORT_SYMBOL(alloc_contig_range_noprof);
  5733. static int __alloc_contig_pages(unsigned long start_pfn,
  5734. unsigned long nr_pages, gfp_t gfp_mask)
  5735. {
  5736. unsigned long end_pfn = start_pfn + nr_pages;
  5737. return alloc_contig_range_noprof(start_pfn, end_pfn, MIGRATE_MOVABLE,
  5738. gfp_mask);
  5739. }
  5740. static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
  5741. unsigned long nr_pages)
  5742. {
  5743. unsigned long i, end_pfn = start_pfn + nr_pages;
  5744. struct page *page;
  5745. for (i = start_pfn; i < end_pfn; i++) {
  5746. page = pfn_to_online_page(i);
  5747. if (!page)
  5748. return false;
  5749. if (page_zone(page) != z)
  5750. return false;
  5751. if (PageReserved(page))
  5752. return false;
  5753. if (PageHuge(page))
  5754. return false;
  5755. }
  5756. return true;
  5757. }
  5758. static bool zone_spans_last_pfn(const struct zone *zone,
  5759. unsigned long start_pfn, unsigned long nr_pages)
  5760. {
  5761. unsigned long last_pfn = start_pfn + nr_pages - 1;
  5762. return zone_spans_pfn(zone, last_pfn);
  5763. }
  5764. /**
  5765. * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
  5766. * @nr_pages: Number of contiguous pages to allocate
  5767. * @gfp_mask: GFP mask to limit search and used during compaction
  5768. * @nid: Target node
  5769. * @nodemask: Mask for other possible nodes
  5770. *
  5771. * This routine is a wrapper around alloc_contig_range(). It scans over zones
  5772. * on an applicable zonelist to find a contiguous pfn range which can then be
  5773. * tried for allocation with alloc_contig_range(). This routine is intended
  5774. * for allocation requests which can not be fulfilled with the buddy allocator.
  5775. *
  5776. * The allocated memory is always aligned to a page boundary. If nr_pages is a
  5777. * power of two, then allocated range is also guaranteed to be aligned to same
  5778. * nr_pages (e.g. 1GB request would be aligned to 1GB).
  5779. *
  5780. * Allocated pages can be freed with free_contig_range() or by manually calling
  5781. * __free_page() on each allocated page.
  5782. *
  5783. * Return: pointer to contiguous pages on success, or NULL if not successful.
  5784. */
  5785. struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask,
  5786. int nid, nodemask_t *nodemask)
  5787. {
  5788. unsigned long ret, pfn, flags;
  5789. struct zonelist *zonelist;
  5790. struct zone *zone;
  5791. struct zoneref *z;
  5792. zonelist = node_zonelist(nid, gfp_mask);
  5793. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  5794. gfp_zone(gfp_mask), nodemask) {
  5795. spin_lock_irqsave(&zone->lock, flags);
  5796. pfn = ALIGN(zone->zone_start_pfn, nr_pages);
  5797. while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
  5798. if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
  5799. /*
  5800. * We release the zone lock here because
  5801. * alloc_contig_range() will also lock the zone
  5802. * at some point. If there's an allocation
  5803. * spinning on this lock, it may win the race
  5804. * and cause alloc_contig_range() to fail...
  5805. */
  5806. spin_unlock_irqrestore(&zone->lock, flags);
  5807. ret = __alloc_contig_pages(pfn, nr_pages,
  5808. gfp_mask);
  5809. if (!ret)
  5810. return pfn_to_page(pfn);
  5811. spin_lock_irqsave(&zone->lock, flags);
  5812. }
  5813. pfn += nr_pages;
  5814. }
  5815. spin_unlock_irqrestore(&zone->lock, flags);
  5816. }
  5817. return NULL;
  5818. }
  5819. #endif /* CONFIG_CONTIG_ALLOC */
  5820. void free_contig_range(unsigned long pfn, unsigned long nr_pages)
  5821. {
  5822. unsigned long count = 0;
  5823. struct folio *folio = pfn_folio(pfn);
  5824. if (folio_test_large(folio)) {
  5825. int expected = folio_nr_pages(folio);
  5826. if (nr_pages == expected)
  5827. folio_put(folio);
  5828. else
  5829. WARN(true, "PFN %lu: nr_pages %lu != expected %d\n",
  5830. pfn, nr_pages, expected);
  5831. return;
  5832. }
  5833. for (; nr_pages--; pfn++) {
  5834. struct page *page = pfn_to_page(pfn);
  5835. count += page_count(page) != 1;
  5836. __free_page(page);
  5837. }
  5838. WARN(count != 0, "%lu pages are still in use!\n", count);
  5839. }
  5840. EXPORT_SYMBOL(free_contig_range);
  5841. /*
  5842. * Effectively disable pcplists for the zone by setting the high limit to 0
  5843. * and draining all cpus. A concurrent page freeing on another CPU that's about
  5844. * to put the page on pcplist will either finish before the drain and the page
  5845. * will be drained, or observe the new high limit and skip the pcplist.
  5846. *
  5847. * Must be paired with a call to zone_pcp_enable().
  5848. */
  5849. void zone_pcp_disable(struct zone *zone)
  5850. {
  5851. mutex_lock(&pcp_batch_high_lock);
  5852. __zone_set_pageset_high_and_batch(zone, 0, 0, 1);
  5853. __drain_all_pages(zone, true);
  5854. }
  5855. void zone_pcp_enable(struct zone *zone)
  5856. {
  5857. __zone_set_pageset_high_and_batch(zone, zone->pageset_high_min,
  5858. zone->pageset_high_max, zone->pageset_batch);
  5859. mutex_unlock(&pcp_batch_high_lock);
  5860. }
  5861. void zone_pcp_reset(struct zone *zone)
  5862. {
  5863. int cpu;
  5864. struct per_cpu_zonestat *pzstats;
  5865. if (zone->per_cpu_pageset != &boot_pageset) {
  5866. for_each_online_cpu(cpu) {
  5867. pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
  5868. drain_zonestat(zone, pzstats);
  5869. }
  5870. free_percpu(zone->per_cpu_pageset);
  5871. zone->per_cpu_pageset = &boot_pageset;
  5872. if (zone->per_cpu_zonestats != &boot_zonestats) {
  5873. free_percpu(zone->per_cpu_zonestats);
  5874. zone->per_cpu_zonestats = &boot_zonestats;
  5875. }
  5876. }
  5877. }
  5878. #ifdef CONFIG_MEMORY_HOTREMOVE
  5879. /*
  5880. * All pages in the range must be in a single zone, must not contain holes,
  5881. * must span full sections, and must be isolated before calling this function.
  5882. *
  5883. * Returns the number of managed (non-PageOffline()) pages in the range: the
  5884. * number of pages for which memory offlining code must adjust managed page
  5885. * counters using adjust_managed_page_count().
  5886. */
  5887. unsigned long __offline_isolated_pages(unsigned long start_pfn,
  5888. unsigned long end_pfn)
  5889. {
  5890. unsigned long already_offline = 0, flags;
  5891. unsigned long pfn = start_pfn;
  5892. struct page *page;
  5893. struct zone *zone;
  5894. unsigned int order;
  5895. offline_mem_sections(pfn, end_pfn);
  5896. zone = page_zone(pfn_to_page(pfn));
  5897. spin_lock_irqsave(&zone->lock, flags);
  5898. while (pfn < end_pfn) {
  5899. page = pfn_to_page(pfn);
  5900. /*
  5901. * The HWPoisoned page may be not in buddy system, and
  5902. * page_count() is not 0.
  5903. */
  5904. if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
  5905. pfn++;
  5906. continue;
  5907. }
  5908. /*
  5909. * At this point all remaining PageOffline() pages have a
  5910. * reference count of 0 and can simply be skipped.
  5911. */
  5912. if (PageOffline(page)) {
  5913. BUG_ON(page_count(page));
  5914. BUG_ON(PageBuddy(page));
  5915. already_offline++;
  5916. pfn++;
  5917. continue;
  5918. }
  5919. BUG_ON(page_count(page));
  5920. BUG_ON(!PageBuddy(page));
  5921. VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE);
  5922. order = buddy_order(page);
  5923. del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE);
  5924. pfn += (1 << order);
  5925. }
  5926. spin_unlock_irqrestore(&zone->lock, flags);
  5927. return end_pfn - start_pfn - already_offline;
  5928. }
  5929. #endif
  5930. /*
  5931. * This function returns a stable result only if called under zone lock.
  5932. */
  5933. bool is_free_buddy_page(const struct page *page)
  5934. {
  5935. unsigned long pfn = page_to_pfn(page);
  5936. unsigned int order;
  5937. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  5938. const struct page *head = page - (pfn & ((1 << order) - 1));
  5939. if (PageBuddy(head) &&
  5940. buddy_order_unsafe(head) >= order)
  5941. break;
  5942. }
  5943. return order <= MAX_PAGE_ORDER;
  5944. }
  5945. EXPORT_SYMBOL(is_free_buddy_page);
  5946. #ifdef CONFIG_MEMORY_FAILURE
  5947. static inline void add_to_free_list(struct page *page, struct zone *zone,
  5948. unsigned int order, int migratetype,
  5949. bool tail)
  5950. {
  5951. __add_to_free_list(page, zone, order, migratetype, tail);
  5952. account_freepages(zone, 1 << order, migratetype);
  5953. }
  5954. /*
  5955. * Break down a higher-order page in sub-pages, and keep our target out of
  5956. * buddy allocator.
  5957. */
  5958. static void break_down_buddy_pages(struct zone *zone, struct page *page,
  5959. struct page *target, int low, int high,
  5960. int migratetype)
  5961. {
  5962. unsigned long size = 1 << high;
  5963. struct page *current_buddy;
  5964. while (high > low) {
  5965. high--;
  5966. size >>= 1;
  5967. if (target >= &page[size]) {
  5968. current_buddy = page;
  5969. page = page + size;
  5970. } else {
  5971. current_buddy = page + size;
  5972. }
  5973. if (set_page_guard(zone, current_buddy, high))
  5974. continue;
  5975. add_to_free_list(current_buddy, zone, high, migratetype, false);
  5976. set_buddy_order(current_buddy, high);
  5977. }
  5978. }
  5979. /*
  5980. * Take a page that will be marked as poisoned off the buddy allocator.
  5981. */
  5982. bool take_page_off_buddy(struct page *page)
  5983. {
  5984. struct zone *zone = page_zone(page);
  5985. unsigned long pfn = page_to_pfn(page);
  5986. unsigned long flags;
  5987. unsigned int order;
  5988. bool ret = false;
  5989. spin_lock_irqsave(&zone->lock, flags);
  5990. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  5991. struct page *page_head = page - (pfn & ((1 << order) - 1));
  5992. int page_order = buddy_order(page_head);
  5993. if (PageBuddy(page_head) && page_order >= order) {
  5994. unsigned long pfn_head = page_to_pfn(page_head);
  5995. int migratetype = get_pfnblock_migratetype(page_head,
  5996. pfn_head);
  5997. del_page_from_free_list(page_head, zone, page_order,
  5998. migratetype);
  5999. break_down_buddy_pages(zone, page_head, page, 0,
  6000. page_order, migratetype);
  6001. SetPageHWPoisonTakenOff(page);
  6002. ret = true;
  6003. break;
  6004. }
  6005. if (page_count(page_head) > 0)
  6006. break;
  6007. }
  6008. spin_unlock_irqrestore(&zone->lock, flags);
  6009. return ret;
  6010. }
  6011. /*
  6012. * Cancel takeoff done by take_page_off_buddy().
  6013. */
  6014. bool put_page_back_buddy(struct page *page)
  6015. {
  6016. struct zone *zone = page_zone(page);
  6017. unsigned long flags;
  6018. bool ret = false;
  6019. spin_lock_irqsave(&zone->lock, flags);
  6020. if (put_page_testzero(page)) {
  6021. unsigned long pfn = page_to_pfn(page);
  6022. int migratetype = get_pfnblock_migratetype(page, pfn);
  6023. ClearPageHWPoisonTakenOff(page);
  6024. __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
  6025. if (TestClearPageHWPoison(page)) {
  6026. ret = true;
  6027. }
  6028. }
  6029. spin_unlock_irqrestore(&zone->lock, flags);
  6030. return ret;
  6031. }
  6032. #endif
  6033. #ifdef CONFIG_ZONE_DMA
  6034. bool has_managed_dma(void)
  6035. {
  6036. struct pglist_data *pgdat;
  6037. for_each_online_pgdat(pgdat) {
  6038. struct zone *zone = &pgdat->node_zones[ZONE_DMA];
  6039. if (managed_zone(zone))
  6040. return true;
  6041. }
  6042. return false;
  6043. }
  6044. #endif /* CONFIG_ZONE_DMA */
  6045. #ifdef CONFIG_UNACCEPTED_MEMORY
  6046. /* Counts number of zones with unaccepted pages. */
  6047. static DEFINE_STATIC_KEY_FALSE(zones_with_unaccepted_pages);
  6048. static bool lazy_accept = true;
  6049. static int __init accept_memory_parse(char *p)
  6050. {
  6051. if (!strcmp(p, "lazy")) {
  6052. lazy_accept = true;
  6053. return 0;
  6054. } else if (!strcmp(p, "eager")) {
  6055. lazy_accept = false;
  6056. return 0;
  6057. } else {
  6058. return -EINVAL;
  6059. }
  6060. }
  6061. early_param("accept_memory", accept_memory_parse);
  6062. static bool page_contains_unaccepted(struct page *page, unsigned int order)
  6063. {
  6064. phys_addr_t start = page_to_phys(page);
  6065. return range_contains_unaccepted_memory(start, PAGE_SIZE << order);
  6066. }
  6067. static void __accept_page(struct zone *zone, unsigned long *flags,
  6068. struct page *page)
  6069. {
  6070. bool last;
  6071. list_del(&page->lru);
  6072. last = list_empty(&zone->unaccepted_pages);
  6073. account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
  6074. __mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES);
  6075. __ClearPageUnaccepted(page);
  6076. spin_unlock_irqrestore(&zone->lock, *flags);
  6077. accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
  6078. __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
  6079. if (last)
  6080. static_branch_dec(&zones_with_unaccepted_pages);
  6081. }
  6082. void accept_page(struct page *page)
  6083. {
  6084. struct zone *zone = page_zone(page);
  6085. unsigned long flags;
  6086. spin_lock_irqsave(&zone->lock, flags);
  6087. if (!PageUnaccepted(page)) {
  6088. spin_unlock_irqrestore(&zone->lock, flags);
  6089. return;
  6090. }
  6091. /* Unlocks zone->lock */
  6092. __accept_page(zone, &flags, page);
  6093. }
  6094. static bool try_to_accept_memory_one(struct zone *zone)
  6095. {
  6096. unsigned long flags;
  6097. struct page *page;
  6098. spin_lock_irqsave(&zone->lock, flags);
  6099. page = list_first_entry_or_null(&zone->unaccepted_pages,
  6100. struct page, lru);
  6101. if (!page) {
  6102. spin_unlock_irqrestore(&zone->lock, flags);
  6103. return false;
  6104. }
  6105. /* Unlocks zone->lock */
  6106. __accept_page(zone, &flags, page);
  6107. return true;
  6108. }
  6109. static inline bool has_unaccepted_memory(void)
  6110. {
  6111. return static_branch_unlikely(&zones_with_unaccepted_pages);
  6112. }
  6113. static bool cond_accept_memory(struct zone *zone, unsigned int order)
  6114. {
  6115. long to_accept;
  6116. bool ret = false;
  6117. if (!has_unaccepted_memory())
  6118. return false;
  6119. if (list_empty(&zone->unaccepted_pages))
  6120. return false;
  6121. /* How much to accept to get to promo watermark? */
  6122. to_accept = promo_wmark_pages(zone) -
  6123. (zone_page_state(zone, NR_FREE_PAGES) -
  6124. __zone_watermark_unusable_free(zone, order, 0) -
  6125. zone_page_state(zone, NR_UNACCEPTED));
  6126. while (to_accept > 0) {
  6127. if (!try_to_accept_memory_one(zone))
  6128. break;
  6129. ret = true;
  6130. to_accept -= MAX_ORDER_NR_PAGES;
  6131. }
  6132. return ret;
  6133. }
  6134. static bool __free_unaccepted(struct page *page)
  6135. {
  6136. struct zone *zone = page_zone(page);
  6137. unsigned long flags;
  6138. bool first = false;
  6139. if (!lazy_accept)
  6140. return false;
  6141. spin_lock_irqsave(&zone->lock, flags);
  6142. first = list_empty(&zone->unaccepted_pages);
  6143. list_add_tail(&page->lru, &zone->unaccepted_pages);
  6144. account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
  6145. __mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES);
  6146. __SetPageUnaccepted(page);
  6147. spin_unlock_irqrestore(&zone->lock, flags);
  6148. if (first)
  6149. static_branch_inc(&zones_with_unaccepted_pages);
  6150. return true;
  6151. }
  6152. #else
  6153. static bool page_contains_unaccepted(struct page *page, unsigned int order)
  6154. {
  6155. return false;
  6156. }
  6157. static bool cond_accept_memory(struct zone *zone, unsigned int order)
  6158. {
  6159. return false;
  6160. }
  6161. static bool __free_unaccepted(struct page *page)
  6162. {
  6163. BUILD_BUG();
  6164. return false;
  6165. }
  6166. #endif /* CONFIG_UNACCEPTED_MEMORY */