page_alloc.c 209 KB

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