page_alloc.c 189 KB

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