page_alloc.c 206 KB

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