page_alloc.c 220 KB

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