page_alloc.c 204 KB

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