page_alloc.c 199 KB

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