page_alloc.c 224 KB

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