page_alloc.c 183 KB

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