page_alloc.c 190 KB

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