page_alloc.c 201 KB

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