page_alloc.c 178 KB

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