page_alloc.c 222 KB

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