page_alloc.c 189 KB

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