page_alloc.c 221 KB

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