page_alloc.c 198 KB

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