page_alloc.c 199 KB

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