page_alloc.c 254 KB

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