page_alloc.c 193 KB

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