page_alloc.c 213 KB

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