page_alloc.c 207 KB

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