page_alloc.c 204 KB

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