page_alloc.c 194 KB

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