page_alloc.c 171 KB

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