page_alloc.c 182 KB

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