page_alloc.c 219 KB

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