page_alloc.c 193 KB

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