page_alloc.c 192 KB

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