page_alloc.c 176 KB

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