page_alloc.c 183 KB

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