page_alloc.c 218 KB

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