page_alloc.c 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196
  1. /*
  2. * linux/mm/page_alloc.c
  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/swap.h>
  19. #include <linux/interrupt.h>
  20. #include <linux/pagemap.h>
  21. #include <linux/jiffies.h>
  22. #include <linux/bootmem.h>
  23. #include <linux/memblock.h>
  24. #include <linux/compiler.h>
  25. #include <linux/kernel.h>
  26. #include <linux/kasan.h>
  27. #include <linux/module.h>
  28. #include <linux/suspend.h>
  29. #include <linux/pagevec.h>
  30. #include <linux/blkdev.h>
  31. #include <linux/slab.h>
  32. #include <linux/ratelimit.h>
  33. #include <linux/oom.h>
  34. #include <linux/topology.h>
  35. #include <linux/sysctl.h>
  36. #include <linux/cpu.h>
  37. #include <linux/cpuset.h>
  38. #include <linux/memory_hotplug.h>
  39. #include <linux/nodemask.h>
  40. #include <linux/vmalloc.h>
  41. #include <linux/vmstat.h>
  42. #include <linux/mempolicy.h>
  43. #include <linux/memremap.h>
  44. #include <linux/stop_machine.h>
  45. #include <linux/sort.h>
  46. #include <linux/pfn.h>
  47. #include <linux/backing-dev.h>
  48. #include <linux/fault-inject.h>
  49. #include <linux/page-isolation.h>
  50. #include <linux/page_ext.h>
  51. #include <linux/debugobjects.h>
  52. #include <linux/kmemleak.h>
  53. #include <linux/compaction.h>
  54. #include <trace/events/kmem.h>
  55. #include <trace/events/oom.h>
  56. #include <linux/prefetch.h>
  57. #include <linux/mm_inline.h>
  58. #include <linux/migrate.h>
  59. #include <linux/hugetlb.h>
  60. #include <linux/sched/rt.h>
  61. #include <linux/sched/mm.h>
  62. #include <linux/page_owner.h>
  63. #include <linux/kthread.h>
  64. #include <linux/memcontrol.h>
  65. #include <linux/ftrace.h>
  66. #include <linux/lockdep.h>
  67. #include <linux/nmi.h>
  68. #include <linux/khugepaged.h>
  69. #include <asm/sections.h>
  70. #include <asm/tlbflush.h>
  71. #include <asm/div64.h>
  72. #include "internal.h"
  73. /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
  74. static DEFINE_MUTEX(pcp_batch_high_lock);
  75. #define MIN_PERCPU_PAGELIST_FRACTION (8)
  76. #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
  77. DEFINE_PER_CPU(int, numa_node);
  78. EXPORT_PER_CPU_SYMBOL(numa_node);
  79. #endif
  80. DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
  81. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  82. /*
  83. * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
  84. * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
  85. * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
  86. * defined in <linux/topology.h>.
  87. */
  88. DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
  89. EXPORT_PER_CPU_SYMBOL(_numa_mem_);
  90. int _node_numa_mem_[MAX_NUMNODES];
  91. #endif
  92. /* work_structs for global per-cpu drains */
  93. DEFINE_MUTEX(pcpu_drain_mutex);
  94. DEFINE_PER_CPU(struct work_struct, pcpu_drain);
  95. #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
  96. volatile unsigned long latent_entropy __latent_entropy;
  97. EXPORT_SYMBOL(latent_entropy);
  98. #endif
  99. /*
  100. * Array of node states.
  101. */
  102. nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
  103. [N_POSSIBLE] = NODE_MASK_ALL,
  104. [N_ONLINE] = { { [0] = 1UL } },
  105. #ifndef CONFIG_NUMA
  106. [N_NORMAL_MEMORY] = { { [0] = 1UL } },
  107. #ifdef CONFIG_HIGHMEM
  108. [N_HIGH_MEMORY] = { { [0] = 1UL } },
  109. #endif
  110. [N_MEMORY] = { { [0] = 1UL } },
  111. [N_CPU] = { { [0] = 1UL } },
  112. #endif /* NUMA */
  113. };
  114. EXPORT_SYMBOL(node_states);
  115. /* Protect totalram_pages and zone->managed_pages */
  116. static DEFINE_SPINLOCK(managed_page_count_lock);
  117. unsigned long totalram_pages __read_mostly;
  118. unsigned long totalreserve_pages __read_mostly;
  119. unsigned long totalcma_pages __read_mostly;
  120. int percpu_pagelist_fraction;
  121. gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
  122. /*
  123. * A cached value of the page's pageblock's migratetype, used when the page is
  124. * put on a pcplist. Used to avoid the pageblock migratetype lookup when
  125. * freeing from pcplists in most cases, at the cost of possibly becoming stale.
  126. * Also the migratetype set in the page does not necessarily match the pcplist
  127. * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
  128. * other index - this ensures that it will be put on the correct CMA freelist.
  129. */
  130. static inline int get_pcppage_migratetype(struct page *page)
  131. {
  132. return page->index;
  133. }
  134. static inline void set_pcppage_migratetype(struct page *page, int migratetype)
  135. {
  136. page->index = migratetype;
  137. }
  138. #ifdef CONFIG_PM_SLEEP
  139. /*
  140. * The following functions are used by the suspend/hibernate code to temporarily
  141. * change gfp_allowed_mask in order to avoid using I/O during memory allocations
  142. * while devices are suspended. To avoid races with the suspend/hibernate code,
  143. * they should always be called with system_transition_mutex held
  144. * (gfp_allowed_mask also should only be modified with system_transition_mutex
  145. * held, unless the suspend/hibernate code is guaranteed not to run in parallel
  146. * with that modification).
  147. */
  148. static gfp_t saved_gfp_mask;
  149. void pm_restore_gfp_mask(void)
  150. {
  151. WARN_ON(!mutex_is_locked(&system_transition_mutex));
  152. if (saved_gfp_mask) {
  153. gfp_allowed_mask = saved_gfp_mask;
  154. saved_gfp_mask = 0;
  155. }
  156. }
  157. void pm_restrict_gfp_mask(void)
  158. {
  159. WARN_ON(!mutex_is_locked(&system_transition_mutex));
  160. WARN_ON(saved_gfp_mask);
  161. saved_gfp_mask = gfp_allowed_mask;
  162. gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
  163. }
  164. bool pm_suspended_storage(void)
  165. {
  166. if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
  167. return false;
  168. return true;
  169. }
  170. #endif /* CONFIG_PM_SLEEP */
  171. #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
  172. unsigned int pageblock_order __read_mostly;
  173. #endif
  174. static void __free_pages_ok(struct page *page, unsigned int order);
  175. /*
  176. * results with 256, 32 in the lowmem_reserve sysctl:
  177. * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
  178. * 1G machine -> (16M dma, 784M normal, 224M high)
  179. * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
  180. * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
  181. * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
  182. *
  183. * TBD: should special case ZONE_DMA32 machines here - in those we normally
  184. * don't need any ZONE_NORMAL reservation
  185. */
  186. int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
  187. #ifdef CONFIG_ZONE_DMA
  188. [ZONE_DMA] = 256,
  189. #endif
  190. #ifdef CONFIG_ZONE_DMA32
  191. [ZONE_DMA32] = 256,
  192. #endif
  193. [ZONE_NORMAL] = 32,
  194. #ifdef CONFIG_HIGHMEM
  195. [ZONE_HIGHMEM] = 0,
  196. #endif
  197. [ZONE_MOVABLE] = 0,
  198. };
  199. EXPORT_SYMBOL(totalram_pages);
  200. static char * const zone_names[MAX_NR_ZONES] = {
  201. #ifdef CONFIG_ZONE_DMA
  202. "DMA",
  203. #endif
  204. #ifdef CONFIG_ZONE_DMA32
  205. "DMA32",
  206. #endif
  207. "Normal",
  208. #ifdef CONFIG_HIGHMEM
  209. "HighMem",
  210. #endif
  211. "Movable",
  212. #ifdef CONFIG_ZONE_DEVICE
  213. "Device",
  214. #endif
  215. };
  216. char * const migratetype_names[MIGRATE_TYPES] = {
  217. "Unmovable",
  218. "Movable",
  219. "Reclaimable",
  220. "HighAtomic",
  221. #ifdef CONFIG_CMA
  222. "CMA",
  223. #endif
  224. #ifdef CONFIG_MEMORY_ISOLATION
  225. "Isolate",
  226. #endif
  227. };
  228. compound_page_dtor * const compound_page_dtors[] = {
  229. NULL,
  230. free_compound_page,
  231. #ifdef CONFIG_HUGETLB_PAGE
  232. free_huge_page,
  233. #endif
  234. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  235. free_transhuge_page,
  236. #endif
  237. };
  238. int min_free_kbytes = 1024;
  239. int user_min_free_kbytes = -1;
  240. int watermark_scale_factor = 10;
  241. static unsigned long nr_kernel_pages __meminitdata;
  242. static unsigned long nr_all_pages __meminitdata;
  243. static unsigned long dma_reserve __meminitdata;
  244. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  245. static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __meminitdata;
  246. static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __meminitdata;
  247. static unsigned long required_kernelcore __initdata;
  248. static unsigned long required_kernelcore_percent __initdata;
  249. static unsigned long required_movablecore __initdata;
  250. static unsigned long required_movablecore_percent __initdata;
  251. static unsigned long zone_movable_pfn[MAX_NUMNODES] __meminitdata;
  252. static bool mirrored_kernelcore __meminitdata;
  253. /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
  254. int movable_zone;
  255. EXPORT_SYMBOL(movable_zone);
  256. #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
  257. #if MAX_NUMNODES > 1
  258. int nr_node_ids __read_mostly = MAX_NUMNODES;
  259. int nr_online_nodes __read_mostly = 1;
  260. EXPORT_SYMBOL(nr_node_ids);
  261. EXPORT_SYMBOL(nr_online_nodes);
  262. #endif
  263. int page_group_by_mobility_disabled __read_mostly;
  264. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  265. /*
  266. * During boot we initialize deferred pages on-demand, as needed, but once
  267. * page_alloc_init_late() has finished, the deferred pages are all initialized,
  268. * and we can permanently disable that path.
  269. */
  270. static DEFINE_STATIC_KEY_TRUE(deferred_pages);
  271. /*
  272. * Calling kasan_free_pages() only after deferred memory initialization
  273. * has completed. Poisoning pages during deferred memory init will greatly
  274. * lengthen the process and cause problem in large memory systems as the
  275. * deferred pages initialization is done with interrupt disabled.
  276. *
  277. * Assuming that there will be no reference to those newly initialized
  278. * pages before they are ever allocated, this should have no effect on
  279. * KASAN memory tracking as the poison will be properly inserted at page
  280. * allocation time. The only corner case is when pages are allocated by
  281. * on-demand allocation and then freed again before the deferred pages
  282. * initialization is done, but this is not likely to happen.
  283. */
  284. static inline void kasan_free_nondeferred_pages(struct page *page, int order)
  285. {
  286. if (!static_branch_unlikely(&deferred_pages))
  287. kasan_free_pages(page, order);
  288. }
  289. /* Returns true if the struct page for the pfn is uninitialised */
  290. static inline bool __meminit early_page_uninitialised(unsigned long pfn)
  291. {
  292. int nid = early_pfn_to_nid(pfn);
  293. if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
  294. return true;
  295. return false;
  296. }
  297. /*
  298. * Returns false when the remaining initialisation should be deferred until
  299. * later in the boot cycle when it can be parallelised.
  300. */
  301. static inline bool update_defer_init(pg_data_t *pgdat,
  302. unsigned long pfn, unsigned long zone_end,
  303. unsigned long *nr_initialised)
  304. {
  305. /* Always populate low zones for address-constrained allocations */
  306. if (zone_end < pgdat_end_pfn(pgdat))
  307. return true;
  308. (*nr_initialised)++;
  309. if ((*nr_initialised > pgdat->static_init_pgcnt) &&
  310. (pfn & (PAGES_PER_SECTION - 1)) == 0) {
  311. pgdat->first_deferred_pfn = pfn;
  312. return false;
  313. }
  314. return true;
  315. }
  316. #else
  317. #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
  318. static inline bool early_page_uninitialised(unsigned long pfn)
  319. {
  320. return false;
  321. }
  322. static inline bool update_defer_init(pg_data_t *pgdat,
  323. unsigned long pfn, unsigned long zone_end,
  324. unsigned long *nr_initialised)
  325. {
  326. return true;
  327. }
  328. #endif
  329. /* Return a pointer to the bitmap storing bits affecting a block of pages */
  330. static inline unsigned long *get_pageblock_bitmap(struct page *page,
  331. unsigned long pfn)
  332. {
  333. #ifdef CONFIG_SPARSEMEM
  334. return __pfn_to_section(pfn)->pageblock_flags;
  335. #else
  336. return page_zone(page)->pageblock_flags;
  337. #endif /* CONFIG_SPARSEMEM */
  338. }
  339. static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
  340. {
  341. #ifdef CONFIG_SPARSEMEM
  342. pfn &= (PAGES_PER_SECTION-1);
  343. return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
  344. #else
  345. pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
  346. return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
  347. #endif /* CONFIG_SPARSEMEM */
  348. }
  349. /**
  350. * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
  351. * @page: The page within the block of interest
  352. * @pfn: The target page frame number
  353. * @end_bitidx: The last bit of interest to retrieve
  354. * @mask: mask of bits that the caller is interested in
  355. *
  356. * Return: pageblock_bits flags
  357. */
  358. static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
  359. unsigned long pfn,
  360. unsigned long end_bitidx,
  361. unsigned long mask)
  362. {
  363. unsigned long *bitmap;
  364. unsigned long bitidx, word_bitidx;
  365. unsigned long word;
  366. bitmap = get_pageblock_bitmap(page, pfn);
  367. bitidx = pfn_to_bitidx(page, pfn);
  368. word_bitidx = bitidx / BITS_PER_LONG;
  369. bitidx &= (BITS_PER_LONG-1);
  370. word = bitmap[word_bitidx];
  371. bitidx += end_bitidx;
  372. return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
  373. }
  374. unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
  375. unsigned long end_bitidx,
  376. unsigned long mask)
  377. {
  378. return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
  379. }
  380. static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
  381. {
  382. return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
  383. }
  384. /**
  385. * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
  386. * @page: The page within the block of interest
  387. * @flags: The flags to set
  388. * @pfn: The target page frame number
  389. * @end_bitidx: The last bit of interest
  390. * @mask: mask of bits that the caller is interested in
  391. */
  392. void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
  393. unsigned long pfn,
  394. unsigned long end_bitidx,
  395. unsigned long mask)
  396. {
  397. unsigned long *bitmap;
  398. unsigned long bitidx, word_bitidx;
  399. unsigned long old_word, word;
  400. BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
  401. bitmap = get_pageblock_bitmap(page, pfn);
  402. bitidx = pfn_to_bitidx(page, pfn);
  403. word_bitidx = bitidx / BITS_PER_LONG;
  404. bitidx &= (BITS_PER_LONG-1);
  405. VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
  406. bitidx += end_bitidx;
  407. mask <<= (BITS_PER_LONG - bitidx - 1);
  408. flags <<= (BITS_PER_LONG - bitidx - 1);
  409. word = READ_ONCE(bitmap[word_bitidx]);
  410. for (;;) {
  411. old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
  412. if (word == old_word)
  413. break;
  414. word = old_word;
  415. }
  416. }
  417. void set_pageblock_migratetype(struct page *page, int migratetype)
  418. {
  419. if (unlikely(page_group_by_mobility_disabled &&
  420. migratetype < MIGRATE_PCPTYPES))
  421. migratetype = MIGRATE_UNMOVABLE;
  422. set_pageblock_flags_group(page, (unsigned long)migratetype,
  423. PB_migrate, PB_migrate_end);
  424. }
  425. #ifdef CONFIG_DEBUG_VM
  426. static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
  427. {
  428. int ret = 0;
  429. unsigned seq;
  430. unsigned long pfn = page_to_pfn(page);
  431. unsigned long sp, start_pfn;
  432. do {
  433. seq = zone_span_seqbegin(zone);
  434. start_pfn = zone->zone_start_pfn;
  435. sp = zone->spanned_pages;
  436. if (!zone_spans_pfn(zone, pfn))
  437. ret = 1;
  438. } while (zone_span_seqretry(zone, seq));
  439. if (ret)
  440. pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
  441. pfn, zone_to_nid(zone), zone->name,
  442. start_pfn, start_pfn + sp);
  443. return ret;
  444. }
  445. static int page_is_consistent(struct zone *zone, struct page *page)
  446. {
  447. if (!pfn_valid_within(page_to_pfn(page)))
  448. return 0;
  449. if (zone != page_zone(page))
  450. return 0;
  451. return 1;
  452. }
  453. /*
  454. * Temporary debugging check for pages not lying within a given zone.
  455. */
  456. static int __maybe_unused bad_range(struct zone *zone, struct page *page)
  457. {
  458. if (page_outside_zone_boundaries(zone, page))
  459. return 1;
  460. if (!page_is_consistent(zone, page))
  461. return 1;
  462. return 0;
  463. }
  464. #else
  465. static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
  466. {
  467. return 0;
  468. }
  469. #endif
  470. static void bad_page(struct page *page, const char *reason,
  471. unsigned long bad_flags)
  472. {
  473. static unsigned long resume;
  474. static unsigned long nr_shown;
  475. static unsigned long nr_unshown;
  476. /*
  477. * Allow a burst of 60 reports, then keep quiet for that minute;
  478. * or allow a steady drip of one report per second.
  479. */
  480. if (nr_shown == 60) {
  481. if (time_before(jiffies, resume)) {
  482. nr_unshown++;
  483. goto out;
  484. }
  485. if (nr_unshown) {
  486. pr_alert(
  487. "BUG: Bad page state: %lu messages suppressed\n",
  488. nr_unshown);
  489. nr_unshown = 0;
  490. }
  491. nr_shown = 0;
  492. }
  493. if (nr_shown++ == 0)
  494. resume = jiffies + 60 * HZ;
  495. pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
  496. current->comm, page_to_pfn(page));
  497. __dump_page(page, reason);
  498. bad_flags &= page->flags;
  499. if (bad_flags)
  500. pr_alert("bad because of flags: %#lx(%pGp)\n",
  501. bad_flags, &bad_flags);
  502. dump_page_owner(page);
  503. print_modules();
  504. dump_stack();
  505. out:
  506. /* Leave bad fields for debug, except PageBuddy could make trouble */
  507. page_mapcount_reset(page); /* remove PageBuddy */
  508. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  509. }
  510. /*
  511. * Higher-order pages are called "compound pages". They are structured thusly:
  512. *
  513. * The first PAGE_SIZE page is called the "head page" and have PG_head set.
  514. *
  515. * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
  516. * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
  517. *
  518. * The first tail page's ->compound_dtor holds the offset in array of compound
  519. * page destructors. See compound_page_dtors.
  520. *
  521. * The first tail page's ->compound_order holds the order of allocation.
  522. * This usage means that zero-order pages may not be compound.
  523. */
  524. void free_compound_page(struct page *page)
  525. {
  526. __free_pages_ok(page, compound_order(page));
  527. }
  528. void prep_compound_page(struct page *page, unsigned int order)
  529. {
  530. int i;
  531. int nr_pages = 1 << order;
  532. set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
  533. set_compound_order(page, order);
  534. __SetPageHead(page);
  535. for (i = 1; i < nr_pages; i++) {
  536. struct page *p = page + i;
  537. set_page_count(p, 0);
  538. p->mapping = TAIL_MAPPING;
  539. set_compound_head(p, page);
  540. }
  541. atomic_set(compound_mapcount_ptr(page), -1);
  542. }
  543. #ifdef CONFIG_DEBUG_PAGEALLOC
  544. unsigned int _debug_guardpage_minorder;
  545. bool _debug_pagealloc_enabled __read_mostly
  546. = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
  547. EXPORT_SYMBOL(_debug_pagealloc_enabled);
  548. bool _debug_guardpage_enabled __read_mostly;
  549. static int __init early_debug_pagealloc(char *buf)
  550. {
  551. if (!buf)
  552. return -EINVAL;
  553. return kstrtobool(buf, &_debug_pagealloc_enabled);
  554. }
  555. early_param("debug_pagealloc", early_debug_pagealloc);
  556. static bool need_debug_guardpage(void)
  557. {
  558. /* If we don't use debug_pagealloc, we don't need guard page */
  559. if (!debug_pagealloc_enabled())
  560. return false;
  561. if (!debug_guardpage_minorder())
  562. return false;
  563. return true;
  564. }
  565. static void init_debug_guardpage(void)
  566. {
  567. if (!debug_pagealloc_enabled())
  568. return;
  569. if (!debug_guardpage_minorder())
  570. return;
  571. _debug_guardpage_enabled = true;
  572. }
  573. struct page_ext_operations debug_guardpage_ops = {
  574. .need = need_debug_guardpage,
  575. .init = init_debug_guardpage,
  576. };
  577. static int __init debug_guardpage_minorder_setup(char *buf)
  578. {
  579. unsigned long res;
  580. if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
  581. pr_err("Bad debug_guardpage_minorder value\n");
  582. return 0;
  583. }
  584. _debug_guardpage_minorder = res;
  585. pr_info("Setting debug_guardpage_minorder to %lu\n", res);
  586. return 0;
  587. }
  588. early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
  589. static inline bool set_page_guard(struct zone *zone, struct page *page,
  590. unsigned int order, int migratetype)
  591. {
  592. struct page_ext *page_ext;
  593. if (!debug_guardpage_enabled())
  594. return false;
  595. if (order >= debug_guardpage_minorder())
  596. return false;
  597. page_ext = lookup_page_ext(page);
  598. if (unlikely(!page_ext))
  599. return false;
  600. __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
  601. INIT_LIST_HEAD(&page->lru);
  602. set_page_private(page, order);
  603. /* Guard pages are not available for any usage */
  604. __mod_zone_freepage_state(zone, -(1 << order), migratetype);
  605. return true;
  606. }
  607. static inline void clear_page_guard(struct zone *zone, struct page *page,
  608. unsigned int order, int migratetype)
  609. {
  610. struct page_ext *page_ext;
  611. if (!debug_guardpage_enabled())
  612. return;
  613. page_ext = lookup_page_ext(page);
  614. if (unlikely(!page_ext))
  615. return;
  616. __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
  617. set_page_private(page, 0);
  618. if (!is_migrate_isolate(migratetype))
  619. __mod_zone_freepage_state(zone, (1 << order), migratetype);
  620. }
  621. #else
  622. struct page_ext_operations debug_guardpage_ops;
  623. static inline bool set_page_guard(struct zone *zone, struct page *page,
  624. unsigned int order, int migratetype) { return false; }
  625. static inline void clear_page_guard(struct zone *zone, struct page *page,
  626. unsigned int order, int migratetype) {}
  627. #endif
  628. static inline void set_page_order(struct page *page, unsigned int order)
  629. {
  630. set_page_private(page, order);
  631. __SetPageBuddy(page);
  632. }
  633. static inline void rmv_page_order(struct page *page)
  634. {
  635. __ClearPageBuddy(page);
  636. set_page_private(page, 0);
  637. }
  638. /*
  639. * This function checks whether a page is free && is the buddy
  640. * we can coalesce a page and its buddy if
  641. * (a) the buddy is not in a hole (check before calling!) &&
  642. * (b) the buddy is in the buddy system &&
  643. * (c) a page and its buddy have the same order &&
  644. * (d) a page and its buddy are in the same zone.
  645. *
  646. * For recording whether a page is in the buddy system, we set PageBuddy.
  647. * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
  648. *
  649. * For recording page's order, we use page_private(page).
  650. */
  651. static inline int page_is_buddy(struct page *page, struct page *buddy,
  652. unsigned int order)
  653. {
  654. if (page_is_guard(buddy) && page_order(buddy) == order) {
  655. if (page_zone_id(page) != page_zone_id(buddy))
  656. return 0;
  657. VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
  658. return 1;
  659. }
  660. if (PageBuddy(buddy) && page_order(buddy) == order) {
  661. /*
  662. * zone check is done late to avoid uselessly
  663. * calculating zone/node ids for pages that could
  664. * never merge.
  665. */
  666. if (page_zone_id(page) != page_zone_id(buddy))
  667. return 0;
  668. VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
  669. return 1;
  670. }
  671. return 0;
  672. }
  673. /*
  674. * Freeing function for a buddy system allocator.
  675. *
  676. * The concept of a buddy system is to maintain direct-mapped table
  677. * (containing bit values) for memory blocks of various "orders".
  678. * The bottom level table contains the map for the smallest allocatable
  679. * units of memory (here, pages), and each level above it describes
  680. * pairs of units from the levels below, hence, "buddies".
  681. * At a high level, all that happens here is marking the table entry
  682. * at the bottom level available, and propagating the changes upward
  683. * as necessary, plus some accounting needed to play nicely with other
  684. * parts of the VM system.
  685. * At each level, we keep a list of pages, which are heads of continuous
  686. * free pages of length of (1 << order) and marked with PageBuddy.
  687. * Page's order is recorded in page_private(page) field.
  688. * So when we are allocating or freeing one, we can derive the state of the
  689. * other. That is, if we allocate a small block, and both were
  690. * free, the remainder of the region must be split into blocks.
  691. * If a block is freed, and its buddy is also free, then this
  692. * triggers coalescing into a block of larger size.
  693. *
  694. * -- nyc
  695. */
  696. static inline void __free_one_page(struct page *page,
  697. unsigned long pfn,
  698. struct zone *zone, unsigned int order,
  699. int migratetype)
  700. {
  701. unsigned long combined_pfn;
  702. unsigned long uninitialized_var(buddy_pfn);
  703. struct page *buddy;
  704. unsigned int max_order;
  705. max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
  706. VM_BUG_ON(!zone_is_initialized(zone));
  707. VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
  708. VM_BUG_ON(migratetype == -1);
  709. if (likely(!is_migrate_isolate(migratetype)))
  710. __mod_zone_freepage_state(zone, 1 << order, migratetype);
  711. VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
  712. VM_BUG_ON_PAGE(bad_range(zone, page), page);
  713. continue_merging:
  714. while (order < max_order - 1) {
  715. buddy_pfn = __find_buddy_pfn(pfn, order);
  716. buddy = page + (buddy_pfn - pfn);
  717. if (!pfn_valid_within(buddy_pfn))
  718. goto done_merging;
  719. if (!page_is_buddy(page, buddy, order))
  720. goto done_merging;
  721. /*
  722. * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
  723. * merge with it and move up one order.
  724. */
  725. if (page_is_guard(buddy)) {
  726. clear_page_guard(zone, buddy, order, migratetype);
  727. } else {
  728. list_del(&buddy->lru);
  729. zone->free_area[order].nr_free--;
  730. rmv_page_order(buddy);
  731. }
  732. combined_pfn = buddy_pfn & pfn;
  733. page = page + (combined_pfn - pfn);
  734. pfn = combined_pfn;
  735. order++;
  736. }
  737. if (max_order < MAX_ORDER) {
  738. /* If we are here, it means order is >= pageblock_order.
  739. * We want to prevent merge between freepages on isolate
  740. * pageblock and normal pageblock. Without this, pageblock
  741. * isolation could cause incorrect freepage or CMA accounting.
  742. *
  743. * We don't want to hit this code for the more frequent
  744. * low-order merging.
  745. */
  746. if (unlikely(has_isolate_pageblock(zone))) {
  747. int buddy_mt;
  748. buddy_pfn = __find_buddy_pfn(pfn, order);
  749. buddy = page + (buddy_pfn - pfn);
  750. buddy_mt = get_pageblock_migratetype(buddy);
  751. if (migratetype != buddy_mt
  752. && (is_migrate_isolate(migratetype) ||
  753. is_migrate_isolate(buddy_mt)))
  754. goto done_merging;
  755. }
  756. max_order++;
  757. goto continue_merging;
  758. }
  759. done_merging:
  760. set_page_order(page, order);
  761. /*
  762. * If this is not the largest possible page, check if the buddy
  763. * of the next-highest order is free. If it is, it's possible
  764. * that pages are being freed that will coalesce soon. In case,
  765. * that is happening, add the free page to the tail of the list
  766. * so it's less likely to be used soon and more likely to be merged
  767. * as a higher order page
  768. */
  769. if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)) {
  770. struct page *higher_page, *higher_buddy;
  771. combined_pfn = buddy_pfn & pfn;
  772. higher_page = page + (combined_pfn - pfn);
  773. buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
  774. higher_buddy = higher_page + (buddy_pfn - combined_pfn);
  775. if (pfn_valid_within(buddy_pfn) &&
  776. page_is_buddy(higher_page, higher_buddy, order + 1)) {
  777. list_add_tail(&page->lru,
  778. &zone->free_area[order].free_list[migratetype]);
  779. goto out;
  780. }
  781. }
  782. list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
  783. out:
  784. zone->free_area[order].nr_free++;
  785. }
  786. /*
  787. * A bad page could be due to a number of fields. Instead of multiple branches,
  788. * try and check multiple fields with one check. The caller must do a detailed
  789. * check if necessary.
  790. */
  791. static inline bool page_expected_state(struct page *page,
  792. unsigned long check_flags)
  793. {
  794. if (unlikely(atomic_read(&page->_mapcount) != -1))
  795. return false;
  796. if (unlikely((unsigned long)page->mapping |
  797. page_ref_count(page) |
  798. #ifdef CONFIG_MEMCG
  799. (unsigned long)page->mem_cgroup |
  800. #endif
  801. (page->flags & check_flags)))
  802. return false;
  803. return true;
  804. }
  805. static void free_pages_check_bad(struct page *page)
  806. {
  807. const char *bad_reason;
  808. unsigned long bad_flags;
  809. bad_reason = NULL;
  810. bad_flags = 0;
  811. if (unlikely(atomic_read(&page->_mapcount) != -1))
  812. bad_reason = "nonzero mapcount";
  813. if (unlikely(page->mapping != NULL))
  814. bad_reason = "non-NULL mapping";
  815. if (unlikely(page_ref_count(page) != 0))
  816. bad_reason = "nonzero _refcount";
  817. if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
  818. bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
  819. bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
  820. }
  821. #ifdef CONFIG_MEMCG
  822. if (unlikely(page->mem_cgroup))
  823. bad_reason = "page still charged to cgroup";
  824. #endif
  825. bad_page(page, bad_reason, bad_flags);
  826. }
  827. static inline int free_pages_check(struct page *page)
  828. {
  829. if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
  830. return 0;
  831. /* Something has gone sideways, find it */
  832. free_pages_check_bad(page);
  833. return 1;
  834. }
  835. static int free_tail_pages_check(struct page *head_page, struct page *page)
  836. {
  837. int ret = 1;
  838. /*
  839. * We rely page->lru.next never has bit 0 set, unless the page
  840. * is PageTail(). Let's make sure that's true even for poisoned ->lru.
  841. */
  842. BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
  843. if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
  844. ret = 0;
  845. goto out;
  846. }
  847. switch (page - head_page) {
  848. case 1:
  849. /* the first tail page: ->mapping may be compound_mapcount() */
  850. if (unlikely(compound_mapcount(page))) {
  851. bad_page(page, "nonzero compound_mapcount", 0);
  852. goto out;
  853. }
  854. break;
  855. case 2:
  856. /*
  857. * the second tail page: ->mapping is
  858. * deferred_list.next -- ignore value.
  859. */
  860. break;
  861. default:
  862. if (page->mapping != TAIL_MAPPING) {
  863. bad_page(page, "corrupted mapping in tail page", 0);
  864. goto out;
  865. }
  866. break;
  867. }
  868. if (unlikely(!PageTail(page))) {
  869. bad_page(page, "PageTail not set", 0);
  870. goto out;
  871. }
  872. if (unlikely(compound_head(page) != head_page)) {
  873. bad_page(page, "compound_head not consistent", 0);
  874. goto out;
  875. }
  876. ret = 0;
  877. out:
  878. page->mapping = NULL;
  879. clear_compound_head(page);
  880. return ret;
  881. }
  882. static __always_inline bool free_pages_prepare(struct page *page,
  883. unsigned int order, bool check_free)
  884. {
  885. int bad = 0;
  886. VM_BUG_ON_PAGE(PageTail(page), page);
  887. trace_mm_page_free(page, order);
  888. /*
  889. * Check tail pages before head page information is cleared to
  890. * avoid checking PageCompound for order-0 pages.
  891. */
  892. if (unlikely(order)) {
  893. bool compound = PageCompound(page);
  894. int i;
  895. VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
  896. if (compound)
  897. ClearPageDoubleMap(page);
  898. for (i = 1; i < (1 << order); i++) {
  899. if (compound)
  900. bad += free_tail_pages_check(page, page + i);
  901. if (unlikely(free_pages_check(page + i))) {
  902. bad++;
  903. continue;
  904. }
  905. (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  906. }
  907. }
  908. if (PageMappingFlags(page))
  909. page->mapping = NULL;
  910. if (memcg_kmem_enabled() && PageKmemcg(page))
  911. memcg_kmem_uncharge(page, order);
  912. if (check_free)
  913. bad += free_pages_check(page);
  914. if (bad)
  915. return false;
  916. page_cpupid_reset_last(page);
  917. page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  918. reset_page_owner(page, order);
  919. if (!PageHighMem(page)) {
  920. debug_check_no_locks_freed(page_address(page),
  921. PAGE_SIZE << order);
  922. debug_check_no_obj_freed(page_address(page),
  923. PAGE_SIZE << order);
  924. }
  925. arch_free_page(page, order);
  926. kernel_poison_pages(page, 1 << order, 0);
  927. kernel_map_pages(page, 1 << order, 0);
  928. kasan_free_nondeferred_pages(page, order);
  929. return true;
  930. }
  931. #ifdef CONFIG_DEBUG_VM
  932. static inline bool free_pcp_prepare(struct page *page)
  933. {
  934. return free_pages_prepare(page, 0, true);
  935. }
  936. static inline bool bulkfree_pcp_prepare(struct page *page)
  937. {
  938. return false;
  939. }
  940. #else
  941. static bool free_pcp_prepare(struct page *page)
  942. {
  943. return free_pages_prepare(page, 0, false);
  944. }
  945. static bool bulkfree_pcp_prepare(struct page *page)
  946. {
  947. return free_pages_check(page);
  948. }
  949. #endif /* CONFIG_DEBUG_VM */
  950. static inline void prefetch_buddy(struct page *page)
  951. {
  952. unsigned long pfn = page_to_pfn(page);
  953. unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
  954. struct page *buddy = page + (buddy_pfn - pfn);
  955. prefetch(buddy);
  956. }
  957. /*
  958. * Frees a number of pages from the PCP lists
  959. * Assumes all pages on list are in same zone, and of same order.
  960. * count is the number of pages to free.
  961. *
  962. * If the zone was previously in an "all pages pinned" state then look to
  963. * see if this freeing clears that state.
  964. *
  965. * And clear the zone's pages_scanned counter, to hold off the "all pages are
  966. * pinned" detection logic.
  967. */
  968. static void free_pcppages_bulk(struct zone *zone, int count,
  969. struct per_cpu_pages *pcp)
  970. {
  971. int migratetype = 0;
  972. int batch_free = 0;
  973. int prefetch_nr = 0;
  974. bool isolated_pageblocks;
  975. struct page *page, *tmp;
  976. LIST_HEAD(head);
  977. /*
  978. * Ensure proper count is passed which otherwise would stuck in the
  979. * below while (list_empty(list)) loop.
  980. */
  981. count = min(pcp->count, count);
  982. while (count) {
  983. struct list_head *list;
  984. /*
  985. * Remove pages from lists in a round-robin fashion. A
  986. * batch_free count is maintained that is incremented when an
  987. * empty list is encountered. This is so more pages are freed
  988. * off fuller lists instead of spinning excessively around empty
  989. * lists
  990. */
  991. do {
  992. batch_free++;
  993. if (++migratetype == MIGRATE_PCPTYPES)
  994. migratetype = 0;
  995. list = &pcp->lists[migratetype];
  996. } while (list_empty(list));
  997. /* This is the only non-empty list. Free them all. */
  998. if (batch_free == MIGRATE_PCPTYPES)
  999. batch_free = count;
  1000. do {
  1001. page = list_last_entry(list, struct page, lru);
  1002. /* must delete to avoid corrupting pcp list */
  1003. list_del(&page->lru);
  1004. pcp->count--;
  1005. if (bulkfree_pcp_prepare(page))
  1006. continue;
  1007. list_add_tail(&page->lru, &head);
  1008. /*
  1009. * We are going to put the page back to the global
  1010. * pool, prefetch its buddy to speed up later access
  1011. * under zone->lock. It is believed the overhead of
  1012. * an additional test and calculating buddy_pfn here
  1013. * can be offset by reduced memory latency later. To
  1014. * avoid excessive prefetching due to large count, only
  1015. * prefetch buddy for the first pcp->batch nr of pages.
  1016. */
  1017. if (prefetch_nr++ < pcp->batch)
  1018. prefetch_buddy(page);
  1019. } while (--count && --batch_free && !list_empty(list));
  1020. }
  1021. spin_lock(&zone->lock);
  1022. isolated_pageblocks = has_isolate_pageblock(zone);
  1023. /*
  1024. * Use safe version since after __free_one_page(),
  1025. * page->lru.next will not point to original list.
  1026. */
  1027. list_for_each_entry_safe(page, tmp, &head, lru) {
  1028. int mt = get_pcppage_migratetype(page);
  1029. /* MIGRATE_ISOLATE page should not go to pcplists */
  1030. VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
  1031. /* Pageblock could have been isolated meanwhile */
  1032. if (unlikely(isolated_pageblocks))
  1033. mt = get_pageblock_migratetype(page);
  1034. __free_one_page(page, page_to_pfn(page), zone, 0, mt);
  1035. trace_mm_page_pcpu_drain(page, 0, mt);
  1036. }
  1037. spin_unlock(&zone->lock);
  1038. }
  1039. static void free_one_page(struct zone *zone,
  1040. struct page *page, unsigned long pfn,
  1041. unsigned int order,
  1042. int migratetype)
  1043. {
  1044. spin_lock(&zone->lock);
  1045. if (unlikely(has_isolate_pageblock(zone) ||
  1046. is_migrate_isolate(migratetype))) {
  1047. migratetype = get_pfnblock_migratetype(page, pfn);
  1048. }
  1049. __free_one_page(page, pfn, zone, order, migratetype);
  1050. spin_unlock(&zone->lock);
  1051. }
  1052. static void __meminit __init_single_page(struct page *page, unsigned long pfn,
  1053. unsigned long zone, int nid)
  1054. {
  1055. mm_zero_struct_page(page);
  1056. set_page_links(page, zone, nid, pfn);
  1057. init_page_count(page);
  1058. page_mapcount_reset(page);
  1059. page_cpupid_reset_last(page);
  1060. INIT_LIST_HEAD(&page->lru);
  1061. #ifdef WANT_PAGE_VIRTUAL
  1062. /* The shift won't overflow because ZONE_NORMAL is below 4G. */
  1063. if (!is_highmem_idx(zone))
  1064. set_page_address(page, __va(pfn << PAGE_SHIFT));
  1065. #endif
  1066. }
  1067. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  1068. static void __meminit init_reserved_page(unsigned long pfn)
  1069. {
  1070. pg_data_t *pgdat;
  1071. int nid, zid;
  1072. if (!early_page_uninitialised(pfn))
  1073. return;
  1074. nid = early_pfn_to_nid(pfn);
  1075. pgdat = NODE_DATA(nid);
  1076. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  1077. struct zone *zone = &pgdat->node_zones[zid];
  1078. if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
  1079. break;
  1080. }
  1081. __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
  1082. }
  1083. #else
  1084. static inline void init_reserved_page(unsigned long pfn)
  1085. {
  1086. }
  1087. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  1088. /*
  1089. * Initialised pages do not have PageReserved set. This function is
  1090. * called for each range allocated by the bootmem allocator and
  1091. * marks the pages PageReserved. The remaining valid pages are later
  1092. * sent to the buddy page allocator.
  1093. */
  1094. void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
  1095. {
  1096. unsigned long start_pfn = PFN_DOWN(start);
  1097. unsigned long end_pfn = PFN_UP(end);
  1098. for (; start_pfn < end_pfn; start_pfn++) {
  1099. if (pfn_valid(start_pfn)) {
  1100. struct page *page = pfn_to_page(start_pfn);
  1101. init_reserved_page(start_pfn);
  1102. /* Avoid false-positive PageTail() */
  1103. INIT_LIST_HEAD(&page->lru);
  1104. SetPageReserved(page);
  1105. }
  1106. }
  1107. }
  1108. static void __free_pages_ok(struct page *page, unsigned int order)
  1109. {
  1110. unsigned long flags;
  1111. int migratetype;
  1112. unsigned long pfn = page_to_pfn(page);
  1113. if (!free_pages_prepare(page, order, true))
  1114. return;
  1115. migratetype = get_pfnblock_migratetype(page, pfn);
  1116. local_irq_save(flags);
  1117. __count_vm_events(PGFREE, 1 << order);
  1118. free_one_page(page_zone(page), page, pfn, order, migratetype);
  1119. local_irq_restore(flags);
  1120. }
  1121. static void __init __free_pages_boot_core(struct page *page, unsigned int order)
  1122. {
  1123. unsigned int nr_pages = 1 << order;
  1124. struct page *p = page;
  1125. unsigned int loop;
  1126. prefetchw(p);
  1127. for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
  1128. prefetchw(p + 1);
  1129. __ClearPageReserved(p);
  1130. set_page_count(p, 0);
  1131. }
  1132. __ClearPageReserved(p);
  1133. set_page_count(p, 0);
  1134. page_zone(page)->managed_pages += nr_pages;
  1135. set_page_refcounted(page);
  1136. __free_pages(page, order);
  1137. }
  1138. #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
  1139. defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
  1140. static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
  1141. int __meminit early_pfn_to_nid(unsigned long pfn)
  1142. {
  1143. static DEFINE_SPINLOCK(early_pfn_lock);
  1144. int nid;
  1145. spin_lock(&early_pfn_lock);
  1146. nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
  1147. if (nid < 0)
  1148. nid = first_online_node;
  1149. spin_unlock(&early_pfn_lock);
  1150. return nid;
  1151. }
  1152. #endif
  1153. #ifdef CONFIG_NODES_SPAN_OTHER_NODES
  1154. static inline bool __meminit __maybe_unused
  1155. meminit_pfn_in_nid(unsigned long pfn, int node,
  1156. struct mminit_pfnnid_cache *state)
  1157. {
  1158. int nid;
  1159. nid = __early_pfn_to_nid(pfn, state);
  1160. if (nid >= 0 && nid != node)
  1161. return false;
  1162. return true;
  1163. }
  1164. /* Only safe to use early in boot when initialisation is single-threaded */
  1165. static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
  1166. {
  1167. return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
  1168. }
  1169. #else
  1170. static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
  1171. {
  1172. return true;
  1173. }
  1174. static inline bool __meminit __maybe_unused
  1175. meminit_pfn_in_nid(unsigned long pfn, int node,
  1176. struct mminit_pfnnid_cache *state)
  1177. {
  1178. return true;
  1179. }
  1180. #endif
  1181. void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
  1182. unsigned int order)
  1183. {
  1184. if (early_page_uninitialised(pfn))
  1185. return;
  1186. return __free_pages_boot_core(page, order);
  1187. }
  1188. /*
  1189. * Check that the whole (or subset of) a pageblock given by the interval of
  1190. * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
  1191. * with the migration of free compaction scanner. The scanners then need to
  1192. * use only pfn_valid_within() check for arches that allow holes within
  1193. * pageblocks.
  1194. *
  1195. * Return struct page pointer of start_pfn, or NULL if checks were not passed.
  1196. *
  1197. * It's possible on some configurations to have a setup like node0 node1 node0
  1198. * i.e. it's possible that all pages within a zones range of pages do not
  1199. * belong to a single zone. We assume that a border between node0 and node1
  1200. * can occur within a single pageblock, but not a node0 node1 node0
  1201. * interleaving within a single pageblock. It is therefore sufficient to check
  1202. * the first and last page of a pageblock and avoid checking each individual
  1203. * page in a pageblock.
  1204. */
  1205. struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
  1206. unsigned long end_pfn, struct zone *zone)
  1207. {
  1208. struct page *start_page;
  1209. struct page *end_page;
  1210. /* end_pfn is one past the range we are checking */
  1211. end_pfn--;
  1212. if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
  1213. return NULL;
  1214. start_page = pfn_to_online_page(start_pfn);
  1215. if (!start_page)
  1216. return NULL;
  1217. if (page_zone(start_page) != zone)
  1218. return NULL;
  1219. end_page = pfn_to_page(end_pfn);
  1220. /* This gives a shorter code than deriving page_zone(end_page) */
  1221. if (page_zone_id(start_page) != page_zone_id(end_page))
  1222. return NULL;
  1223. return start_page;
  1224. }
  1225. void set_zone_contiguous(struct zone *zone)
  1226. {
  1227. unsigned long block_start_pfn = zone->zone_start_pfn;
  1228. unsigned long block_end_pfn;
  1229. block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
  1230. for (; block_start_pfn < zone_end_pfn(zone);
  1231. block_start_pfn = block_end_pfn,
  1232. block_end_pfn += pageblock_nr_pages) {
  1233. block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
  1234. if (!__pageblock_pfn_to_page(block_start_pfn,
  1235. block_end_pfn, zone))
  1236. return;
  1237. cond_resched();
  1238. }
  1239. /* We confirm that there is no hole */
  1240. zone->contiguous = true;
  1241. }
  1242. void clear_zone_contiguous(struct zone *zone)
  1243. {
  1244. zone->contiguous = false;
  1245. }
  1246. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  1247. static void __init deferred_free_range(unsigned long pfn,
  1248. unsigned long nr_pages)
  1249. {
  1250. struct page *page;
  1251. unsigned long i;
  1252. if (!nr_pages)
  1253. return;
  1254. page = pfn_to_page(pfn);
  1255. /* Free a large naturally-aligned chunk if possible */
  1256. if (nr_pages == pageblock_nr_pages &&
  1257. (pfn & (pageblock_nr_pages - 1)) == 0) {
  1258. set_pageblock_migratetype(page, MIGRATE_MOVABLE);
  1259. __free_pages_boot_core(page, pageblock_order);
  1260. return;
  1261. }
  1262. for (i = 0; i < nr_pages; i++, page++, pfn++) {
  1263. if ((pfn & (pageblock_nr_pages - 1)) == 0)
  1264. set_pageblock_migratetype(page, MIGRATE_MOVABLE);
  1265. __free_pages_boot_core(page, 0);
  1266. }
  1267. }
  1268. /* Completion tracking for deferred_init_memmap() threads */
  1269. static atomic_t pgdat_init_n_undone __initdata;
  1270. static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
  1271. static inline void __init pgdat_init_report_one_done(void)
  1272. {
  1273. if (atomic_dec_and_test(&pgdat_init_n_undone))
  1274. complete(&pgdat_init_all_done_comp);
  1275. }
  1276. /*
  1277. * Returns true if page needs to be initialized or freed to buddy allocator.
  1278. *
  1279. * First we check if pfn is valid on architectures where it is possible to have
  1280. * holes within pageblock_nr_pages. On systems where it is not possible, this
  1281. * function is optimized out.
  1282. *
  1283. * Then, we check if a current large page is valid by only checking the validity
  1284. * of the head pfn.
  1285. *
  1286. * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
  1287. * within a node: a pfn is between start and end of a node, but does not belong
  1288. * to this memory node.
  1289. */
  1290. static inline bool __init
  1291. deferred_pfn_valid(int nid, unsigned long pfn,
  1292. struct mminit_pfnnid_cache *nid_init_state)
  1293. {
  1294. if (!pfn_valid_within(pfn))
  1295. return false;
  1296. if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
  1297. return false;
  1298. if (!meminit_pfn_in_nid(pfn, nid, nid_init_state))
  1299. return false;
  1300. return true;
  1301. }
  1302. /*
  1303. * Free pages to buddy allocator. Try to free aligned pages in
  1304. * pageblock_nr_pages sizes.
  1305. */
  1306. static void __init deferred_free_pages(int nid, int zid, unsigned long pfn,
  1307. unsigned long end_pfn)
  1308. {
  1309. struct mminit_pfnnid_cache nid_init_state = { };
  1310. unsigned long nr_pgmask = pageblock_nr_pages - 1;
  1311. unsigned long nr_free = 0;
  1312. for (; pfn < end_pfn; pfn++) {
  1313. if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
  1314. deferred_free_range(pfn - nr_free, nr_free);
  1315. nr_free = 0;
  1316. } else if (!(pfn & nr_pgmask)) {
  1317. deferred_free_range(pfn - nr_free, nr_free);
  1318. nr_free = 1;
  1319. touch_nmi_watchdog();
  1320. } else {
  1321. nr_free++;
  1322. }
  1323. }
  1324. /* Free the last block of pages to allocator */
  1325. deferred_free_range(pfn - nr_free, nr_free);
  1326. }
  1327. /*
  1328. * Initialize struct pages. We minimize pfn page lookups and scheduler checks
  1329. * by performing it only once every pageblock_nr_pages.
  1330. * Return number of pages initialized.
  1331. */
  1332. static unsigned long __init deferred_init_pages(int nid, int zid,
  1333. unsigned long pfn,
  1334. unsigned long end_pfn)
  1335. {
  1336. struct mminit_pfnnid_cache nid_init_state = { };
  1337. unsigned long nr_pgmask = pageblock_nr_pages - 1;
  1338. unsigned long nr_pages = 0;
  1339. struct page *page = NULL;
  1340. for (; pfn < end_pfn; pfn++) {
  1341. if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
  1342. page = NULL;
  1343. continue;
  1344. } else if (!page || !(pfn & nr_pgmask)) {
  1345. page = pfn_to_page(pfn);
  1346. touch_nmi_watchdog();
  1347. } else {
  1348. page++;
  1349. }
  1350. __init_single_page(page, pfn, zid, nid);
  1351. nr_pages++;
  1352. }
  1353. return (nr_pages);
  1354. }
  1355. /* Initialise remaining memory on a node */
  1356. static int __init deferred_init_memmap(void *data)
  1357. {
  1358. pg_data_t *pgdat = data;
  1359. int nid = pgdat->node_id;
  1360. unsigned long start = jiffies;
  1361. unsigned long nr_pages = 0;
  1362. unsigned long spfn, epfn, first_init_pfn, flags;
  1363. phys_addr_t spa, epa;
  1364. int zid;
  1365. struct zone *zone;
  1366. const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
  1367. u64 i;
  1368. /* Bind memory initialisation thread to a local node if possible */
  1369. if (!cpumask_empty(cpumask))
  1370. set_cpus_allowed_ptr(current, cpumask);
  1371. pgdat_resize_lock(pgdat, &flags);
  1372. first_init_pfn = pgdat->first_deferred_pfn;
  1373. if (first_init_pfn == ULONG_MAX) {
  1374. pgdat_resize_unlock(pgdat, &flags);
  1375. pgdat_init_report_one_done();
  1376. return 0;
  1377. }
  1378. /* Sanity check boundaries */
  1379. BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
  1380. BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
  1381. pgdat->first_deferred_pfn = ULONG_MAX;
  1382. /*
  1383. * Once we unlock here, the zone cannot be grown anymore, thus if an
  1384. * interrupt thread must allocate this early in boot, zone must be
  1385. * pre-grown prior to start of deferred page initialization.
  1386. */
  1387. pgdat_resize_unlock(pgdat, &flags);
  1388. /* Only the highest zone is deferred so find it */
  1389. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  1390. zone = pgdat->node_zones + zid;
  1391. if (first_init_pfn < zone_end_pfn(zone))
  1392. break;
  1393. }
  1394. first_init_pfn = max(zone->zone_start_pfn, first_init_pfn);
  1395. /*
  1396. * Initialize and free pages. We do it in two loops: first we initialize
  1397. * struct page, than free to buddy allocator, because while we are
  1398. * freeing pages we can access pages that are ahead (computing buddy
  1399. * page in __free_one_page()).
  1400. */
  1401. for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
  1402. spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
  1403. epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
  1404. nr_pages += deferred_init_pages(nid, zid, spfn, epfn);
  1405. }
  1406. for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
  1407. spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
  1408. epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
  1409. deferred_free_pages(nid, zid, spfn, epfn);
  1410. }
  1411. /* Sanity check that the next zone really is unpopulated */
  1412. WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
  1413. pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
  1414. jiffies_to_msecs(jiffies - start));
  1415. pgdat_init_report_one_done();
  1416. return 0;
  1417. }
  1418. /*
  1419. * If this zone has deferred pages, try to grow it by initializing enough
  1420. * deferred pages to satisfy the allocation specified by order, rounded up to
  1421. * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
  1422. * of SECTION_SIZE bytes by initializing struct pages in increments of
  1423. * PAGES_PER_SECTION * sizeof(struct page) bytes.
  1424. *
  1425. * Return true when zone was grown, otherwise return false. We return true even
  1426. * when we grow less than requested, to let the caller decide if there are
  1427. * enough pages to satisfy the allocation.
  1428. *
  1429. * Note: We use noinline because this function is needed only during boot, and
  1430. * it is called from a __ref function _deferred_grow_zone. This way we are
  1431. * making sure that it is not inlined into permanent text section.
  1432. */
  1433. static noinline bool __init
  1434. deferred_grow_zone(struct zone *zone, unsigned int order)
  1435. {
  1436. int zid = zone_idx(zone);
  1437. int nid = zone_to_nid(zone);
  1438. pg_data_t *pgdat = NODE_DATA(nid);
  1439. unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
  1440. unsigned long nr_pages = 0;
  1441. unsigned long first_init_pfn, spfn, epfn, t, flags;
  1442. unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
  1443. phys_addr_t spa, epa;
  1444. u64 i;
  1445. /* Only the last zone may have deferred pages */
  1446. if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
  1447. return false;
  1448. pgdat_resize_lock(pgdat, &flags);
  1449. /*
  1450. * If someone grew this zone while we were waiting for spinlock, return
  1451. * true, as there might be enough pages already.
  1452. */
  1453. if (first_deferred_pfn != pgdat->first_deferred_pfn) {
  1454. pgdat_resize_unlock(pgdat, &flags);
  1455. return true;
  1456. }
  1457. first_init_pfn = max(zone->zone_start_pfn, first_deferred_pfn);
  1458. if (first_init_pfn >= pgdat_end_pfn(pgdat)) {
  1459. pgdat_resize_unlock(pgdat, &flags);
  1460. return false;
  1461. }
  1462. for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
  1463. spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
  1464. epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
  1465. while (spfn < epfn && nr_pages < nr_pages_needed) {
  1466. t = ALIGN(spfn + PAGES_PER_SECTION, PAGES_PER_SECTION);
  1467. first_deferred_pfn = min(t, epfn);
  1468. nr_pages += deferred_init_pages(nid, zid, spfn,
  1469. first_deferred_pfn);
  1470. spfn = first_deferred_pfn;
  1471. }
  1472. if (nr_pages >= nr_pages_needed)
  1473. break;
  1474. }
  1475. for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
  1476. spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
  1477. epfn = min_t(unsigned long, first_deferred_pfn, PFN_DOWN(epa));
  1478. deferred_free_pages(nid, zid, spfn, epfn);
  1479. if (first_deferred_pfn == epfn)
  1480. break;
  1481. }
  1482. pgdat->first_deferred_pfn = first_deferred_pfn;
  1483. pgdat_resize_unlock(pgdat, &flags);
  1484. return nr_pages > 0;
  1485. }
  1486. /*
  1487. * deferred_grow_zone() is __init, but it is called from
  1488. * get_page_from_freelist() during early boot until deferred_pages permanently
  1489. * disables this call. This is why we have refdata wrapper to avoid warning,
  1490. * and to ensure that the function body gets unloaded.
  1491. */
  1492. static bool __ref
  1493. _deferred_grow_zone(struct zone *zone, unsigned int order)
  1494. {
  1495. return deferred_grow_zone(zone, order);
  1496. }
  1497. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  1498. void __init page_alloc_init_late(void)
  1499. {
  1500. struct zone *zone;
  1501. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  1502. int nid;
  1503. /* There will be num_node_state(N_MEMORY) threads */
  1504. atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
  1505. for_each_node_state(nid, N_MEMORY) {
  1506. kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
  1507. }
  1508. /* Block until all are initialised */
  1509. wait_for_completion(&pgdat_init_all_done_comp);
  1510. /*
  1511. * The number of managed pages has changed due to the initialisation
  1512. * so the pcpu batch and high limits needs to be updated or the limits
  1513. * will be artificially small.
  1514. */
  1515. for_each_populated_zone(zone)
  1516. zone_pcp_update(zone);
  1517. /*
  1518. * We initialized the rest of the deferred pages. Permanently disable
  1519. * on-demand struct page initialization.
  1520. */
  1521. static_branch_disable(&deferred_pages);
  1522. /* Reinit limits that are based on free pages after the kernel is up */
  1523. files_maxfiles_init();
  1524. #endif
  1525. #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
  1526. /* Discard memblock private memory */
  1527. memblock_discard();
  1528. #endif
  1529. for_each_populated_zone(zone)
  1530. set_zone_contiguous(zone);
  1531. }
  1532. #ifdef CONFIG_CMA
  1533. /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
  1534. void __init init_cma_reserved_pageblock(struct page *page)
  1535. {
  1536. unsigned i = pageblock_nr_pages;
  1537. struct page *p = page;
  1538. do {
  1539. __ClearPageReserved(p);
  1540. set_page_count(p, 0);
  1541. } while (++p, --i);
  1542. set_pageblock_migratetype(page, MIGRATE_CMA);
  1543. if (pageblock_order >= MAX_ORDER) {
  1544. i = pageblock_nr_pages;
  1545. p = page;
  1546. do {
  1547. set_page_refcounted(p);
  1548. __free_pages(p, MAX_ORDER - 1);
  1549. p += MAX_ORDER_NR_PAGES;
  1550. } while (i -= MAX_ORDER_NR_PAGES);
  1551. } else {
  1552. set_page_refcounted(page);
  1553. __free_pages(page, pageblock_order);
  1554. }
  1555. adjust_managed_page_count(page, pageblock_nr_pages);
  1556. }
  1557. #endif
  1558. /*
  1559. * The order of subdivision here is critical for the IO subsystem.
  1560. * Please do not alter this order without good reasons and regression
  1561. * testing. Specifically, as large blocks of memory are subdivided,
  1562. * the order in which smaller blocks are delivered depends on the order
  1563. * they're subdivided in this function. This is the primary factor
  1564. * influencing the order in which pages are delivered to the IO
  1565. * subsystem according to empirical testing, and this is also justified
  1566. * by considering the behavior of a buddy system containing a single
  1567. * large block of memory acted on by a series of small allocations.
  1568. * This behavior is a critical factor in sglist merging's success.
  1569. *
  1570. * -- nyc
  1571. */
  1572. static inline void expand(struct zone *zone, struct page *page,
  1573. int low, int high, struct free_area *area,
  1574. int migratetype)
  1575. {
  1576. unsigned long size = 1 << high;
  1577. while (high > low) {
  1578. area--;
  1579. high--;
  1580. size >>= 1;
  1581. VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
  1582. /*
  1583. * Mark as guard pages (or page), that will allow to
  1584. * merge back to allocator when buddy will be freed.
  1585. * Corresponding page table entries will not be touched,
  1586. * pages will stay not present in virtual address space
  1587. */
  1588. if (set_page_guard(zone, &page[size], high, migratetype))
  1589. continue;
  1590. list_add(&page[size].lru, &area->free_list[migratetype]);
  1591. area->nr_free++;
  1592. set_page_order(&page[size], high);
  1593. }
  1594. }
  1595. static void check_new_page_bad(struct page *page)
  1596. {
  1597. const char *bad_reason = NULL;
  1598. unsigned long bad_flags = 0;
  1599. if (unlikely(atomic_read(&page->_mapcount) != -1))
  1600. bad_reason = "nonzero mapcount";
  1601. if (unlikely(page->mapping != NULL))
  1602. bad_reason = "non-NULL mapping";
  1603. if (unlikely(page_ref_count(page) != 0))
  1604. bad_reason = "nonzero _count";
  1605. if (unlikely(page->flags & __PG_HWPOISON)) {
  1606. bad_reason = "HWPoisoned (hardware-corrupted)";
  1607. bad_flags = __PG_HWPOISON;
  1608. /* Don't complain about hwpoisoned pages */
  1609. page_mapcount_reset(page); /* remove PageBuddy */
  1610. return;
  1611. }
  1612. if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
  1613. bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
  1614. bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
  1615. }
  1616. #ifdef CONFIG_MEMCG
  1617. if (unlikely(page->mem_cgroup))
  1618. bad_reason = "page still charged to cgroup";
  1619. #endif
  1620. bad_page(page, bad_reason, bad_flags);
  1621. }
  1622. /*
  1623. * This page is about to be returned from the page allocator
  1624. */
  1625. static inline int check_new_page(struct page *page)
  1626. {
  1627. if (likely(page_expected_state(page,
  1628. PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
  1629. return 0;
  1630. check_new_page_bad(page);
  1631. return 1;
  1632. }
  1633. static inline bool free_pages_prezeroed(void)
  1634. {
  1635. return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
  1636. page_poisoning_enabled();
  1637. }
  1638. #ifdef CONFIG_DEBUG_VM
  1639. static bool check_pcp_refill(struct page *page)
  1640. {
  1641. return false;
  1642. }
  1643. static bool check_new_pcp(struct page *page)
  1644. {
  1645. return check_new_page(page);
  1646. }
  1647. #else
  1648. static bool check_pcp_refill(struct page *page)
  1649. {
  1650. return check_new_page(page);
  1651. }
  1652. static bool check_new_pcp(struct page *page)
  1653. {
  1654. return false;
  1655. }
  1656. #endif /* CONFIG_DEBUG_VM */
  1657. static bool check_new_pages(struct page *page, unsigned int order)
  1658. {
  1659. int i;
  1660. for (i = 0; i < (1 << order); i++) {
  1661. struct page *p = page + i;
  1662. if (unlikely(check_new_page(p)))
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. inline void post_alloc_hook(struct page *page, unsigned int order,
  1668. gfp_t gfp_flags)
  1669. {
  1670. set_page_private(page, 0);
  1671. set_page_refcounted(page);
  1672. arch_alloc_page(page, order);
  1673. kernel_map_pages(page, 1 << order, 1);
  1674. kasan_alloc_pages(page, order);
  1675. kernel_poison_pages(page, 1 << order, 1);
  1676. set_page_owner(page, order, gfp_flags);
  1677. }
  1678. static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
  1679. unsigned int alloc_flags)
  1680. {
  1681. int i;
  1682. post_alloc_hook(page, order, gfp_flags);
  1683. if (!free_pages_prezeroed() && (gfp_flags & __GFP_ZERO))
  1684. for (i = 0; i < (1 << order); i++)
  1685. clear_highpage(page + i);
  1686. if (order && (gfp_flags & __GFP_COMP))
  1687. prep_compound_page(page, order);
  1688. /*
  1689. * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
  1690. * allocate the page. The expectation is that the caller is taking
  1691. * steps that will free more memory. The caller should avoid the page
  1692. * being used for !PFMEMALLOC purposes.
  1693. */
  1694. if (alloc_flags & ALLOC_NO_WATERMARKS)
  1695. set_page_pfmemalloc(page);
  1696. else
  1697. clear_page_pfmemalloc(page);
  1698. }
  1699. /*
  1700. * Go through the free lists for the given migratetype and remove
  1701. * the smallest available page from the freelists
  1702. */
  1703. static __always_inline
  1704. struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
  1705. int migratetype)
  1706. {
  1707. unsigned int current_order;
  1708. struct free_area *area;
  1709. struct page *page;
  1710. /* Find a page of the appropriate size in the preferred list */
  1711. for (current_order = order; current_order < MAX_ORDER; ++current_order) {
  1712. area = &(zone->free_area[current_order]);
  1713. page = list_first_entry_or_null(&area->free_list[migratetype],
  1714. struct page, lru);
  1715. if (!page)
  1716. continue;
  1717. list_del(&page->lru);
  1718. rmv_page_order(page);
  1719. area->nr_free--;
  1720. expand(zone, page, order, current_order, area, migratetype);
  1721. set_pcppage_migratetype(page, migratetype);
  1722. return page;
  1723. }
  1724. return NULL;
  1725. }
  1726. /*
  1727. * This array describes the order lists are fallen back to when
  1728. * the free lists for the desirable migrate type are depleted
  1729. */
  1730. static int fallbacks[MIGRATE_TYPES][4] = {
  1731. [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
  1732. [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
  1733. [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
  1734. #ifdef CONFIG_CMA
  1735. [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
  1736. #endif
  1737. #ifdef CONFIG_MEMORY_ISOLATION
  1738. [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
  1739. #endif
  1740. };
  1741. #ifdef CONFIG_CMA
  1742. static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1743. unsigned int order)
  1744. {
  1745. return __rmqueue_smallest(zone, order, MIGRATE_CMA);
  1746. }
  1747. #else
  1748. static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1749. unsigned int order) { return NULL; }
  1750. #endif
  1751. /*
  1752. * Move the free pages in a range to the free lists of the requested type.
  1753. * Note that start_page and end_pages are not aligned on a pageblock
  1754. * boundary. If alignment is required, use move_freepages_block()
  1755. */
  1756. static int move_freepages(struct zone *zone,
  1757. struct page *start_page, struct page *end_page,
  1758. int migratetype, int *num_movable)
  1759. {
  1760. struct page *page;
  1761. unsigned int order;
  1762. int pages_moved = 0;
  1763. #ifndef CONFIG_HOLES_IN_ZONE
  1764. /*
  1765. * page_zone is not safe to call in this context when
  1766. * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
  1767. * anyway as we check zone boundaries in move_freepages_block().
  1768. * Remove at a later date when no bug reports exist related to
  1769. * grouping pages by mobility
  1770. */
  1771. VM_BUG_ON(pfn_valid(page_to_pfn(start_page)) &&
  1772. pfn_valid(page_to_pfn(end_page)) &&
  1773. page_zone(start_page) != page_zone(end_page));
  1774. #endif
  1775. if (num_movable)
  1776. *num_movable = 0;
  1777. for (page = start_page; page <= end_page;) {
  1778. if (!pfn_valid_within(page_to_pfn(page))) {
  1779. page++;
  1780. continue;
  1781. }
  1782. /* Make sure we are not inadvertently changing nodes */
  1783. VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
  1784. if (!PageBuddy(page)) {
  1785. /*
  1786. * We assume that pages that could be isolated for
  1787. * migration are movable. But we don't actually try
  1788. * isolating, as that would be expensive.
  1789. */
  1790. if (num_movable &&
  1791. (PageLRU(page) || __PageMovable(page)))
  1792. (*num_movable)++;
  1793. page++;
  1794. continue;
  1795. }
  1796. order = page_order(page);
  1797. list_move(&page->lru,
  1798. &zone->free_area[order].free_list[migratetype]);
  1799. page += 1 << order;
  1800. pages_moved += 1 << order;
  1801. }
  1802. return pages_moved;
  1803. }
  1804. int move_freepages_block(struct zone *zone, struct page *page,
  1805. int migratetype, int *num_movable)
  1806. {
  1807. unsigned long start_pfn, end_pfn;
  1808. struct page *start_page, *end_page;
  1809. start_pfn = page_to_pfn(page);
  1810. start_pfn = start_pfn & ~(pageblock_nr_pages-1);
  1811. start_page = pfn_to_page(start_pfn);
  1812. end_page = start_page + pageblock_nr_pages - 1;
  1813. end_pfn = start_pfn + pageblock_nr_pages - 1;
  1814. /* Do not cross zone boundaries */
  1815. if (!zone_spans_pfn(zone, start_pfn))
  1816. start_page = page;
  1817. if (!zone_spans_pfn(zone, end_pfn))
  1818. return 0;
  1819. return move_freepages(zone, start_page, end_page, migratetype,
  1820. num_movable);
  1821. }
  1822. static void change_pageblock_range(struct page *pageblock_page,
  1823. int start_order, int migratetype)
  1824. {
  1825. int nr_pageblocks = 1 << (start_order - pageblock_order);
  1826. while (nr_pageblocks--) {
  1827. set_pageblock_migratetype(pageblock_page, migratetype);
  1828. pageblock_page += pageblock_nr_pages;
  1829. }
  1830. }
  1831. /*
  1832. * When we are falling back to another migratetype during allocation, try to
  1833. * steal extra free pages from the same pageblocks to satisfy further
  1834. * allocations, instead of polluting multiple pageblocks.
  1835. *
  1836. * If we are stealing a relatively large buddy page, it is likely there will
  1837. * be more free pages in the pageblock, so try to steal them all. For
  1838. * reclaimable and unmovable allocations, we steal regardless of page size,
  1839. * as fragmentation caused by those allocations polluting movable pageblocks
  1840. * is worse than movable allocations stealing from unmovable and reclaimable
  1841. * pageblocks.
  1842. */
  1843. static bool can_steal_fallback(unsigned int order, int start_mt)
  1844. {
  1845. /*
  1846. * Leaving this order check is intended, although there is
  1847. * relaxed order check in next check. The reason is that
  1848. * we can actually steal whole pageblock if this condition met,
  1849. * but, below check doesn't guarantee it and that is just heuristic
  1850. * so could be changed anytime.
  1851. */
  1852. if (order >= pageblock_order)
  1853. return true;
  1854. if (order >= pageblock_order / 2 ||
  1855. start_mt == MIGRATE_RECLAIMABLE ||
  1856. start_mt == MIGRATE_UNMOVABLE ||
  1857. page_group_by_mobility_disabled)
  1858. return true;
  1859. return false;
  1860. }
  1861. /*
  1862. * This function implements actual steal behaviour. If order is large enough,
  1863. * we can steal whole pageblock. If not, we first move freepages in this
  1864. * pageblock to our migratetype and determine how many already-allocated pages
  1865. * are there in the pageblock with a compatible migratetype. If at least half
  1866. * of pages are free or compatible, we can change migratetype of the pageblock
  1867. * itself, so pages freed in the future will be put on the correct free list.
  1868. */
  1869. static void steal_suitable_fallback(struct zone *zone, struct page *page,
  1870. int start_type, bool whole_block)
  1871. {
  1872. unsigned int current_order = page_order(page);
  1873. struct free_area *area;
  1874. int free_pages, movable_pages, alike_pages;
  1875. int old_block_type;
  1876. old_block_type = get_pageblock_migratetype(page);
  1877. /*
  1878. * This can happen due to races and we want to prevent broken
  1879. * highatomic accounting.
  1880. */
  1881. if (is_migrate_highatomic(old_block_type))
  1882. goto single_page;
  1883. /* Take ownership for orders >= pageblock_order */
  1884. if (current_order >= pageblock_order) {
  1885. change_pageblock_range(page, current_order, start_type);
  1886. goto single_page;
  1887. }
  1888. /* We are not allowed to try stealing from the whole block */
  1889. if (!whole_block)
  1890. goto single_page;
  1891. free_pages = move_freepages_block(zone, page, start_type,
  1892. &movable_pages);
  1893. /*
  1894. * Determine how many pages are compatible with our allocation.
  1895. * For movable allocation, it's the number of movable pages which
  1896. * we just obtained. For other types it's a bit more tricky.
  1897. */
  1898. if (start_type == MIGRATE_MOVABLE) {
  1899. alike_pages = movable_pages;
  1900. } else {
  1901. /*
  1902. * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
  1903. * to MOVABLE pageblock, consider all non-movable pages as
  1904. * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
  1905. * vice versa, be conservative since we can't distinguish the
  1906. * exact migratetype of non-movable pages.
  1907. */
  1908. if (old_block_type == MIGRATE_MOVABLE)
  1909. alike_pages = pageblock_nr_pages
  1910. - (free_pages + movable_pages);
  1911. else
  1912. alike_pages = 0;
  1913. }
  1914. /* moving whole block can fail due to zone boundary conditions */
  1915. if (!free_pages)
  1916. goto single_page;
  1917. /*
  1918. * If a sufficient number of pages in the block are either free or of
  1919. * comparable migratability as our allocation, claim the whole block.
  1920. */
  1921. if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
  1922. page_group_by_mobility_disabled)
  1923. set_pageblock_migratetype(page, start_type);
  1924. return;
  1925. single_page:
  1926. area = &zone->free_area[current_order];
  1927. list_move(&page->lru, &area->free_list[start_type]);
  1928. }
  1929. /*
  1930. * Check whether there is a suitable fallback freepage with requested order.
  1931. * If only_stealable is true, this function returns fallback_mt only if
  1932. * we can steal other freepages all together. This would help to reduce
  1933. * fragmentation due to mixed migratetype pages in one pageblock.
  1934. */
  1935. int find_suitable_fallback(struct free_area *area, unsigned int order,
  1936. int migratetype, bool only_stealable, bool *can_steal)
  1937. {
  1938. int i;
  1939. int fallback_mt;
  1940. if (area->nr_free == 0)
  1941. return -1;
  1942. *can_steal = false;
  1943. for (i = 0;; i++) {
  1944. fallback_mt = fallbacks[migratetype][i];
  1945. if (fallback_mt == MIGRATE_TYPES)
  1946. break;
  1947. if (list_empty(&area->free_list[fallback_mt]))
  1948. continue;
  1949. if (can_steal_fallback(order, migratetype))
  1950. *can_steal = true;
  1951. if (!only_stealable)
  1952. return fallback_mt;
  1953. if (*can_steal)
  1954. return fallback_mt;
  1955. }
  1956. return -1;
  1957. }
  1958. /*
  1959. * Reserve a pageblock for exclusive use of high-order atomic allocations if
  1960. * there are no empty page blocks that contain a page with a suitable order
  1961. */
  1962. static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
  1963. unsigned int alloc_order)
  1964. {
  1965. int mt;
  1966. unsigned long max_managed, flags;
  1967. /*
  1968. * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
  1969. * Check is race-prone but harmless.
  1970. */
  1971. max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
  1972. if (zone->nr_reserved_highatomic >= max_managed)
  1973. return;
  1974. spin_lock_irqsave(&zone->lock, flags);
  1975. /* Recheck the nr_reserved_highatomic limit under the lock */
  1976. if (zone->nr_reserved_highatomic >= max_managed)
  1977. goto out_unlock;
  1978. /* Yoink! */
  1979. mt = get_pageblock_migratetype(page);
  1980. if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
  1981. && !is_migrate_cma(mt)) {
  1982. zone->nr_reserved_highatomic += pageblock_nr_pages;
  1983. set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
  1984. move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
  1985. }
  1986. out_unlock:
  1987. spin_unlock_irqrestore(&zone->lock, flags);
  1988. }
  1989. /*
  1990. * Used when an allocation is about to fail under memory pressure. This
  1991. * potentially hurts the reliability of high-order allocations when under
  1992. * intense memory pressure but failed atomic allocations should be easier
  1993. * to recover from than an OOM.
  1994. *
  1995. * If @force is true, try to unreserve a pageblock even though highatomic
  1996. * pageblock is exhausted.
  1997. */
  1998. static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
  1999. bool force)
  2000. {
  2001. struct zonelist *zonelist = ac->zonelist;
  2002. unsigned long flags;
  2003. struct zoneref *z;
  2004. struct zone *zone;
  2005. struct page *page;
  2006. int order;
  2007. bool ret;
  2008. for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
  2009. ac->nodemask) {
  2010. /*
  2011. * Preserve at least one pageblock unless memory pressure
  2012. * is really high.
  2013. */
  2014. if (!force && zone->nr_reserved_highatomic <=
  2015. pageblock_nr_pages)
  2016. continue;
  2017. spin_lock_irqsave(&zone->lock, flags);
  2018. for (order = 0; order < MAX_ORDER; order++) {
  2019. struct free_area *area = &(zone->free_area[order]);
  2020. page = list_first_entry_or_null(
  2021. &area->free_list[MIGRATE_HIGHATOMIC],
  2022. struct page, lru);
  2023. if (!page)
  2024. continue;
  2025. /*
  2026. * In page freeing path, migratetype change is racy so
  2027. * we can counter several free pages in a pageblock
  2028. * in this loop althoug we changed the pageblock type
  2029. * from highatomic to ac->migratetype. So we should
  2030. * adjust the count once.
  2031. */
  2032. if (is_migrate_highatomic_page(page)) {
  2033. /*
  2034. * It should never happen but changes to
  2035. * locking could inadvertently allow a per-cpu
  2036. * drain to add pages to MIGRATE_HIGHATOMIC
  2037. * while unreserving so be safe and watch for
  2038. * underflows.
  2039. */
  2040. zone->nr_reserved_highatomic -= min(
  2041. pageblock_nr_pages,
  2042. zone->nr_reserved_highatomic);
  2043. }
  2044. /*
  2045. * Convert to ac->migratetype and avoid the normal
  2046. * pageblock stealing heuristics. Minimally, the caller
  2047. * is doing the work and needs the pages. More
  2048. * importantly, if the block was always converted to
  2049. * MIGRATE_UNMOVABLE or another type then the number
  2050. * of pageblocks that cannot be completely freed
  2051. * may increase.
  2052. */
  2053. set_pageblock_migratetype(page, ac->migratetype);
  2054. ret = move_freepages_block(zone, page, ac->migratetype,
  2055. NULL);
  2056. if (ret) {
  2057. spin_unlock_irqrestore(&zone->lock, flags);
  2058. return ret;
  2059. }
  2060. }
  2061. spin_unlock_irqrestore(&zone->lock, flags);
  2062. }
  2063. return false;
  2064. }
  2065. /*
  2066. * Try finding a free buddy page on the fallback list and put it on the free
  2067. * list of requested migratetype, possibly along with other pages from the same
  2068. * block, depending on fragmentation avoidance heuristics. Returns true if
  2069. * fallback was found so that __rmqueue_smallest() can grab it.
  2070. *
  2071. * The use of signed ints for order and current_order is a deliberate
  2072. * deviation from the rest of this file, to make the for loop
  2073. * condition simpler.
  2074. */
  2075. static __always_inline bool
  2076. __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
  2077. {
  2078. struct free_area *area;
  2079. int current_order;
  2080. struct page *page;
  2081. int fallback_mt;
  2082. bool can_steal;
  2083. /*
  2084. * Find the largest available free page in the other list. This roughly
  2085. * approximates finding the pageblock with the most free pages, which
  2086. * would be too costly to do exactly.
  2087. */
  2088. for (current_order = MAX_ORDER - 1; current_order >= order;
  2089. --current_order) {
  2090. area = &(zone->free_area[current_order]);
  2091. fallback_mt = find_suitable_fallback(area, current_order,
  2092. start_migratetype, false, &can_steal);
  2093. if (fallback_mt == -1)
  2094. continue;
  2095. /*
  2096. * We cannot steal all free pages from the pageblock and the
  2097. * requested migratetype is movable. In that case it's better to
  2098. * steal and split the smallest available page instead of the
  2099. * largest available page, because even if the next movable
  2100. * allocation falls back into a different pageblock than this
  2101. * one, it won't cause permanent fragmentation.
  2102. */
  2103. if (!can_steal && start_migratetype == MIGRATE_MOVABLE
  2104. && current_order > order)
  2105. goto find_smallest;
  2106. goto do_steal;
  2107. }
  2108. return false;
  2109. find_smallest:
  2110. for (current_order = order; current_order < MAX_ORDER;
  2111. current_order++) {
  2112. area = &(zone->free_area[current_order]);
  2113. fallback_mt = find_suitable_fallback(area, current_order,
  2114. start_migratetype, false, &can_steal);
  2115. if (fallback_mt != -1)
  2116. break;
  2117. }
  2118. /*
  2119. * This should not happen - we already found a suitable fallback
  2120. * when looking for the largest page.
  2121. */
  2122. VM_BUG_ON(current_order == MAX_ORDER);
  2123. do_steal:
  2124. page = list_first_entry(&area->free_list[fallback_mt],
  2125. struct page, lru);
  2126. steal_suitable_fallback(zone, page, start_migratetype, can_steal);
  2127. trace_mm_page_alloc_extfrag(page, order, current_order,
  2128. start_migratetype, fallback_mt);
  2129. return true;
  2130. }
  2131. /*
  2132. * Do the hard work of removing an element from the buddy allocator.
  2133. * Call me with the zone->lock already held.
  2134. */
  2135. static __always_inline struct page *
  2136. __rmqueue(struct zone *zone, unsigned int order, int migratetype)
  2137. {
  2138. struct page *page;
  2139. retry:
  2140. page = __rmqueue_smallest(zone, order, migratetype);
  2141. if (unlikely(!page)) {
  2142. if (migratetype == MIGRATE_MOVABLE)
  2143. page = __rmqueue_cma_fallback(zone, order);
  2144. if (!page && __rmqueue_fallback(zone, order, migratetype))
  2145. goto retry;
  2146. }
  2147. trace_mm_page_alloc_zone_locked(page, order, migratetype);
  2148. return page;
  2149. }
  2150. /*
  2151. * Obtain a specified number of elements from the buddy allocator, all under
  2152. * a single hold of the lock, for efficiency. Add them to the supplied list.
  2153. * Returns the number of new pages which were placed at *list.
  2154. */
  2155. static int rmqueue_bulk(struct zone *zone, unsigned int order,
  2156. unsigned long count, struct list_head *list,
  2157. int migratetype)
  2158. {
  2159. int i, alloced = 0;
  2160. spin_lock(&zone->lock);
  2161. for (i = 0; i < count; ++i) {
  2162. struct page *page = __rmqueue(zone, order, migratetype);
  2163. if (unlikely(page == NULL))
  2164. break;
  2165. if (unlikely(check_pcp_refill(page)))
  2166. continue;
  2167. /*
  2168. * Split buddy pages returned by expand() are received here in
  2169. * physical page order. The page is added to the tail of
  2170. * caller's list. From the callers perspective, the linked list
  2171. * is ordered by page number under some conditions. This is
  2172. * useful for IO devices that can forward direction from the
  2173. * head, thus also in the physical page order. This is useful
  2174. * for IO devices that can merge IO requests if the physical
  2175. * pages are ordered properly.
  2176. */
  2177. list_add_tail(&page->lru, list);
  2178. alloced++;
  2179. if (is_migrate_cma(get_pcppage_migratetype(page)))
  2180. __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
  2181. -(1 << order));
  2182. }
  2183. /*
  2184. * i pages were removed from the buddy list even if some leak due
  2185. * to check_pcp_refill failing so adjust NR_FREE_PAGES based
  2186. * on i. Do not confuse with 'alloced' which is the number of
  2187. * pages added to the pcp list.
  2188. */
  2189. __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
  2190. spin_unlock(&zone->lock);
  2191. return alloced;
  2192. }
  2193. #ifdef CONFIG_NUMA
  2194. /*
  2195. * Called from the vmstat counter updater to drain pagesets of this
  2196. * currently executing processor on remote nodes after they have
  2197. * expired.
  2198. *
  2199. * Note that this function must be called with the thread pinned to
  2200. * a single processor.
  2201. */
  2202. void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
  2203. {
  2204. unsigned long flags;
  2205. int to_drain, batch;
  2206. local_irq_save(flags);
  2207. batch = READ_ONCE(pcp->batch);
  2208. to_drain = min(pcp->count, batch);
  2209. if (to_drain > 0)
  2210. free_pcppages_bulk(zone, to_drain, pcp);
  2211. local_irq_restore(flags);
  2212. }
  2213. #endif
  2214. /*
  2215. * Drain pcplists of the indicated processor and zone.
  2216. *
  2217. * The processor must either be the current processor and the
  2218. * thread pinned to the current processor or a processor that
  2219. * is not online.
  2220. */
  2221. static void drain_pages_zone(unsigned int cpu, struct zone *zone)
  2222. {
  2223. unsigned long flags;
  2224. struct per_cpu_pageset *pset;
  2225. struct per_cpu_pages *pcp;
  2226. local_irq_save(flags);
  2227. pset = per_cpu_ptr(zone->pageset, cpu);
  2228. pcp = &pset->pcp;
  2229. if (pcp->count)
  2230. free_pcppages_bulk(zone, pcp->count, pcp);
  2231. local_irq_restore(flags);
  2232. }
  2233. /*
  2234. * Drain pcplists of all zones on the indicated processor.
  2235. *
  2236. * The processor must either be the current processor and the
  2237. * thread pinned to the current processor or a processor that
  2238. * is not online.
  2239. */
  2240. static void drain_pages(unsigned int cpu)
  2241. {
  2242. struct zone *zone;
  2243. for_each_populated_zone(zone) {
  2244. drain_pages_zone(cpu, zone);
  2245. }
  2246. }
  2247. /*
  2248. * Spill all of this CPU's per-cpu pages back into the buddy allocator.
  2249. *
  2250. * The CPU has to be pinned. When zone parameter is non-NULL, spill just
  2251. * the single zone's pages.
  2252. */
  2253. void drain_local_pages(struct zone *zone)
  2254. {
  2255. int cpu = smp_processor_id();
  2256. if (zone)
  2257. drain_pages_zone(cpu, zone);
  2258. else
  2259. drain_pages(cpu);
  2260. }
  2261. static void drain_local_pages_wq(struct work_struct *work)
  2262. {
  2263. /*
  2264. * drain_all_pages doesn't use proper cpu hotplug protection so
  2265. * we can race with cpu offline when the WQ can move this from
  2266. * a cpu pinned worker to an unbound one. We can operate on a different
  2267. * cpu which is allright but we also have to make sure to not move to
  2268. * a different one.
  2269. */
  2270. preempt_disable();
  2271. drain_local_pages(NULL);
  2272. preempt_enable();
  2273. }
  2274. /*
  2275. * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
  2276. *
  2277. * When zone parameter is non-NULL, spill just the single zone's pages.
  2278. *
  2279. * Note that this can be extremely slow as the draining happens in a workqueue.
  2280. */
  2281. void drain_all_pages(struct zone *zone)
  2282. {
  2283. int cpu;
  2284. /*
  2285. * Allocate in the BSS so we wont require allocation in
  2286. * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
  2287. */
  2288. static cpumask_t cpus_with_pcps;
  2289. /*
  2290. * Make sure nobody triggers this path before mm_percpu_wq is fully
  2291. * initialized.
  2292. */
  2293. if (WARN_ON_ONCE(!mm_percpu_wq))
  2294. return;
  2295. /*
  2296. * Do not drain if one is already in progress unless it's specific to
  2297. * a zone. Such callers are primarily CMA and memory hotplug and need
  2298. * the drain to be complete when the call returns.
  2299. */
  2300. if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
  2301. if (!zone)
  2302. return;
  2303. mutex_lock(&pcpu_drain_mutex);
  2304. }
  2305. /*
  2306. * We don't care about racing with CPU hotplug event
  2307. * as offline notification will cause the notified
  2308. * cpu to drain that CPU pcps and on_each_cpu_mask
  2309. * disables preemption as part of its processing
  2310. */
  2311. for_each_online_cpu(cpu) {
  2312. struct per_cpu_pageset *pcp;
  2313. struct zone *z;
  2314. bool has_pcps = false;
  2315. if (zone) {
  2316. pcp = per_cpu_ptr(zone->pageset, cpu);
  2317. if (pcp->pcp.count)
  2318. has_pcps = true;
  2319. } else {
  2320. for_each_populated_zone(z) {
  2321. pcp = per_cpu_ptr(z->pageset, cpu);
  2322. if (pcp->pcp.count) {
  2323. has_pcps = true;
  2324. break;
  2325. }
  2326. }
  2327. }
  2328. if (has_pcps)
  2329. cpumask_set_cpu(cpu, &cpus_with_pcps);
  2330. else
  2331. cpumask_clear_cpu(cpu, &cpus_with_pcps);
  2332. }
  2333. for_each_cpu(cpu, &cpus_with_pcps) {
  2334. struct work_struct *work = per_cpu_ptr(&pcpu_drain, cpu);
  2335. INIT_WORK(work, drain_local_pages_wq);
  2336. queue_work_on(cpu, mm_percpu_wq, work);
  2337. }
  2338. for_each_cpu(cpu, &cpus_with_pcps)
  2339. flush_work(per_cpu_ptr(&pcpu_drain, cpu));
  2340. mutex_unlock(&pcpu_drain_mutex);
  2341. }
  2342. #ifdef CONFIG_HIBERNATION
  2343. /*
  2344. * Touch the watchdog for every WD_PAGE_COUNT pages.
  2345. */
  2346. #define WD_PAGE_COUNT (128*1024)
  2347. void mark_free_pages(struct zone *zone)
  2348. {
  2349. unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
  2350. unsigned long flags;
  2351. unsigned int order, t;
  2352. struct page *page;
  2353. if (zone_is_empty(zone))
  2354. return;
  2355. spin_lock_irqsave(&zone->lock, flags);
  2356. max_zone_pfn = zone_end_pfn(zone);
  2357. for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
  2358. if (pfn_valid(pfn)) {
  2359. page = pfn_to_page(pfn);
  2360. if (!--page_count) {
  2361. touch_nmi_watchdog();
  2362. page_count = WD_PAGE_COUNT;
  2363. }
  2364. if (page_zone(page) != zone)
  2365. continue;
  2366. if (!swsusp_page_is_forbidden(page))
  2367. swsusp_unset_page_free(page);
  2368. }
  2369. for_each_migratetype_order(order, t) {
  2370. list_for_each_entry(page,
  2371. &zone->free_area[order].free_list[t], lru) {
  2372. unsigned long i;
  2373. pfn = page_to_pfn(page);
  2374. for (i = 0; i < (1UL << order); i++) {
  2375. if (!--page_count) {
  2376. touch_nmi_watchdog();
  2377. page_count = WD_PAGE_COUNT;
  2378. }
  2379. swsusp_set_page_free(pfn_to_page(pfn + i));
  2380. }
  2381. }
  2382. }
  2383. spin_unlock_irqrestore(&zone->lock, flags);
  2384. }
  2385. #endif /* CONFIG_PM */
  2386. static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
  2387. {
  2388. int migratetype;
  2389. if (!free_pcp_prepare(page))
  2390. return false;
  2391. migratetype = get_pfnblock_migratetype(page, pfn);
  2392. set_pcppage_migratetype(page, migratetype);
  2393. return true;
  2394. }
  2395. static void free_unref_page_commit(struct page *page, unsigned long pfn)
  2396. {
  2397. struct zone *zone = page_zone(page);
  2398. struct per_cpu_pages *pcp;
  2399. int migratetype;
  2400. migratetype = get_pcppage_migratetype(page);
  2401. __count_vm_event(PGFREE);
  2402. /*
  2403. * We only track unmovable, reclaimable and movable on pcp lists.
  2404. * Free ISOLATE pages back to the allocator because they are being
  2405. * offlined but treat HIGHATOMIC as movable pages so we can get those
  2406. * areas back if necessary. Otherwise, we may have to free
  2407. * excessively into the page allocator
  2408. */
  2409. if (migratetype >= MIGRATE_PCPTYPES) {
  2410. if (unlikely(is_migrate_isolate(migratetype))) {
  2411. free_one_page(zone, page, pfn, 0, migratetype);
  2412. return;
  2413. }
  2414. migratetype = MIGRATE_MOVABLE;
  2415. }
  2416. pcp = &this_cpu_ptr(zone->pageset)->pcp;
  2417. list_add(&page->lru, &pcp->lists[migratetype]);
  2418. pcp->count++;
  2419. if (pcp->count >= pcp->high) {
  2420. unsigned long batch = READ_ONCE(pcp->batch);
  2421. free_pcppages_bulk(zone, batch, pcp);
  2422. }
  2423. }
  2424. /*
  2425. * Free a 0-order page
  2426. */
  2427. void free_unref_page(struct page *page)
  2428. {
  2429. unsigned long flags;
  2430. unsigned long pfn = page_to_pfn(page);
  2431. if (!free_unref_page_prepare(page, pfn))
  2432. return;
  2433. local_irq_save(flags);
  2434. free_unref_page_commit(page, pfn);
  2435. local_irq_restore(flags);
  2436. }
  2437. /*
  2438. * Free a list of 0-order pages
  2439. */
  2440. void free_unref_page_list(struct list_head *list)
  2441. {
  2442. struct page *page, *next;
  2443. unsigned long flags, pfn;
  2444. int batch_count = 0;
  2445. /* Prepare pages for freeing */
  2446. list_for_each_entry_safe(page, next, list, lru) {
  2447. pfn = page_to_pfn(page);
  2448. if (!free_unref_page_prepare(page, pfn))
  2449. list_del(&page->lru);
  2450. set_page_private(page, pfn);
  2451. }
  2452. local_irq_save(flags);
  2453. list_for_each_entry_safe(page, next, list, lru) {
  2454. unsigned long pfn = page_private(page);
  2455. set_page_private(page, 0);
  2456. trace_mm_page_free_batched(page);
  2457. free_unref_page_commit(page, pfn);
  2458. /*
  2459. * Guard against excessive IRQ disabled times when we get
  2460. * a large list of pages to free.
  2461. */
  2462. if (++batch_count == SWAP_CLUSTER_MAX) {
  2463. local_irq_restore(flags);
  2464. batch_count = 0;
  2465. local_irq_save(flags);
  2466. }
  2467. }
  2468. local_irq_restore(flags);
  2469. }
  2470. /*
  2471. * split_page takes a non-compound higher-order page, and splits it into
  2472. * n (1<<order) sub-pages: page[0..n]
  2473. * Each sub-page must be freed individually.
  2474. *
  2475. * Note: this is probably too low level an operation for use in drivers.
  2476. * Please consult with lkml before using this in your driver.
  2477. */
  2478. void split_page(struct page *page, unsigned int order)
  2479. {
  2480. int i;
  2481. VM_BUG_ON_PAGE(PageCompound(page), page);
  2482. VM_BUG_ON_PAGE(!page_count(page), page);
  2483. for (i = 1; i < (1 << order); i++)
  2484. set_page_refcounted(page + i);
  2485. split_page_owner(page, order);
  2486. }
  2487. EXPORT_SYMBOL_GPL(split_page);
  2488. int __isolate_free_page(struct page *page, unsigned int order)
  2489. {
  2490. unsigned long watermark;
  2491. struct zone *zone;
  2492. int mt;
  2493. BUG_ON(!PageBuddy(page));
  2494. zone = page_zone(page);
  2495. mt = get_pageblock_migratetype(page);
  2496. if (!is_migrate_isolate(mt)) {
  2497. /*
  2498. * Obey watermarks as if the page was being allocated. We can
  2499. * emulate a high-order watermark check with a raised order-0
  2500. * watermark, because we already know our high-order page
  2501. * exists.
  2502. */
  2503. watermark = min_wmark_pages(zone) + (1UL << order);
  2504. if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
  2505. return 0;
  2506. __mod_zone_freepage_state(zone, -(1UL << order), mt);
  2507. }
  2508. /* Remove page from free list */
  2509. list_del(&page->lru);
  2510. zone->free_area[order].nr_free--;
  2511. rmv_page_order(page);
  2512. /*
  2513. * Set the pageblock if the isolated page is at least half of a
  2514. * pageblock
  2515. */
  2516. if (order >= pageblock_order - 1) {
  2517. struct page *endpage = page + (1 << order) - 1;
  2518. for (; page < endpage; page += pageblock_nr_pages) {
  2519. int mt = get_pageblock_migratetype(page);
  2520. if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
  2521. && !is_migrate_highatomic(mt))
  2522. set_pageblock_migratetype(page,
  2523. MIGRATE_MOVABLE);
  2524. }
  2525. }
  2526. return 1UL << order;
  2527. }
  2528. /*
  2529. * Update NUMA hit/miss statistics
  2530. *
  2531. * Must be called with interrupts disabled.
  2532. */
  2533. static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
  2534. {
  2535. #ifdef CONFIG_NUMA
  2536. enum numa_stat_item local_stat = NUMA_LOCAL;
  2537. /* skip numa counters update if numa stats is disabled */
  2538. if (!static_branch_likely(&vm_numa_stat_key))
  2539. return;
  2540. if (zone_to_nid(z) != numa_node_id())
  2541. local_stat = NUMA_OTHER;
  2542. if (zone_to_nid(z) == zone_to_nid(preferred_zone))
  2543. __inc_numa_state(z, NUMA_HIT);
  2544. else {
  2545. __inc_numa_state(z, NUMA_MISS);
  2546. __inc_numa_state(preferred_zone, NUMA_FOREIGN);
  2547. }
  2548. __inc_numa_state(z, local_stat);
  2549. #endif
  2550. }
  2551. /* Remove page from the per-cpu list, caller must protect the list */
  2552. static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
  2553. struct per_cpu_pages *pcp,
  2554. struct list_head *list)
  2555. {
  2556. struct page *page;
  2557. do {
  2558. if (list_empty(list)) {
  2559. pcp->count += rmqueue_bulk(zone, 0,
  2560. pcp->batch, list,
  2561. migratetype);
  2562. if (unlikely(list_empty(list)))
  2563. return NULL;
  2564. }
  2565. page = list_first_entry(list, struct page, lru);
  2566. list_del(&page->lru);
  2567. pcp->count--;
  2568. } while (check_new_pcp(page));
  2569. return page;
  2570. }
  2571. /* Lock and remove page from the per-cpu list */
  2572. static struct page *rmqueue_pcplist(struct zone *preferred_zone,
  2573. struct zone *zone, unsigned int order,
  2574. gfp_t gfp_flags, int migratetype)
  2575. {
  2576. struct per_cpu_pages *pcp;
  2577. struct list_head *list;
  2578. struct page *page;
  2579. unsigned long flags;
  2580. local_irq_save(flags);
  2581. pcp = &this_cpu_ptr(zone->pageset)->pcp;
  2582. list = &pcp->lists[migratetype];
  2583. page = __rmqueue_pcplist(zone, migratetype, pcp, list);
  2584. if (page) {
  2585. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2586. zone_statistics(preferred_zone, zone);
  2587. }
  2588. local_irq_restore(flags);
  2589. return page;
  2590. }
  2591. /*
  2592. * Allocate a page from the given zone. Use pcplists for order-0 allocations.
  2593. */
  2594. static inline
  2595. struct page *rmqueue(struct zone *preferred_zone,
  2596. struct zone *zone, unsigned int order,
  2597. gfp_t gfp_flags, unsigned int alloc_flags,
  2598. int migratetype)
  2599. {
  2600. unsigned long flags;
  2601. struct page *page;
  2602. if (likely(order == 0)) {
  2603. page = rmqueue_pcplist(preferred_zone, zone, order,
  2604. gfp_flags, migratetype);
  2605. goto out;
  2606. }
  2607. /*
  2608. * We most definitely don't want callers attempting to
  2609. * allocate greater than order-1 page units with __GFP_NOFAIL.
  2610. */
  2611. WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
  2612. spin_lock_irqsave(&zone->lock, flags);
  2613. do {
  2614. page = NULL;
  2615. if (alloc_flags & ALLOC_HARDER) {
  2616. page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
  2617. if (page)
  2618. trace_mm_page_alloc_zone_locked(page, order, migratetype);
  2619. }
  2620. if (!page)
  2621. page = __rmqueue(zone, order, migratetype);
  2622. } while (page && check_new_pages(page, order));
  2623. spin_unlock(&zone->lock);
  2624. if (!page)
  2625. goto failed;
  2626. __mod_zone_freepage_state(zone, -(1 << order),
  2627. get_pcppage_migratetype(page));
  2628. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2629. zone_statistics(preferred_zone, zone);
  2630. local_irq_restore(flags);
  2631. out:
  2632. VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
  2633. return page;
  2634. failed:
  2635. local_irq_restore(flags);
  2636. return NULL;
  2637. }
  2638. #ifdef CONFIG_FAIL_PAGE_ALLOC
  2639. static struct {
  2640. struct fault_attr attr;
  2641. bool ignore_gfp_highmem;
  2642. bool ignore_gfp_reclaim;
  2643. u32 min_order;
  2644. } fail_page_alloc = {
  2645. .attr = FAULT_ATTR_INITIALIZER,
  2646. .ignore_gfp_reclaim = true,
  2647. .ignore_gfp_highmem = true,
  2648. .min_order = 1,
  2649. };
  2650. static int __init setup_fail_page_alloc(char *str)
  2651. {
  2652. return setup_fault_attr(&fail_page_alloc.attr, str);
  2653. }
  2654. __setup("fail_page_alloc=", setup_fail_page_alloc);
  2655. static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
  2656. {
  2657. if (order < fail_page_alloc.min_order)
  2658. return false;
  2659. if (gfp_mask & __GFP_NOFAIL)
  2660. return false;
  2661. if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
  2662. return false;
  2663. if (fail_page_alloc.ignore_gfp_reclaim &&
  2664. (gfp_mask & __GFP_DIRECT_RECLAIM))
  2665. return false;
  2666. return should_fail(&fail_page_alloc.attr, 1 << order);
  2667. }
  2668. #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
  2669. static int __init fail_page_alloc_debugfs(void)
  2670. {
  2671. umode_t mode = S_IFREG | 0600;
  2672. struct dentry *dir;
  2673. dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
  2674. &fail_page_alloc.attr);
  2675. if (IS_ERR(dir))
  2676. return PTR_ERR(dir);
  2677. if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
  2678. &fail_page_alloc.ignore_gfp_reclaim))
  2679. goto fail;
  2680. if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
  2681. &fail_page_alloc.ignore_gfp_highmem))
  2682. goto fail;
  2683. if (!debugfs_create_u32("min-order", mode, dir,
  2684. &fail_page_alloc.min_order))
  2685. goto fail;
  2686. return 0;
  2687. fail:
  2688. debugfs_remove_recursive(dir);
  2689. return -ENOMEM;
  2690. }
  2691. late_initcall(fail_page_alloc_debugfs);
  2692. #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
  2693. #else /* CONFIG_FAIL_PAGE_ALLOC */
  2694. static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
  2695. {
  2696. return false;
  2697. }
  2698. #endif /* CONFIG_FAIL_PAGE_ALLOC */
  2699. /*
  2700. * Return true if free base pages are above 'mark'. For high-order checks it
  2701. * will return true of the order-0 watermark is reached and there is at least
  2702. * one free page of a suitable size. Checking now avoids taking the zone lock
  2703. * to check in the allocation paths if no pages are free.
  2704. */
  2705. bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2706. int classzone_idx, unsigned int alloc_flags,
  2707. long free_pages)
  2708. {
  2709. long min = mark;
  2710. int o;
  2711. const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
  2712. /* free_pages may go negative - that's OK */
  2713. free_pages -= (1 << order) - 1;
  2714. if (alloc_flags & ALLOC_HIGH)
  2715. min -= min / 2;
  2716. /*
  2717. * If the caller does not have rights to ALLOC_HARDER then subtract
  2718. * the high-atomic reserves. This will over-estimate the size of the
  2719. * atomic reserve but it avoids a search.
  2720. */
  2721. if (likely(!alloc_harder)) {
  2722. free_pages -= z->nr_reserved_highatomic;
  2723. } else {
  2724. /*
  2725. * OOM victims can try even harder than normal ALLOC_HARDER
  2726. * users on the grounds that it's definitely going to be in
  2727. * the exit path shortly and free memory. Any allocation it
  2728. * makes during the free path will be small and short-lived.
  2729. */
  2730. if (alloc_flags & ALLOC_OOM)
  2731. min -= min / 2;
  2732. else
  2733. min -= min / 4;
  2734. }
  2735. #ifdef CONFIG_CMA
  2736. /* If allocation can't use CMA areas don't use free CMA pages */
  2737. if (!(alloc_flags & ALLOC_CMA))
  2738. free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
  2739. #endif
  2740. /*
  2741. * Check watermarks for an order-0 allocation request. If these
  2742. * are not met, then a high-order request also cannot go ahead
  2743. * even if a suitable page happened to be free.
  2744. */
  2745. if (free_pages <= min + z->lowmem_reserve[classzone_idx])
  2746. return false;
  2747. /* If this is an order-0 request then the watermark is fine */
  2748. if (!order)
  2749. return true;
  2750. /* For a high-order request, check at least one suitable page is free */
  2751. for (o = order; o < MAX_ORDER; o++) {
  2752. struct free_area *area = &z->free_area[o];
  2753. int mt;
  2754. if (!area->nr_free)
  2755. continue;
  2756. for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
  2757. if (!list_empty(&area->free_list[mt]))
  2758. return true;
  2759. }
  2760. #ifdef CONFIG_CMA
  2761. if ((alloc_flags & ALLOC_CMA) &&
  2762. !list_empty(&area->free_list[MIGRATE_CMA])) {
  2763. return true;
  2764. }
  2765. #endif
  2766. if (alloc_harder &&
  2767. !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
  2768. return true;
  2769. }
  2770. return false;
  2771. }
  2772. bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2773. int classzone_idx, unsigned int alloc_flags)
  2774. {
  2775. return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
  2776. zone_page_state(z, NR_FREE_PAGES));
  2777. }
  2778. static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
  2779. unsigned long mark, int classzone_idx, unsigned int alloc_flags)
  2780. {
  2781. long free_pages = zone_page_state(z, NR_FREE_PAGES);
  2782. long cma_pages = 0;
  2783. #ifdef CONFIG_CMA
  2784. /* If allocation can't use CMA areas don't use free CMA pages */
  2785. if (!(alloc_flags & ALLOC_CMA))
  2786. cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
  2787. #endif
  2788. /*
  2789. * Fast check for order-0 only. If this fails then the reserves
  2790. * need to be calculated. There is a corner case where the check
  2791. * passes but only the high-order atomic reserve are free. If
  2792. * the caller is !atomic then it'll uselessly search the free
  2793. * list. That corner case is then slower but it is harmless.
  2794. */
  2795. if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
  2796. return true;
  2797. return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
  2798. free_pages);
  2799. }
  2800. bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
  2801. unsigned long mark, int classzone_idx)
  2802. {
  2803. long free_pages = zone_page_state(z, NR_FREE_PAGES);
  2804. if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
  2805. free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
  2806. return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
  2807. free_pages);
  2808. }
  2809. #ifdef CONFIG_NUMA
  2810. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2811. {
  2812. return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
  2813. RECLAIM_DISTANCE;
  2814. }
  2815. #else /* CONFIG_NUMA */
  2816. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2817. {
  2818. return true;
  2819. }
  2820. #endif /* CONFIG_NUMA */
  2821. /*
  2822. * get_page_from_freelist goes through the zonelist trying to allocate
  2823. * a page.
  2824. */
  2825. static struct page *
  2826. get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
  2827. const struct alloc_context *ac)
  2828. {
  2829. struct zoneref *z = ac->preferred_zoneref;
  2830. struct zone *zone;
  2831. struct pglist_data *last_pgdat_dirty_limit = NULL;
  2832. /*
  2833. * Scan zonelist, looking for a zone with enough free.
  2834. * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
  2835. */
  2836. for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
  2837. ac->nodemask) {
  2838. struct page *page;
  2839. unsigned long mark;
  2840. if (cpusets_enabled() &&
  2841. (alloc_flags & ALLOC_CPUSET) &&
  2842. !__cpuset_zone_allowed(zone, gfp_mask))
  2843. continue;
  2844. /*
  2845. * When allocating a page cache page for writing, we
  2846. * want to get it from a node that is within its dirty
  2847. * limit, such that no single node holds more than its
  2848. * proportional share of globally allowed dirty pages.
  2849. * The dirty limits take into account the node's
  2850. * lowmem reserves and high watermark so that kswapd
  2851. * should be able to balance it without having to
  2852. * write pages from its LRU list.
  2853. *
  2854. * XXX: For now, allow allocations to potentially
  2855. * exceed the per-node dirty limit in the slowpath
  2856. * (spread_dirty_pages unset) before going into reclaim,
  2857. * which is important when on a NUMA setup the allowed
  2858. * nodes are together not big enough to reach the
  2859. * global limit. The proper fix for these situations
  2860. * will require awareness of nodes in the
  2861. * dirty-throttling and the flusher threads.
  2862. */
  2863. if (ac->spread_dirty_pages) {
  2864. if (last_pgdat_dirty_limit == zone->zone_pgdat)
  2865. continue;
  2866. if (!node_dirty_ok(zone->zone_pgdat)) {
  2867. last_pgdat_dirty_limit = zone->zone_pgdat;
  2868. continue;
  2869. }
  2870. }
  2871. mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
  2872. if (!zone_watermark_fast(zone, order, mark,
  2873. ac_classzone_idx(ac), alloc_flags)) {
  2874. int ret;
  2875. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  2876. /*
  2877. * Watermark failed for this zone, but see if we can
  2878. * grow this zone if it contains deferred pages.
  2879. */
  2880. if (static_branch_unlikely(&deferred_pages)) {
  2881. if (_deferred_grow_zone(zone, order))
  2882. goto try_this_zone;
  2883. }
  2884. #endif
  2885. /* Checked here to keep the fast path fast */
  2886. BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
  2887. if (alloc_flags & ALLOC_NO_WATERMARKS)
  2888. goto try_this_zone;
  2889. if (node_reclaim_mode == 0 ||
  2890. !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
  2891. continue;
  2892. ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
  2893. switch (ret) {
  2894. case NODE_RECLAIM_NOSCAN:
  2895. /* did not scan */
  2896. continue;
  2897. case NODE_RECLAIM_FULL:
  2898. /* scanned but unreclaimable */
  2899. continue;
  2900. default:
  2901. /* did we reclaim enough */
  2902. if (zone_watermark_ok(zone, order, mark,
  2903. ac_classzone_idx(ac), alloc_flags))
  2904. goto try_this_zone;
  2905. continue;
  2906. }
  2907. }
  2908. try_this_zone:
  2909. page = rmqueue(ac->preferred_zoneref->zone, zone, order,
  2910. gfp_mask, alloc_flags, ac->migratetype);
  2911. if (page) {
  2912. prep_new_page(page, order, gfp_mask, alloc_flags);
  2913. /*
  2914. * If this is a high-order atomic allocation then check
  2915. * if the pageblock should be reserved for the future
  2916. */
  2917. if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
  2918. reserve_highatomic_pageblock(page, zone, order);
  2919. return page;
  2920. } else {
  2921. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  2922. /* Try again if zone has deferred pages */
  2923. if (static_branch_unlikely(&deferred_pages)) {
  2924. if (_deferred_grow_zone(zone, order))
  2925. goto try_this_zone;
  2926. }
  2927. #endif
  2928. }
  2929. }
  2930. return NULL;
  2931. }
  2932. /*
  2933. * Large machines with many possible nodes should not always dump per-node
  2934. * meminfo in irq context.
  2935. */
  2936. static inline bool should_suppress_show_mem(void)
  2937. {
  2938. bool ret = false;
  2939. #if NODES_SHIFT > 8
  2940. ret = in_interrupt();
  2941. #endif
  2942. return ret;
  2943. }
  2944. static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
  2945. {
  2946. unsigned int filter = SHOW_MEM_FILTER_NODES;
  2947. static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
  2948. if (should_suppress_show_mem() || !__ratelimit(&show_mem_rs))
  2949. return;
  2950. /*
  2951. * This documents exceptions given to allocations in certain
  2952. * contexts that are allowed to allocate outside current's set
  2953. * of allowed nodes.
  2954. */
  2955. if (!(gfp_mask & __GFP_NOMEMALLOC))
  2956. if (tsk_is_oom_victim(current) ||
  2957. (current->flags & (PF_MEMALLOC | PF_EXITING)))
  2958. filter &= ~SHOW_MEM_FILTER_NODES;
  2959. if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
  2960. filter &= ~SHOW_MEM_FILTER_NODES;
  2961. show_mem(filter, nodemask);
  2962. }
  2963. void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
  2964. {
  2965. struct va_format vaf;
  2966. va_list args;
  2967. static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
  2968. DEFAULT_RATELIMIT_BURST);
  2969. if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
  2970. return;
  2971. va_start(args, fmt);
  2972. vaf.fmt = fmt;
  2973. vaf.va = &args;
  2974. pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl\n",
  2975. current->comm, &vaf, gfp_mask, &gfp_mask,
  2976. nodemask_pr_args(nodemask));
  2977. va_end(args);
  2978. cpuset_print_current_mems_allowed();
  2979. dump_stack();
  2980. warn_alloc_show_mem(gfp_mask, nodemask);
  2981. }
  2982. static inline struct page *
  2983. __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
  2984. unsigned int alloc_flags,
  2985. const struct alloc_context *ac)
  2986. {
  2987. struct page *page;
  2988. page = get_page_from_freelist(gfp_mask, order,
  2989. alloc_flags|ALLOC_CPUSET, ac);
  2990. /*
  2991. * fallback to ignore cpuset restriction if our nodes
  2992. * are depleted
  2993. */
  2994. if (!page)
  2995. page = get_page_from_freelist(gfp_mask, order,
  2996. alloc_flags, ac);
  2997. return page;
  2998. }
  2999. static inline struct page *
  3000. __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
  3001. const struct alloc_context *ac, unsigned long *did_some_progress)
  3002. {
  3003. struct oom_control oc = {
  3004. .zonelist = ac->zonelist,
  3005. .nodemask = ac->nodemask,
  3006. .memcg = NULL,
  3007. .gfp_mask = gfp_mask,
  3008. .order = order,
  3009. };
  3010. struct page *page;
  3011. *did_some_progress = 0;
  3012. /*
  3013. * Acquire the oom lock. If that fails, somebody else is
  3014. * making progress for us.
  3015. */
  3016. if (!mutex_trylock(&oom_lock)) {
  3017. *did_some_progress = 1;
  3018. schedule_timeout_uninterruptible(1);
  3019. return NULL;
  3020. }
  3021. /*
  3022. * Go through the zonelist yet one more time, keep very high watermark
  3023. * here, this is only to catch a parallel oom killing, we must fail if
  3024. * we're still under heavy pressure. But make sure that this reclaim
  3025. * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
  3026. * allocation which will never fail due to oom_lock already held.
  3027. */
  3028. page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
  3029. ~__GFP_DIRECT_RECLAIM, order,
  3030. ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
  3031. if (page)
  3032. goto out;
  3033. /* Coredumps can quickly deplete all memory reserves */
  3034. if (current->flags & PF_DUMPCORE)
  3035. goto out;
  3036. /* The OOM killer will not help higher order allocs */
  3037. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3038. goto out;
  3039. /*
  3040. * We have already exhausted all our reclaim opportunities without any
  3041. * success so it is time to admit defeat. We will skip the OOM killer
  3042. * because it is very likely that the caller has a more reasonable
  3043. * fallback than shooting a random task.
  3044. */
  3045. if (gfp_mask & __GFP_RETRY_MAYFAIL)
  3046. goto out;
  3047. /* The OOM killer does not needlessly kill tasks for lowmem */
  3048. if (ac->high_zoneidx < ZONE_NORMAL)
  3049. goto out;
  3050. if (pm_suspended_storage())
  3051. goto out;
  3052. /*
  3053. * XXX: GFP_NOFS allocations should rather fail than rely on
  3054. * other request to make a forward progress.
  3055. * We are in an unfortunate situation where out_of_memory cannot
  3056. * do much for this context but let's try it to at least get
  3057. * access to memory reserved if the current task is killed (see
  3058. * out_of_memory). Once filesystems are ready to handle allocation
  3059. * failures more gracefully we should just bail out here.
  3060. */
  3061. /* The OOM killer may not free memory on a specific node */
  3062. if (gfp_mask & __GFP_THISNODE)
  3063. goto out;
  3064. /* Exhausted what can be done so it's blame time */
  3065. if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
  3066. *did_some_progress = 1;
  3067. /*
  3068. * Help non-failing allocations by giving them access to memory
  3069. * reserves
  3070. */
  3071. if (gfp_mask & __GFP_NOFAIL)
  3072. page = __alloc_pages_cpuset_fallback(gfp_mask, order,
  3073. ALLOC_NO_WATERMARKS, ac);
  3074. }
  3075. out:
  3076. mutex_unlock(&oom_lock);
  3077. return page;
  3078. }
  3079. /*
  3080. * Maximum number of compaction retries wit a progress before OOM
  3081. * killer is consider as the only way to move forward.
  3082. */
  3083. #define MAX_COMPACT_RETRIES 16
  3084. #ifdef CONFIG_COMPACTION
  3085. /* Try memory compaction for high-order allocations before reclaim */
  3086. static struct page *
  3087. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3088. unsigned int alloc_flags, const struct alloc_context *ac,
  3089. enum compact_priority prio, enum compact_result *compact_result)
  3090. {
  3091. struct page *page;
  3092. unsigned int noreclaim_flag;
  3093. if (!order)
  3094. return NULL;
  3095. noreclaim_flag = memalloc_noreclaim_save();
  3096. *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
  3097. prio);
  3098. memalloc_noreclaim_restore(noreclaim_flag);
  3099. if (*compact_result <= COMPACT_INACTIVE)
  3100. return NULL;
  3101. /*
  3102. * At least in one zone compaction wasn't deferred or skipped, so let's
  3103. * count a compaction stall
  3104. */
  3105. count_vm_event(COMPACTSTALL);
  3106. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3107. if (page) {
  3108. struct zone *zone = page_zone(page);
  3109. zone->compact_blockskip_flush = false;
  3110. compaction_defer_reset(zone, order, true);
  3111. count_vm_event(COMPACTSUCCESS);
  3112. return page;
  3113. }
  3114. /*
  3115. * It's bad if compaction run occurs and fails. The most likely reason
  3116. * is that pages exist, but not enough to satisfy watermarks.
  3117. */
  3118. count_vm_event(COMPACTFAIL);
  3119. cond_resched();
  3120. return NULL;
  3121. }
  3122. static inline bool
  3123. should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
  3124. enum compact_result compact_result,
  3125. enum compact_priority *compact_priority,
  3126. int *compaction_retries)
  3127. {
  3128. int max_retries = MAX_COMPACT_RETRIES;
  3129. int min_priority;
  3130. bool ret = false;
  3131. int retries = *compaction_retries;
  3132. enum compact_priority priority = *compact_priority;
  3133. if (!order)
  3134. return false;
  3135. if (compaction_made_progress(compact_result))
  3136. (*compaction_retries)++;
  3137. /*
  3138. * compaction considers all the zone as desperately out of memory
  3139. * so it doesn't really make much sense to retry except when the
  3140. * failure could be caused by insufficient priority
  3141. */
  3142. if (compaction_failed(compact_result))
  3143. goto check_priority;
  3144. /*
  3145. * make sure the compaction wasn't deferred or didn't bail out early
  3146. * due to locks contention before we declare that we should give up.
  3147. * But do not retry if the given zonelist is not suitable for
  3148. * compaction.
  3149. */
  3150. if (compaction_withdrawn(compact_result)) {
  3151. ret = compaction_zonelist_suitable(ac, order, alloc_flags);
  3152. goto out;
  3153. }
  3154. /*
  3155. * !costly requests are much more important than __GFP_RETRY_MAYFAIL
  3156. * costly ones because they are de facto nofail and invoke OOM
  3157. * killer to move on while costly can fail and users are ready
  3158. * to cope with that. 1/4 retries is rather arbitrary but we
  3159. * would need much more detailed feedback from compaction to
  3160. * make a better decision.
  3161. */
  3162. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3163. max_retries /= 4;
  3164. if (*compaction_retries <= max_retries) {
  3165. ret = true;
  3166. goto out;
  3167. }
  3168. /*
  3169. * Make sure there are attempts at the highest priority if we exhausted
  3170. * all retries or failed at the lower priorities.
  3171. */
  3172. check_priority:
  3173. min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
  3174. MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
  3175. if (*compact_priority > min_priority) {
  3176. (*compact_priority)--;
  3177. *compaction_retries = 0;
  3178. ret = true;
  3179. }
  3180. out:
  3181. trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
  3182. return ret;
  3183. }
  3184. #else
  3185. static inline struct page *
  3186. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3187. unsigned int alloc_flags, const struct alloc_context *ac,
  3188. enum compact_priority prio, enum compact_result *compact_result)
  3189. {
  3190. *compact_result = COMPACT_SKIPPED;
  3191. return NULL;
  3192. }
  3193. static inline bool
  3194. should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
  3195. enum compact_result compact_result,
  3196. enum compact_priority *compact_priority,
  3197. int *compaction_retries)
  3198. {
  3199. struct zone *zone;
  3200. struct zoneref *z;
  3201. if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
  3202. return false;
  3203. /*
  3204. * There are setups with compaction disabled which would prefer to loop
  3205. * inside the allocator rather than hit the oom killer prematurely.
  3206. * Let's give them a good hope and keep retrying while the order-0
  3207. * watermarks are OK.
  3208. */
  3209. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
  3210. ac->nodemask) {
  3211. if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
  3212. ac_classzone_idx(ac), alloc_flags))
  3213. return true;
  3214. }
  3215. return false;
  3216. }
  3217. #endif /* CONFIG_COMPACTION */
  3218. #ifdef CONFIG_LOCKDEP
  3219. static struct lockdep_map __fs_reclaim_map =
  3220. STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
  3221. static bool __need_fs_reclaim(gfp_t gfp_mask)
  3222. {
  3223. gfp_mask = current_gfp_context(gfp_mask);
  3224. /* no reclaim without waiting on it */
  3225. if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
  3226. return false;
  3227. /* this guy won't enter reclaim */
  3228. if (current->flags & PF_MEMALLOC)
  3229. return false;
  3230. /* We're only interested __GFP_FS allocations for now */
  3231. if (!(gfp_mask & __GFP_FS))
  3232. return false;
  3233. if (gfp_mask & __GFP_NOLOCKDEP)
  3234. return false;
  3235. return true;
  3236. }
  3237. void __fs_reclaim_acquire(void)
  3238. {
  3239. lock_map_acquire(&__fs_reclaim_map);
  3240. }
  3241. void __fs_reclaim_release(void)
  3242. {
  3243. lock_map_release(&__fs_reclaim_map);
  3244. }
  3245. void fs_reclaim_acquire(gfp_t gfp_mask)
  3246. {
  3247. if (__need_fs_reclaim(gfp_mask))
  3248. __fs_reclaim_acquire();
  3249. }
  3250. EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
  3251. void fs_reclaim_release(gfp_t gfp_mask)
  3252. {
  3253. if (__need_fs_reclaim(gfp_mask))
  3254. __fs_reclaim_release();
  3255. }
  3256. EXPORT_SYMBOL_GPL(fs_reclaim_release);
  3257. #endif
  3258. /* Perform direct synchronous page reclaim */
  3259. static int
  3260. __perform_reclaim(gfp_t gfp_mask, unsigned int order,
  3261. const struct alloc_context *ac)
  3262. {
  3263. struct reclaim_state reclaim_state;
  3264. int progress;
  3265. unsigned int noreclaim_flag;
  3266. cond_resched();
  3267. /* We now go into synchronous reclaim */
  3268. cpuset_memory_pressure_bump();
  3269. fs_reclaim_acquire(gfp_mask);
  3270. noreclaim_flag = memalloc_noreclaim_save();
  3271. reclaim_state.reclaimed_slab = 0;
  3272. current->reclaim_state = &reclaim_state;
  3273. progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
  3274. ac->nodemask);
  3275. current->reclaim_state = NULL;
  3276. memalloc_noreclaim_restore(noreclaim_flag);
  3277. fs_reclaim_release(gfp_mask);
  3278. cond_resched();
  3279. return progress;
  3280. }
  3281. /* The really slow allocator path where we enter direct reclaim */
  3282. static inline struct page *
  3283. __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
  3284. unsigned int alloc_flags, const struct alloc_context *ac,
  3285. unsigned long *did_some_progress)
  3286. {
  3287. struct page *page = NULL;
  3288. bool drained = false;
  3289. *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
  3290. if (unlikely(!(*did_some_progress)))
  3291. return NULL;
  3292. retry:
  3293. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3294. /*
  3295. * If an allocation failed after direct reclaim, it could be because
  3296. * pages are pinned on the per-cpu lists or in high alloc reserves.
  3297. * Shrink them them and try again
  3298. */
  3299. if (!page && !drained) {
  3300. unreserve_highatomic_pageblock(ac, false);
  3301. drain_all_pages(NULL);
  3302. drained = true;
  3303. goto retry;
  3304. }
  3305. return page;
  3306. }
  3307. static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
  3308. const struct alloc_context *ac)
  3309. {
  3310. struct zoneref *z;
  3311. struct zone *zone;
  3312. pg_data_t *last_pgdat = NULL;
  3313. enum zone_type high_zoneidx = ac->high_zoneidx;
  3314. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, high_zoneidx,
  3315. ac->nodemask) {
  3316. if (last_pgdat != zone->zone_pgdat)
  3317. wakeup_kswapd(zone, gfp_mask, order, high_zoneidx);
  3318. last_pgdat = zone->zone_pgdat;
  3319. }
  3320. }
  3321. static inline unsigned int
  3322. gfp_to_alloc_flags(gfp_t gfp_mask)
  3323. {
  3324. unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
  3325. /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
  3326. BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
  3327. /*
  3328. * The caller may dip into page reserves a bit more if the caller
  3329. * cannot run direct reclaim, or if the caller has realtime scheduling
  3330. * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
  3331. * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
  3332. */
  3333. alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
  3334. if (gfp_mask & __GFP_ATOMIC) {
  3335. /*
  3336. * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
  3337. * if it can't schedule.
  3338. */
  3339. if (!(gfp_mask & __GFP_NOMEMALLOC))
  3340. alloc_flags |= ALLOC_HARDER;
  3341. /*
  3342. * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
  3343. * comment for __cpuset_node_allowed().
  3344. */
  3345. alloc_flags &= ~ALLOC_CPUSET;
  3346. } else if (unlikely(rt_task(current)) && !in_interrupt())
  3347. alloc_flags |= ALLOC_HARDER;
  3348. #ifdef CONFIG_CMA
  3349. if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
  3350. alloc_flags |= ALLOC_CMA;
  3351. #endif
  3352. return alloc_flags;
  3353. }
  3354. static bool oom_reserves_allowed(struct task_struct *tsk)
  3355. {
  3356. if (!tsk_is_oom_victim(tsk))
  3357. return false;
  3358. /*
  3359. * !MMU doesn't have oom reaper so give access to memory reserves
  3360. * only to the thread with TIF_MEMDIE set
  3361. */
  3362. if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
  3363. return false;
  3364. return true;
  3365. }
  3366. /*
  3367. * Distinguish requests which really need access to full memory
  3368. * reserves from oom victims which can live with a portion of it
  3369. */
  3370. static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
  3371. {
  3372. if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
  3373. return 0;
  3374. if (gfp_mask & __GFP_MEMALLOC)
  3375. return ALLOC_NO_WATERMARKS;
  3376. if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
  3377. return ALLOC_NO_WATERMARKS;
  3378. if (!in_interrupt()) {
  3379. if (current->flags & PF_MEMALLOC)
  3380. return ALLOC_NO_WATERMARKS;
  3381. else if (oom_reserves_allowed(current))
  3382. return ALLOC_OOM;
  3383. }
  3384. return 0;
  3385. }
  3386. bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
  3387. {
  3388. return !!__gfp_pfmemalloc_flags(gfp_mask);
  3389. }
  3390. /*
  3391. * Checks whether it makes sense to retry the reclaim to make a forward progress
  3392. * for the given allocation request.
  3393. *
  3394. * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
  3395. * without success, or when we couldn't even meet the watermark if we
  3396. * reclaimed all remaining pages on the LRU lists.
  3397. *
  3398. * Returns true if a retry is viable or false to enter the oom path.
  3399. */
  3400. static inline bool
  3401. should_reclaim_retry(gfp_t gfp_mask, unsigned order,
  3402. struct alloc_context *ac, int alloc_flags,
  3403. bool did_some_progress, int *no_progress_loops)
  3404. {
  3405. struct zone *zone;
  3406. struct zoneref *z;
  3407. /*
  3408. * Costly allocations might have made a progress but this doesn't mean
  3409. * their order will become available due to high fragmentation so
  3410. * always increment the no progress counter for them
  3411. */
  3412. if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
  3413. *no_progress_loops = 0;
  3414. else
  3415. (*no_progress_loops)++;
  3416. /*
  3417. * Make sure we converge to OOM if we cannot make any progress
  3418. * several times in the row.
  3419. */
  3420. if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
  3421. /* Before OOM, exhaust highatomic_reserve */
  3422. return unreserve_highatomic_pageblock(ac, true);
  3423. }
  3424. /*
  3425. * Keep reclaiming pages while there is a chance this will lead
  3426. * somewhere. If none of the target zones can satisfy our allocation
  3427. * request even if all reclaimable pages are considered then we are
  3428. * screwed and have to go OOM.
  3429. */
  3430. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
  3431. ac->nodemask) {
  3432. unsigned long available;
  3433. unsigned long reclaimable;
  3434. unsigned long min_wmark = min_wmark_pages(zone);
  3435. bool wmark;
  3436. available = reclaimable = zone_reclaimable_pages(zone);
  3437. available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  3438. /*
  3439. * Would the allocation succeed if we reclaimed all
  3440. * reclaimable pages?
  3441. */
  3442. wmark = __zone_watermark_ok(zone, order, min_wmark,
  3443. ac_classzone_idx(ac), alloc_flags, available);
  3444. trace_reclaim_retry_zone(z, order, reclaimable,
  3445. available, min_wmark, *no_progress_loops, wmark);
  3446. if (wmark) {
  3447. /*
  3448. * If we didn't make any progress and have a lot of
  3449. * dirty + writeback pages then we should wait for
  3450. * an IO to complete to slow down the reclaim and
  3451. * prevent from pre mature OOM
  3452. */
  3453. if (!did_some_progress) {
  3454. unsigned long write_pending;
  3455. write_pending = zone_page_state_snapshot(zone,
  3456. NR_ZONE_WRITE_PENDING);
  3457. if (2 * write_pending > reclaimable) {
  3458. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3459. return true;
  3460. }
  3461. }
  3462. /*
  3463. * Memory allocation/reclaim might be called from a WQ
  3464. * context and the current implementation of the WQ
  3465. * concurrency control doesn't recognize that
  3466. * a particular WQ is congested if the worker thread is
  3467. * looping without ever sleeping. Therefore we have to
  3468. * do a short sleep here rather than calling
  3469. * cond_resched().
  3470. */
  3471. if (current->flags & PF_WQ_WORKER)
  3472. schedule_timeout_uninterruptible(1);
  3473. else
  3474. cond_resched();
  3475. return true;
  3476. }
  3477. }
  3478. return false;
  3479. }
  3480. static inline bool
  3481. check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
  3482. {
  3483. /*
  3484. * It's possible that cpuset's mems_allowed and the nodemask from
  3485. * mempolicy don't intersect. This should be normally dealt with by
  3486. * policy_nodemask(), but it's possible to race with cpuset update in
  3487. * such a way the check therein was true, and then it became false
  3488. * before we got our cpuset_mems_cookie here.
  3489. * This assumes that for all allocations, ac->nodemask can come only
  3490. * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
  3491. * when it does not intersect with the cpuset restrictions) or the
  3492. * caller can deal with a violated nodemask.
  3493. */
  3494. if (cpusets_enabled() && ac->nodemask &&
  3495. !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
  3496. ac->nodemask = NULL;
  3497. return true;
  3498. }
  3499. /*
  3500. * When updating a task's mems_allowed or mempolicy nodemask, it is
  3501. * possible to race with parallel threads in such a way that our
  3502. * allocation can fail while the mask is being updated. If we are about
  3503. * to fail, check if the cpuset changed during allocation and if so,
  3504. * retry.
  3505. */
  3506. if (read_mems_allowed_retry(cpuset_mems_cookie))
  3507. return true;
  3508. return false;
  3509. }
  3510. static inline struct page *
  3511. __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
  3512. struct alloc_context *ac)
  3513. {
  3514. bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
  3515. const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
  3516. struct page *page = NULL;
  3517. unsigned int alloc_flags;
  3518. unsigned long did_some_progress;
  3519. enum compact_priority compact_priority;
  3520. enum compact_result compact_result;
  3521. int compaction_retries;
  3522. int no_progress_loops;
  3523. unsigned int cpuset_mems_cookie;
  3524. int reserve_flags;
  3525. /*
  3526. * We also sanity check to catch abuse of atomic reserves being used by
  3527. * callers that are not in atomic context.
  3528. */
  3529. if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
  3530. (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
  3531. gfp_mask &= ~__GFP_ATOMIC;
  3532. retry_cpuset:
  3533. compaction_retries = 0;
  3534. no_progress_loops = 0;
  3535. compact_priority = DEF_COMPACT_PRIORITY;
  3536. cpuset_mems_cookie = read_mems_allowed_begin();
  3537. /*
  3538. * The fast path uses conservative alloc_flags to succeed only until
  3539. * kswapd needs to be woken up, and to avoid the cost of setting up
  3540. * alloc_flags precisely. So we do that now.
  3541. */
  3542. alloc_flags = gfp_to_alloc_flags(gfp_mask);
  3543. /*
  3544. * We need to recalculate the starting point for the zonelist iterator
  3545. * because we might have used different nodemask in the fast path, or
  3546. * there was a cpuset modification and we are retrying - otherwise we
  3547. * could end up iterating over non-eligible zones endlessly.
  3548. */
  3549. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3550. ac->high_zoneidx, ac->nodemask);
  3551. if (!ac->preferred_zoneref->zone)
  3552. goto nopage;
  3553. if (gfp_mask & __GFP_KSWAPD_RECLAIM)
  3554. wake_all_kswapds(order, gfp_mask, ac);
  3555. /*
  3556. * The adjusted alloc_flags might result in immediate success, so try
  3557. * that first
  3558. */
  3559. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3560. if (page)
  3561. goto got_pg;
  3562. /*
  3563. * For costly allocations, try direct compaction first, as it's likely
  3564. * that we have enough base pages and don't need to reclaim. For non-
  3565. * movable high-order allocations, do that as well, as compaction will
  3566. * try prevent permanent fragmentation by migrating from blocks of the
  3567. * same migratetype.
  3568. * Don't try this for allocations that are allowed to ignore
  3569. * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
  3570. */
  3571. if (can_direct_reclaim &&
  3572. (costly_order ||
  3573. (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
  3574. && !gfp_pfmemalloc_allowed(gfp_mask)) {
  3575. page = __alloc_pages_direct_compact(gfp_mask, order,
  3576. alloc_flags, ac,
  3577. INIT_COMPACT_PRIORITY,
  3578. &compact_result);
  3579. if (page)
  3580. goto got_pg;
  3581. /*
  3582. * Checks for costly allocations with __GFP_NORETRY, which
  3583. * includes THP page fault allocations
  3584. */
  3585. if (costly_order && (gfp_mask & __GFP_NORETRY)) {
  3586. /*
  3587. * If compaction is deferred for high-order allocations,
  3588. * it is because sync compaction recently failed. If
  3589. * this is the case and the caller requested a THP
  3590. * allocation, we do not want to heavily disrupt the
  3591. * system, so we fail the allocation instead of entering
  3592. * direct reclaim.
  3593. */
  3594. if (compact_result == COMPACT_DEFERRED)
  3595. goto nopage;
  3596. /*
  3597. * Looks like reclaim/compaction is worth trying, but
  3598. * sync compaction could be very expensive, so keep
  3599. * using async compaction.
  3600. */
  3601. compact_priority = INIT_COMPACT_PRIORITY;
  3602. }
  3603. }
  3604. retry:
  3605. /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
  3606. if (gfp_mask & __GFP_KSWAPD_RECLAIM)
  3607. wake_all_kswapds(order, gfp_mask, ac);
  3608. reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
  3609. if (reserve_flags)
  3610. alloc_flags = reserve_flags;
  3611. /*
  3612. * Reset the nodemask and zonelist iterators if memory policies can be
  3613. * ignored. These allocations are high priority and system rather than
  3614. * user oriented.
  3615. */
  3616. if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
  3617. ac->nodemask = NULL;
  3618. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3619. ac->high_zoneidx, ac->nodemask);
  3620. }
  3621. /* Attempt with potentially adjusted zonelist and alloc_flags */
  3622. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3623. if (page)
  3624. goto got_pg;
  3625. /* Caller is not willing to reclaim, we can't balance anything */
  3626. if (!can_direct_reclaim)
  3627. goto nopage;
  3628. /* Avoid recursion of direct reclaim */
  3629. if (current->flags & PF_MEMALLOC)
  3630. goto nopage;
  3631. /* Try direct reclaim and then allocating */
  3632. page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
  3633. &did_some_progress);
  3634. if (page)
  3635. goto got_pg;
  3636. /* Try direct compaction and then allocating */
  3637. page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
  3638. compact_priority, &compact_result);
  3639. if (page)
  3640. goto got_pg;
  3641. /* Do not loop if specifically requested */
  3642. if (gfp_mask & __GFP_NORETRY)
  3643. goto nopage;
  3644. /*
  3645. * Do not retry costly high order allocations unless they are
  3646. * __GFP_RETRY_MAYFAIL
  3647. */
  3648. if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
  3649. goto nopage;
  3650. if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
  3651. did_some_progress > 0, &no_progress_loops))
  3652. goto retry;
  3653. /*
  3654. * It doesn't make any sense to retry for the compaction if the order-0
  3655. * reclaim is not able to make any progress because the current
  3656. * implementation of the compaction depends on the sufficient amount
  3657. * of free memory (see __compaction_suitable)
  3658. */
  3659. if (did_some_progress > 0 &&
  3660. should_compact_retry(ac, order, alloc_flags,
  3661. compact_result, &compact_priority,
  3662. &compaction_retries))
  3663. goto retry;
  3664. /* Deal with possible cpuset update races before we start OOM killing */
  3665. if (check_retry_cpuset(cpuset_mems_cookie, ac))
  3666. goto retry_cpuset;
  3667. /* Reclaim has failed us, start killing things */
  3668. page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
  3669. if (page)
  3670. goto got_pg;
  3671. /* Avoid allocations with no watermarks from looping endlessly */
  3672. if (tsk_is_oom_victim(current) &&
  3673. (alloc_flags == ALLOC_OOM ||
  3674. (gfp_mask & __GFP_NOMEMALLOC)))
  3675. goto nopage;
  3676. /* Retry as long as the OOM killer is making progress */
  3677. if (did_some_progress) {
  3678. no_progress_loops = 0;
  3679. goto retry;
  3680. }
  3681. nopage:
  3682. /* Deal with possible cpuset update races before we fail */
  3683. if (check_retry_cpuset(cpuset_mems_cookie, ac))
  3684. goto retry_cpuset;
  3685. /*
  3686. * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
  3687. * we always retry
  3688. */
  3689. if (gfp_mask & __GFP_NOFAIL) {
  3690. /*
  3691. * All existing users of the __GFP_NOFAIL are blockable, so warn
  3692. * of any new users that actually require GFP_NOWAIT
  3693. */
  3694. if (WARN_ON_ONCE(!can_direct_reclaim))
  3695. goto fail;
  3696. /*
  3697. * PF_MEMALLOC request from this context is rather bizarre
  3698. * because we cannot reclaim anything and only can loop waiting
  3699. * for somebody to do a work for us
  3700. */
  3701. WARN_ON_ONCE(current->flags & PF_MEMALLOC);
  3702. /*
  3703. * non failing costly orders are a hard requirement which we
  3704. * are not prepared for much so let's warn about these users
  3705. * so that we can identify them and convert them to something
  3706. * else.
  3707. */
  3708. WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
  3709. /*
  3710. * Help non-failing allocations by giving them access to memory
  3711. * reserves but do not use ALLOC_NO_WATERMARKS because this
  3712. * could deplete whole memory reserves which would just make
  3713. * the situation worse
  3714. */
  3715. page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
  3716. if (page)
  3717. goto got_pg;
  3718. cond_resched();
  3719. goto retry;
  3720. }
  3721. fail:
  3722. warn_alloc(gfp_mask, ac->nodemask,
  3723. "page allocation failure: order:%u", order);
  3724. got_pg:
  3725. return page;
  3726. }
  3727. static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
  3728. int preferred_nid, nodemask_t *nodemask,
  3729. struct alloc_context *ac, gfp_t *alloc_mask,
  3730. unsigned int *alloc_flags)
  3731. {
  3732. ac->high_zoneidx = gfp_zone(gfp_mask);
  3733. ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
  3734. ac->nodemask = nodemask;
  3735. ac->migratetype = gfpflags_to_migratetype(gfp_mask);
  3736. if (cpusets_enabled()) {
  3737. *alloc_mask |= __GFP_HARDWALL;
  3738. if (!ac->nodemask)
  3739. ac->nodemask = &cpuset_current_mems_allowed;
  3740. else
  3741. *alloc_flags |= ALLOC_CPUSET;
  3742. }
  3743. fs_reclaim_acquire(gfp_mask);
  3744. fs_reclaim_release(gfp_mask);
  3745. might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
  3746. if (should_fail_alloc_page(gfp_mask, order))
  3747. return false;
  3748. if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
  3749. *alloc_flags |= ALLOC_CMA;
  3750. return true;
  3751. }
  3752. /* Determine whether to spread dirty pages and what the first usable zone */
  3753. static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
  3754. {
  3755. /* Dirty zone balancing only done in the fast path */
  3756. ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
  3757. /*
  3758. * The preferred zone is used for statistics but crucially it is
  3759. * also used as the starting point for the zonelist iterator. It
  3760. * may get reset for allocations that ignore memory policies.
  3761. */
  3762. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3763. ac->high_zoneidx, ac->nodemask);
  3764. }
  3765. /*
  3766. * This is the 'heart' of the zoned buddy allocator.
  3767. */
  3768. struct page *
  3769. __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
  3770. nodemask_t *nodemask)
  3771. {
  3772. struct page *page;
  3773. unsigned int alloc_flags = ALLOC_WMARK_LOW;
  3774. gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
  3775. struct alloc_context ac = { };
  3776. /*
  3777. * There are several places where we assume that the order value is sane
  3778. * so bail out early if the request is out of bound.
  3779. */
  3780. if (unlikely(order >= MAX_ORDER)) {
  3781. WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
  3782. return NULL;
  3783. }
  3784. gfp_mask &= gfp_allowed_mask;
  3785. alloc_mask = gfp_mask;
  3786. if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
  3787. return NULL;
  3788. finalise_ac(gfp_mask, &ac);
  3789. /* First allocation attempt */
  3790. page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
  3791. if (likely(page))
  3792. goto out;
  3793. /*
  3794. * Apply scoped allocation constraints. This is mainly about GFP_NOFS
  3795. * resp. GFP_NOIO which has to be inherited for all allocation requests
  3796. * from a particular context which has been marked by
  3797. * memalloc_no{fs,io}_{save,restore}.
  3798. */
  3799. alloc_mask = current_gfp_context(gfp_mask);
  3800. ac.spread_dirty_pages = false;
  3801. /*
  3802. * Restore the original nodemask if it was potentially replaced with
  3803. * &cpuset_current_mems_allowed to optimize the fast-path attempt.
  3804. */
  3805. if (unlikely(ac.nodemask != nodemask))
  3806. ac.nodemask = nodemask;
  3807. page = __alloc_pages_slowpath(alloc_mask, order, &ac);
  3808. out:
  3809. if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
  3810. unlikely(memcg_kmem_charge(page, gfp_mask, order) != 0)) {
  3811. __free_pages(page, order);
  3812. page = NULL;
  3813. }
  3814. trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
  3815. return page;
  3816. }
  3817. EXPORT_SYMBOL(__alloc_pages_nodemask);
  3818. /*
  3819. * Common helper functions. Never use with __GFP_HIGHMEM because the returned
  3820. * address cannot represent highmem pages. Use alloc_pages and then kmap if
  3821. * you need to access high mem.
  3822. */
  3823. unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
  3824. {
  3825. struct page *page;
  3826. page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
  3827. if (!page)
  3828. return 0;
  3829. return (unsigned long) page_address(page);
  3830. }
  3831. EXPORT_SYMBOL(__get_free_pages);
  3832. unsigned long get_zeroed_page(gfp_t gfp_mask)
  3833. {
  3834. return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
  3835. }
  3836. EXPORT_SYMBOL(get_zeroed_page);
  3837. static inline void free_the_page(struct page *page, unsigned int order)
  3838. {
  3839. if (order == 0) /* Via pcp? */
  3840. free_unref_page(page);
  3841. else
  3842. __free_pages_ok(page, order);
  3843. }
  3844. void __free_pages(struct page *page, unsigned int order)
  3845. {
  3846. if (put_page_testzero(page))
  3847. free_the_page(page, order);
  3848. }
  3849. EXPORT_SYMBOL(__free_pages);
  3850. void free_pages(unsigned long addr, unsigned int order)
  3851. {
  3852. if (addr != 0) {
  3853. VM_BUG_ON(!virt_addr_valid((void *)addr));
  3854. __free_pages(virt_to_page((void *)addr), order);
  3855. }
  3856. }
  3857. EXPORT_SYMBOL(free_pages);
  3858. /*
  3859. * Page Fragment:
  3860. * An arbitrary-length arbitrary-offset area of memory which resides
  3861. * within a 0 or higher order page. Multiple fragments within that page
  3862. * are individually refcounted, in the page's reference counter.
  3863. *
  3864. * The page_frag functions below provide a simple allocation framework for
  3865. * page fragments. This is used by the network stack and network device
  3866. * drivers to provide a backing region of memory for use as either an
  3867. * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
  3868. */
  3869. static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
  3870. gfp_t gfp_mask)
  3871. {
  3872. struct page *page = NULL;
  3873. gfp_t gfp = gfp_mask;
  3874. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  3875. gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
  3876. __GFP_NOMEMALLOC;
  3877. page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
  3878. PAGE_FRAG_CACHE_MAX_ORDER);
  3879. nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
  3880. #endif
  3881. if (unlikely(!page))
  3882. page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
  3883. nc->va = page ? page_address(page) : NULL;
  3884. return page;
  3885. }
  3886. void __page_frag_cache_drain(struct page *page, unsigned int count)
  3887. {
  3888. VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
  3889. if (page_ref_sub_and_test(page, count))
  3890. free_the_page(page, compound_order(page));
  3891. }
  3892. EXPORT_SYMBOL(__page_frag_cache_drain);
  3893. void *page_frag_alloc(struct page_frag_cache *nc,
  3894. unsigned int fragsz, gfp_t gfp_mask)
  3895. {
  3896. unsigned int size = PAGE_SIZE;
  3897. struct page *page;
  3898. int offset;
  3899. if (unlikely(!nc->va)) {
  3900. refill:
  3901. page = __page_frag_cache_refill(nc, gfp_mask);
  3902. if (!page)
  3903. return NULL;
  3904. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  3905. /* if size can vary use size else just use PAGE_SIZE */
  3906. size = nc->size;
  3907. #endif
  3908. /* Even if we own the page, we do not use atomic_set().
  3909. * This would break get_page_unless_zero() users.
  3910. */
  3911. page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
  3912. /* reset page count bias and offset to start of new frag */
  3913. nc->pfmemalloc = page_is_pfmemalloc(page);
  3914. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  3915. nc->offset = size;
  3916. }
  3917. offset = nc->offset - fragsz;
  3918. if (unlikely(offset < 0)) {
  3919. page = virt_to_page(nc->va);
  3920. if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
  3921. goto refill;
  3922. if (unlikely(nc->pfmemalloc)) {
  3923. free_the_page(page, compound_order(page));
  3924. goto refill;
  3925. }
  3926. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  3927. /* if size can vary use size else just use PAGE_SIZE */
  3928. size = nc->size;
  3929. #endif
  3930. /* OK, page count is 0, we can safely set it */
  3931. set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
  3932. /* reset page count bias and offset to start of new frag */
  3933. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  3934. offset = size - fragsz;
  3935. }
  3936. nc->pagecnt_bias--;
  3937. nc->offset = offset;
  3938. return nc->va + offset;
  3939. }
  3940. EXPORT_SYMBOL(page_frag_alloc);
  3941. /*
  3942. * Frees a page fragment allocated out of either a compound or order 0 page.
  3943. */
  3944. void page_frag_free(void *addr)
  3945. {
  3946. struct page *page = virt_to_head_page(addr);
  3947. if (unlikely(put_page_testzero(page)))
  3948. free_the_page(page, compound_order(page));
  3949. }
  3950. EXPORT_SYMBOL(page_frag_free);
  3951. static void *make_alloc_exact(unsigned long addr, unsigned int order,
  3952. size_t size)
  3953. {
  3954. if (addr) {
  3955. unsigned long alloc_end = addr + (PAGE_SIZE << order);
  3956. unsigned long used = addr + PAGE_ALIGN(size);
  3957. split_page(virt_to_page((void *)addr), order);
  3958. while (used < alloc_end) {
  3959. free_page(used);
  3960. used += PAGE_SIZE;
  3961. }
  3962. }
  3963. return (void *)addr;
  3964. }
  3965. /**
  3966. * alloc_pages_exact - allocate an exact number physically-contiguous pages.
  3967. * @size: the number of bytes to allocate
  3968. * @gfp_mask: GFP flags for the allocation
  3969. *
  3970. * This function is similar to alloc_pages(), except that it allocates the
  3971. * minimum number of pages to satisfy the request. alloc_pages() can only
  3972. * allocate memory in power-of-two pages.
  3973. *
  3974. * This function is also limited by MAX_ORDER.
  3975. *
  3976. * Memory allocated by this function must be released by free_pages_exact().
  3977. */
  3978. void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
  3979. {
  3980. unsigned int order = get_order(size);
  3981. unsigned long addr;
  3982. addr = __get_free_pages(gfp_mask, order);
  3983. return make_alloc_exact(addr, order, size);
  3984. }
  3985. EXPORT_SYMBOL(alloc_pages_exact);
  3986. /**
  3987. * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
  3988. * pages on a node.
  3989. * @nid: the preferred node ID where memory should be allocated
  3990. * @size: the number of bytes to allocate
  3991. * @gfp_mask: GFP flags for the allocation
  3992. *
  3993. * Like alloc_pages_exact(), but try to allocate on node nid first before falling
  3994. * back.
  3995. */
  3996. void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
  3997. {
  3998. unsigned int order = get_order(size);
  3999. struct page *p = alloc_pages_node(nid, gfp_mask, order);
  4000. if (!p)
  4001. return NULL;
  4002. return make_alloc_exact((unsigned long)page_address(p), order, size);
  4003. }
  4004. /**
  4005. * free_pages_exact - release memory allocated via alloc_pages_exact()
  4006. * @virt: the value returned by alloc_pages_exact.
  4007. * @size: size of allocation, same value as passed to alloc_pages_exact().
  4008. *
  4009. * Release the memory allocated by a previous call to alloc_pages_exact.
  4010. */
  4011. void free_pages_exact(void *virt, size_t size)
  4012. {
  4013. unsigned long addr = (unsigned long)virt;
  4014. unsigned long end = addr + PAGE_ALIGN(size);
  4015. while (addr < end) {
  4016. free_page(addr);
  4017. addr += PAGE_SIZE;
  4018. }
  4019. }
  4020. EXPORT_SYMBOL(free_pages_exact);
  4021. /**
  4022. * nr_free_zone_pages - count number of pages beyond high watermark
  4023. * @offset: The zone index of the highest zone
  4024. *
  4025. * nr_free_zone_pages() counts the number of counts pages which are beyond the
  4026. * high watermark within all zones at or below a given zone index. For each
  4027. * zone, the number of pages is calculated as:
  4028. *
  4029. * nr_free_zone_pages = managed_pages - high_pages
  4030. */
  4031. static unsigned long nr_free_zone_pages(int offset)
  4032. {
  4033. struct zoneref *z;
  4034. struct zone *zone;
  4035. /* Just pick one node, since fallback list is circular */
  4036. unsigned long sum = 0;
  4037. struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
  4038. for_each_zone_zonelist(zone, z, zonelist, offset) {
  4039. unsigned long size = zone->managed_pages;
  4040. unsigned long high = high_wmark_pages(zone);
  4041. if (size > high)
  4042. sum += size - high;
  4043. }
  4044. return sum;
  4045. }
  4046. /**
  4047. * nr_free_buffer_pages - count number of pages beyond high watermark
  4048. *
  4049. * nr_free_buffer_pages() counts the number of pages which are beyond the high
  4050. * watermark within ZONE_DMA and ZONE_NORMAL.
  4051. */
  4052. unsigned long nr_free_buffer_pages(void)
  4053. {
  4054. return nr_free_zone_pages(gfp_zone(GFP_USER));
  4055. }
  4056. EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
  4057. /**
  4058. * nr_free_pagecache_pages - count number of pages beyond high watermark
  4059. *
  4060. * nr_free_pagecache_pages() counts the number of pages which are beyond the
  4061. * high watermark within all zones.
  4062. */
  4063. unsigned long nr_free_pagecache_pages(void)
  4064. {
  4065. return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
  4066. }
  4067. static inline void show_node(struct zone *zone)
  4068. {
  4069. if (IS_ENABLED(CONFIG_NUMA))
  4070. printk("Node %d ", zone_to_nid(zone));
  4071. }
  4072. long si_mem_available(void)
  4073. {
  4074. long available;
  4075. unsigned long pagecache;
  4076. unsigned long wmark_low = 0;
  4077. unsigned long pages[NR_LRU_LISTS];
  4078. struct zone *zone;
  4079. int lru;
  4080. for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
  4081. pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
  4082. for_each_zone(zone)
  4083. wmark_low += zone->watermark[WMARK_LOW];
  4084. /*
  4085. * Estimate the amount of memory available for userspace allocations,
  4086. * without causing swapping.
  4087. */
  4088. available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
  4089. /*
  4090. * Not all the page cache can be freed, otherwise the system will
  4091. * start swapping. Assume at least half of the page cache, or the
  4092. * low watermark worth of cache, needs to stay.
  4093. */
  4094. pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
  4095. pagecache -= min(pagecache / 2, wmark_low);
  4096. available += pagecache;
  4097. /*
  4098. * Part of the reclaimable slab consists of items that are in use,
  4099. * and cannot be freed. Cap this estimate at the low watermark.
  4100. */
  4101. available += global_node_page_state(NR_SLAB_RECLAIMABLE) -
  4102. min(global_node_page_state(NR_SLAB_RECLAIMABLE) / 2,
  4103. wmark_low);
  4104. /*
  4105. * Part of the kernel memory, which can be released under memory
  4106. * pressure.
  4107. */
  4108. available += global_node_page_state(NR_INDIRECTLY_RECLAIMABLE_BYTES) >>
  4109. PAGE_SHIFT;
  4110. if (available < 0)
  4111. available = 0;
  4112. return available;
  4113. }
  4114. EXPORT_SYMBOL_GPL(si_mem_available);
  4115. void si_meminfo(struct sysinfo *val)
  4116. {
  4117. val->totalram = totalram_pages;
  4118. val->sharedram = global_node_page_state(NR_SHMEM);
  4119. val->freeram = global_zone_page_state(NR_FREE_PAGES);
  4120. val->bufferram = nr_blockdev_pages();
  4121. val->totalhigh = totalhigh_pages;
  4122. val->freehigh = nr_free_highpages();
  4123. val->mem_unit = PAGE_SIZE;
  4124. }
  4125. EXPORT_SYMBOL(si_meminfo);
  4126. #ifdef CONFIG_NUMA
  4127. void si_meminfo_node(struct sysinfo *val, int nid)
  4128. {
  4129. int zone_type; /* needs to be signed */
  4130. unsigned long managed_pages = 0;
  4131. unsigned long managed_highpages = 0;
  4132. unsigned long free_highpages = 0;
  4133. pg_data_t *pgdat = NODE_DATA(nid);
  4134. for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
  4135. managed_pages += pgdat->node_zones[zone_type].managed_pages;
  4136. val->totalram = managed_pages;
  4137. val->sharedram = node_page_state(pgdat, NR_SHMEM);
  4138. val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
  4139. #ifdef CONFIG_HIGHMEM
  4140. for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
  4141. struct zone *zone = &pgdat->node_zones[zone_type];
  4142. if (is_highmem(zone)) {
  4143. managed_highpages += zone->managed_pages;
  4144. free_highpages += zone_page_state(zone, NR_FREE_PAGES);
  4145. }
  4146. }
  4147. val->totalhigh = managed_highpages;
  4148. val->freehigh = free_highpages;
  4149. #else
  4150. val->totalhigh = managed_highpages;
  4151. val->freehigh = free_highpages;
  4152. #endif
  4153. val->mem_unit = PAGE_SIZE;
  4154. }
  4155. #endif
  4156. /*
  4157. * Determine whether the node should be displayed or not, depending on whether
  4158. * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
  4159. */
  4160. static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
  4161. {
  4162. if (!(flags & SHOW_MEM_FILTER_NODES))
  4163. return false;
  4164. /*
  4165. * no node mask - aka implicit memory numa policy. Do not bother with
  4166. * the synchronization - read_mems_allowed_begin - because we do not
  4167. * have to be precise here.
  4168. */
  4169. if (!nodemask)
  4170. nodemask = &cpuset_current_mems_allowed;
  4171. return !node_isset(nid, *nodemask);
  4172. }
  4173. #define K(x) ((x) << (PAGE_SHIFT-10))
  4174. static void show_migration_types(unsigned char type)
  4175. {
  4176. static const char types[MIGRATE_TYPES] = {
  4177. [MIGRATE_UNMOVABLE] = 'U',
  4178. [MIGRATE_MOVABLE] = 'M',
  4179. [MIGRATE_RECLAIMABLE] = 'E',
  4180. [MIGRATE_HIGHATOMIC] = 'H',
  4181. #ifdef CONFIG_CMA
  4182. [MIGRATE_CMA] = 'C',
  4183. #endif
  4184. #ifdef CONFIG_MEMORY_ISOLATION
  4185. [MIGRATE_ISOLATE] = 'I',
  4186. #endif
  4187. };
  4188. char tmp[MIGRATE_TYPES + 1];
  4189. char *p = tmp;
  4190. int i;
  4191. for (i = 0; i < MIGRATE_TYPES; i++) {
  4192. if (type & (1 << i))
  4193. *p++ = types[i];
  4194. }
  4195. *p = '\0';
  4196. printk(KERN_CONT "(%s) ", tmp);
  4197. }
  4198. /*
  4199. * Show free area list (used inside shift_scroll-lock stuff)
  4200. * We also calculate the percentage fragmentation. We do this by counting the
  4201. * memory on each free list with the exception of the first item on the list.
  4202. *
  4203. * Bits in @filter:
  4204. * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
  4205. * cpuset.
  4206. */
  4207. void show_free_areas(unsigned int filter, nodemask_t *nodemask)
  4208. {
  4209. unsigned long free_pcp = 0;
  4210. int cpu;
  4211. struct zone *zone;
  4212. pg_data_t *pgdat;
  4213. for_each_populated_zone(zone) {
  4214. if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
  4215. continue;
  4216. for_each_online_cpu(cpu)
  4217. free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
  4218. }
  4219. printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
  4220. " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
  4221. " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
  4222. " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
  4223. " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
  4224. " free:%lu free_pcp:%lu free_cma:%lu\n",
  4225. global_node_page_state(NR_ACTIVE_ANON),
  4226. global_node_page_state(NR_INACTIVE_ANON),
  4227. global_node_page_state(NR_ISOLATED_ANON),
  4228. global_node_page_state(NR_ACTIVE_FILE),
  4229. global_node_page_state(NR_INACTIVE_FILE),
  4230. global_node_page_state(NR_ISOLATED_FILE),
  4231. global_node_page_state(NR_UNEVICTABLE),
  4232. global_node_page_state(NR_FILE_DIRTY),
  4233. global_node_page_state(NR_WRITEBACK),
  4234. global_node_page_state(NR_UNSTABLE_NFS),
  4235. global_node_page_state(NR_SLAB_RECLAIMABLE),
  4236. global_node_page_state(NR_SLAB_UNRECLAIMABLE),
  4237. global_node_page_state(NR_FILE_MAPPED),
  4238. global_node_page_state(NR_SHMEM),
  4239. global_zone_page_state(NR_PAGETABLE),
  4240. global_zone_page_state(NR_BOUNCE),
  4241. global_zone_page_state(NR_FREE_PAGES),
  4242. free_pcp,
  4243. global_zone_page_state(NR_FREE_CMA_PAGES));
  4244. for_each_online_pgdat(pgdat) {
  4245. if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
  4246. continue;
  4247. printk("Node %d"
  4248. " active_anon:%lukB"
  4249. " inactive_anon:%lukB"
  4250. " active_file:%lukB"
  4251. " inactive_file:%lukB"
  4252. " unevictable:%lukB"
  4253. " isolated(anon):%lukB"
  4254. " isolated(file):%lukB"
  4255. " mapped:%lukB"
  4256. " dirty:%lukB"
  4257. " writeback:%lukB"
  4258. " shmem:%lukB"
  4259. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4260. " shmem_thp: %lukB"
  4261. " shmem_pmdmapped: %lukB"
  4262. " anon_thp: %lukB"
  4263. #endif
  4264. " writeback_tmp:%lukB"
  4265. " unstable:%lukB"
  4266. " all_unreclaimable? %s"
  4267. "\n",
  4268. pgdat->node_id,
  4269. K(node_page_state(pgdat, NR_ACTIVE_ANON)),
  4270. K(node_page_state(pgdat, NR_INACTIVE_ANON)),
  4271. K(node_page_state(pgdat, NR_ACTIVE_FILE)),
  4272. K(node_page_state(pgdat, NR_INACTIVE_FILE)),
  4273. K(node_page_state(pgdat, NR_UNEVICTABLE)),
  4274. K(node_page_state(pgdat, NR_ISOLATED_ANON)),
  4275. K(node_page_state(pgdat, NR_ISOLATED_FILE)),
  4276. K(node_page_state(pgdat, NR_FILE_MAPPED)),
  4277. K(node_page_state(pgdat, NR_FILE_DIRTY)),
  4278. K(node_page_state(pgdat, NR_WRITEBACK)),
  4279. K(node_page_state(pgdat, NR_SHMEM)),
  4280. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4281. K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
  4282. K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
  4283. * HPAGE_PMD_NR),
  4284. K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
  4285. #endif
  4286. K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
  4287. K(node_page_state(pgdat, NR_UNSTABLE_NFS)),
  4288. pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
  4289. "yes" : "no");
  4290. }
  4291. for_each_populated_zone(zone) {
  4292. int i;
  4293. if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
  4294. continue;
  4295. free_pcp = 0;
  4296. for_each_online_cpu(cpu)
  4297. free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
  4298. show_node(zone);
  4299. printk(KERN_CONT
  4300. "%s"
  4301. " free:%lukB"
  4302. " min:%lukB"
  4303. " low:%lukB"
  4304. " high:%lukB"
  4305. " active_anon:%lukB"
  4306. " inactive_anon:%lukB"
  4307. " active_file:%lukB"
  4308. " inactive_file:%lukB"
  4309. " unevictable:%lukB"
  4310. " writepending:%lukB"
  4311. " present:%lukB"
  4312. " managed:%lukB"
  4313. " mlocked:%lukB"
  4314. " kernel_stack:%lukB"
  4315. " pagetables:%lukB"
  4316. " bounce:%lukB"
  4317. " free_pcp:%lukB"
  4318. " local_pcp:%ukB"
  4319. " free_cma:%lukB"
  4320. "\n",
  4321. zone->name,
  4322. K(zone_page_state(zone, NR_FREE_PAGES)),
  4323. K(min_wmark_pages(zone)),
  4324. K(low_wmark_pages(zone)),
  4325. K(high_wmark_pages(zone)),
  4326. K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
  4327. K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
  4328. K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
  4329. K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
  4330. K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
  4331. K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
  4332. K(zone->present_pages),
  4333. K(zone->managed_pages),
  4334. K(zone_page_state(zone, NR_MLOCK)),
  4335. zone_page_state(zone, NR_KERNEL_STACK_KB),
  4336. K(zone_page_state(zone, NR_PAGETABLE)),
  4337. K(zone_page_state(zone, NR_BOUNCE)),
  4338. K(free_pcp),
  4339. K(this_cpu_read(zone->pageset->pcp.count)),
  4340. K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
  4341. printk("lowmem_reserve[]:");
  4342. for (i = 0; i < MAX_NR_ZONES; i++)
  4343. printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
  4344. printk(KERN_CONT "\n");
  4345. }
  4346. for_each_populated_zone(zone) {
  4347. unsigned int order;
  4348. unsigned long nr[MAX_ORDER], flags, total = 0;
  4349. unsigned char types[MAX_ORDER];
  4350. if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
  4351. continue;
  4352. show_node(zone);
  4353. printk(KERN_CONT "%s: ", zone->name);
  4354. spin_lock_irqsave(&zone->lock, flags);
  4355. for (order = 0; order < MAX_ORDER; order++) {
  4356. struct free_area *area = &zone->free_area[order];
  4357. int type;
  4358. nr[order] = area->nr_free;
  4359. total += nr[order] << order;
  4360. types[order] = 0;
  4361. for (type = 0; type < MIGRATE_TYPES; type++) {
  4362. if (!list_empty(&area->free_list[type]))
  4363. types[order] |= 1 << type;
  4364. }
  4365. }
  4366. spin_unlock_irqrestore(&zone->lock, flags);
  4367. for (order = 0; order < MAX_ORDER; order++) {
  4368. printk(KERN_CONT "%lu*%lukB ",
  4369. nr[order], K(1UL) << order);
  4370. if (nr[order])
  4371. show_migration_types(types[order]);
  4372. }
  4373. printk(KERN_CONT "= %lukB\n", K(total));
  4374. }
  4375. hugetlb_show_meminfo();
  4376. printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
  4377. show_swap_cache_info();
  4378. }
  4379. static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
  4380. {
  4381. zoneref->zone = zone;
  4382. zoneref->zone_idx = zone_idx(zone);
  4383. }
  4384. /*
  4385. * Builds allocation fallback zone lists.
  4386. *
  4387. * Add all populated zones of a node to the zonelist.
  4388. */
  4389. static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
  4390. {
  4391. struct zone *zone;
  4392. enum zone_type zone_type = MAX_NR_ZONES;
  4393. int nr_zones = 0;
  4394. do {
  4395. zone_type--;
  4396. zone = pgdat->node_zones + zone_type;
  4397. if (managed_zone(zone)) {
  4398. zoneref_set_zone(zone, &zonerefs[nr_zones++]);
  4399. check_highest_zone(zone_type);
  4400. }
  4401. } while (zone_type);
  4402. return nr_zones;
  4403. }
  4404. #ifdef CONFIG_NUMA
  4405. static int __parse_numa_zonelist_order(char *s)
  4406. {
  4407. /*
  4408. * We used to support different zonlists modes but they turned
  4409. * out to be just not useful. Let's keep the warning in place
  4410. * if somebody still use the cmd line parameter so that we do
  4411. * not fail it silently
  4412. */
  4413. if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
  4414. pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
  4415. return -EINVAL;
  4416. }
  4417. return 0;
  4418. }
  4419. static __init int setup_numa_zonelist_order(char *s)
  4420. {
  4421. if (!s)
  4422. return 0;
  4423. return __parse_numa_zonelist_order(s);
  4424. }
  4425. early_param("numa_zonelist_order", setup_numa_zonelist_order);
  4426. char numa_zonelist_order[] = "Node";
  4427. /*
  4428. * sysctl handler for numa_zonelist_order
  4429. */
  4430. int numa_zonelist_order_handler(struct ctl_table *table, int write,
  4431. void __user *buffer, size_t *length,
  4432. loff_t *ppos)
  4433. {
  4434. char *str;
  4435. int ret;
  4436. if (!write)
  4437. return proc_dostring(table, write, buffer, length, ppos);
  4438. str = memdup_user_nul(buffer, 16);
  4439. if (IS_ERR(str))
  4440. return PTR_ERR(str);
  4441. ret = __parse_numa_zonelist_order(str);
  4442. kfree(str);
  4443. return ret;
  4444. }
  4445. #define MAX_NODE_LOAD (nr_online_nodes)
  4446. static int node_load[MAX_NUMNODES];
  4447. /**
  4448. * find_next_best_node - find the next node that should appear in a given node's fallback list
  4449. * @node: node whose fallback list we're appending
  4450. * @used_node_mask: nodemask_t of already used nodes
  4451. *
  4452. * We use a number of factors to determine which is the next node that should
  4453. * appear on a given node's fallback list. The node should not have appeared
  4454. * already in @node's fallback list, and it should be the next closest node
  4455. * according to the distance array (which contains arbitrary distance values
  4456. * from each node to each node in the system), and should also prefer nodes
  4457. * with no CPUs, since presumably they'll have very little allocation pressure
  4458. * on them otherwise.
  4459. * It returns -1 if no node is found.
  4460. */
  4461. static int find_next_best_node(int node, nodemask_t *used_node_mask)
  4462. {
  4463. int n, val;
  4464. int min_val = INT_MAX;
  4465. int best_node = NUMA_NO_NODE;
  4466. const struct cpumask *tmp = cpumask_of_node(0);
  4467. /* Use the local node if we haven't already */
  4468. if (!node_isset(node, *used_node_mask)) {
  4469. node_set(node, *used_node_mask);
  4470. return node;
  4471. }
  4472. for_each_node_state(n, N_MEMORY) {
  4473. /* Don't want a node to appear more than once */
  4474. if (node_isset(n, *used_node_mask))
  4475. continue;
  4476. /* Use the distance array to find the distance */
  4477. val = node_distance(node, n);
  4478. /* Penalize nodes under us ("prefer the next node") */
  4479. val += (n < node);
  4480. /* Give preference to headless and unused nodes */
  4481. tmp = cpumask_of_node(n);
  4482. if (!cpumask_empty(tmp))
  4483. val += PENALTY_FOR_NODE_WITH_CPUS;
  4484. /* Slight preference for less loaded node */
  4485. val *= (MAX_NODE_LOAD*MAX_NUMNODES);
  4486. val += node_load[n];
  4487. if (val < min_val) {
  4488. min_val = val;
  4489. best_node = n;
  4490. }
  4491. }
  4492. if (best_node >= 0)
  4493. node_set(best_node, *used_node_mask);
  4494. return best_node;
  4495. }
  4496. /*
  4497. * Build zonelists ordered by node and zones within node.
  4498. * This results in maximum locality--normal zone overflows into local
  4499. * DMA zone, if any--but risks exhausting DMA zone.
  4500. */
  4501. static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
  4502. unsigned nr_nodes)
  4503. {
  4504. struct zoneref *zonerefs;
  4505. int i;
  4506. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4507. for (i = 0; i < nr_nodes; i++) {
  4508. int nr_zones;
  4509. pg_data_t *node = NODE_DATA(node_order[i]);
  4510. nr_zones = build_zonerefs_node(node, zonerefs);
  4511. zonerefs += nr_zones;
  4512. }
  4513. zonerefs->zone = NULL;
  4514. zonerefs->zone_idx = 0;
  4515. }
  4516. /*
  4517. * Build gfp_thisnode zonelists
  4518. */
  4519. static void build_thisnode_zonelists(pg_data_t *pgdat)
  4520. {
  4521. struct zoneref *zonerefs;
  4522. int nr_zones;
  4523. zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
  4524. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4525. zonerefs += nr_zones;
  4526. zonerefs->zone = NULL;
  4527. zonerefs->zone_idx = 0;
  4528. }
  4529. /*
  4530. * Build zonelists ordered by zone and nodes within zones.
  4531. * This results in conserving DMA zone[s] until all Normal memory is
  4532. * exhausted, but results in overflowing to remote node while memory
  4533. * may still exist in local DMA zone.
  4534. */
  4535. static void build_zonelists(pg_data_t *pgdat)
  4536. {
  4537. static int node_order[MAX_NUMNODES];
  4538. int node, load, nr_nodes = 0;
  4539. nodemask_t used_mask;
  4540. int local_node, prev_node;
  4541. /* NUMA-aware ordering of nodes */
  4542. local_node = pgdat->node_id;
  4543. load = nr_online_nodes;
  4544. prev_node = local_node;
  4545. nodes_clear(used_mask);
  4546. memset(node_order, 0, sizeof(node_order));
  4547. while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
  4548. /*
  4549. * We don't want to pressure a particular node.
  4550. * So adding penalty to the first node in same
  4551. * distance group to make it round-robin.
  4552. */
  4553. if (node_distance(local_node, node) !=
  4554. node_distance(local_node, prev_node))
  4555. node_load[node] = load;
  4556. node_order[nr_nodes++] = node;
  4557. prev_node = node;
  4558. load--;
  4559. }
  4560. build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
  4561. build_thisnode_zonelists(pgdat);
  4562. }
  4563. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4564. /*
  4565. * Return node id of node used for "local" allocations.
  4566. * I.e., first node id of first zone in arg node's generic zonelist.
  4567. * Used for initializing percpu 'numa_mem', which is used primarily
  4568. * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
  4569. */
  4570. int local_memory_node(int node)
  4571. {
  4572. struct zoneref *z;
  4573. z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
  4574. gfp_zone(GFP_KERNEL),
  4575. NULL);
  4576. return zone_to_nid(z->zone);
  4577. }
  4578. #endif
  4579. static void setup_min_unmapped_ratio(void);
  4580. static void setup_min_slab_ratio(void);
  4581. #else /* CONFIG_NUMA */
  4582. static void build_zonelists(pg_data_t *pgdat)
  4583. {
  4584. int node, local_node;
  4585. struct zoneref *zonerefs;
  4586. int nr_zones;
  4587. local_node = pgdat->node_id;
  4588. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4589. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4590. zonerefs += nr_zones;
  4591. /*
  4592. * Now we build the zonelist so that it contains the zones
  4593. * of all the other nodes.
  4594. * We don't want to pressure a particular node, so when
  4595. * building the zones for node N, we make sure that the
  4596. * zones coming right after the local ones are those from
  4597. * node N+1 (modulo N)
  4598. */
  4599. for (node = local_node + 1; node < MAX_NUMNODES; node++) {
  4600. if (!node_online(node))
  4601. continue;
  4602. nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
  4603. zonerefs += nr_zones;
  4604. }
  4605. for (node = 0; node < local_node; node++) {
  4606. if (!node_online(node))
  4607. continue;
  4608. nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
  4609. zonerefs += nr_zones;
  4610. }
  4611. zonerefs->zone = NULL;
  4612. zonerefs->zone_idx = 0;
  4613. }
  4614. #endif /* CONFIG_NUMA */
  4615. /*
  4616. * Boot pageset table. One per cpu which is going to be used for all
  4617. * zones and all nodes. The parameters will be set in such a way
  4618. * that an item put on a list will immediately be handed over to
  4619. * the buddy list. This is safe since pageset manipulation is done
  4620. * with interrupts disabled.
  4621. *
  4622. * The boot_pagesets must be kept even after bootup is complete for
  4623. * unused processors and/or zones. They do play a role for bootstrapping
  4624. * hotplugged processors.
  4625. *
  4626. * zoneinfo_show() and maybe other functions do
  4627. * not check if the processor is online before following the pageset pointer.
  4628. * Other parts of the kernel may not check if the zone is available.
  4629. */
  4630. static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
  4631. static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
  4632. static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
  4633. static void __build_all_zonelists(void *data)
  4634. {
  4635. int nid;
  4636. int __maybe_unused cpu;
  4637. pg_data_t *self = data;
  4638. static DEFINE_SPINLOCK(lock);
  4639. spin_lock(&lock);
  4640. #ifdef CONFIG_NUMA
  4641. memset(node_load, 0, sizeof(node_load));
  4642. #endif
  4643. /*
  4644. * This node is hotadded and no memory is yet present. So just
  4645. * building zonelists is fine - no need to touch other nodes.
  4646. */
  4647. if (self && !node_online(self->node_id)) {
  4648. build_zonelists(self);
  4649. } else {
  4650. for_each_online_node(nid) {
  4651. pg_data_t *pgdat = NODE_DATA(nid);
  4652. build_zonelists(pgdat);
  4653. }
  4654. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4655. /*
  4656. * We now know the "local memory node" for each node--
  4657. * i.e., the node of the first zone in the generic zonelist.
  4658. * Set up numa_mem percpu variable for on-line cpus. During
  4659. * boot, only the boot cpu should be on-line; we'll init the
  4660. * secondary cpus' numa_mem as they come on-line. During
  4661. * node/memory hotplug, we'll fixup all on-line cpus.
  4662. */
  4663. for_each_online_cpu(cpu)
  4664. set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
  4665. #endif
  4666. }
  4667. spin_unlock(&lock);
  4668. }
  4669. static noinline void __init
  4670. build_all_zonelists_init(void)
  4671. {
  4672. int cpu;
  4673. __build_all_zonelists(NULL);
  4674. /*
  4675. * Initialize the boot_pagesets that are going to be used
  4676. * for bootstrapping processors. The real pagesets for
  4677. * each zone will be allocated later when the per cpu
  4678. * allocator is available.
  4679. *
  4680. * boot_pagesets are used also for bootstrapping offline
  4681. * cpus if the system is already booted because the pagesets
  4682. * are needed to initialize allocators on a specific cpu too.
  4683. * F.e. the percpu allocator needs the page allocator which
  4684. * needs the percpu allocator in order to allocate its pagesets
  4685. * (a chicken-egg dilemma).
  4686. */
  4687. for_each_possible_cpu(cpu)
  4688. setup_pageset(&per_cpu(boot_pageset, cpu), 0);
  4689. mminit_verify_zonelist();
  4690. cpuset_init_current_mems_allowed();
  4691. }
  4692. /*
  4693. * unless system_state == SYSTEM_BOOTING.
  4694. *
  4695. * __ref due to call of __init annotated helper build_all_zonelists_init
  4696. * [protected by SYSTEM_BOOTING].
  4697. */
  4698. void __ref build_all_zonelists(pg_data_t *pgdat)
  4699. {
  4700. if (system_state == SYSTEM_BOOTING) {
  4701. build_all_zonelists_init();
  4702. } else {
  4703. __build_all_zonelists(pgdat);
  4704. /* cpuset refresh routine should be here */
  4705. }
  4706. vm_total_pages = nr_free_pagecache_pages();
  4707. /*
  4708. * Disable grouping by mobility if the number of pages in the
  4709. * system is too low to allow the mechanism to work. It would be
  4710. * more accurate, but expensive to check per-zone. This check is
  4711. * made on memory-hotadd so a system can start with mobility
  4712. * disabled and enable it later
  4713. */
  4714. if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
  4715. page_group_by_mobility_disabled = 1;
  4716. else
  4717. page_group_by_mobility_disabled = 0;
  4718. pr_info("Built %i zonelists, mobility grouping %s. Total pages: %ld\n",
  4719. nr_online_nodes,
  4720. page_group_by_mobility_disabled ? "off" : "on",
  4721. vm_total_pages);
  4722. #ifdef CONFIG_NUMA
  4723. pr_info("Policy zone: %s\n", zone_names[policy_zone]);
  4724. #endif
  4725. }
  4726. /*
  4727. * Initially all pages are reserved - free ones are freed
  4728. * up by free_all_bootmem() once the early boot process is
  4729. * done. Non-atomic initialization, single-pass.
  4730. */
  4731. void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
  4732. unsigned long start_pfn, enum meminit_context context,
  4733. struct vmem_altmap *altmap)
  4734. {
  4735. unsigned long end_pfn = start_pfn + size;
  4736. pg_data_t *pgdat = NODE_DATA(nid);
  4737. unsigned long pfn;
  4738. unsigned long nr_initialised = 0;
  4739. struct page *page;
  4740. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  4741. struct memblock_region *r = NULL, *tmp;
  4742. #endif
  4743. if (highest_memmap_pfn < end_pfn - 1)
  4744. highest_memmap_pfn = end_pfn - 1;
  4745. /*
  4746. * Honor reservation requested by the driver for this ZONE_DEVICE
  4747. * memory
  4748. */
  4749. if (altmap && start_pfn == altmap->base_pfn)
  4750. start_pfn += altmap->reserve;
  4751. for (pfn = start_pfn; pfn < end_pfn; pfn++) {
  4752. /*
  4753. * There can be holes in boot-time mem_map[]s handed to this
  4754. * function. They do not exist on hotplugged memory.
  4755. */
  4756. if (context != MEMINIT_EARLY)
  4757. goto not_early;
  4758. if (!early_pfn_valid(pfn))
  4759. continue;
  4760. if (!early_pfn_in_nid(pfn, nid))
  4761. continue;
  4762. if (!update_defer_init(pgdat, pfn, end_pfn, &nr_initialised))
  4763. break;
  4764. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  4765. /*
  4766. * Check given memblock attribute by firmware which can affect
  4767. * kernel memory layout. If zone==ZONE_MOVABLE but memory is
  4768. * mirrored, it's an overlapped memmap init. skip it.
  4769. */
  4770. if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
  4771. if (!r || pfn >= memblock_region_memory_end_pfn(r)) {
  4772. for_each_memblock(memory, tmp)
  4773. if (pfn < memblock_region_memory_end_pfn(tmp))
  4774. break;
  4775. r = tmp;
  4776. }
  4777. if (pfn >= memblock_region_memory_base_pfn(r) &&
  4778. memblock_is_mirror(r)) {
  4779. /* already initialized as NORMAL */
  4780. pfn = memblock_region_memory_end_pfn(r);
  4781. continue;
  4782. }
  4783. }
  4784. #endif
  4785. not_early:
  4786. page = pfn_to_page(pfn);
  4787. __init_single_page(page, pfn, zone, nid);
  4788. if (context == MEMINIT_HOTPLUG)
  4789. SetPageReserved(page);
  4790. /*
  4791. * Mark the block movable so that blocks are reserved for
  4792. * movable at startup. This will force kernel allocations
  4793. * to reserve their blocks rather than leaking throughout
  4794. * the address space during boot when many long-lived
  4795. * kernel allocations are made.
  4796. *
  4797. * bitmap is created for zone's valid pfn range. but memmap
  4798. * can be created for invalid pages (for alignment)
  4799. * check here not to call set_pageblock_migratetype() against
  4800. * pfn out of zone.
  4801. *
  4802. * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
  4803. * because this is done early in sparse_add_one_section
  4804. */
  4805. if (!(pfn & (pageblock_nr_pages - 1))) {
  4806. set_pageblock_migratetype(page, MIGRATE_MOVABLE);
  4807. cond_resched();
  4808. }
  4809. }
  4810. }
  4811. static void __meminit zone_init_free_lists(struct zone *zone)
  4812. {
  4813. unsigned int order, t;
  4814. for_each_migratetype_order(order, t) {
  4815. INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
  4816. zone->free_area[order].nr_free = 0;
  4817. }
  4818. }
  4819. #ifndef __HAVE_ARCH_MEMMAP_INIT
  4820. #define memmap_init(size, nid, zone, start_pfn) \
  4821. memmap_init_zone((size), (nid), (zone), (start_pfn), \
  4822. MEMINIT_EARLY, NULL)
  4823. #endif
  4824. static int zone_batchsize(struct zone *zone)
  4825. {
  4826. #ifdef CONFIG_MMU
  4827. int batch;
  4828. /*
  4829. * The per-cpu-pages pools are set to around 1000th of the
  4830. * size of the zone.
  4831. */
  4832. batch = zone->managed_pages / 1024;
  4833. /* But no more than a meg. */
  4834. if (batch * PAGE_SIZE > 1024 * 1024)
  4835. batch = (1024 * 1024) / PAGE_SIZE;
  4836. batch /= 4; /* We effectively *= 4 below */
  4837. if (batch < 1)
  4838. batch = 1;
  4839. /*
  4840. * Clamp the batch to a 2^n - 1 value. Having a power
  4841. * of 2 value was found to be more likely to have
  4842. * suboptimal cache aliasing properties in some cases.
  4843. *
  4844. * For example if 2 tasks are alternately allocating
  4845. * batches of pages, one task can end up with a lot
  4846. * of pages of one half of the possible page colors
  4847. * and the other with pages of the other colors.
  4848. */
  4849. batch = rounddown_pow_of_two(batch + batch/2) - 1;
  4850. return batch;
  4851. #else
  4852. /* The deferral and batching of frees should be suppressed under NOMMU
  4853. * conditions.
  4854. *
  4855. * The problem is that NOMMU needs to be able to allocate large chunks
  4856. * of contiguous memory as there's no hardware page translation to
  4857. * assemble apparent contiguous memory from discontiguous pages.
  4858. *
  4859. * Queueing large contiguous runs of pages for batching, however,
  4860. * causes the pages to actually be freed in smaller chunks. As there
  4861. * can be a significant delay between the individual batches being
  4862. * recycled, this leads to the once large chunks of space being
  4863. * fragmented and becoming unavailable for high-order allocations.
  4864. */
  4865. return 0;
  4866. #endif
  4867. }
  4868. /*
  4869. * pcp->high and pcp->batch values are related and dependent on one another:
  4870. * ->batch must never be higher then ->high.
  4871. * The following function updates them in a safe manner without read side
  4872. * locking.
  4873. *
  4874. * Any new users of pcp->batch and pcp->high should ensure they can cope with
  4875. * those fields changing asynchronously (acording the the above rule).
  4876. *
  4877. * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
  4878. * outside of boot time (or some other assurance that no concurrent updaters
  4879. * exist).
  4880. */
  4881. static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
  4882. unsigned long batch)
  4883. {
  4884. /* start with a fail safe value for batch */
  4885. pcp->batch = 1;
  4886. smp_wmb();
  4887. /* Update high, then batch, in order */
  4888. pcp->high = high;
  4889. smp_wmb();
  4890. pcp->batch = batch;
  4891. }
  4892. /* a companion to pageset_set_high() */
  4893. static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
  4894. {
  4895. pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
  4896. }
  4897. static void pageset_init(struct per_cpu_pageset *p)
  4898. {
  4899. struct per_cpu_pages *pcp;
  4900. int migratetype;
  4901. memset(p, 0, sizeof(*p));
  4902. pcp = &p->pcp;
  4903. pcp->count = 0;
  4904. for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
  4905. INIT_LIST_HEAD(&pcp->lists[migratetype]);
  4906. }
  4907. static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
  4908. {
  4909. pageset_init(p);
  4910. pageset_set_batch(p, batch);
  4911. }
  4912. /*
  4913. * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
  4914. * to the value high for the pageset p.
  4915. */
  4916. static void pageset_set_high(struct per_cpu_pageset *p,
  4917. unsigned long high)
  4918. {
  4919. unsigned long batch = max(1UL, high / 4);
  4920. if ((high / 4) > (PAGE_SHIFT * 8))
  4921. batch = PAGE_SHIFT * 8;
  4922. pageset_update(&p->pcp, high, batch);
  4923. }
  4924. static void pageset_set_high_and_batch(struct zone *zone,
  4925. struct per_cpu_pageset *pcp)
  4926. {
  4927. if (percpu_pagelist_fraction)
  4928. pageset_set_high(pcp,
  4929. (zone->managed_pages /
  4930. percpu_pagelist_fraction));
  4931. else
  4932. pageset_set_batch(pcp, zone_batchsize(zone));
  4933. }
  4934. static void __meminit zone_pageset_init(struct zone *zone, int cpu)
  4935. {
  4936. struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
  4937. pageset_init(pcp);
  4938. pageset_set_high_and_batch(zone, pcp);
  4939. }
  4940. void __meminit setup_zone_pageset(struct zone *zone)
  4941. {
  4942. int cpu;
  4943. zone->pageset = alloc_percpu(struct per_cpu_pageset);
  4944. for_each_possible_cpu(cpu)
  4945. zone_pageset_init(zone, cpu);
  4946. }
  4947. /*
  4948. * Allocate per cpu pagesets and initialize them.
  4949. * Before this call only boot pagesets were available.
  4950. */
  4951. void __init setup_per_cpu_pageset(void)
  4952. {
  4953. struct pglist_data *pgdat;
  4954. struct zone *zone;
  4955. for_each_populated_zone(zone)
  4956. setup_zone_pageset(zone);
  4957. for_each_online_pgdat(pgdat)
  4958. pgdat->per_cpu_nodestats =
  4959. alloc_percpu(struct per_cpu_nodestat);
  4960. }
  4961. static __meminit void zone_pcp_init(struct zone *zone)
  4962. {
  4963. /*
  4964. * per cpu subsystem is not up at this point. The following code
  4965. * relies on the ability of the linker to provide the
  4966. * offset of a (static) per cpu variable into the per cpu area.
  4967. */
  4968. zone->pageset = &boot_pageset;
  4969. if (populated_zone(zone))
  4970. printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
  4971. zone->name, zone->present_pages,
  4972. zone_batchsize(zone));
  4973. }
  4974. void __meminit init_currently_empty_zone(struct zone *zone,
  4975. unsigned long zone_start_pfn,
  4976. unsigned long size)
  4977. {
  4978. struct pglist_data *pgdat = zone->zone_pgdat;
  4979. int zone_idx = zone_idx(zone) + 1;
  4980. if (zone_idx > pgdat->nr_zones)
  4981. pgdat->nr_zones = zone_idx;
  4982. zone->zone_start_pfn = zone_start_pfn;
  4983. mminit_dprintk(MMINIT_TRACE, "memmap_init",
  4984. "Initialising map node %d zone %lu pfns %lu -> %lu\n",
  4985. pgdat->node_id,
  4986. (unsigned long)zone_idx(zone),
  4987. zone_start_pfn, (zone_start_pfn + size));
  4988. zone_init_free_lists(zone);
  4989. zone->initialized = 1;
  4990. }
  4991. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  4992. #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
  4993. /*
  4994. * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
  4995. */
  4996. int __meminit __early_pfn_to_nid(unsigned long pfn,
  4997. struct mminit_pfnnid_cache *state)
  4998. {
  4999. unsigned long start_pfn, end_pfn;
  5000. int nid;
  5001. if (state->last_start <= pfn && pfn < state->last_end)
  5002. return state->last_nid;
  5003. nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
  5004. if (nid != -1) {
  5005. state->last_start = start_pfn;
  5006. state->last_end = end_pfn;
  5007. state->last_nid = nid;
  5008. }
  5009. return nid;
  5010. }
  5011. #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
  5012. /**
  5013. * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
  5014. * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
  5015. * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
  5016. *
  5017. * If an architecture guarantees that all ranges registered contain no holes
  5018. * and may be freed, this this function may be used instead of calling
  5019. * memblock_free_early_nid() manually.
  5020. */
  5021. void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
  5022. {
  5023. unsigned long start_pfn, end_pfn;
  5024. int i, this_nid;
  5025. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
  5026. start_pfn = min(start_pfn, max_low_pfn);
  5027. end_pfn = min(end_pfn, max_low_pfn);
  5028. if (start_pfn < end_pfn)
  5029. memblock_free_early_nid(PFN_PHYS(start_pfn),
  5030. (end_pfn - start_pfn) << PAGE_SHIFT,
  5031. this_nid);
  5032. }
  5033. }
  5034. /**
  5035. * sparse_memory_present_with_active_regions - Call memory_present for each active range
  5036. * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
  5037. *
  5038. * If an architecture guarantees that all ranges registered contain no holes and may
  5039. * be freed, this function may be used instead of calling memory_present() manually.
  5040. */
  5041. void __init sparse_memory_present_with_active_regions(int nid)
  5042. {
  5043. unsigned long start_pfn, end_pfn;
  5044. int i, this_nid;
  5045. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
  5046. memory_present(this_nid, start_pfn, end_pfn);
  5047. }
  5048. /**
  5049. * get_pfn_range_for_nid - Return the start and end page frames for a node
  5050. * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
  5051. * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
  5052. * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
  5053. *
  5054. * It returns the start and end page frame of a node based on information
  5055. * provided by memblock_set_node(). If called for a node
  5056. * with no available memory, a warning is printed and the start and end
  5057. * PFNs will be 0.
  5058. */
  5059. void __meminit get_pfn_range_for_nid(unsigned int nid,
  5060. unsigned long *start_pfn, unsigned long *end_pfn)
  5061. {
  5062. unsigned long this_start_pfn, this_end_pfn;
  5063. int i;
  5064. *start_pfn = -1UL;
  5065. *end_pfn = 0;
  5066. for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
  5067. *start_pfn = min(*start_pfn, this_start_pfn);
  5068. *end_pfn = max(*end_pfn, this_end_pfn);
  5069. }
  5070. if (*start_pfn == -1UL)
  5071. *start_pfn = 0;
  5072. }
  5073. /*
  5074. * This finds a zone that can be used for ZONE_MOVABLE pages. The
  5075. * assumption is made that zones within a node are ordered in monotonic
  5076. * increasing memory addresses so that the "highest" populated zone is used
  5077. */
  5078. static void __init find_usable_zone_for_movable(void)
  5079. {
  5080. int zone_index;
  5081. for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
  5082. if (zone_index == ZONE_MOVABLE)
  5083. continue;
  5084. if (arch_zone_highest_possible_pfn[zone_index] >
  5085. arch_zone_lowest_possible_pfn[zone_index])
  5086. break;
  5087. }
  5088. VM_BUG_ON(zone_index == -1);
  5089. movable_zone = zone_index;
  5090. }
  5091. /*
  5092. * The zone ranges provided by the architecture do not include ZONE_MOVABLE
  5093. * because it is sized independent of architecture. Unlike the other zones,
  5094. * the starting point for ZONE_MOVABLE is not fixed. It may be different
  5095. * in each node depending on the size of each node and how evenly kernelcore
  5096. * is distributed. This helper function adjusts the zone ranges
  5097. * provided by the architecture for a given node by using the end of the
  5098. * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
  5099. * zones within a node are in order of monotonic increases memory addresses
  5100. */
  5101. static void __meminit adjust_zone_range_for_zone_movable(int nid,
  5102. unsigned long zone_type,
  5103. unsigned long node_start_pfn,
  5104. unsigned long node_end_pfn,
  5105. unsigned long *zone_start_pfn,
  5106. unsigned long *zone_end_pfn)
  5107. {
  5108. /* Only adjust if ZONE_MOVABLE is on this node */
  5109. if (zone_movable_pfn[nid]) {
  5110. /* Size ZONE_MOVABLE */
  5111. if (zone_type == ZONE_MOVABLE) {
  5112. *zone_start_pfn = zone_movable_pfn[nid];
  5113. *zone_end_pfn = min(node_end_pfn,
  5114. arch_zone_highest_possible_pfn[movable_zone]);
  5115. /* Adjust for ZONE_MOVABLE starting within this range */
  5116. } else if (!mirrored_kernelcore &&
  5117. *zone_start_pfn < zone_movable_pfn[nid] &&
  5118. *zone_end_pfn > zone_movable_pfn[nid]) {
  5119. *zone_end_pfn = zone_movable_pfn[nid];
  5120. /* Check if this whole range is within ZONE_MOVABLE */
  5121. } else if (*zone_start_pfn >= zone_movable_pfn[nid])
  5122. *zone_start_pfn = *zone_end_pfn;
  5123. }
  5124. }
  5125. /*
  5126. * Return the number of pages a zone spans in a node, including holes
  5127. * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
  5128. */
  5129. static unsigned long __meminit zone_spanned_pages_in_node(int nid,
  5130. unsigned long zone_type,
  5131. unsigned long node_start_pfn,
  5132. unsigned long node_end_pfn,
  5133. unsigned long *zone_start_pfn,
  5134. unsigned long *zone_end_pfn,
  5135. unsigned long *ignored)
  5136. {
  5137. unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
  5138. unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
  5139. /* When hotadd a new node from cpu_up(), the node should be empty */
  5140. if (!node_start_pfn && !node_end_pfn)
  5141. return 0;
  5142. /* Get the start and end of the zone */
  5143. *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
  5144. *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
  5145. adjust_zone_range_for_zone_movable(nid, zone_type,
  5146. node_start_pfn, node_end_pfn,
  5147. zone_start_pfn, zone_end_pfn);
  5148. /* Check that this node has pages within the zone's required range */
  5149. if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
  5150. return 0;
  5151. /* Move the zone boundaries inside the node if necessary */
  5152. *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
  5153. *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
  5154. /* Return the spanned pages */
  5155. return *zone_end_pfn - *zone_start_pfn;
  5156. }
  5157. /*
  5158. * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
  5159. * then all holes in the requested range will be accounted for.
  5160. */
  5161. unsigned long __meminit __absent_pages_in_range(int nid,
  5162. unsigned long range_start_pfn,
  5163. unsigned long range_end_pfn)
  5164. {
  5165. unsigned long nr_absent = range_end_pfn - range_start_pfn;
  5166. unsigned long start_pfn, end_pfn;
  5167. int i;
  5168. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
  5169. start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
  5170. end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
  5171. nr_absent -= end_pfn - start_pfn;
  5172. }
  5173. return nr_absent;
  5174. }
  5175. /**
  5176. * absent_pages_in_range - Return number of page frames in holes within a range
  5177. * @start_pfn: The start PFN to start searching for holes
  5178. * @end_pfn: The end PFN to stop searching for holes
  5179. *
  5180. * It returns the number of pages frames in memory holes within a range.
  5181. */
  5182. unsigned long __init absent_pages_in_range(unsigned long start_pfn,
  5183. unsigned long end_pfn)
  5184. {
  5185. return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
  5186. }
  5187. /* Return the number of page frames in holes in a zone on a node */
  5188. static unsigned long __meminit zone_absent_pages_in_node(int nid,
  5189. unsigned long zone_type,
  5190. unsigned long node_start_pfn,
  5191. unsigned long node_end_pfn,
  5192. unsigned long *ignored)
  5193. {
  5194. unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
  5195. unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
  5196. unsigned long zone_start_pfn, zone_end_pfn;
  5197. unsigned long nr_absent;
  5198. /* When hotadd a new node from cpu_up(), the node should be empty */
  5199. if (!node_start_pfn && !node_end_pfn)
  5200. return 0;
  5201. zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
  5202. zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
  5203. adjust_zone_range_for_zone_movable(nid, zone_type,
  5204. node_start_pfn, node_end_pfn,
  5205. &zone_start_pfn, &zone_end_pfn);
  5206. nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
  5207. /*
  5208. * ZONE_MOVABLE handling.
  5209. * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
  5210. * and vice versa.
  5211. */
  5212. if (mirrored_kernelcore && zone_movable_pfn[nid]) {
  5213. unsigned long start_pfn, end_pfn;
  5214. struct memblock_region *r;
  5215. for_each_memblock(memory, r) {
  5216. start_pfn = clamp(memblock_region_memory_base_pfn(r),
  5217. zone_start_pfn, zone_end_pfn);
  5218. end_pfn = clamp(memblock_region_memory_end_pfn(r),
  5219. zone_start_pfn, zone_end_pfn);
  5220. if (zone_type == ZONE_MOVABLE &&
  5221. memblock_is_mirror(r))
  5222. nr_absent += end_pfn - start_pfn;
  5223. if (zone_type == ZONE_NORMAL &&
  5224. !memblock_is_mirror(r))
  5225. nr_absent += end_pfn - start_pfn;
  5226. }
  5227. }
  5228. return nr_absent;
  5229. }
  5230. #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
  5231. static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
  5232. unsigned long zone_type,
  5233. unsigned long node_start_pfn,
  5234. unsigned long node_end_pfn,
  5235. unsigned long *zone_start_pfn,
  5236. unsigned long *zone_end_pfn,
  5237. unsigned long *zones_size)
  5238. {
  5239. unsigned int zone;
  5240. *zone_start_pfn = node_start_pfn;
  5241. for (zone = 0; zone < zone_type; zone++)
  5242. *zone_start_pfn += zones_size[zone];
  5243. *zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
  5244. return zones_size[zone_type];
  5245. }
  5246. static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
  5247. unsigned long zone_type,
  5248. unsigned long node_start_pfn,
  5249. unsigned long node_end_pfn,
  5250. unsigned long *zholes_size)
  5251. {
  5252. if (!zholes_size)
  5253. return 0;
  5254. return zholes_size[zone_type];
  5255. }
  5256. #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
  5257. static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
  5258. unsigned long node_start_pfn,
  5259. unsigned long node_end_pfn,
  5260. unsigned long *zones_size,
  5261. unsigned long *zholes_size)
  5262. {
  5263. unsigned long realtotalpages = 0, totalpages = 0;
  5264. enum zone_type i;
  5265. for (i = 0; i < MAX_NR_ZONES; i++) {
  5266. struct zone *zone = pgdat->node_zones + i;
  5267. unsigned long zone_start_pfn, zone_end_pfn;
  5268. unsigned long size, real_size;
  5269. size = zone_spanned_pages_in_node(pgdat->node_id, i,
  5270. node_start_pfn,
  5271. node_end_pfn,
  5272. &zone_start_pfn,
  5273. &zone_end_pfn,
  5274. zones_size);
  5275. real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
  5276. node_start_pfn, node_end_pfn,
  5277. zholes_size);
  5278. if (size)
  5279. zone->zone_start_pfn = zone_start_pfn;
  5280. else
  5281. zone->zone_start_pfn = 0;
  5282. zone->spanned_pages = size;
  5283. zone->present_pages = real_size;
  5284. totalpages += size;
  5285. realtotalpages += real_size;
  5286. }
  5287. pgdat->node_spanned_pages = totalpages;
  5288. pgdat->node_present_pages = realtotalpages;
  5289. printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
  5290. realtotalpages);
  5291. }
  5292. #ifndef CONFIG_SPARSEMEM
  5293. /*
  5294. * Calculate the size of the zone->blockflags rounded to an unsigned long
  5295. * Start by making sure zonesize is a multiple of pageblock_order by rounding
  5296. * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
  5297. * round what is now in bits to nearest long in bits, then return it in
  5298. * bytes.
  5299. */
  5300. static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
  5301. {
  5302. unsigned long usemapsize;
  5303. zonesize += zone_start_pfn & (pageblock_nr_pages-1);
  5304. usemapsize = roundup(zonesize, pageblock_nr_pages);
  5305. usemapsize = usemapsize >> pageblock_order;
  5306. usemapsize *= NR_PAGEBLOCK_BITS;
  5307. usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
  5308. return usemapsize / 8;
  5309. }
  5310. static void __ref setup_usemap(struct pglist_data *pgdat,
  5311. struct zone *zone,
  5312. unsigned long zone_start_pfn,
  5313. unsigned long zonesize)
  5314. {
  5315. unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
  5316. zone->pageblock_flags = NULL;
  5317. if (usemapsize)
  5318. zone->pageblock_flags =
  5319. memblock_virt_alloc_node_nopanic(usemapsize,
  5320. pgdat->node_id);
  5321. }
  5322. #else
  5323. static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
  5324. unsigned long zone_start_pfn, unsigned long zonesize) {}
  5325. #endif /* CONFIG_SPARSEMEM */
  5326. #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
  5327. /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
  5328. void __init set_pageblock_order(void)
  5329. {
  5330. unsigned int order;
  5331. /* Check that pageblock_nr_pages has not already been setup */
  5332. if (pageblock_order)
  5333. return;
  5334. if (HPAGE_SHIFT > PAGE_SHIFT)
  5335. order = HUGETLB_PAGE_ORDER;
  5336. else
  5337. order = MAX_ORDER - 1;
  5338. /*
  5339. * Assume the largest contiguous order of interest is a huge page.
  5340. * This value may be variable depending on boot parameters on IA64 and
  5341. * powerpc.
  5342. */
  5343. pageblock_order = order;
  5344. }
  5345. #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
  5346. /*
  5347. * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
  5348. * is unused as pageblock_order is set at compile-time. See
  5349. * include/linux/pageblock-flags.h for the values of pageblock_order based on
  5350. * the kernel config
  5351. */
  5352. void __init set_pageblock_order(void)
  5353. {
  5354. }
  5355. #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
  5356. static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
  5357. unsigned long present_pages)
  5358. {
  5359. unsigned long pages = spanned_pages;
  5360. /*
  5361. * Provide a more accurate estimation if there are holes within
  5362. * the zone and SPARSEMEM is in use. If there are holes within the
  5363. * zone, each populated memory region may cost us one or two extra
  5364. * memmap pages due to alignment because memmap pages for each
  5365. * populated regions may not be naturally aligned on page boundary.
  5366. * So the (present_pages >> 4) heuristic is a tradeoff for that.
  5367. */
  5368. if (spanned_pages > present_pages + (present_pages >> 4) &&
  5369. IS_ENABLED(CONFIG_SPARSEMEM))
  5370. pages = present_pages;
  5371. return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
  5372. }
  5373. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  5374. static void pgdat_init_split_queue(struct pglist_data *pgdat)
  5375. {
  5376. spin_lock_init(&pgdat->split_queue_lock);
  5377. INIT_LIST_HEAD(&pgdat->split_queue);
  5378. pgdat->split_queue_len = 0;
  5379. }
  5380. #else
  5381. static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
  5382. #endif
  5383. #ifdef CONFIG_COMPACTION
  5384. static void pgdat_init_kcompactd(struct pglist_data *pgdat)
  5385. {
  5386. init_waitqueue_head(&pgdat->kcompactd_wait);
  5387. }
  5388. #else
  5389. static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
  5390. #endif
  5391. static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
  5392. {
  5393. pgdat_resize_init(pgdat);
  5394. pgdat_init_split_queue(pgdat);
  5395. pgdat_init_kcompactd(pgdat);
  5396. init_waitqueue_head(&pgdat->kswapd_wait);
  5397. init_waitqueue_head(&pgdat->pfmemalloc_wait);
  5398. pgdat_page_ext_init(pgdat);
  5399. spin_lock_init(&pgdat->lru_lock);
  5400. lruvec_init(node_lruvec(pgdat));
  5401. }
  5402. static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
  5403. unsigned long remaining_pages)
  5404. {
  5405. zone->managed_pages = remaining_pages;
  5406. zone_set_nid(zone, nid);
  5407. zone->name = zone_names[idx];
  5408. zone->zone_pgdat = NODE_DATA(nid);
  5409. spin_lock_init(&zone->lock);
  5410. zone_seqlock_init(zone);
  5411. zone_pcp_init(zone);
  5412. }
  5413. /*
  5414. * Set up the zone data structures
  5415. * - init pgdat internals
  5416. * - init all zones belonging to this node
  5417. *
  5418. * NOTE: this function is only called during memory hotplug
  5419. */
  5420. #ifdef CONFIG_MEMORY_HOTPLUG
  5421. void __ref free_area_init_core_hotplug(int nid)
  5422. {
  5423. enum zone_type z;
  5424. pg_data_t *pgdat = NODE_DATA(nid);
  5425. pgdat_init_internals(pgdat);
  5426. for (z = 0; z < MAX_NR_ZONES; z++)
  5427. zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
  5428. }
  5429. #endif
  5430. /*
  5431. * Set up the zone data structures:
  5432. * - mark all pages reserved
  5433. * - mark all memory queues empty
  5434. * - clear the memory bitmaps
  5435. *
  5436. * NOTE: pgdat should get zeroed by caller.
  5437. * NOTE: this function is only called during early init.
  5438. */
  5439. static void __init free_area_init_core(struct pglist_data *pgdat)
  5440. {
  5441. enum zone_type j;
  5442. int nid = pgdat->node_id;
  5443. pgdat_init_internals(pgdat);
  5444. pgdat->per_cpu_nodestats = &boot_nodestats;
  5445. for (j = 0; j < MAX_NR_ZONES; j++) {
  5446. struct zone *zone = pgdat->node_zones + j;
  5447. unsigned long size, freesize, memmap_pages;
  5448. unsigned long zone_start_pfn = zone->zone_start_pfn;
  5449. size = zone->spanned_pages;
  5450. freesize = zone->present_pages;
  5451. /*
  5452. * Adjust freesize so that it accounts for how much memory
  5453. * is used by this zone for memmap. This affects the watermark
  5454. * and per-cpu initialisations
  5455. */
  5456. memmap_pages = calc_memmap_size(size, freesize);
  5457. if (!is_highmem_idx(j)) {
  5458. if (freesize >= memmap_pages) {
  5459. freesize -= memmap_pages;
  5460. if (memmap_pages)
  5461. printk(KERN_DEBUG
  5462. " %s zone: %lu pages used for memmap\n",
  5463. zone_names[j], memmap_pages);
  5464. } else
  5465. pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
  5466. zone_names[j], memmap_pages, freesize);
  5467. }
  5468. /* Account for reserved pages */
  5469. if (j == 0 && freesize > dma_reserve) {
  5470. freesize -= dma_reserve;
  5471. printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
  5472. zone_names[0], dma_reserve);
  5473. }
  5474. if (!is_highmem_idx(j))
  5475. nr_kernel_pages += freesize;
  5476. /* Charge for highmem memmap if there are enough kernel pages */
  5477. else if (nr_kernel_pages > memmap_pages * 2)
  5478. nr_kernel_pages -= memmap_pages;
  5479. nr_all_pages += freesize;
  5480. /*
  5481. * Set an approximate value for lowmem here, it will be adjusted
  5482. * when the bootmem allocator frees pages into the buddy system.
  5483. * And all highmem pages will be managed by the buddy system.
  5484. */
  5485. zone_init_internals(zone, j, nid, freesize);
  5486. if (!size)
  5487. continue;
  5488. set_pageblock_order();
  5489. setup_usemap(pgdat, zone, zone_start_pfn, size);
  5490. init_currently_empty_zone(zone, zone_start_pfn, size);
  5491. memmap_init(size, nid, j, zone_start_pfn);
  5492. }
  5493. }
  5494. #ifdef CONFIG_FLAT_NODE_MEM_MAP
  5495. static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
  5496. {
  5497. unsigned long __maybe_unused start = 0;
  5498. unsigned long __maybe_unused offset = 0;
  5499. /* Skip empty nodes */
  5500. if (!pgdat->node_spanned_pages)
  5501. return;
  5502. start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
  5503. offset = pgdat->node_start_pfn - start;
  5504. /* ia64 gets its own node_mem_map, before this, without bootmem */
  5505. if (!pgdat->node_mem_map) {
  5506. unsigned long size, end;
  5507. struct page *map;
  5508. /*
  5509. * The zone's endpoints aren't required to be MAX_ORDER
  5510. * aligned but the node_mem_map endpoints must be in order
  5511. * for the buddy allocator to function correctly.
  5512. */
  5513. end = pgdat_end_pfn(pgdat);
  5514. end = ALIGN(end, MAX_ORDER_NR_PAGES);
  5515. size = (end - start) * sizeof(struct page);
  5516. map = memblock_virt_alloc_node_nopanic(size, pgdat->node_id);
  5517. pgdat->node_mem_map = map + offset;
  5518. }
  5519. pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
  5520. __func__, pgdat->node_id, (unsigned long)pgdat,
  5521. (unsigned long)pgdat->node_mem_map);
  5522. #ifndef CONFIG_NEED_MULTIPLE_NODES
  5523. /*
  5524. * With no DISCONTIG, the global mem_map is just set as node 0's
  5525. */
  5526. if (pgdat == NODE_DATA(0)) {
  5527. mem_map = NODE_DATA(0)->node_mem_map;
  5528. #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
  5529. if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
  5530. mem_map -= offset;
  5531. #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
  5532. }
  5533. #endif
  5534. }
  5535. #else
  5536. static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
  5537. #endif /* CONFIG_FLAT_NODE_MEM_MAP */
  5538. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  5539. static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
  5540. {
  5541. /*
  5542. * We start only with one section of pages, more pages are added as
  5543. * needed until the rest of deferred pages are initialized.
  5544. */
  5545. pgdat->static_init_pgcnt = min_t(unsigned long, PAGES_PER_SECTION,
  5546. pgdat->node_spanned_pages);
  5547. pgdat->first_deferred_pfn = ULONG_MAX;
  5548. }
  5549. #else
  5550. static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
  5551. #endif
  5552. void __init free_area_init_node(int nid, unsigned long *zones_size,
  5553. unsigned long node_start_pfn,
  5554. unsigned long *zholes_size)
  5555. {
  5556. pg_data_t *pgdat = NODE_DATA(nid);
  5557. unsigned long start_pfn = 0;
  5558. unsigned long end_pfn = 0;
  5559. /* pg_data_t should be reset to zero when it's allocated */
  5560. WARN_ON(pgdat->nr_zones || pgdat->kswapd_classzone_idx);
  5561. pgdat->node_id = nid;
  5562. pgdat->node_start_pfn = node_start_pfn;
  5563. pgdat->per_cpu_nodestats = NULL;
  5564. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  5565. get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
  5566. pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
  5567. (u64)start_pfn << PAGE_SHIFT,
  5568. end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
  5569. #else
  5570. start_pfn = node_start_pfn;
  5571. #endif
  5572. calculate_node_totalpages(pgdat, start_pfn, end_pfn,
  5573. zones_size, zholes_size);
  5574. alloc_node_mem_map(pgdat);
  5575. pgdat_set_deferred_range(pgdat);
  5576. free_area_init_core(pgdat);
  5577. }
  5578. #if defined(CONFIG_HAVE_MEMBLOCK) && !defined(CONFIG_FLAT_NODE_MEM_MAP)
  5579. /*
  5580. * Zero all valid struct pages in range [spfn, epfn), return number of struct
  5581. * pages zeroed
  5582. */
  5583. static u64 zero_pfn_range(unsigned long spfn, unsigned long epfn)
  5584. {
  5585. unsigned long pfn;
  5586. u64 pgcnt = 0;
  5587. for (pfn = spfn; pfn < epfn; pfn++) {
  5588. if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
  5589. pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
  5590. + pageblock_nr_pages - 1;
  5591. continue;
  5592. }
  5593. mm_zero_struct_page(pfn_to_page(pfn));
  5594. pgcnt++;
  5595. }
  5596. return pgcnt;
  5597. }
  5598. /*
  5599. * Only struct pages that are backed by physical memory are zeroed and
  5600. * initialized by going through __init_single_page(). But, there are some
  5601. * struct pages which are reserved in memblock allocator and their fields
  5602. * may be accessed (for example page_to_pfn() on some configuration accesses
  5603. * flags). We must explicitly zero those struct pages.
  5604. *
  5605. * This function also addresses a similar issue where struct pages are left
  5606. * uninitialized because the physical address range is not covered by
  5607. * memblock.memory or memblock.reserved. That could happen when memblock
  5608. * layout is manually configured via memmap=, or when the highest physical
  5609. * address (max_pfn) does not end on a section boundary.
  5610. */
  5611. void __init zero_resv_unavail(void)
  5612. {
  5613. phys_addr_t start, end;
  5614. u64 i, pgcnt;
  5615. phys_addr_t next = 0;
  5616. /*
  5617. * Loop through unavailable ranges not covered by memblock.memory.
  5618. */
  5619. pgcnt = 0;
  5620. for_each_mem_range(i, &memblock.memory, NULL,
  5621. NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
  5622. if (next < start)
  5623. pgcnt += zero_pfn_range(PFN_DOWN(next), PFN_UP(start));
  5624. next = end;
  5625. }
  5626. /*
  5627. * Early sections always have a fully populated memmap for the whole
  5628. * section - see pfn_valid(). If the last section has holes at the
  5629. * end and that section is marked "online", the memmap will be
  5630. * considered initialized. Make sure that memmap has a well defined
  5631. * state.
  5632. */
  5633. pgcnt += zero_pfn_range(PFN_DOWN(next),
  5634. round_up(max_pfn, PAGES_PER_SECTION));
  5635. /*
  5636. * Struct pages that do not have backing memory. This could be because
  5637. * firmware is using some of this memory, or for some other reasons.
  5638. */
  5639. if (pgcnt)
  5640. pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
  5641. }
  5642. #endif /* CONFIG_HAVE_MEMBLOCK && !CONFIG_FLAT_NODE_MEM_MAP */
  5643. #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
  5644. #if MAX_NUMNODES > 1
  5645. /*
  5646. * Figure out the number of possible node ids.
  5647. */
  5648. void __init setup_nr_node_ids(void)
  5649. {
  5650. unsigned int highest;
  5651. highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
  5652. nr_node_ids = highest + 1;
  5653. }
  5654. #endif
  5655. /**
  5656. * node_map_pfn_alignment - determine the maximum internode alignment
  5657. *
  5658. * This function should be called after node map is populated and sorted.
  5659. * It calculates the maximum power of two alignment which can distinguish
  5660. * all the nodes.
  5661. *
  5662. * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
  5663. * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
  5664. * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
  5665. * shifted, 1GiB is enough and this function will indicate so.
  5666. *
  5667. * This is used to test whether pfn -> nid mapping of the chosen memory
  5668. * model has fine enough granularity to avoid incorrect mapping for the
  5669. * populated node map.
  5670. *
  5671. * Returns the determined alignment in pfn's. 0 if there is no alignment
  5672. * requirement (single node).
  5673. */
  5674. unsigned long __init node_map_pfn_alignment(void)
  5675. {
  5676. unsigned long accl_mask = 0, last_end = 0;
  5677. unsigned long start, end, mask;
  5678. int last_nid = -1;
  5679. int i, nid;
  5680. for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
  5681. if (!start || last_nid < 0 || last_nid == nid) {
  5682. last_nid = nid;
  5683. last_end = end;
  5684. continue;
  5685. }
  5686. /*
  5687. * Start with a mask granular enough to pin-point to the
  5688. * start pfn and tick off bits one-by-one until it becomes
  5689. * too coarse to separate the current node from the last.
  5690. */
  5691. mask = ~((1 << __ffs(start)) - 1);
  5692. while (mask && last_end <= (start & (mask << 1)))
  5693. mask <<= 1;
  5694. /* accumulate all internode masks */
  5695. accl_mask |= mask;
  5696. }
  5697. /* convert mask to number of pages */
  5698. return ~accl_mask + 1;
  5699. }
  5700. /* Find the lowest pfn for a node */
  5701. static unsigned long __init find_min_pfn_for_node(int nid)
  5702. {
  5703. unsigned long min_pfn = ULONG_MAX;
  5704. unsigned long start_pfn;
  5705. int i;
  5706. for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
  5707. min_pfn = min(min_pfn, start_pfn);
  5708. if (min_pfn == ULONG_MAX) {
  5709. pr_warn("Could not find start_pfn for node %d\n", nid);
  5710. return 0;
  5711. }
  5712. return min_pfn;
  5713. }
  5714. /**
  5715. * find_min_pfn_with_active_regions - Find the minimum PFN registered
  5716. *
  5717. * It returns the minimum PFN based on information provided via
  5718. * memblock_set_node().
  5719. */
  5720. unsigned long __init find_min_pfn_with_active_regions(void)
  5721. {
  5722. return find_min_pfn_for_node(MAX_NUMNODES);
  5723. }
  5724. /*
  5725. * early_calculate_totalpages()
  5726. * Sum pages in active regions for movable zone.
  5727. * Populate N_MEMORY for calculating usable_nodes.
  5728. */
  5729. static unsigned long __init early_calculate_totalpages(void)
  5730. {
  5731. unsigned long totalpages = 0;
  5732. unsigned long start_pfn, end_pfn;
  5733. int i, nid;
  5734. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
  5735. unsigned long pages = end_pfn - start_pfn;
  5736. totalpages += pages;
  5737. if (pages)
  5738. node_set_state(nid, N_MEMORY);
  5739. }
  5740. return totalpages;
  5741. }
  5742. /*
  5743. * Find the PFN the Movable zone begins in each node. Kernel memory
  5744. * is spread evenly between nodes as long as the nodes have enough
  5745. * memory. When they don't, some nodes will have more kernelcore than
  5746. * others
  5747. */
  5748. static void __init find_zone_movable_pfns_for_nodes(void)
  5749. {
  5750. int i, nid;
  5751. unsigned long usable_startpfn;
  5752. unsigned long kernelcore_node, kernelcore_remaining;
  5753. /* save the state before borrow the nodemask */
  5754. nodemask_t saved_node_state = node_states[N_MEMORY];
  5755. unsigned long totalpages = early_calculate_totalpages();
  5756. int usable_nodes = nodes_weight(node_states[N_MEMORY]);
  5757. struct memblock_region *r;
  5758. /* Need to find movable_zone earlier when movable_node is specified. */
  5759. find_usable_zone_for_movable();
  5760. /*
  5761. * If movable_node is specified, ignore kernelcore and movablecore
  5762. * options.
  5763. */
  5764. if (movable_node_is_enabled()) {
  5765. for_each_memblock(memory, r) {
  5766. if (!memblock_is_hotpluggable(r))
  5767. continue;
  5768. nid = r->nid;
  5769. usable_startpfn = PFN_DOWN(r->base);
  5770. zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
  5771. min(usable_startpfn, zone_movable_pfn[nid]) :
  5772. usable_startpfn;
  5773. }
  5774. goto out2;
  5775. }
  5776. /*
  5777. * If kernelcore=mirror is specified, ignore movablecore option
  5778. */
  5779. if (mirrored_kernelcore) {
  5780. bool mem_below_4gb_not_mirrored = false;
  5781. for_each_memblock(memory, r) {
  5782. if (memblock_is_mirror(r))
  5783. continue;
  5784. nid = r->nid;
  5785. usable_startpfn = memblock_region_memory_base_pfn(r);
  5786. if (usable_startpfn < 0x100000) {
  5787. mem_below_4gb_not_mirrored = true;
  5788. continue;
  5789. }
  5790. zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
  5791. min(usable_startpfn, zone_movable_pfn[nid]) :
  5792. usable_startpfn;
  5793. }
  5794. if (mem_below_4gb_not_mirrored)
  5795. pr_warn("This configuration results in unmirrored kernel memory.");
  5796. goto out2;
  5797. }
  5798. /*
  5799. * If kernelcore=nn% or movablecore=nn% was specified, calculate the
  5800. * amount of necessary memory.
  5801. */
  5802. if (required_kernelcore_percent)
  5803. required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
  5804. 10000UL;
  5805. if (required_movablecore_percent)
  5806. required_movablecore = (totalpages * 100 * required_movablecore_percent) /
  5807. 10000UL;
  5808. /*
  5809. * If movablecore= was specified, calculate what size of
  5810. * kernelcore that corresponds so that memory usable for
  5811. * any allocation type is evenly spread. If both kernelcore
  5812. * and movablecore are specified, then the value of kernelcore
  5813. * will be used for required_kernelcore if it's greater than
  5814. * what movablecore would have allowed.
  5815. */
  5816. if (required_movablecore) {
  5817. unsigned long corepages;
  5818. /*
  5819. * Round-up so that ZONE_MOVABLE is at least as large as what
  5820. * was requested by the user
  5821. */
  5822. required_movablecore =
  5823. roundup(required_movablecore, MAX_ORDER_NR_PAGES);
  5824. required_movablecore = min(totalpages, required_movablecore);
  5825. corepages = totalpages - required_movablecore;
  5826. required_kernelcore = max(required_kernelcore, corepages);
  5827. }
  5828. /*
  5829. * If kernelcore was not specified or kernelcore size is larger
  5830. * than totalpages, there is no ZONE_MOVABLE.
  5831. */
  5832. if (!required_kernelcore || required_kernelcore >= totalpages)
  5833. goto out;
  5834. /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
  5835. usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
  5836. restart:
  5837. /* Spread kernelcore memory as evenly as possible throughout nodes */
  5838. kernelcore_node = required_kernelcore / usable_nodes;
  5839. for_each_node_state(nid, N_MEMORY) {
  5840. unsigned long start_pfn, end_pfn;
  5841. /*
  5842. * Recalculate kernelcore_node if the division per node
  5843. * now exceeds what is necessary to satisfy the requested
  5844. * amount of memory for the kernel
  5845. */
  5846. if (required_kernelcore < kernelcore_node)
  5847. kernelcore_node = required_kernelcore / usable_nodes;
  5848. /*
  5849. * As the map is walked, we track how much memory is usable
  5850. * by the kernel using kernelcore_remaining. When it is
  5851. * 0, the rest of the node is usable by ZONE_MOVABLE
  5852. */
  5853. kernelcore_remaining = kernelcore_node;
  5854. /* Go through each range of PFNs within this node */
  5855. for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
  5856. unsigned long size_pages;
  5857. start_pfn = max(start_pfn, zone_movable_pfn[nid]);
  5858. if (start_pfn >= end_pfn)
  5859. continue;
  5860. /* Account for what is only usable for kernelcore */
  5861. if (start_pfn < usable_startpfn) {
  5862. unsigned long kernel_pages;
  5863. kernel_pages = min(end_pfn, usable_startpfn)
  5864. - start_pfn;
  5865. kernelcore_remaining -= min(kernel_pages,
  5866. kernelcore_remaining);
  5867. required_kernelcore -= min(kernel_pages,
  5868. required_kernelcore);
  5869. /* Continue if range is now fully accounted */
  5870. if (end_pfn <= usable_startpfn) {
  5871. /*
  5872. * Push zone_movable_pfn to the end so
  5873. * that if we have to rebalance
  5874. * kernelcore across nodes, we will
  5875. * not double account here
  5876. */
  5877. zone_movable_pfn[nid] = end_pfn;
  5878. continue;
  5879. }
  5880. start_pfn = usable_startpfn;
  5881. }
  5882. /*
  5883. * The usable PFN range for ZONE_MOVABLE is from
  5884. * start_pfn->end_pfn. Calculate size_pages as the
  5885. * number of pages used as kernelcore
  5886. */
  5887. size_pages = end_pfn - start_pfn;
  5888. if (size_pages > kernelcore_remaining)
  5889. size_pages = kernelcore_remaining;
  5890. zone_movable_pfn[nid] = start_pfn + size_pages;
  5891. /*
  5892. * Some kernelcore has been met, update counts and
  5893. * break if the kernelcore for this node has been
  5894. * satisfied
  5895. */
  5896. required_kernelcore -= min(required_kernelcore,
  5897. size_pages);
  5898. kernelcore_remaining -= size_pages;
  5899. if (!kernelcore_remaining)
  5900. break;
  5901. }
  5902. }
  5903. /*
  5904. * If there is still required_kernelcore, we do another pass with one
  5905. * less node in the count. This will push zone_movable_pfn[nid] further
  5906. * along on the nodes that still have memory until kernelcore is
  5907. * satisfied
  5908. */
  5909. usable_nodes--;
  5910. if (usable_nodes && required_kernelcore > usable_nodes)
  5911. goto restart;
  5912. out2:
  5913. /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
  5914. for (nid = 0; nid < MAX_NUMNODES; nid++)
  5915. zone_movable_pfn[nid] =
  5916. roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
  5917. out:
  5918. /* restore the node_state */
  5919. node_states[N_MEMORY] = saved_node_state;
  5920. }
  5921. /* Any regular or high memory on that node ? */
  5922. static void check_for_memory(pg_data_t *pgdat, int nid)
  5923. {
  5924. enum zone_type zone_type;
  5925. if (N_MEMORY == N_NORMAL_MEMORY)
  5926. return;
  5927. for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
  5928. struct zone *zone = &pgdat->node_zones[zone_type];
  5929. if (populated_zone(zone)) {
  5930. node_set_state(nid, N_HIGH_MEMORY);
  5931. if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
  5932. zone_type <= ZONE_NORMAL)
  5933. node_set_state(nid, N_NORMAL_MEMORY);
  5934. break;
  5935. }
  5936. }
  5937. }
  5938. /**
  5939. * free_area_init_nodes - Initialise all pg_data_t and zone data
  5940. * @max_zone_pfn: an array of max PFNs for each zone
  5941. *
  5942. * This will call free_area_init_node() for each active node in the system.
  5943. * Using the page ranges provided by memblock_set_node(), the size of each
  5944. * zone in each node and their holes is calculated. If the maximum PFN
  5945. * between two adjacent zones match, it is assumed that the zone is empty.
  5946. * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
  5947. * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
  5948. * starts where the previous one ended. For example, ZONE_DMA32 starts
  5949. * at arch_max_dma_pfn.
  5950. */
  5951. void __init free_area_init_nodes(unsigned long *max_zone_pfn)
  5952. {
  5953. unsigned long start_pfn, end_pfn;
  5954. int i, nid;
  5955. /* Record where the zone boundaries are */
  5956. memset(arch_zone_lowest_possible_pfn, 0,
  5957. sizeof(arch_zone_lowest_possible_pfn));
  5958. memset(arch_zone_highest_possible_pfn, 0,
  5959. sizeof(arch_zone_highest_possible_pfn));
  5960. start_pfn = find_min_pfn_with_active_regions();
  5961. for (i = 0; i < MAX_NR_ZONES; i++) {
  5962. if (i == ZONE_MOVABLE)
  5963. continue;
  5964. end_pfn = max(max_zone_pfn[i], start_pfn);
  5965. arch_zone_lowest_possible_pfn[i] = start_pfn;
  5966. arch_zone_highest_possible_pfn[i] = end_pfn;
  5967. start_pfn = end_pfn;
  5968. }
  5969. /* Find the PFNs that ZONE_MOVABLE begins at in each node */
  5970. memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
  5971. find_zone_movable_pfns_for_nodes();
  5972. /* Print out the zone ranges */
  5973. pr_info("Zone ranges:\n");
  5974. for (i = 0; i < MAX_NR_ZONES; i++) {
  5975. if (i == ZONE_MOVABLE)
  5976. continue;
  5977. pr_info(" %-8s ", zone_names[i]);
  5978. if (arch_zone_lowest_possible_pfn[i] ==
  5979. arch_zone_highest_possible_pfn[i])
  5980. pr_cont("empty\n");
  5981. else
  5982. pr_cont("[mem %#018Lx-%#018Lx]\n",
  5983. (u64)arch_zone_lowest_possible_pfn[i]
  5984. << PAGE_SHIFT,
  5985. ((u64)arch_zone_highest_possible_pfn[i]
  5986. << PAGE_SHIFT) - 1);
  5987. }
  5988. /* Print out the PFNs ZONE_MOVABLE begins at in each node */
  5989. pr_info("Movable zone start for each node\n");
  5990. for (i = 0; i < MAX_NUMNODES; i++) {
  5991. if (zone_movable_pfn[i])
  5992. pr_info(" Node %d: %#018Lx\n", i,
  5993. (u64)zone_movable_pfn[i] << PAGE_SHIFT);
  5994. }
  5995. /* Print out the early node map */
  5996. pr_info("Early memory node ranges\n");
  5997. for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
  5998. pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
  5999. (u64)start_pfn << PAGE_SHIFT,
  6000. ((u64)end_pfn << PAGE_SHIFT) - 1);
  6001. /* Initialise every node */
  6002. mminit_verify_pageflags_layout();
  6003. setup_nr_node_ids();
  6004. zero_resv_unavail();
  6005. for_each_online_node(nid) {
  6006. pg_data_t *pgdat = NODE_DATA(nid);
  6007. free_area_init_node(nid, NULL,
  6008. find_min_pfn_for_node(nid), NULL);
  6009. /* Any memory on that node */
  6010. if (pgdat->node_present_pages)
  6011. node_set_state(nid, N_MEMORY);
  6012. check_for_memory(pgdat, nid);
  6013. }
  6014. }
  6015. static int __init cmdline_parse_core(char *p, unsigned long *core,
  6016. unsigned long *percent)
  6017. {
  6018. unsigned long long coremem;
  6019. char *endptr;
  6020. if (!p)
  6021. return -EINVAL;
  6022. /* Value may be a percentage of total memory, otherwise bytes */
  6023. coremem = simple_strtoull(p, &endptr, 0);
  6024. if (*endptr == '%') {
  6025. /* Paranoid check for percent values greater than 100 */
  6026. WARN_ON(coremem > 100);
  6027. *percent = coremem;
  6028. } else {
  6029. coremem = memparse(p, &p);
  6030. /* Paranoid check that UL is enough for the coremem value */
  6031. WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
  6032. *core = coremem >> PAGE_SHIFT;
  6033. *percent = 0UL;
  6034. }
  6035. return 0;
  6036. }
  6037. /*
  6038. * kernelcore=size sets the amount of memory for use for allocations that
  6039. * cannot be reclaimed or migrated.
  6040. */
  6041. static int __init cmdline_parse_kernelcore(char *p)
  6042. {
  6043. /* parse kernelcore=mirror */
  6044. if (parse_option_str(p, "mirror")) {
  6045. mirrored_kernelcore = true;
  6046. return 0;
  6047. }
  6048. return cmdline_parse_core(p, &required_kernelcore,
  6049. &required_kernelcore_percent);
  6050. }
  6051. /*
  6052. * movablecore=size sets the amount of memory for use for allocations that
  6053. * can be reclaimed or migrated.
  6054. */
  6055. static int __init cmdline_parse_movablecore(char *p)
  6056. {
  6057. return cmdline_parse_core(p, &required_movablecore,
  6058. &required_movablecore_percent);
  6059. }
  6060. early_param("kernelcore", cmdline_parse_kernelcore);
  6061. early_param("movablecore", cmdline_parse_movablecore);
  6062. #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
  6063. void adjust_managed_page_count(struct page *page, long count)
  6064. {
  6065. spin_lock(&managed_page_count_lock);
  6066. page_zone(page)->managed_pages += count;
  6067. totalram_pages += count;
  6068. #ifdef CONFIG_HIGHMEM
  6069. if (PageHighMem(page))
  6070. totalhigh_pages += count;
  6071. #endif
  6072. spin_unlock(&managed_page_count_lock);
  6073. }
  6074. EXPORT_SYMBOL(adjust_managed_page_count);
  6075. unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
  6076. {
  6077. void *pos;
  6078. unsigned long pages = 0;
  6079. start = (void *)PAGE_ALIGN((unsigned long)start);
  6080. end = (void *)((unsigned long)end & PAGE_MASK);
  6081. for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
  6082. struct page *page = virt_to_page(pos);
  6083. void *direct_map_addr;
  6084. /*
  6085. * 'direct_map_addr' might be different from 'pos'
  6086. * because some architectures' virt_to_page()
  6087. * work with aliases. Getting the direct map
  6088. * address ensures that we get a _writeable_
  6089. * alias for the memset().
  6090. */
  6091. direct_map_addr = page_address(page);
  6092. if ((unsigned int)poison <= 0xFF)
  6093. memset(direct_map_addr, poison, PAGE_SIZE);
  6094. free_reserved_page(page);
  6095. }
  6096. if (pages && s)
  6097. pr_info("Freeing %s memory: %ldK\n",
  6098. s, pages << (PAGE_SHIFT - 10));
  6099. return pages;
  6100. }
  6101. EXPORT_SYMBOL(free_reserved_area);
  6102. #ifdef CONFIG_HIGHMEM
  6103. void free_highmem_page(struct page *page)
  6104. {
  6105. __free_reserved_page(page);
  6106. totalram_pages++;
  6107. page_zone(page)->managed_pages++;
  6108. totalhigh_pages++;
  6109. }
  6110. #endif
  6111. void __init mem_init_print_info(const char *str)
  6112. {
  6113. unsigned long physpages, codesize, datasize, rosize, bss_size;
  6114. unsigned long init_code_size, init_data_size;
  6115. physpages = get_num_physpages();
  6116. codesize = _etext - _stext;
  6117. datasize = _edata - _sdata;
  6118. rosize = __end_rodata - __start_rodata;
  6119. bss_size = __bss_stop - __bss_start;
  6120. init_data_size = __init_end - __init_begin;
  6121. init_code_size = _einittext - _sinittext;
  6122. /*
  6123. * Detect special cases and adjust section sizes accordingly:
  6124. * 1) .init.* may be embedded into .data sections
  6125. * 2) .init.text.* may be out of [__init_begin, __init_end],
  6126. * please refer to arch/tile/kernel/vmlinux.lds.S.
  6127. * 3) .rodata.* may be embedded into .text or .data sections.
  6128. */
  6129. #define adj_init_size(start, end, size, pos, adj) \
  6130. do { \
  6131. if (start <= pos && pos < end && size > adj) \
  6132. size -= adj; \
  6133. } while (0)
  6134. adj_init_size(__init_begin, __init_end, init_data_size,
  6135. _sinittext, init_code_size);
  6136. adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
  6137. adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
  6138. adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
  6139. adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
  6140. #undef adj_init_size
  6141. pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
  6142. #ifdef CONFIG_HIGHMEM
  6143. ", %luK highmem"
  6144. #endif
  6145. "%s%s)\n",
  6146. nr_free_pages() << (PAGE_SHIFT - 10),
  6147. physpages << (PAGE_SHIFT - 10),
  6148. codesize >> 10, datasize >> 10, rosize >> 10,
  6149. (init_data_size + init_code_size) >> 10, bss_size >> 10,
  6150. (physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT - 10),
  6151. totalcma_pages << (PAGE_SHIFT - 10),
  6152. #ifdef CONFIG_HIGHMEM
  6153. totalhigh_pages << (PAGE_SHIFT - 10),
  6154. #endif
  6155. str ? ", " : "", str ? str : "");
  6156. }
  6157. /**
  6158. * set_dma_reserve - set the specified number of pages reserved in the first zone
  6159. * @new_dma_reserve: The number of pages to mark reserved
  6160. *
  6161. * The per-cpu batchsize and zone watermarks are determined by managed_pages.
  6162. * In the DMA zone, a significant percentage may be consumed by kernel image
  6163. * and other unfreeable allocations which can skew the watermarks badly. This
  6164. * function may optionally be used to account for unfreeable pages in the
  6165. * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
  6166. * smaller per-cpu batchsize.
  6167. */
  6168. void __init set_dma_reserve(unsigned long new_dma_reserve)
  6169. {
  6170. dma_reserve = new_dma_reserve;
  6171. }
  6172. void __init free_area_init(unsigned long *zones_size)
  6173. {
  6174. zero_resv_unavail();
  6175. free_area_init_node(0, zones_size,
  6176. __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
  6177. }
  6178. static int page_alloc_cpu_dead(unsigned int cpu)
  6179. {
  6180. lru_add_drain_cpu(cpu);
  6181. drain_pages(cpu);
  6182. /*
  6183. * Spill the event counters of the dead processor
  6184. * into the current processors event counters.
  6185. * This artificially elevates the count of the current
  6186. * processor.
  6187. */
  6188. vm_events_fold_cpu(cpu);
  6189. /*
  6190. * Zero the differential counters of the dead processor
  6191. * so that the vm statistics are consistent.
  6192. *
  6193. * This is only okay since the processor is dead and cannot
  6194. * race with what we are doing.
  6195. */
  6196. cpu_vm_stats_fold(cpu);
  6197. return 0;
  6198. }
  6199. void __init page_alloc_init(void)
  6200. {
  6201. int ret;
  6202. ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
  6203. "mm/page_alloc:dead", NULL,
  6204. page_alloc_cpu_dead);
  6205. WARN_ON(ret < 0);
  6206. }
  6207. /*
  6208. * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
  6209. * or min_free_kbytes changes.
  6210. */
  6211. static void calculate_totalreserve_pages(void)
  6212. {
  6213. struct pglist_data *pgdat;
  6214. unsigned long reserve_pages = 0;
  6215. enum zone_type i, j;
  6216. for_each_online_pgdat(pgdat) {
  6217. pgdat->totalreserve_pages = 0;
  6218. for (i = 0; i < MAX_NR_ZONES; i++) {
  6219. struct zone *zone = pgdat->node_zones + i;
  6220. long max = 0;
  6221. /* Find valid and maximum lowmem_reserve in the zone */
  6222. for (j = i; j < MAX_NR_ZONES; j++) {
  6223. if (zone->lowmem_reserve[j] > max)
  6224. max = zone->lowmem_reserve[j];
  6225. }
  6226. /* we treat the high watermark as reserved pages. */
  6227. max += high_wmark_pages(zone);
  6228. if (max > zone->managed_pages)
  6229. max = zone->managed_pages;
  6230. pgdat->totalreserve_pages += max;
  6231. reserve_pages += max;
  6232. }
  6233. }
  6234. totalreserve_pages = reserve_pages;
  6235. }
  6236. /*
  6237. * setup_per_zone_lowmem_reserve - called whenever
  6238. * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
  6239. * has a correct pages reserved value, so an adequate number of
  6240. * pages are left in the zone after a successful __alloc_pages().
  6241. */
  6242. static void setup_per_zone_lowmem_reserve(void)
  6243. {
  6244. struct pglist_data *pgdat;
  6245. enum zone_type j, idx;
  6246. for_each_online_pgdat(pgdat) {
  6247. for (j = 0; j < MAX_NR_ZONES; j++) {
  6248. struct zone *zone = pgdat->node_zones + j;
  6249. unsigned long managed_pages = zone->managed_pages;
  6250. zone->lowmem_reserve[j] = 0;
  6251. idx = j;
  6252. while (idx) {
  6253. struct zone *lower_zone;
  6254. idx--;
  6255. lower_zone = pgdat->node_zones + idx;
  6256. if (sysctl_lowmem_reserve_ratio[idx] < 1) {
  6257. sysctl_lowmem_reserve_ratio[idx] = 0;
  6258. lower_zone->lowmem_reserve[j] = 0;
  6259. } else {
  6260. lower_zone->lowmem_reserve[j] =
  6261. managed_pages / sysctl_lowmem_reserve_ratio[idx];
  6262. }
  6263. managed_pages += lower_zone->managed_pages;
  6264. }
  6265. }
  6266. }
  6267. /* update totalreserve_pages */
  6268. calculate_totalreserve_pages();
  6269. }
  6270. static void __setup_per_zone_wmarks(void)
  6271. {
  6272. unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
  6273. unsigned long lowmem_pages = 0;
  6274. struct zone *zone;
  6275. unsigned long flags;
  6276. /* Calculate total number of !ZONE_HIGHMEM pages */
  6277. for_each_zone(zone) {
  6278. if (!is_highmem(zone))
  6279. lowmem_pages += zone->managed_pages;
  6280. }
  6281. for_each_zone(zone) {
  6282. u64 tmp;
  6283. spin_lock_irqsave(&zone->lock, flags);
  6284. tmp = (u64)pages_min * zone->managed_pages;
  6285. do_div(tmp, lowmem_pages);
  6286. if (is_highmem(zone)) {
  6287. /*
  6288. * __GFP_HIGH and PF_MEMALLOC allocations usually don't
  6289. * need highmem pages, so cap pages_min to a small
  6290. * value here.
  6291. *
  6292. * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
  6293. * deltas control asynch page reclaim, and so should
  6294. * not be capped for highmem.
  6295. */
  6296. unsigned long min_pages;
  6297. min_pages = zone->managed_pages / 1024;
  6298. min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
  6299. zone->watermark[WMARK_MIN] = min_pages;
  6300. } else {
  6301. /*
  6302. * If it's a lowmem zone, reserve a number of pages
  6303. * proportionate to the zone's size.
  6304. */
  6305. zone->watermark[WMARK_MIN] = tmp;
  6306. }
  6307. /*
  6308. * Set the kswapd watermarks distance according to the
  6309. * scale factor in proportion to available memory, but
  6310. * ensure a minimum size on small systems.
  6311. */
  6312. tmp = max_t(u64, tmp >> 2,
  6313. mult_frac(zone->managed_pages,
  6314. watermark_scale_factor, 10000));
  6315. zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
  6316. zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
  6317. spin_unlock_irqrestore(&zone->lock, flags);
  6318. }
  6319. /* update totalreserve_pages */
  6320. calculate_totalreserve_pages();
  6321. }
  6322. /**
  6323. * setup_per_zone_wmarks - called when min_free_kbytes changes
  6324. * or when memory is hot-{added|removed}
  6325. *
  6326. * Ensures that the watermark[min,low,high] values for each zone are set
  6327. * correctly with respect to min_free_kbytes.
  6328. */
  6329. void setup_per_zone_wmarks(void)
  6330. {
  6331. static DEFINE_SPINLOCK(lock);
  6332. spin_lock(&lock);
  6333. __setup_per_zone_wmarks();
  6334. spin_unlock(&lock);
  6335. }
  6336. /*
  6337. * Initialise min_free_kbytes.
  6338. *
  6339. * For small machines we want it small (128k min). For large machines
  6340. * we want it large (64MB max). But it is not linear, because network
  6341. * bandwidth does not increase linearly with machine size. We use
  6342. *
  6343. * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
  6344. * min_free_kbytes = sqrt(lowmem_kbytes * 16)
  6345. *
  6346. * which yields
  6347. *
  6348. * 16MB: 512k
  6349. * 32MB: 724k
  6350. * 64MB: 1024k
  6351. * 128MB: 1448k
  6352. * 256MB: 2048k
  6353. * 512MB: 2896k
  6354. * 1024MB: 4096k
  6355. * 2048MB: 5792k
  6356. * 4096MB: 8192k
  6357. * 8192MB: 11584k
  6358. * 16384MB: 16384k
  6359. */
  6360. int __meminit init_per_zone_wmark_min(void)
  6361. {
  6362. unsigned long lowmem_kbytes;
  6363. int new_min_free_kbytes;
  6364. lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
  6365. new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
  6366. if (new_min_free_kbytes > user_min_free_kbytes) {
  6367. min_free_kbytes = new_min_free_kbytes;
  6368. if (min_free_kbytes < 128)
  6369. min_free_kbytes = 128;
  6370. if (min_free_kbytes > 65536)
  6371. min_free_kbytes = 65536;
  6372. } else {
  6373. pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
  6374. new_min_free_kbytes, user_min_free_kbytes);
  6375. }
  6376. setup_per_zone_wmarks();
  6377. refresh_zone_stat_thresholds();
  6378. setup_per_zone_lowmem_reserve();
  6379. #ifdef CONFIG_NUMA
  6380. setup_min_unmapped_ratio();
  6381. setup_min_slab_ratio();
  6382. #endif
  6383. khugepaged_min_free_kbytes_update();
  6384. return 0;
  6385. }
  6386. postcore_initcall(init_per_zone_wmark_min)
  6387. /*
  6388. * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
  6389. * that we can call two helper functions whenever min_free_kbytes
  6390. * changes.
  6391. */
  6392. int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
  6393. void __user *buffer, size_t *length, loff_t *ppos)
  6394. {
  6395. int rc;
  6396. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  6397. if (rc)
  6398. return rc;
  6399. if (write) {
  6400. user_min_free_kbytes = min_free_kbytes;
  6401. setup_per_zone_wmarks();
  6402. }
  6403. return 0;
  6404. }
  6405. int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
  6406. void __user *buffer, size_t *length, loff_t *ppos)
  6407. {
  6408. int rc;
  6409. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  6410. if (rc)
  6411. return rc;
  6412. if (write)
  6413. setup_per_zone_wmarks();
  6414. return 0;
  6415. }
  6416. #ifdef CONFIG_NUMA
  6417. static void setup_min_unmapped_ratio(void)
  6418. {
  6419. pg_data_t *pgdat;
  6420. struct zone *zone;
  6421. for_each_online_pgdat(pgdat)
  6422. pgdat->min_unmapped_pages = 0;
  6423. for_each_zone(zone)
  6424. zone->zone_pgdat->min_unmapped_pages += (zone->managed_pages *
  6425. sysctl_min_unmapped_ratio) / 100;
  6426. }
  6427. int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
  6428. void __user *buffer, size_t *length, loff_t *ppos)
  6429. {
  6430. int rc;
  6431. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  6432. if (rc)
  6433. return rc;
  6434. setup_min_unmapped_ratio();
  6435. return 0;
  6436. }
  6437. static void setup_min_slab_ratio(void)
  6438. {
  6439. pg_data_t *pgdat;
  6440. struct zone *zone;
  6441. for_each_online_pgdat(pgdat)
  6442. pgdat->min_slab_pages = 0;
  6443. for_each_zone(zone)
  6444. zone->zone_pgdat->min_slab_pages += (zone->managed_pages *
  6445. sysctl_min_slab_ratio) / 100;
  6446. }
  6447. int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
  6448. void __user *buffer, size_t *length, loff_t *ppos)
  6449. {
  6450. int rc;
  6451. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  6452. if (rc)
  6453. return rc;
  6454. setup_min_slab_ratio();
  6455. return 0;
  6456. }
  6457. #endif
  6458. /*
  6459. * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
  6460. * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
  6461. * whenever sysctl_lowmem_reserve_ratio changes.
  6462. *
  6463. * The reserve ratio obviously has absolutely no relation with the
  6464. * minimum watermarks. The lowmem reserve ratio can only make sense
  6465. * if in function of the boot time zone sizes.
  6466. */
  6467. int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
  6468. void __user *buffer, size_t *length, loff_t *ppos)
  6469. {
  6470. proc_dointvec_minmax(table, write, buffer, length, ppos);
  6471. setup_per_zone_lowmem_reserve();
  6472. return 0;
  6473. }
  6474. /*
  6475. * percpu_pagelist_fraction - changes the pcp->high for each zone on each
  6476. * cpu. It is the fraction of total pages in each zone that a hot per cpu
  6477. * pagelist can have before it gets flushed back to buddy allocator.
  6478. */
  6479. int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
  6480. void __user *buffer, size_t *length, loff_t *ppos)
  6481. {
  6482. struct zone *zone;
  6483. int old_percpu_pagelist_fraction;
  6484. int ret;
  6485. mutex_lock(&pcp_batch_high_lock);
  6486. old_percpu_pagelist_fraction = percpu_pagelist_fraction;
  6487. ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
  6488. if (!write || ret < 0)
  6489. goto out;
  6490. /* Sanity checking to avoid pcp imbalance */
  6491. if (percpu_pagelist_fraction &&
  6492. percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
  6493. percpu_pagelist_fraction = old_percpu_pagelist_fraction;
  6494. ret = -EINVAL;
  6495. goto out;
  6496. }
  6497. /* No change? */
  6498. if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
  6499. goto out;
  6500. for_each_populated_zone(zone) {
  6501. unsigned int cpu;
  6502. for_each_possible_cpu(cpu)
  6503. pageset_set_high_and_batch(zone,
  6504. per_cpu_ptr(zone->pageset, cpu));
  6505. }
  6506. out:
  6507. mutex_unlock(&pcp_batch_high_lock);
  6508. return ret;
  6509. }
  6510. #ifdef CONFIG_NUMA
  6511. int hashdist = HASHDIST_DEFAULT;
  6512. static int __init set_hashdist(char *str)
  6513. {
  6514. if (!str)
  6515. return 0;
  6516. hashdist = simple_strtoul(str, &str, 0);
  6517. return 1;
  6518. }
  6519. __setup("hashdist=", set_hashdist);
  6520. #endif
  6521. #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
  6522. /*
  6523. * Returns the number of pages that arch has reserved but
  6524. * is not known to alloc_large_system_hash().
  6525. */
  6526. static unsigned long __init arch_reserved_kernel_pages(void)
  6527. {
  6528. return 0;
  6529. }
  6530. #endif
  6531. /*
  6532. * Adaptive scale is meant to reduce sizes of hash tables on large memory
  6533. * machines. As memory size is increased the scale is also increased but at
  6534. * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
  6535. * quadruples the scale is increased by one, which means the size of hash table
  6536. * only doubles, instead of quadrupling as well.
  6537. * Because 32-bit systems cannot have large physical memory, where this scaling
  6538. * makes sense, it is disabled on such platforms.
  6539. */
  6540. #if __BITS_PER_LONG > 32
  6541. #define ADAPT_SCALE_BASE (64ul << 30)
  6542. #define ADAPT_SCALE_SHIFT 2
  6543. #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
  6544. #endif
  6545. /*
  6546. * allocate a large system hash table from bootmem
  6547. * - it is assumed that the hash table must contain an exact power-of-2
  6548. * quantity of entries
  6549. * - limit is the number of hash buckets, not the total allocation size
  6550. */
  6551. void *__init alloc_large_system_hash(const char *tablename,
  6552. unsigned long bucketsize,
  6553. unsigned long numentries,
  6554. int scale,
  6555. int flags,
  6556. unsigned int *_hash_shift,
  6557. unsigned int *_hash_mask,
  6558. unsigned long low_limit,
  6559. unsigned long high_limit)
  6560. {
  6561. unsigned long long max = high_limit;
  6562. unsigned long log2qty, size;
  6563. void *table = NULL;
  6564. gfp_t gfp_flags;
  6565. /* allow the kernel cmdline to have a say */
  6566. if (!numentries) {
  6567. /* round applicable memory size up to nearest megabyte */
  6568. numentries = nr_kernel_pages;
  6569. numentries -= arch_reserved_kernel_pages();
  6570. /* It isn't necessary when PAGE_SIZE >= 1MB */
  6571. if (PAGE_SHIFT < 20)
  6572. numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
  6573. #if __BITS_PER_LONG > 32
  6574. if (!high_limit) {
  6575. unsigned long adapt;
  6576. for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
  6577. adapt <<= ADAPT_SCALE_SHIFT)
  6578. scale++;
  6579. }
  6580. #endif
  6581. /* limit to 1 bucket per 2^scale bytes of low memory */
  6582. if (scale > PAGE_SHIFT)
  6583. numentries >>= (scale - PAGE_SHIFT);
  6584. else
  6585. numentries <<= (PAGE_SHIFT - scale);
  6586. /* Make sure we've got at least a 0-order allocation.. */
  6587. if (unlikely(flags & HASH_SMALL)) {
  6588. /* Makes no sense without HASH_EARLY */
  6589. WARN_ON(!(flags & HASH_EARLY));
  6590. if (!(numentries >> *_hash_shift)) {
  6591. numentries = 1UL << *_hash_shift;
  6592. BUG_ON(!numentries);
  6593. }
  6594. } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
  6595. numentries = PAGE_SIZE / bucketsize;
  6596. }
  6597. numentries = roundup_pow_of_two(numentries);
  6598. /* limit allocation size to 1/16 total memory by default */
  6599. if (max == 0) {
  6600. max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
  6601. do_div(max, bucketsize);
  6602. }
  6603. max = min(max, 0x80000000ULL);
  6604. if (numentries < low_limit)
  6605. numentries = low_limit;
  6606. if (numentries > max)
  6607. numentries = max;
  6608. log2qty = ilog2(numentries);
  6609. gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
  6610. do {
  6611. size = bucketsize << log2qty;
  6612. if (flags & HASH_EARLY) {
  6613. if (flags & HASH_ZERO)
  6614. table = memblock_virt_alloc_nopanic(size, 0);
  6615. else
  6616. table = memblock_virt_alloc_raw(size, 0);
  6617. } else if (hashdist) {
  6618. table = __vmalloc(size, gfp_flags, PAGE_KERNEL);
  6619. } else {
  6620. /*
  6621. * If bucketsize is not a power-of-two, we may free
  6622. * some pages at the end of hash table which
  6623. * alloc_pages_exact() automatically does
  6624. */
  6625. if (get_order(size) < MAX_ORDER) {
  6626. table = alloc_pages_exact(size, gfp_flags);
  6627. kmemleak_alloc(table, size, 1, gfp_flags);
  6628. }
  6629. }
  6630. } while (!table && size > PAGE_SIZE && --log2qty);
  6631. if (!table)
  6632. panic("Failed to allocate %s hash table\n", tablename);
  6633. pr_info("%s hash table entries: %ld (order: %d, %lu bytes)\n",
  6634. tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size);
  6635. if (_hash_shift)
  6636. *_hash_shift = log2qty;
  6637. if (_hash_mask)
  6638. *_hash_mask = (1 << log2qty) - 1;
  6639. return table;
  6640. }
  6641. /*
  6642. * This function checks whether pageblock includes unmovable pages or not.
  6643. * If @count is not zero, it is okay to include less @count unmovable pages
  6644. *
  6645. * PageLRU check without isolation or lru_lock could race so that
  6646. * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
  6647. * check without lock_page also may miss some movable non-lru pages at
  6648. * race condition. So you can't expect this function should be exact.
  6649. */
  6650. bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
  6651. int migratetype,
  6652. bool skip_hwpoisoned_pages)
  6653. {
  6654. unsigned long pfn, iter, found;
  6655. /*
  6656. * TODO we could make this much more efficient by not checking every
  6657. * page in the range if we know all of them are in MOVABLE_ZONE and
  6658. * that the movable zone guarantees that pages are migratable but
  6659. * the later is not the case right now unfortunatelly. E.g. movablecore
  6660. * can still lead to having bootmem allocations in zone_movable.
  6661. */
  6662. /*
  6663. * CMA allocations (alloc_contig_range) really need to mark isolate
  6664. * CMA pageblocks even when they are not movable in fact so consider
  6665. * them movable here.
  6666. */
  6667. if (is_migrate_cma(migratetype) &&
  6668. is_migrate_cma(get_pageblock_migratetype(page)))
  6669. return false;
  6670. pfn = page_to_pfn(page);
  6671. for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
  6672. unsigned long check = pfn + iter;
  6673. if (!pfn_valid_within(check))
  6674. continue;
  6675. page = pfn_to_page(check);
  6676. if (PageReserved(page))
  6677. goto unmovable;
  6678. /*
  6679. * If the zone is movable and we have ruled out all reserved
  6680. * pages then it should be reasonably safe to assume the rest
  6681. * is movable.
  6682. */
  6683. if (zone_idx(zone) == ZONE_MOVABLE)
  6684. continue;
  6685. /*
  6686. * Hugepages are not in LRU lists, but they're movable.
  6687. * We need not scan over tail pages bacause we don't
  6688. * handle each tail page individually in migration.
  6689. */
  6690. if (PageHuge(page)) {
  6691. struct page *head = compound_head(page);
  6692. unsigned int skip_pages;
  6693. if (!hugepage_migration_supported(page_hstate(head)))
  6694. goto unmovable;
  6695. skip_pages = (1 << compound_order(head)) - (page - head);
  6696. iter += skip_pages - 1;
  6697. continue;
  6698. }
  6699. /*
  6700. * We can't use page_count without pin a page
  6701. * because another CPU can free compound page.
  6702. * This check already skips compound tails of THP
  6703. * because their page->_refcount is zero at all time.
  6704. */
  6705. if (!page_ref_count(page)) {
  6706. if (PageBuddy(page))
  6707. iter += (1 << page_order(page)) - 1;
  6708. continue;
  6709. }
  6710. /*
  6711. * The HWPoisoned page may be not in buddy system, and
  6712. * page_count() is not 0.
  6713. */
  6714. if (skip_hwpoisoned_pages && PageHWPoison(page))
  6715. continue;
  6716. if (__PageMovable(page))
  6717. continue;
  6718. if (!PageLRU(page))
  6719. found++;
  6720. /*
  6721. * If there are RECLAIMABLE pages, we need to check
  6722. * it. But now, memory offline itself doesn't call
  6723. * shrink_node_slabs() and it still to be fixed.
  6724. */
  6725. /*
  6726. * If the page is not RAM, page_count()should be 0.
  6727. * we don't need more check. This is an _used_ not-movable page.
  6728. *
  6729. * The problematic thing here is PG_reserved pages. PG_reserved
  6730. * is set to both of a memory hole page and a _used_ kernel
  6731. * page at boot.
  6732. */
  6733. if (found > count)
  6734. goto unmovable;
  6735. }
  6736. return false;
  6737. unmovable:
  6738. WARN_ON_ONCE(zone_idx(zone) == ZONE_MOVABLE);
  6739. return true;
  6740. }
  6741. #if (defined(CONFIG_MEMORY_ISOLATION) && defined(CONFIG_COMPACTION)) || defined(CONFIG_CMA)
  6742. static unsigned long pfn_max_align_down(unsigned long pfn)
  6743. {
  6744. return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
  6745. pageblock_nr_pages) - 1);
  6746. }
  6747. static unsigned long pfn_max_align_up(unsigned long pfn)
  6748. {
  6749. return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
  6750. pageblock_nr_pages));
  6751. }
  6752. /* [start, end) must belong to a single zone. */
  6753. static int __alloc_contig_migrate_range(struct compact_control *cc,
  6754. unsigned long start, unsigned long end)
  6755. {
  6756. /* This function is based on compact_zone() from compaction.c. */
  6757. unsigned long nr_reclaimed;
  6758. unsigned long pfn = start;
  6759. unsigned int tries = 0;
  6760. int ret = 0;
  6761. migrate_prep();
  6762. while (pfn < end || !list_empty(&cc->migratepages)) {
  6763. if (fatal_signal_pending(current)) {
  6764. ret = -EINTR;
  6765. break;
  6766. }
  6767. if (list_empty(&cc->migratepages)) {
  6768. cc->nr_migratepages = 0;
  6769. pfn = isolate_migratepages_range(cc, pfn, end);
  6770. if (!pfn) {
  6771. ret = -EINTR;
  6772. break;
  6773. }
  6774. tries = 0;
  6775. } else if (++tries == 5) {
  6776. ret = ret < 0 ? ret : -EBUSY;
  6777. break;
  6778. }
  6779. nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
  6780. &cc->migratepages);
  6781. cc->nr_migratepages -= nr_reclaimed;
  6782. ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
  6783. NULL, 0, cc->mode, MR_CONTIG_RANGE);
  6784. }
  6785. if (ret < 0) {
  6786. putback_movable_pages(&cc->migratepages);
  6787. return ret;
  6788. }
  6789. return 0;
  6790. }
  6791. /**
  6792. * alloc_contig_range() -- tries to allocate given range of pages
  6793. * @start: start PFN to allocate
  6794. * @end: one-past-the-last PFN to allocate
  6795. * @migratetype: migratetype of the underlaying pageblocks (either
  6796. * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
  6797. * in range must have the same migratetype and it must
  6798. * be either of the two.
  6799. * @gfp_mask: GFP mask to use during compaction
  6800. *
  6801. * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
  6802. * aligned. The PFN range must belong to a single zone.
  6803. *
  6804. * The first thing this routine does is attempt to MIGRATE_ISOLATE all
  6805. * pageblocks in the range. Once isolated, the pageblocks should not
  6806. * be modified by others.
  6807. *
  6808. * Returns zero on success or negative error code. On success all
  6809. * pages which PFN is in [start, end) are allocated for the caller and
  6810. * need to be freed with free_contig_range().
  6811. */
  6812. int alloc_contig_range(unsigned long start, unsigned long end,
  6813. unsigned migratetype, gfp_t gfp_mask)
  6814. {
  6815. unsigned long outer_start, outer_end;
  6816. unsigned int order;
  6817. int ret = 0;
  6818. struct compact_control cc = {
  6819. .nr_migratepages = 0,
  6820. .order = -1,
  6821. .zone = page_zone(pfn_to_page(start)),
  6822. .mode = MIGRATE_SYNC,
  6823. .ignore_skip_hint = true,
  6824. .no_set_skip_hint = true,
  6825. .gfp_mask = current_gfp_context(gfp_mask),
  6826. };
  6827. INIT_LIST_HEAD(&cc.migratepages);
  6828. /*
  6829. * What we do here is we mark all pageblocks in range as
  6830. * MIGRATE_ISOLATE. Because pageblock and max order pages may
  6831. * have different sizes, and due to the way page allocator
  6832. * work, we align the range to biggest of the two pages so
  6833. * that page allocator won't try to merge buddies from
  6834. * different pageblocks and change MIGRATE_ISOLATE to some
  6835. * other migration type.
  6836. *
  6837. * Once the pageblocks are marked as MIGRATE_ISOLATE, we
  6838. * migrate the pages from an unaligned range (ie. pages that
  6839. * we are interested in). This will put all the pages in
  6840. * range back to page allocator as MIGRATE_ISOLATE.
  6841. *
  6842. * When this is done, we take the pages in range from page
  6843. * allocator removing them from the buddy system. This way
  6844. * page allocator will never consider using them.
  6845. *
  6846. * This lets us mark the pageblocks back as
  6847. * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
  6848. * aligned range but not in the unaligned, original range are
  6849. * put back to page allocator so that buddy can use them.
  6850. */
  6851. ret = start_isolate_page_range(pfn_max_align_down(start),
  6852. pfn_max_align_up(end), migratetype,
  6853. false);
  6854. if (ret)
  6855. return ret;
  6856. /*
  6857. * In case of -EBUSY, we'd like to know which page causes problem.
  6858. * So, just fall through. test_pages_isolated() has a tracepoint
  6859. * which will report the busy page.
  6860. *
  6861. * It is possible that busy pages could become available before
  6862. * the call to test_pages_isolated, and the range will actually be
  6863. * allocated. So, if we fall through be sure to clear ret so that
  6864. * -EBUSY is not accidentally used or returned to caller.
  6865. */
  6866. ret = __alloc_contig_migrate_range(&cc, start, end);
  6867. if (ret && ret != -EBUSY)
  6868. goto done;
  6869. ret =0;
  6870. /*
  6871. * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
  6872. * aligned blocks that are marked as MIGRATE_ISOLATE. What's
  6873. * more, all pages in [start, end) are free in page allocator.
  6874. * What we are going to do is to allocate all pages from
  6875. * [start, end) (that is remove them from page allocator).
  6876. *
  6877. * The only problem is that pages at the beginning and at the
  6878. * end of interesting range may be not aligned with pages that
  6879. * page allocator holds, ie. they can be part of higher order
  6880. * pages. Because of this, we reserve the bigger range and
  6881. * once this is done free the pages we are not interested in.
  6882. *
  6883. * We don't have to hold zone->lock here because the pages are
  6884. * isolated thus they won't get removed from buddy.
  6885. */
  6886. lru_add_drain_all();
  6887. drain_all_pages(cc.zone);
  6888. order = 0;
  6889. outer_start = start;
  6890. while (!PageBuddy(pfn_to_page(outer_start))) {
  6891. if (++order >= MAX_ORDER) {
  6892. outer_start = start;
  6893. break;
  6894. }
  6895. outer_start &= ~0UL << order;
  6896. }
  6897. if (outer_start != start) {
  6898. order = page_order(pfn_to_page(outer_start));
  6899. /*
  6900. * outer_start page could be small order buddy page and
  6901. * it doesn't include start page. Adjust outer_start
  6902. * in this case to report failed page properly
  6903. * on tracepoint in test_pages_isolated()
  6904. */
  6905. if (outer_start + (1UL << order) <= start)
  6906. outer_start = start;
  6907. }
  6908. /* Make sure the range is really isolated. */
  6909. if (test_pages_isolated(outer_start, end, false)) {
  6910. pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
  6911. __func__, outer_start, end);
  6912. ret = -EBUSY;
  6913. goto done;
  6914. }
  6915. /* Grab isolated pages from freelists. */
  6916. outer_end = isolate_freepages_range(&cc, outer_start, end);
  6917. if (!outer_end) {
  6918. ret = -EBUSY;
  6919. goto done;
  6920. }
  6921. /* Free head and tail (if any) */
  6922. if (start != outer_start)
  6923. free_contig_range(outer_start, start - outer_start);
  6924. if (end != outer_end)
  6925. free_contig_range(end, outer_end - end);
  6926. done:
  6927. undo_isolate_page_range(pfn_max_align_down(start),
  6928. pfn_max_align_up(end), migratetype);
  6929. return ret;
  6930. }
  6931. void free_contig_range(unsigned long pfn, unsigned nr_pages)
  6932. {
  6933. unsigned int count = 0;
  6934. for (; nr_pages--; pfn++) {
  6935. struct page *page = pfn_to_page(pfn);
  6936. count += page_count(page) != 1;
  6937. __free_page(page);
  6938. }
  6939. WARN(count != 0, "%d pages are still in use!\n", count);
  6940. }
  6941. #endif
  6942. /*
  6943. * The zone indicated has a new number of managed_pages; batch sizes and percpu
  6944. * page high values need to be recalulated.
  6945. */
  6946. void __meminit zone_pcp_update(struct zone *zone)
  6947. {
  6948. unsigned cpu;
  6949. mutex_lock(&pcp_batch_high_lock);
  6950. for_each_possible_cpu(cpu)
  6951. pageset_set_high_and_batch(zone,
  6952. per_cpu_ptr(zone->pageset, cpu));
  6953. mutex_unlock(&pcp_batch_high_lock);
  6954. }
  6955. void zone_pcp_reset(struct zone *zone)
  6956. {
  6957. unsigned long flags;
  6958. int cpu;
  6959. struct per_cpu_pageset *pset;
  6960. /* avoid races with drain_pages() */
  6961. local_irq_save(flags);
  6962. if (zone->pageset != &boot_pageset) {
  6963. for_each_online_cpu(cpu) {
  6964. pset = per_cpu_ptr(zone->pageset, cpu);
  6965. drain_zonestat(zone, pset);
  6966. }
  6967. free_percpu(zone->pageset);
  6968. zone->pageset = &boot_pageset;
  6969. }
  6970. local_irq_restore(flags);
  6971. }
  6972. #ifdef CONFIG_MEMORY_HOTREMOVE
  6973. /*
  6974. * All pages in the range must be in a single zone and isolated
  6975. * before calling this.
  6976. */
  6977. void
  6978. __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
  6979. {
  6980. struct page *page;
  6981. struct zone *zone;
  6982. unsigned int order, i;
  6983. unsigned long pfn;
  6984. unsigned long flags;
  6985. /* find the first valid pfn */
  6986. for (pfn = start_pfn; pfn < end_pfn; pfn++)
  6987. if (pfn_valid(pfn))
  6988. break;
  6989. if (pfn == end_pfn)
  6990. return;
  6991. offline_mem_sections(pfn, end_pfn);
  6992. zone = page_zone(pfn_to_page(pfn));
  6993. spin_lock_irqsave(&zone->lock, flags);
  6994. pfn = start_pfn;
  6995. while (pfn < end_pfn) {
  6996. if (!pfn_valid(pfn)) {
  6997. pfn++;
  6998. continue;
  6999. }
  7000. page = pfn_to_page(pfn);
  7001. /*
  7002. * The HWPoisoned page may be not in buddy system, and
  7003. * page_count() is not 0.
  7004. */
  7005. if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
  7006. pfn++;
  7007. SetPageReserved(page);
  7008. continue;
  7009. }
  7010. BUG_ON(page_count(page));
  7011. BUG_ON(!PageBuddy(page));
  7012. order = page_order(page);
  7013. #ifdef CONFIG_DEBUG_VM
  7014. pr_info("remove from free list %lx %d %lx\n",
  7015. pfn, 1 << order, end_pfn);
  7016. #endif
  7017. list_del(&page->lru);
  7018. rmv_page_order(page);
  7019. zone->free_area[order].nr_free--;
  7020. for (i = 0; i < (1 << order); i++)
  7021. SetPageReserved((page+i));
  7022. pfn += (1 << order);
  7023. }
  7024. spin_unlock_irqrestore(&zone->lock, flags);
  7025. }
  7026. #endif
  7027. bool is_free_buddy_page(struct page *page)
  7028. {
  7029. struct zone *zone = page_zone(page);
  7030. unsigned long pfn = page_to_pfn(page);
  7031. unsigned long flags;
  7032. unsigned int order;
  7033. spin_lock_irqsave(&zone->lock, flags);
  7034. for (order = 0; order < MAX_ORDER; order++) {
  7035. struct page *page_head = page - (pfn & ((1 << order) - 1));
  7036. if (PageBuddy(page_head) && page_order(page_head) >= order)
  7037. break;
  7038. }
  7039. spin_unlock_irqrestore(&zone->lock, flags);
  7040. return order < MAX_ORDER;
  7041. }
  7042. #ifdef CONFIG_MEMORY_FAILURE
  7043. /*
  7044. * Set PG_hwpoison flag if a given page is confirmed to be a free page. This
  7045. * test is performed under the zone lock to prevent a race against page
  7046. * allocation.
  7047. */
  7048. bool set_hwpoison_free_buddy_page(struct page *page)
  7049. {
  7050. struct zone *zone = page_zone(page);
  7051. unsigned long pfn = page_to_pfn(page);
  7052. unsigned long flags;
  7053. unsigned int order;
  7054. bool hwpoisoned = false;
  7055. spin_lock_irqsave(&zone->lock, flags);
  7056. for (order = 0; order < MAX_ORDER; order++) {
  7057. struct page *page_head = page - (pfn & ((1 << order) - 1));
  7058. if (PageBuddy(page_head) && page_order(page_head) >= order) {
  7059. if (!TestSetPageHWPoison(page))
  7060. hwpoisoned = true;
  7061. break;
  7062. }
  7063. }
  7064. spin_unlock_irqrestore(&zone->lock, flags);
  7065. return hwpoisoned;
  7066. }
  7067. #endif