page_alloc.c 205 KB

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