page_alloc.c 222 KB

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