page_alloc.c 219 KB

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