page_alloc.c 217 KB

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