page_alloc.c 192 KB

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