page_alloc.c 206 KB

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