page_alloc.c 214 KB

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