page_alloc.c 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/page_alloc.c
  4. *
  5. * Manages the free list, the system allocates free pages here.
  6. * Note that kmalloc() lives in slab.c
  7. *
  8. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  9. * Swap reorganised 29.12.95, Stephen Tweedie
  10. * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
  11. * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
  12. * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
  13. * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
  14. * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
  15. * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
  16. */
  17. #include <linux/stddef.h>
  18. #include <linux/mm.h>
  19. #include <linux/highmem.h>
  20. #include <linux/interrupt.h>
  21. #include <linux/jiffies.h>
  22. #include <linux/compiler.h>
  23. #include <linux/kernel.h>
  24. #include <linux/kasan.h>
  25. #include <linux/kmsan.h>
  26. #include <linux/module.h>
  27. #include <linux/suspend.h>
  28. #include <linux/ratelimit.h>
  29. #include <linux/oom.h>
  30. #include <linux/topology.h>
  31. #include <linux/sysctl.h>
  32. #include <linux/cpu.h>
  33. #include <linux/cpuset.h>
  34. #include <linux/pagevec.h>
  35. #include <linux/memory_hotplug.h>
  36. #include <linux/nodemask.h>
  37. #include <linux/vmstat.h>
  38. #include <linux/fault-inject.h>
  39. #include <linux/compaction.h>
  40. #include <trace/events/kmem.h>
  41. #include <trace/events/oom.h>
  42. #include <linux/prefetch.h>
  43. #include <linux/mm_inline.h>
  44. #include <linux/mmu_notifier.h>
  45. #include <linux/migrate.h>
  46. #include <linux/sched/mm.h>
  47. #include <linux/page_owner.h>
  48. #include <linux/page_table_check.h>
  49. #include <linux/memcontrol.h>
  50. #include <linux/ftrace.h>
  51. #include <linux/lockdep.h>
  52. #include <linux/psi.h>
  53. #include <linux/khugepaged.h>
  54. #include <linux/delayacct.h>
  55. #include <linux/cacheinfo.h>
  56. #include <linux/pgalloc_tag.h>
  57. #include <asm/div64.h>
  58. #include "internal.h"
  59. #include "shuffle.h"
  60. #include "page_reporting.h"
  61. /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
  62. typedef int __bitwise fpi_t;
  63. /* No special request */
  64. #define FPI_NONE ((__force fpi_t)0)
  65. /*
  66. * Skip free page reporting notification for the (possibly merged) page.
  67. * This does not hinder free page reporting from grabbing the page,
  68. * reporting it and marking it "reported" - it only skips notifying
  69. * the free page reporting infrastructure about a newly freed page. For
  70. * example, used when temporarily pulling a page from a freelist and
  71. * putting it back unmodified.
  72. */
  73. #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
  74. /*
  75. * Place the (possibly merged) page to the tail of the freelist. Will ignore
  76. * page shuffling (relevant code - e.g., memory onlining - is expected to
  77. * shuffle the whole zone).
  78. *
  79. * Note: No code should rely on this flag for correctness - it's purely
  80. * to allow for optimizations when handing back either fresh pages
  81. * (memory onlining) or untouched pages (page isolation, free page
  82. * reporting).
  83. */
  84. #define FPI_TO_TAIL ((__force fpi_t)BIT(1))
  85. /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
  86. static DEFINE_MUTEX(pcp_batch_high_lock);
  87. #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8)
  88. #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT)
  89. /*
  90. * On SMP, spin_trylock is sufficient protection.
  91. * On PREEMPT_RT, spin_trylock is equivalent on both SMP and UP.
  92. */
  93. #define pcp_trylock_prepare(flags) do { } while (0)
  94. #define pcp_trylock_finish(flag) do { } while (0)
  95. #else
  96. /* UP spin_trylock always succeeds so disable IRQs to prevent re-entrancy. */
  97. #define pcp_trylock_prepare(flags) local_irq_save(flags)
  98. #define pcp_trylock_finish(flags) local_irq_restore(flags)
  99. #endif
  100. /*
  101. * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid
  102. * a migration causing the wrong PCP to be locked and remote memory being
  103. * potentially allocated, pin the task to the CPU for the lookup+lock.
  104. * preempt_disable is used on !RT because it is faster than migrate_disable.
  105. * migrate_disable is used on RT because otherwise RT spinlock usage is
  106. * interfered with and a high priority task cannot preempt the allocator.
  107. */
  108. #ifndef CONFIG_PREEMPT_RT
  109. #define pcpu_task_pin() preempt_disable()
  110. #define pcpu_task_unpin() preempt_enable()
  111. #else
  112. #define pcpu_task_pin() migrate_disable()
  113. #define pcpu_task_unpin() migrate_enable()
  114. #endif
  115. /*
  116. * Generic helper to lookup and a per-cpu variable with an embedded spinlock.
  117. * Return value should be used with equivalent unlock helper.
  118. */
  119. #define pcpu_spin_lock(type, member, ptr) \
  120. ({ \
  121. type *_ret; \
  122. pcpu_task_pin(); \
  123. _ret = this_cpu_ptr(ptr); \
  124. spin_lock(&_ret->member); \
  125. _ret; \
  126. })
  127. #define pcpu_spin_trylock(type, member, ptr) \
  128. ({ \
  129. type *_ret; \
  130. pcpu_task_pin(); \
  131. _ret = this_cpu_ptr(ptr); \
  132. if (!spin_trylock(&_ret->member)) { \
  133. pcpu_task_unpin(); \
  134. _ret = NULL; \
  135. } \
  136. _ret; \
  137. })
  138. #define pcpu_spin_unlock(member, ptr) \
  139. ({ \
  140. spin_unlock(&ptr->member); \
  141. pcpu_task_unpin(); \
  142. })
  143. /* struct per_cpu_pages specific helpers. */
  144. #define pcp_spin_lock(ptr) \
  145. pcpu_spin_lock(struct per_cpu_pages, lock, ptr)
  146. #define pcp_spin_trylock(ptr) \
  147. pcpu_spin_trylock(struct per_cpu_pages, lock, ptr)
  148. #define pcp_spin_unlock(ptr) \
  149. pcpu_spin_unlock(lock, ptr)
  150. #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
  151. DEFINE_PER_CPU(int, numa_node);
  152. EXPORT_PER_CPU_SYMBOL(numa_node);
  153. #endif
  154. DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
  155. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  156. /*
  157. * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
  158. * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
  159. * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
  160. * defined in <linux/topology.h>.
  161. */
  162. DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
  163. EXPORT_PER_CPU_SYMBOL(_numa_mem_);
  164. #endif
  165. static DEFINE_MUTEX(pcpu_drain_mutex);
  166. #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
  167. volatile unsigned long latent_entropy __latent_entropy;
  168. EXPORT_SYMBOL(latent_entropy);
  169. #endif
  170. /*
  171. * Array of node states.
  172. */
  173. nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
  174. [N_POSSIBLE] = NODE_MASK_ALL,
  175. [N_ONLINE] = { { [0] = 1UL } },
  176. #ifndef CONFIG_NUMA
  177. [N_NORMAL_MEMORY] = { { [0] = 1UL } },
  178. #ifdef CONFIG_HIGHMEM
  179. [N_HIGH_MEMORY] = { { [0] = 1UL } },
  180. #endif
  181. [N_MEMORY] = { { [0] = 1UL } },
  182. [N_CPU] = { { [0] = 1UL } },
  183. #endif /* NUMA */
  184. };
  185. EXPORT_SYMBOL(node_states);
  186. gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
  187. #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
  188. unsigned int pageblock_order __read_mostly;
  189. #endif
  190. static void __free_pages_ok(struct page *page, unsigned int order,
  191. fpi_t fpi_flags);
  192. /*
  193. * results with 256, 32 in the lowmem_reserve sysctl:
  194. * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
  195. * 1G machine -> (16M dma, 784M normal, 224M high)
  196. * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
  197. * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
  198. * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
  199. *
  200. * TBD: should special case ZONE_DMA32 machines here - in those we normally
  201. * don't need any ZONE_NORMAL reservation
  202. */
  203. static int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
  204. #ifdef CONFIG_ZONE_DMA
  205. [ZONE_DMA] = 256,
  206. #endif
  207. #ifdef CONFIG_ZONE_DMA32
  208. [ZONE_DMA32] = 256,
  209. #endif
  210. [ZONE_NORMAL] = 32,
  211. #ifdef CONFIG_HIGHMEM
  212. [ZONE_HIGHMEM] = 0,
  213. #endif
  214. [ZONE_MOVABLE] = 0,
  215. };
  216. char * const zone_names[MAX_NR_ZONES] = {
  217. #ifdef CONFIG_ZONE_DMA
  218. "DMA",
  219. #endif
  220. #ifdef CONFIG_ZONE_DMA32
  221. "DMA32",
  222. #endif
  223. "Normal",
  224. #ifdef CONFIG_HIGHMEM
  225. "HighMem",
  226. #endif
  227. "Movable",
  228. #ifdef CONFIG_ZONE_DEVICE
  229. "Device",
  230. #endif
  231. };
  232. const char * const migratetype_names[MIGRATE_TYPES] = {
  233. "Unmovable",
  234. "Movable",
  235. "Reclaimable",
  236. "HighAtomic",
  237. #ifdef CONFIG_CMA
  238. "CMA",
  239. #endif
  240. #ifdef CONFIG_MEMORY_ISOLATION
  241. "Isolate",
  242. #endif
  243. };
  244. int min_free_kbytes = 1024;
  245. int user_min_free_kbytes = -1;
  246. static int watermark_boost_factor __read_mostly = 15000;
  247. static int watermark_scale_factor = 10;
  248. /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
  249. int movable_zone;
  250. EXPORT_SYMBOL(movable_zone);
  251. #if MAX_NUMNODES > 1
  252. unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
  253. unsigned int nr_online_nodes __read_mostly = 1;
  254. EXPORT_SYMBOL(nr_node_ids);
  255. EXPORT_SYMBOL(nr_online_nodes);
  256. #endif
  257. static bool page_contains_unaccepted(struct page *page, unsigned int order);
  258. static bool cond_accept_memory(struct zone *zone, unsigned int order);
  259. static bool __free_unaccepted(struct page *page);
  260. int page_group_by_mobility_disabled __read_mostly;
  261. #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
  262. /*
  263. * During boot we initialize deferred pages on-demand, as needed, but once
  264. * page_alloc_init_late() has finished, the deferred pages are all initialized,
  265. * and we can permanently disable that path.
  266. */
  267. DEFINE_STATIC_KEY_TRUE(deferred_pages);
  268. static inline bool deferred_pages_enabled(void)
  269. {
  270. return static_branch_unlikely(&deferred_pages);
  271. }
  272. /*
  273. * deferred_grow_zone() is __init, but it is called from
  274. * get_page_from_freelist() during early boot until deferred_pages permanently
  275. * disables this call. This is why we have refdata wrapper to avoid warning,
  276. * and to ensure that the function body gets unloaded.
  277. */
  278. static bool __ref
  279. _deferred_grow_zone(struct zone *zone, unsigned int order)
  280. {
  281. return deferred_grow_zone(zone, order);
  282. }
  283. #else
  284. static inline bool deferred_pages_enabled(void)
  285. {
  286. return false;
  287. }
  288. static inline bool _deferred_grow_zone(struct zone *zone, unsigned int order)
  289. {
  290. return false;
  291. }
  292. #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
  293. /* Return a pointer to the bitmap storing bits affecting a block of pages */
  294. static inline unsigned long *get_pageblock_bitmap(const struct page *page,
  295. unsigned long pfn)
  296. {
  297. #ifdef CONFIG_SPARSEMEM
  298. return section_to_usemap(__pfn_to_section(pfn));
  299. #else
  300. return page_zone(page)->pageblock_flags;
  301. #endif /* CONFIG_SPARSEMEM */
  302. }
  303. static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
  304. {
  305. #ifdef CONFIG_SPARSEMEM
  306. pfn &= (PAGES_PER_SECTION-1);
  307. #else
  308. pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn);
  309. #endif /* CONFIG_SPARSEMEM */
  310. return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
  311. }
  312. /**
  313. * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
  314. * @page: The page within the block of interest
  315. * @pfn: The target page frame number
  316. * @mask: mask of bits that the caller is interested in
  317. *
  318. * Return: pageblock_bits flags
  319. */
  320. unsigned long get_pfnblock_flags_mask(const struct page *page,
  321. unsigned long pfn, unsigned long mask)
  322. {
  323. unsigned long *bitmap;
  324. unsigned long bitidx, word_bitidx;
  325. unsigned long word;
  326. bitmap = get_pageblock_bitmap(page, pfn);
  327. bitidx = pfn_to_bitidx(page, pfn);
  328. word_bitidx = bitidx / BITS_PER_LONG;
  329. bitidx &= (BITS_PER_LONG-1);
  330. /*
  331. * This races, without locks, with set_pfnblock_flags_mask(). Ensure
  332. * a consistent read of the memory array, so that results, even though
  333. * racy, are not corrupted.
  334. */
  335. word = READ_ONCE(bitmap[word_bitidx]);
  336. return (word >> bitidx) & mask;
  337. }
  338. static __always_inline int get_pfnblock_migratetype(const struct page *page,
  339. unsigned long pfn)
  340. {
  341. return get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK);
  342. }
  343. /**
  344. * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
  345. * @page: The page within the block of interest
  346. * @flags: The flags to set
  347. * @pfn: The target page frame number
  348. * @mask: mask of bits that the caller is interested in
  349. */
  350. void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
  351. unsigned long pfn,
  352. unsigned long mask)
  353. {
  354. unsigned long *bitmap;
  355. unsigned long bitidx, word_bitidx;
  356. unsigned long word;
  357. BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
  358. BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
  359. bitmap = get_pageblock_bitmap(page, pfn);
  360. bitidx = pfn_to_bitidx(page, pfn);
  361. word_bitidx = bitidx / BITS_PER_LONG;
  362. bitidx &= (BITS_PER_LONG-1);
  363. VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
  364. mask <<= bitidx;
  365. flags <<= bitidx;
  366. word = READ_ONCE(bitmap[word_bitidx]);
  367. do {
  368. } while (!try_cmpxchg(&bitmap[word_bitidx], &word, (word & ~mask) | flags));
  369. }
  370. void set_pageblock_migratetype(struct page *page, int migratetype)
  371. {
  372. if (unlikely(page_group_by_mobility_disabled &&
  373. migratetype < MIGRATE_PCPTYPES))
  374. migratetype = MIGRATE_UNMOVABLE;
  375. set_pfnblock_flags_mask(page, (unsigned long)migratetype,
  376. page_to_pfn(page), MIGRATETYPE_MASK);
  377. }
  378. #ifdef CONFIG_DEBUG_VM
  379. static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
  380. {
  381. int ret;
  382. unsigned seq;
  383. unsigned long pfn = page_to_pfn(page);
  384. unsigned long sp, start_pfn;
  385. do {
  386. seq = zone_span_seqbegin(zone);
  387. start_pfn = zone->zone_start_pfn;
  388. sp = zone->spanned_pages;
  389. ret = !zone_spans_pfn(zone, pfn);
  390. } while (zone_span_seqretry(zone, seq));
  391. if (ret)
  392. pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
  393. pfn, zone_to_nid(zone), zone->name,
  394. start_pfn, start_pfn + sp);
  395. return ret;
  396. }
  397. /*
  398. * Temporary debugging check for pages not lying within a given zone.
  399. */
  400. static bool __maybe_unused bad_range(struct zone *zone, struct page *page)
  401. {
  402. if (page_outside_zone_boundaries(zone, page))
  403. return true;
  404. if (zone != page_zone(page))
  405. return true;
  406. return false;
  407. }
  408. #else
  409. static inline bool __maybe_unused bad_range(struct zone *zone, struct page *page)
  410. {
  411. return false;
  412. }
  413. #endif
  414. static void bad_page(struct page *page, const char *reason)
  415. {
  416. static unsigned long resume;
  417. static unsigned long nr_shown;
  418. static unsigned long nr_unshown;
  419. /*
  420. * Allow a burst of 60 reports, then keep quiet for that minute;
  421. * or allow a steady drip of one report per second.
  422. */
  423. if (nr_shown == 60) {
  424. if (time_before(jiffies, resume)) {
  425. nr_unshown++;
  426. goto out;
  427. }
  428. if (nr_unshown) {
  429. pr_alert(
  430. "BUG: Bad page state: %lu messages suppressed\n",
  431. nr_unshown);
  432. nr_unshown = 0;
  433. }
  434. nr_shown = 0;
  435. }
  436. if (nr_shown++ == 0)
  437. resume = jiffies + 60 * HZ;
  438. pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
  439. current->comm, page_to_pfn(page));
  440. dump_page(page, reason);
  441. print_modules();
  442. dump_stack();
  443. out:
  444. /* Leave bad fields for debug, except PageBuddy could make trouble */
  445. if (PageBuddy(page))
  446. __ClearPageBuddy(page);
  447. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  448. }
  449. static inline unsigned int order_to_pindex(int migratetype, int order)
  450. {
  451. bool __maybe_unused movable;
  452. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  453. if (order > PAGE_ALLOC_COSTLY_ORDER) {
  454. VM_BUG_ON(order != HPAGE_PMD_ORDER);
  455. movable = migratetype == MIGRATE_MOVABLE;
  456. return NR_LOWORDER_PCP_LISTS + movable;
  457. }
  458. #else
  459. VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
  460. #endif
  461. return (MIGRATE_PCPTYPES * order) + migratetype;
  462. }
  463. static inline int pindex_to_order(unsigned int pindex)
  464. {
  465. int order = pindex / MIGRATE_PCPTYPES;
  466. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  467. if (pindex >= NR_LOWORDER_PCP_LISTS)
  468. order = HPAGE_PMD_ORDER;
  469. #else
  470. VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
  471. #endif
  472. return order;
  473. }
  474. static inline bool pcp_allowed_order(unsigned int order)
  475. {
  476. if (order <= PAGE_ALLOC_COSTLY_ORDER)
  477. return true;
  478. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  479. if (order == HPAGE_PMD_ORDER)
  480. return true;
  481. #endif
  482. return false;
  483. }
  484. /*
  485. * Higher-order pages are called "compound pages". They are structured thusly:
  486. *
  487. * The first PAGE_SIZE page is called the "head page" and have PG_head set.
  488. *
  489. * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
  490. * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
  491. *
  492. * The first tail page's ->compound_order holds the order of allocation.
  493. * This usage means that zero-order pages may not be compound.
  494. */
  495. void prep_compound_page(struct page *page, unsigned int order)
  496. {
  497. int i;
  498. int nr_pages = 1 << order;
  499. __SetPageHead(page);
  500. for (i = 1; i < nr_pages; i++)
  501. prep_compound_tail(page, i);
  502. prep_compound_head(page, order);
  503. }
  504. static inline void set_buddy_order(struct page *page, unsigned int order)
  505. {
  506. set_page_private(page, order);
  507. __SetPageBuddy(page);
  508. }
  509. #ifdef CONFIG_COMPACTION
  510. static inline struct capture_control *task_capc(struct zone *zone)
  511. {
  512. struct capture_control *capc = current->capture_control;
  513. return unlikely(capc) &&
  514. !(current->flags & PF_KTHREAD) &&
  515. !capc->page &&
  516. capc->cc->zone == zone ? capc : NULL;
  517. }
  518. static inline bool
  519. compaction_capture(struct capture_control *capc, struct page *page,
  520. int order, int migratetype)
  521. {
  522. if (!capc || order != capc->cc->order)
  523. return false;
  524. /* Do not accidentally pollute CMA or isolated regions*/
  525. if (is_migrate_cma(migratetype) ||
  526. is_migrate_isolate(migratetype))
  527. return false;
  528. /*
  529. * Do not let lower order allocations pollute a movable pageblock
  530. * unless compaction is also requesting movable pages.
  531. * This might let an unmovable request use a reclaimable pageblock
  532. * and vice-versa but no more than normal fallback logic which can
  533. * have trouble finding a high-order free page.
  534. */
  535. if (order < pageblock_order && migratetype == MIGRATE_MOVABLE &&
  536. capc->cc->migratetype != MIGRATE_MOVABLE)
  537. return false;
  538. capc->page = page;
  539. return true;
  540. }
  541. #else
  542. static inline struct capture_control *task_capc(struct zone *zone)
  543. {
  544. return NULL;
  545. }
  546. static inline bool
  547. compaction_capture(struct capture_control *capc, struct page *page,
  548. int order, int migratetype)
  549. {
  550. return false;
  551. }
  552. #endif /* CONFIG_COMPACTION */
  553. static inline void account_freepages(struct zone *zone, int nr_pages,
  554. int migratetype)
  555. {
  556. lockdep_assert_held(&zone->lock);
  557. if (is_migrate_isolate(migratetype))
  558. return;
  559. __mod_zone_page_state(zone, NR_FREE_PAGES, nr_pages);
  560. if (is_migrate_cma(migratetype))
  561. __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, nr_pages);
  562. else if (is_migrate_highatomic(migratetype))
  563. WRITE_ONCE(zone->nr_free_highatomic,
  564. zone->nr_free_highatomic + nr_pages);
  565. }
  566. /* Used for pages not on another list */
  567. static inline void __add_to_free_list(struct page *page, struct zone *zone,
  568. unsigned int order, int migratetype,
  569. bool tail)
  570. {
  571. struct free_area *area = &zone->free_area[order];
  572. VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
  573. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  574. get_pageblock_migratetype(page), migratetype, 1 << order);
  575. if (tail)
  576. list_add_tail(&page->buddy_list, &area->free_list[migratetype]);
  577. else
  578. list_add(&page->buddy_list, &area->free_list[migratetype]);
  579. area->nr_free++;
  580. }
  581. /*
  582. * Used for pages which are on another list. Move the pages to the tail
  583. * of the list - so the moved pages won't immediately be considered for
  584. * allocation again (e.g., optimization for memory onlining).
  585. */
  586. static inline void move_to_free_list(struct page *page, struct zone *zone,
  587. unsigned int order, int old_mt, int new_mt)
  588. {
  589. struct free_area *area = &zone->free_area[order];
  590. /* Free page moving can fail, so it happens before the type update */
  591. VM_WARN_ONCE(get_pageblock_migratetype(page) != old_mt,
  592. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  593. get_pageblock_migratetype(page), old_mt, 1 << order);
  594. list_move_tail(&page->buddy_list, &area->free_list[new_mt]);
  595. account_freepages(zone, -(1 << order), old_mt);
  596. account_freepages(zone, 1 << order, new_mt);
  597. }
  598. static inline void __del_page_from_free_list(struct page *page, struct zone *zone,
  599. unsigned int order, int migratetype)
  600. {
  601. VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
  602. "page type is %lu, passed migratetype is %d (nr=%d)\n",
  603. get_pageblock_migratetype(page), migratetype, 1 << order);
  604. /* clear reported state and update reported page count */
  605. if (page_reported(page))
  606. __ClearPageReported(page);
  607. list_del(&page->buddy_list);
  608. __ClearPageBuddy(page);
  609. set_page_private(page, 0);
  610. zone->free_area[order].nr_free--;
  611. }
  612. static inline void del_page_from_free_list(struct page *page, struct zone *zone,
  613. unsigned int order, int migratetype)
  614. {
  615. __del_page_from_free_list(page, zone, order, migratetype);
  616. account_freepages(zone, -(1 << order), migratetype);
  617. }
  618. static inline struct page *get_page_from_free_area(struct free_area *area,
  619. int migratetype)
  620. {
  621. return list_first_entry_or_null(&area->free_list[migratetype],
  622. struct page, buddy_list);
  623. }
  624. /*
  625. * If this is less than the 2nd largest possible page, check if the buddy
  626. * of the next-higher order is free. If it is, it's possible
  627. * that pages are being freed that will coalesce soon. In case,
  628. * that is happening, add the free page to the tail of the list
  629. * so it's less likely to be used soon and more likely to be merged
  630. * as a 2-level higher order page
  631. */
  632. static inline bool
  633. buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
  634. struct page *page, unsigned int order)
  635. {
  636. unsigned long higher_page_pfn;
  637. struct page *higher_page;
  638. if (order >= MAX_PAGE_ORDER - 1)
  639. return false;
  640. higher_page_pfn = buddy_pfn & pfn;
  641. higher_page = page + (higher_page_pfn - pfn);
  642. return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1,
  643. NULL) != NULL;
  644. }
  645. /*
  646. * Freeing function for a buddy system allocator.
  647. *
  648. * The concept of a buddy system is to maintain direct-mapped table
  649. * (containing bit values) for memory blocks of various "orders".
  650. * The bottom level table contains the map for the smallest allocatable
  651. * units of memory (here, pages), and each level above it describes
  652. * pairs of units from the levels below, hence, "buddies".
  653. * At a high level, all that happens here is marking the table entry
  654. * at the bottom level available, and propagating the changes upward
  655. * as necessary, plus some accounting needed to play nicely with other
  656. * parts of the VM system.
  657. * At each level, we keep a list of pages, which are heads of continuous
  658. * free pages of length of (1 << order) and marked with PageBuddy.
  659. * Page's order is recorded in page_private(page) field.
  660. * So when we are allocating or freeing one, we can derive the state of the
  661. * other. That is, if we allocate a small block, and both were
  662. * free, the remainder of the region must be split into blocks.
  663. * If a block is freed, and its buddy is also free, then this
  664. * triggers coalescing into a block of larger size.
  665. *
  666. * -- nyc
  667. */
  668. static inline void __free_one_page(struct page *page,
  669. unsigned long pfn,
  670. struct zone *zone, unsigned int order,
  671. int migratetype, fpi_t fpi_flags)
  672. {
  673. struct capture_control *capc = task_capc(zone);
  674. unsigned long buddy_pfn = 0;
  675. unsigned long combined_pfn;
  676. struct page *buddy;
  677. bool to_tail;
  678. VM_BUG_ON(!zone_is_initialized(zone));
  679. VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
  680. VM_BUG_ON(migratetype == -1);
  681. VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
  682. VM_BUG_ON_PAGE(bad_range(zone, page), page);
  683. account_freepages(zone, 1 << order, migratetype);
  684. while (order < MAX_PAGE_ORDER) {
  685. int buddy_mt = migratetype;
  686. if (compaction_capture(capc, page, order, migratetype)) {
  687. account_freepages(zone, -(1 << order), migratetype);
  688. return;
  689. }
  690. buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn);
  691. if (!buddy)
  692. goto done_merging;
  693. if (unlikely(order >= pageblock_order)) {
  694. /*
  695. * We want to prevent merge between freepages on pageblock
  696. * without fallbacks and normal pageblock. Without this,
  697. * pageblock isolation could cause incorrect freepage or CMA
  698. * accounting or HIGHATOMIC accounting.
  699. */
  700. buddy_mt = get_pfnblock_migratetype(buddy, buddy_pfn);
  701. if (migratetype != buddy_mt &&
  702. (!migratetype_is_mergeable(migratetype) ||
  703. !migratetype_is_mergeable(buddy_mt)))
  704. goto done_merging;
  705. }
  706. /*
  707. * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
  708. * merge with it and move up one order.
  709. */
  710. if (page_is_guard(buddy))
  711. clear_page_guard(zone, buddy, order);
  712. else
  713. __del_page_from_free_list(buddy, zone, order, buddy_mt);
  714. if (unlikely(buddy_mt != migratetype)) {
  715. /*
  716. * Match buddy type. This ensures that an
  717. * expand() down the line puts the sub-blocks
  718. * on the right freelists.
  719. */
  720. set_pageblock_migratetype(buddy, migratetype);
  721. }
  722. combined_pfn = buddy_pfn & pfn;
  723. page = page + (combined_pfn - pfn);
  724. pfn = combined_pfn;
  725. order++;
  726. }
  727. done_merging:
  728. set_buddy_order(page, order);
  729. if (fpi_flags & FPI_TO_TAIL)
  730. to_tail = true;
  731. else if (is_shuffle_order(order))
  732. to_tail = shuffle_pick_tail();
  733. else
  734. to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
  735. __add_to_free_list(page, zone, order, migratetype, to_tail);
  736. /* Notify page reporting subsystem of freed page */
  737. if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
  738. page_reporting_notify_free(order);
  739. }
  740. /*
  741. * A bad page could be due to a number of fields. Instead of multiple branches,
  742. * try and check multiple fields with one check. The caller must do a detailed
  743. * check if necessary.
  744. */
  745. static inline bool page_expected_state(struct page *page,
  746. unsigned long check_flags)
  747. {
  748. if (unlikely(atomic_read(&page->_mapcount) != -1))
  749. return false;
  750. if (unlikely((unsigned long)page->mapping |
  751. page_ref_count(page) |
  752. #ifdef CONFIG_MEMCG
  753. page->memcg_data |
  754. #endif
  755. page_pool_page_is_pp(page) |
  756. (page->flags & check_flags)))
  757. return false;
  758. return true;
  759. }
  760. static const char *page_bad_reason(struct page *page, unsigned long flags)
  761. {
  762. const char *bad_reason = NULL;
  763. if (unlikely(atomic_read(&page->_mapcount) != -1))
  764. bad_reason = "nonzero mapcount";
  765. if (unlikely(page->mapping != NULL))
  766. bad_reason = "non-NULL mapping";
  767. if (unlikely(page_ref_count(page) != 0))
  768. bad_reason = "nonzero _refcount";
  769. if (unlikely(page->flags & flags)) {
  770. if (flags == PAGE_FLAGS_CHECK_AT_PREP)
  771. bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
  772. else
  773. bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
  774. }
  775. #ifdef CONFIG_MEMCG
  776. if (unlikely(page->memcg_data))
  777. bad_reason = "page still charged to cgroup";
  778. #endif
  779. if (unlikely(page_pool_page_is_pp(page)))
  780. bad_reason = "page_pool leak";
  781. return bad_reason;
  782. }
  783. static void free_page_is_bad_report(struct page *page)
  784. {
  785. bad_page(page,
  786. page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
  787. }
  788. static inline bool free_page_is_bad(struct page *page)
  789. {
  790. if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
  791. return false;
  792. /* Something has gone sideways, find it */
  793. free_page_is_bad_report(page);
  794. return true;
  795. }
  796. static inline bool is_check_pages_enabled(void)
  797. {
  798. return static_branch_unlikely(&check_pages_enabled);
  799. }
  800. static int free_tail_page_prepare(struct page *head_page, struct page *page)
  801. {
  802. struct folio *folio = (struct folio *)head_page;
  803. int ret = 1;
  804. /*
  805. * We rely page->lru.next never has bit 0 set, unless the page
  806. * is PageTail(). Let's make sure that's true even for poisoned ->lru.
  807. */
  808. BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
  809. if (!is_check_pages_enabled()) {
  810. ret = 0;
  811. goto out;
  812. }
  813. switch (page - head_page) {
  814. case 1:
  815. /* the first tail page: these may be in place of ->mapping */
  816. if (unlikely(folio_entire_mapcount(folio))) {
  817. bad_page(page, "nonzero entire_mapcount");
  818. goto out;
  819. }
  820. if (unlikely(folio_large_mapcount(folio))) {
  821. bad_page(page, "nonzero large_mapcount");
  822. goto out;
  823. }
  824. if (unlikely(atomic_read(&folio->_nr_pages_mapped))) {
  825. bad_page(page, "nonzero nr_pages_mapped");
  826. goto out;
  827. }
  828. if (unlikely(atomic_read(&folio->_pincount))) {
  829. bad_page(page, "nonzero pincount");
  830. goto out;
  831. }
  832. break;
  833. case 2:
  834. /* the second tail page: deferred_list overlaps ->mapping */
  835. if (unlikely(!list_empty(&folio->_deferred_list))) {
  836. bad_page(page, "on deferred list");
  837. goto out;
  838. }
  839. break;
  840. default:
  841. if (page->mapping != TAIL_MAPPING) {
  842. bad_page(page, "corrupted mapping in tail page");
  843. goto out;
  844. }
  845. break;
  846. }
  847. if (unlikely(!PageTail(page))) {
  848. bad_page(page, "PageTail not set");
  849. goto out;
  850. }
  851. if (unlikely(compound_head(page) != head_page)) {
  852. bad_page(page, "compound_head not consistent");
  853. goto out;
  854. }
  855. ret = 0;
  856. out:
  857. page->mapping = NULL;
  858. clear_compound_head(page);
  859. return ret;
  860. }
  861. /*
  862. * Skip KASAN memory poisoning when either:
  863. *
  864. * 1. For generic KASAN: deferred memory initialization has not yet completed.
  865. * Tag-based KASAN modes skip pages freed via deferred memory initialization
  866. * using page tags instead (see below).
  867. * 2. For tag-based KASAN modes: the page has a match-all KASAN tag, indicating
  868. * that error detection is disabled for accesses via the page address.
  869. *
  870. * Pages will have match-all tags in the following circumstances:
  871. *
  872. * 1. Pages are being initialized for the first time, including during deferred
  873. * memory init; see the call to page_kasan_tag_reset in __init_single_page.
  874. * 2. The allocation was not unpoisoned due to __GFP_SKIP_KASAN, with the
  875. * exception of pages unpoisoned by kasan_unpoison_vmalloc.
  876. * 3. The allocation was excluded from being checked due to sampling,
  877. * see the call to kasan_unpoison_pages.
  878. *
  879. * Poisoning pages during deferred memory init will greatly lengthen the
  880. * process and cause problem in large memory systems as the deferred pages
  881. * initialization is done with interrupt disabled.
  882. *
  883. * Assuming that there will be no reference to those newly initialized
  884. * pages before they are ever allocated, this should have no effect on
  885. * KASAN memory tracking as the poison will be properly inserted at page
  886. * allocation time. The only corner case is when pages are allocated by
  887. * on-demand allocation and then freed again before the deferred pages
  888. * initialization is done, but this is not likely to happen.
  889. */
  890. static inline bool should_skip_kasan_poison(struct page *page)
  891. {
  892. if (IS_ENABLED(CONFIG_KASAN_GENERIC))
  893. return deferred_pages_enabled();
  894. return page_kasan_tag(page) == KASAN_TAG_KERNEL;
  895. }
  896. static void kernel_init_pages(struct page *page, int numpages)
  897. {
  898. int i;
  899. /* s390's use of memset() could override KASAN redzones. */
  900. kasan_disable_current();
  901. for (i = 0; i < numpages; i++)
  902. clear_highpage_kasan_tagged(page + i);
  903. kasan_enable_current();
  904. }
  905. __always_inline bool free_pages_prepare(struct page *page,
  906. unsigned int order)
  907. {
  908. int bad = 0;
  909. bool skip_kasan_poison = should_skip_kasan_poison(page);
  910. bool init = want_init_on_free();
  911. bool compound = PageCompound(page);
  912. struct folio *folio = page_folio(page);
  913. VM_BUG_ON_PAGE(PageTail(page), page);
  914. trace_mm_page_free(page, order);
  915. kmsan_free_page(page, order);
  916. if (memcg_kmem_online() && PageMemcgKmem(page))
  917. __memcg_kmem_uncharge_page(page, order);
  918. /*
  919. * In rare cases, when truncation or holepunching raced with
  920. * munlock after VM_LOCKED was cleared, Mlocked may still be
  921. * found set here. This does not indicate a problem, unless
  922. * "unevictable_pgs_cleared" appears worryingly large.
  923. */
  924. if (unlikely(folio_test_mlocked(folio))) {
  925. long nr_pages = folio_nr_pages(folio);
  926. __folio_clear_mlocked(folio);
  927. zone_stat_mod_folio(folio, NR_MLOCK, -nr_pages);
  928. count_vm_events(UNEVICTABLE_PGCLEARED, nr_pages);
  929. }
  930. if (unlikely(PageHWPoison(page)) && !order) {
  931. /* Do not let hwpoison pages hit pcplists/buddy */
  932. reset_page_owner(page, order);
  933. page_table_check_free(page, order);
  934. pgalloc_tag_sub(page, 1 << order);
  935. /*
  936. * The page is isolated and accounted for.
  937. * Mark the codetag as empty to avoid accounting error
  938. * when the page is freed by unpoison_memory().
  939. */
  940. clear_page_tag_ref(page);
  941. return false;
  942. }
  943. VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
  944. /*
  945. * Check tail pages before head page information is cleared to
  946. * avoid checking PageCompound for order-0 pages.
  947. */
  948. if (unlikely(order)) {
  949. int i;
  950. if (compound)
  951. page[1].flags &= ~PAGE_FLAGS_SECOND;
  952. for (i = 1; i < (1 << order); i++) {
  953. if (compound)
  954. bad += free_tail_page_prepare(page, page + i);
  955. if (is_check_pages_enabled()) {
  956. if (free_page_is_bad(page + i)) {
  957. bad++;
  958. continue;
  959. }
  960. }
  961. (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  962. }
  963. }
  964. if (PageMappingFlags(page)) {
  965. if (PageAnon(page))
  966. mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1);
  967. page->mapping = NULL;
  968. }
  969. if (is_check_pages_enabled()) {
  970. if (free_page_is_bad(page))
  971. bad++;
  972. if (bad)
  973. return false;
  974. }
  975. page_cpupid_reset_last(page);
  976. page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
  977. reset_page_owner(page, order);
  978. page_table_check_free(page, order);
  979. pgalloc_tag_sub(page, 1 << order);
  980. if (!PageHighMem(page)) {
  981. debug_check_no_locks_freed(page_address(page),
  982. PAGE_SIZE << order);
  983. debug_check_no_obj_freed(page_address(page),
  984. PAGE_SIZE << order);
  985. }
  986. kernel_poison_pages(page, 1 << order);
  987. /*
  988. * As memory initialization might be integrated into KASAN,
  989. * KASAN poisoning and memory initialization code must be
  990. * kept together to avoid discrepancies in behavior.
  991. *
  992. * With hardware tag-based KASAN, memory tags must be set before the
  993. * page becomes unavailable via debug_pagealloc or arch_free_page.
  994. */
  995. if (!skip_kasan_poison) {
  996. kasan_poison_pages(page, order, init);
  997. /* Memory is already initialized if KASAN did it internally. */
  998. if (kasan_has_integrated_init())
  999. init = false;
  1000. }
  1001. if (init)
  1002. kernel_init_pages(page, 1 << order);
  1003. /*
  1004. * arch_free_page() can make the page's contents inaccessible. s390
  1005. * does this. So nothing which can access the page's contents should
  1006. * happen after this.
  1007. */
  1008. arch_free_page(page, order);
  1009. debug_pagealloc_unmap_pages(page, 1 << order);
  1010. return true;
  1011. }
  1012. /*
  1013. * Frees a number of pages from the PCP lists
  1014. * Assumes all pages on list are in same zone.
  1015. * count is the number of pages to free.
  1016. */
  1017. static void free_pcppages_bulk(struct zone *zone, int count,
  1018. struct per_cpu_pages *pcp,
  1019. int pindex)
  1020. {
  1021. unsigned long flags;
  1022. unsigned int order;
  1023. struct page *page;
  1024. /*
  1025. * Ensure proper count is passed which otherwise would stuck in the
  1026. * below while (list_empty(list)) loop.
  1027. */
  1028. count = min(pcp->count, count);
  1029. /* Ensure requested pindex is drained first. */
  1030. pindex = pindex - 1;
  1031. spin_lock_irqsave(&zone->lock, flags);
  1032. while (count > 0) {
  1033. struct list_head *list;
  1034. int nr_pages;
  1035. /* Remove pages from lists in a round-robin fashion. */
  1036. do {
  1037. if (++pindex > NR_PCP_LISTS - 1)
  1038. pindex = 0;
  1039. list = &pcp->lists[pindex];
  1040. } while (list_empty(list));
  1041. order = pindex_to_order(pindex);
  1042. nr_pages = 1 << order;
  1043. do {
  1044. unsigned long pfn;
  1045. int mt;
  1046. page = list_last_entry(list, struct page, pcp_list);
  1047. pfn = page_to_pfn(page);
  1048. mt = get_pfnblock_migratetype(page, pfn);
  1049. /* must delete to avoid corrupting pcp list */
  1050. list_del(&page->pcp_list);
  1051. count -= nr_pages;
  1052. pcp->count -= nr_pages;
  1053. __free_one_page(page, pfn, zone, order, mt, FPI_NONE);
  1054. trace_mm_page_pcpu_drain(page, order, mt);
  1055. } while (count > 0 && !list_empty(list));
  1056. }
  1057. spin_unlock_irqrestore(&zone->lock, flags);
  1058. }
  1059. /* Split a multi-block free page into its individual pageblocks. */
  1060. static void split_large_buddy(struct zone *zone, struct page *page,
  1061. unsigned long pfn, int order, fpi_t fpi)
  1062. {
  1063. unsigned long end = pfn + (1 << order);
  1064. VM_WARN_ON_ONCE(!IS_ALIGNED(pfn, 1 << order));
  1065. /* Caller removed page from freelist, buddy info cleared! */
  1066. VM_WARN_ON_ONCE(PageBuddy(page));
  1067. if (order > pageblock_order)
  1068. order = pageblock_order;
  1069. do {
  1070. int mt = get_pfnblock_migratetype(page, pfn);
  1071. __free_one_page(page, pfn, zone, order, mt, fpi);
  1072. pfn += 1 << order;
  1073. if (pfn == end)
  1074. break;
  1075. page = pfn_to_page(pfn);
  1076. } while (1);
  1077. }
  1078. static void free_one_page(struct zone *zone, struct page *page,
  1079. unsigned long pfn, unsigned int order,
  1080. fpi_t fpi_flags)
  1081. {
  1082. unsigned long flags;
  1083. spin_lock_irqsave(&zone->lock, flags);
  1084. split_large_buddy(zone, page, pfn, order, fpi_flags);
  1085. spin_unlock_irqrestore(&zone->lock, flags);
  1086. __count_vm_events(PGFREE, 1 << order);
  1087. }
  1088. static void __free_pages_ok(struct page *page, unsigned int order,
  1089. fpi_t fpi_flags)
  1090. {
  1091. unsigned long pfn = page_to_pfn(page);
  1092. struct zone *zone = page_zone(page);
  1093. if (free_pages_prepare(page, order))
  1094. free_one_page(zone, page, pfn, order, fpi_flags);
  1095. }
  1096. void __meminit __free_pages_core(struct page *page, unsigned int order,
  1097. enum meminit_context context)
  1098. {
  1099. unsigned int nr_pages = 1 << order;
  1100. struct page *p = page;
  1101. unsigned int loop;
  1102. /*
  1103. * When initializing the memmap, __init_single_page() sets the refcount
  1104. * of all pages to 1 ("allocated"/"not free"). We have to set the
  1105. * refcount of all involved pages to 0.
  1106. *
  1107. * Note that hotplugged memory pages are initialized to PageOffline().
  1108. * Pages freed from memblock might be marked as reserved.
  1109. */
  1110. if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG) &&
  1111. unlikely(context == MEMINIT_HOTPLUG)) {
  1112. for (loop = 0; loop < nr_pages; loop++, p++) {
  1113. VM_WARN_ON_ONCE(PageReserved(p));
  1114. __ClearPageOffline(p);
  1115. set_page_count(p, 0);
  1116. }
  1117. /*
  1118. * Freeing the page with debug_pagealloc enabled will try to
  1119. * unmap it; some archs don't like double-unmappings, so
  1120. * map it first.
  1121. */
  1122. debug_pagealloc_map_pages(page, nr_pages);
  1123. adjust_managed_page_count(page, nr_pages);
  1124. } else {
  1125. for (loop = 0; loop < nr_pages; loop++, p++) {
  1126. __ClearPageReserved(p);
  1127. set_page_count(p, 0);
  1128. }
  1129. /* memblock adjusts totalram_pages() manually. */
  1130. atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
  1131. }
  1132. if (page_contains_unaccepted(page, order)) {
  1133. if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
  1134. return;
  1135. accept_memory(page_to_phys(page), PAGE_SIZE << order);
  1136. }
  1137. /*
  1138. * Bypass PCP and place fresh pages right to the tail, primarily
  1139. * relevant for memory onlining.
  1140. */
  1141. __free_pages_ok(page, order, FPI_TO_TAIL);
  1142. }
  1143. /*
  1144. * Check that the whole (or subset of) a pageblock given by the interval of
  1145. * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
  1146. * with the migration of free compaction scanner.
  1147. *
  1148. * Return struct page pointer of start_pfn, or NULL if checks were not passed.
  1149. *
  1150. * It's possible on some configurations to have a setup like node0 node1 node0
  1151. * i.e. it's possible that all pages within a zones range of pages do not
  1152. * belong to a single zone. We assume that a border between node0 and node1
  1153. * can occur within a single pageblock, but not a node0 node1 node0
  1154. * interleaving within a single pageblock. It is therefore sufficient to check
  1155. * the first and last page of a pageblock and avoid checking each individual
  1156. * page in a pageblock.
  1157. *
  1158. * Note: the function may return non-NULL struct page even for a page block
  1159. * which contains a memory hole (i.e. there is no physical memory for a subset
  1160. * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
  1161. * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
  1162. * even though the start pfn is online and valid. This should be safe most of
  1163. * the time because struct pages are still initialized via init_unavailable_range()
  1164. * and pfn walkers shouldn't touch any physical memory range for which they do
  1165. * not recognize any specific metadata in struct pages.
  1166. */
  1167. struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
  1168. unsigned long end_pfn, struct zone *zone)
  1169. {
  1170. struct page *start_page;
  1171. struct page *end_page;
  1172. /* end_pfn is one past the range we are checking */
  1173. end_pfn--;
  1174. if (!pfn_valid(end_pfn))
  1175. return NULL;
  1176. start_page = pfn_to_online_page(start_pfn);
  1177. if (!start_page)
  1178. return NULL;
  1179. if (page_zone(start_page) != zone)
  1180. return NULL;
  1181. end_page = pfn_to_page(end_pfn);
  1182. /* This gives a shorter code than deriving page_zone(end_page) */
  1183. if (page_zone_id(start_page) != page_zone_id(end_page))
  1184. return NULL;
  1185. return start_page;
  1186. }
  1187. /*
  1188. * The order of subdivision here is critical for the IO subsystem.
  1189. * Please do not alter this order without good reasons and regression
  1190. * testing. Specifically, as large blocks of memory are subdivided,
  1191. * the order in which smaller blocks are delivered depends on the order
  1192. * they're subdivided in this function. This is the primary factor
  1193. * influencing the order in which pages are delivered to the IO
  1194. * subsystem according to empirical testing, and this is also justified
  1195. * by considering the behavior of a buddy system containing a single
  1196. * large block of memory acted on by a series of small allocations.
  1197. * This behavior is a critical factor in sglist merging's success.
  1198. *
  1199. * -- nyc
  1200. */
  1201. static inline unsigned int expand(struct zone *zone, struct page *page, int low,
  1202. int high, int migratetype)
  1203. {
  1204. unsigned int size = 1 << high;
  1205. unsigned int nr_added = 0;
  1206. while (high > low) {
  1207. high--;
  1208. size >>= 1;
  1209. VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
  1210. /*
  1211. * Mark as guard pages (or page), that will allow to
  1212. * merge back to allocator when buddy will be freed.
  1213. * Corresponding page table entries will not be touched,
  1214. * pages will stay not present in virtual address space
  1215. */
  1216. if (set_page_guard(zone, &page[size], high))
  1217. continue;
  1218. __add_to_free_list(&page[size], zone, high, migratetype, false);
  1219. set_buddy_order(&page[size], high);
  1220. nr_added += size;
  1221. }
  1222. return nr_added;
  1223. }
  1224. static __always_inline void page_del_and_expand(struct zone *zone,
  1225. struct page *page, int low,
  1226. int high, int migratetype)
  1227. {
  1228. int nr_pages = 1 << high;
  1229. __del_page_from_free_list(page, zone, high, migratetype);
  1230. nr_pages -= expand(zone, page, low, high, migratetype);
  1231. account_freepages(zone, -nr_pages, migratetype);
  1232. }
  1233. static void check_new_page_bad(struct page *page)
  1234. {
  1235. if (unlikely(page->flags & __PG_HWPOISON)) {
  1236. /* Don't complain about hwpoisoned pages */
  1237. if (PageBuddy(page))
  1238. __ClearPageBuddy(page);
  1239. return;
  1240. }
  1241. bad_page(page,
  1242. page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
  1243. }
  1244. /*
  1245. * This page is about to be returned from the page allocator
  1246. */
  1247. static bool check_new_page(struct page *page)
  1248. {
  1249. if (likely(page_expected_state(page,
  1250. PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
  1251. return false;
  1252. check_new_page_bad(page);
  1253. return true;
  1254. }
  1255. static inline bool check_new_pages(struct page *page, unsigned int order)
  1256. {
  1257. if (is_check_pages_enabled()) {
  1258. for (int i = 0; i < (1 << order); i++) {
  1259. struct page *p = page + i;
  1260. if (check_new_page(p))
  1261. return true;
  1262. }
  1263. }
  1264. return false;
  1265. }
  1266. static inline bool should_skip_kasan_unpoison(gfp_t flags)
  1267. {
  1268. /* Don't skip if a software KASAN mode is enabled. */
  1269. if (IS_ENABLED(CONFIG_KASAN_GENERIC) ||
  1270. IS_ENABLED(CONFIG_KASAN_SW_TAGS))
  1271. return false;
  1272. /* Skip, if hardware tag-based KASAN is not enabled. */
  1273. if (!kasan_hw_tags_enabled())
  1274. return true;
  1275. /*
  1276. * With hardware tag-based KASAN enabled, skip if this has been
  1277. * requested via __GFP_SKIP_KASAN.
  1278. */
  1279. return flags & __GFP_SKIP_KASAN;
  1280. }
  1281. static inline bool should_skip_init(gfp_t flags)
  1282. {
  1283. /* Don't skip, if hardware tag-based KASAN is not enabled. */
  1284. if (!kasan_hw_tags_enabled())
  1285. return false;
  1286. /* For hardware tag-based KASAN, skip if requested. */
  1287. return (flags & __GFP_SKIP_ZERO);
  1288. }
  1289. inline void post_alloc_hook(struct page *page, unsigned int order,
  1290. gfp_t gfp_flags)
  1291. {
  1292. bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) &&
  1293. !should_skip_init(gfp_flags);
  1294. bool zero_tags = init && (gfp_flags & __GFP_ZEROTAGS);
  1295. int i;
  1296. set_page_private(page, 0);
  1297. set_page_refcounted(page);
  1298. arch_alloc_page(page, order);
  1299. debug_pagealloc_map_pages(page, 1 << order);
  1300. /*
  1301. * Page unpoisoning must happen before memory initialization.
  1302. * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
  1303. * allocations and the page unpoisoning code will complain.
  1304. */
  1305. kernel_unpoison_pages(page, 1 << order);
  1306. /*
  1307. * As memory initialization might be integrated into KASAN,
  1308. * KASAN unpoisoning and memory initializion code must be
  1309. * kept together to avoid discrepancies in behavior.
  1310. */
  1311. /*
  1312. * If memory tags should be zeroed
  1313. * (which happens only when memory should be initialized as well).
  1314. */
  1315. if (zero_tags) {
  1316. /* Initialize both memory and memory tags. */
  1317. for (i = 0; i != 1 << order; ++i)
  1318. tag_clear_highpage(page + i);
  1319. /* Take note that memory was initialized by the loop above. */
  1320. init = false;
  1321. }
  1322. if (!should_skip_kasan_unpoison(gfp_flags) &&
  1323. kasan_unpoison_pages(page, order, init)) {
  1324. /* Take note that memory was initialized by KASAN. */
  1325. if (kasan_has_integrated_init())
  1326. init = false;
  1327. } else {
  1328. /*
  1329. * If memory tags have not been set by KASAN, reset the page
  1330. * tags to ensure page_address() dereferencing does not fault.
  1331. */
  1332. for (i = 0; i != 1 << order; ++i)
  1333. page_kasan_tag_reset(page + i);
  1334. }
  1335. /* If memory is still not initialized, initialize it now. */
  1336. if (init)
  1337. kernel_init_pages(page, 1 << order);
  1338. set_page_owner(page, order, gfp_flags);
  1339. page_table_check_alloc(page, order);
  1340. pgalloc_tag_add(page, current, 1 << order);
  1341. }
  1342. static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
  1343. unsigned int alloc_flags)
  1344. {
  1345. post_alloc_hook(page, order, gfp_flags);
  1346. if (order && (gfp_flags & __GFP_COMP))
  1347. prep_compound_page(page, order);
  1348. /*
  1349. * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
  1350. * allocate the page. The expectation is that the caller is taking
  1351. * steps that will free more memory. The caller should avoid the page
  1352. * being used for !PFMEMALLOC purposes.
  1353. */
  1354. if (alloc_flags & ALLOC_NO_WATERMARKS)
  1355. set_page_pfmemalloc(page);
  1356. else
  1357. clear_page_pfmemalloc(page);
  1358. }
  1359. /*
  1360. * Go through the free lists for the given migratetype and remove
  1361. * the smallest available page from the freelists
  1362. */
  1363. static __always_inline
  1364. struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
  1365. int migratetype)
  1366. {
  1367. unsigned int current_order;
  1368. struct free_area *area;
  1369. struct page *page;
  1370. /* Find a page of the appropriate size in the preferred list */
  1371. for (current_order = order; current_order < NR_PAGE_ORDERS; ++current_order) {
  1372. area = &(zone->free_area[current_order]);
  1373. page = get_page_from_free_area(area, migratetype);
  1374. if (!page)
  1375. continue;
  1376. page_del_and_expand(zone, page, order, current_order,
  1377. migratetype);
  1378. trace_mm_page_alloc_zone_locked(page, order, migratetype,
  1379. pcp_allowed_order(order) &&
  1380. migratetype < MIGRATE_PCPTYPES);
  1381. return page;
  1382. }
  1383. return NULL;
  1384. }
  1385. /*
  1386. * This array describes the order lists are fallen back to when
  1387. * the free lists for the desirable migrate type are depleted
  1388. *
  1389. * The other migratetypes do not have fallbacks.
  1390. */
  1391. static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = {
  1392. [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE },
  1393. [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE },
  1394. [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE },
  1395. };
  1396. #ifdef CONFIG_CMA
  1397. static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1398. unsigned int order)
  1399. {
  1400. return __rmqueue_smallest(zone, order, MIGRATE_CMA);
  1401. }
  1402. #else
  1403. static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
  1404. unsigned int order) { return NULL; }
  1405. #endif
  1406. /*
  1407. * Change the type of a block and move all its free pages to that
  1408. * type's freelist.
  1409. */
  1410. static int __move_freepages_block(struct zone *zone, unsigned long start_pfn,
  1411. int old_mt, int new_mt)
  1412. {
  1413. struct page *page;
  1414. unsigned long pfn, end_pfn;
  1415. unsigned int order;
  1416. int pages_moved = 0;
  1417. VM_WARN_ON(start_pfn & (pageblock_nr_pages - 1));
  1418. end_pfn = pageblock_end_pfn(start_pfn);
  1419. for (pfn = start_pfn; pfn < end_pfn;) {
  1420. page = pfn_to_page(pfn);
  1421. if (!PageBuddy(page)) {
  1422. pfn++;
  1423. continue;
  1424. }
  1425. /* Make sure we are not inadvertently changing nodes */
  1426. VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
  1427. VM_BUG_ON_PAGE(page_zone(page) != zone, page);
  1428. order = buddy_order(page);
  1429. move_to_free_list(page, zone, order, old_mt, new_mt);
  1430. pfn += 1 << order;
  1431. pages_moved += 1 << order;
  1432. }
  1433. set_pageblock_migratetype(pfn_to_page(start_pfn), new_mt);
  1434. return pages_moved;
  1435. }
  1436. static bool prep_move_freepages_block(struct zone *zone, struct page *page,
  1437. unsigned long *start_pfn,
  1438. int *num_free, int *num_movable)
  1439. {
  1440. unsigned long pfn, start, end;
  1441. pfn = page_to_pfn(page);
  1442. start = pageblock_start_pfn(pfn);
  1443. end = pageblock_end_pfn(pfn);
  1444. /*
  1445. * The caller only has the lock for @zone, don't touch ranges
  1446. * that straddle into other zones. While we could move part of
  1447. * the range that's inside the zone, this call is usually
  1448. * accompanied by other operations such as migratetype updates
  1449. * which also should be locked.
  1450. */
  1451. if (!zone_spans_pfn(zone, start))
  1452. return false;
  1453. if (!zone_spans_pfn(zone, end - 1))
  1454. return false;
  1455. *start_pfn = start;
  1456. if (num_free) {
  1457. *num_free = 0;
  1458. *num_movable = 0;
  1459. for (pfn = start; pfn < end;) {
  1460. page = pfn_to_page(pfn);
  1461. if (PageBuddy(page)) {
  1462. int nr = 1 << buddy_order(page);
  1463. *num_free += nr;
  1464. pfn += nr;
  1465. continue;
  1466. }
  1467. /*
  1468. * We assume that pages that could be isolated for
  1469. * migration are movable. But we don't actually try
  1470. * isolating, as that would be expensive.
  1471. */
  1472. if (PageLRU(page) || __PageMovable(page))
  1473. (*num_movable)++;
  1474. pfn++;
  1475. }
  1476. }
  1477. return true;
  1478. }
  1479. static int move_freepages_block(struct zone *zone, struct page *page,
  1480. int old_mt, int new_mt)
  1481. {
  1482. unsigned long start_pfn;
  1483. if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
  1484. return -1;
  1485. return __move_freepages_block(zone, start_pfn, old_mt, new_mt);
  1486. }
  1487. #ifdef CONFIG_MEMORY_ISOLATION
  1488. /* Look for a buddy that straddles start_pfn */
  1489. static unsigned long find_large_buddy(unsigned long start_pfn)
  1490. {
  1491. int order = 0;
  1492. struct page *page;
  1493. unsigned long pfn = start_pfn;
  1494. while (!PageBuddy(page = pfn_to_page(pfn))) {
  1495. /* Nothing found */
  1496. if (++order > MAX_PAGE_ORDER)
  1497. return start_pfn;
  1498. pfn &= ~0UL << order;
  1499. }
  1500. /*
  1501. * Found a preceding buddy, but does it straddle?
  1502. */
  1503. if (pfn + (1 << buddy_order(page)) > start_pfn)
  1504. return pfn;
  1505. /* Nothing found */
  1506. return start_pfn;
  1507. }
  1508. /**
  1509. * move_freepages_block_isolate - move free pages in block for page isolation
  1510. * @zone: the zone
  1511. * @page: the pageblock page
  1512. * @migratetype: migratetype to set on the pageblock
  1513. *
  1514. * This is similar to move_freepages_block(), but handles the special
  1515. * case encountered in page isolation, where the block of interest
  1516. * might be part of a larger buddy spanning multiple pageblocks.
  1517. *
  1518. * Unlike the regular page allocator path, which moves pages while
  1519. * stealing buddies off the freelist, page isolation is interested in
  1520. * arbitrary pfn ranges that may have overlapping buddies on both ends.
  1521. *
  1522. * This function handles that. Straddling buddies are split into
  1523. * individual pageblocks. Only the block of interest is moved.
  1524. *
  1525. * Returns %true if pages could be moved, %false otherwise.
  1526. */
  1527. bool move_freepages_block_isolate(struct zone *zone, struct page *page,
  1528. int migratetype)
  1529. {
  1530. unsigned long start_pfn, pfn;
  1531. if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
  1532. return false;
  1533. /* No splits needed if buddies can't span multiple blocks */
  1534. if (pageblock_order == MAX_PAGE_ORDER)
  1535. goto move;
  1536. /* We're a tail block in a larger buddy */
  1537. pfn = find_large_buddy(start_pfn);
  1538. if (pfn != start_pfn) {
  1539. struct page *buddy = pfn_to_page(pfn);
  1540. int order = buddy_order(buddy);
  1541. del_page_from_free_list(buddy, zone, order,
  1542. get_pfnblock_migratetype(buddy, pfn));
  1543. set_pageblock_migratetype(page, migratetype);
  1544. split_large_buddy(zone, buddy, pfn, order, FPI_NONE);
  1545. return true;
  1546. }
  1547. /* We're the starting block of a larger buddy */
  1548. if (PageBuddy(page) && buddy_order(page) > pageblock_order) {
  1549. int order = buddy_order(page);
  1550. del_page_from_free_list(page, zone, order,
  1551. get_pfnblock_migratetype(page, pfn));
  1552. set_pageblock_migratetype(page, migratetype);
  1553. split_large_buddy(zone, page, pfn, order, FPI_NONE);
  1554. return true;
  1555. }
  1556. move:
  1557. __move_freepages_block(zone, start_pfn,
  1558. get_pfnblock_migratetype(page, start_pfn),
  1559. migratetype);
  1560. return true;
  1561. }
  1562. #endif /* CONFIG_MEMORY_ISOLATION */
  1563. static void change_pageblock_range(struct page *pageblock_page,
  1564. int start_order, int migratetype)
  1565. {
  1566. int nr_pageblocks = 1 << (start_order - pageblock_order);
  1567. while (nr_pageblocks--) {
  1568. set_pageblock_migratetype(pageblock_page, migratetype);
  1569. pageblock_page += pageblock_nr_pages;
  1570. }
  1571. }
  1572. /*
  1573. * When we are falling back to another migratetype during allocation, try to
  1574. * steal extra free pages from the same pageblocks to satisfy further
  1575. * allocations, instead of polluting multiple pageblocks.
  1576. *
  1577. * If we are stealing a relatively large buddy page, it is likely there will
  1578. * be more free pages in the pageblock, so try to steal them all. For
  1579. * reclaimable and unmovable allocations, we steal regardless of page size,
  1580. * as fragmentation caused by those allocations polluting movable pageblocks
  1581. * is worse than movable allocations stealing from unmovable and reclaimable
  1582. * pageblocks.
  1583. */
  1584. static bool can_steal_fallback(unsigned int order, int start_mt)
  1585. {
  1586. /*
  1587. * Leaving this order check is intended, although there is
  1588. * relaxed order check in next check. The reason is that
  1589. * we can actually steal whole pageblock if this condition met,
  1590. * but, below check doesn't guarantee it and that is just heuristic
  1591. * so could be changed anytime.
  1592. */
  1593. if (order >= pageblock_order)
  1594. return true;
  1595. if (order >= pageblock_order / 2 ||
  1596. start_mt == MIGRATE_RECLAIMABLE ||
  1597. start_mt == MIGRATE_UNMOVABLE ||
  1598. page_group_by_mobility_disabled)
  1599. return true;
  1600. return false;
  1601. }
  1602. static inline bool boost_watermark(struct zone *zone)
  1603. {
  1604. unsigned long max_boost;
  1605. if (!watermark_boost_factor)
  1606. return false;
  1607. /*
  1608. * Don't bother in zones that are unlikely to produce results.
  1609. * On small machines, including kdump capture kernels running
  1610. * in a small area, boosting the watermark can cause an out of
  1611. * memory situation immediately.
  1612. */
  1613. if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
  1614. return false;
  1615. max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
  1616. watermark_boost_factor, 10000);
  1617. /*
  1618. * high watermark may be uninitialised if fragmentation occurs
  1619. * very early in boot so do not boost. We do not fall
  1620. * through and boost by pageblock_nr_pages as failing
  1621. * allocations that early means that reclaim is not going
  1622. * to help and it may even be impossible to reclaim the
  1623. * boosted watermark resulting in a hang.
  1624. */
  1625. if (!max_boost)
  1626. return false;
  1627. max_boost = max(pageblock_nr_pages, max_boost);
  1628. zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
  1629. max_boost);
  1630. return true;
  1631. }
  1632. /*
  1633. * This function implements actual steal behaviour. If order is large enough, we
  1634. * can claim the whole pageblock for the requested migratetype. If not, we check
  1635. * the pageblock for constituent pages; if at least half of the pages are free
  1636. * or compatible, we can still claim the whole block, so pages freed in the
  1637. * future will be put on the correct free list.
  1638. */
  1639. static struct page *
  1640. try_to_steal_block(struct zone *zone, struct page *page,
  1641. int current_order, int order, int start_type,
  1642. unsigned int alloc_flags)
  1643. {
  1644. int free_pages, movable_pages, alike_pages;
  1645. unsigned long start_pfn;
  1646. int block_type;
  1647. block_type = get_pageblock_migratetype(page);
  1648. /*
  1649. * This can happen due to races and we want to prevent broken
  1650. * highatomic accounting.
  1651. */
  1652. if (is_migrate_highatomic(block_type))
  1653. return NULL;
  1654. /* Take ownership for orders >= pageblock_order */
  1655. if (current_order >= pageblock_order) {
  1656. unsigned int nr_added;
  1657. del_page_from_free_list(page, zone, current_order, block_type);
  1658. change_pageblock_range(page, current_order, start_type);
  1659. nr_added = expand(zone, page, order, current_order, start_type);
  1660. account_freepages(zone, nr_added, start_type);
  1661. return page;
  1662. }
  1663. /*
  1664. * Boost watermarks to increase reclaim pressure to reduce the
  1665. * likelihood of future fallbacks. Wake kswapd now as the node
  1666. * may be balanced overall and kswapd will not wake naturally.
  1667. */
  1668. if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
  1669. set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
  1670. /* moving whole block can fail due to zone boundary conditions */
  1671. if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages,
  1672. &movable_pages))
  1673. return NULL;
  1674. /*
  1675. * Determine how many pages are compatible with our allocation.
  1676. * For movable allocation, it's the number of movable pages which
  1677. * we just obtained. For other types it's a bit more tricky.
  1678. */
  1679. if (start_type == MIGRATE_MOVABLE) {
  1680. alike_pages = movable_pages;
  1681. } else {
  1682. /*
  1683. * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
  1684. * to MOVABLE pageblock, consider all non-movable pages as
  1685. * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
  1686. * vice versa, be conservative since we can't distinguish the
  1687. * exact migratetype of non-movable pages.
  1688. */
  1689. if (block_type == MIGRATE_MOVABLE)
  1690. alike_pages = pageblock_nr_pages
  1691. - (free_pages + movable_pages);
  1692. else
  1693. alike_pages = 0;
  1694. }
  1695. /*
  1696. * If a sufficient number of pages in the block are either free or of
  1697. * compatible migratability as our allocation, claim the whole block.
  1698. */
  1699. if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
  1700. page_group_by_mobility_disabled) {
  1701. __move_freepages_block(zone, start_pfn, block_type, start_type);
  1702. return __rmqueue_smallest(zone, order, start_type);
  1703. }
  1704. return NULL;
  1705. }
  1706. /*
  1707. * Check whether there is a suitable fallback freepage with requested order.
  1708. * If only_stealable is true, this function returns fallback_mt only if
  1709. * we can steal other freepages all together. This would help to reduce
  1710. * fragmentation due to mixed migratetype pages in one pageblock.
  1711. */
  1712. int find_suitable_fallback(struct free_area *area, unsigned int order,
  1713. int migratetype, bool only_stealable, bool *can_steal)
  1714. {
  1715. int i;
  1716. int fallback_mt;
  1717. if (area->nr_free == 0)
  1718. return -1;
  1719. *can_steal = false;
  1720. for (i = 0; i < MIGRATE_PCPTYPES - 1 ; i++) {
  1721. fallback_mt = fallbacks[migratetype][i];
  1722. if (free_area_empty(area, fallback_mt))
  1723. continue;
  1724. if (can_steal_fallback(order, migratetype))
  1725. *can_steal = true;
  1726. if (!only_stealable)
  1727. return fallback_mt;
  1728. if (*can_steal)
  1729. return fallback_mt;
  1730. }
  1731. return -1;
  1732. }
  1733. /*
  1734. * Reserve the pageblock(s) surrounding an allocation request for
  1735. * exclusive use of high-order atomic allocations if there are no
  1736. * empty page blocks that contain a page with a suitable order
  1737. */
  1738. static void reserve_highatomic_pageblock(struct page *page, int order,
  1739. struct zone *zone)
  1740. {
  1741. int mt;
  1742. unsigned long max_managed, flags;
  1743. /*
  1744. * The number reserved as: minimum is 1 pageblock, maximum is
  1745. * roughly 1% of a zone. But if 1% of a zone falls below a
  1746. * pageblock size, then don't reserve any pageblocks.
  1747. * Check is race-prone but harmless.
  1748. */
  1749. if ((zone_managed_pages(zone) / 100) < pageblock_nr_pages)
  1750. return;
  1751. max_managed = ALIGN((zone_managed_pages(zone) / 100), pageblock_nr_pages);
  1752. if (zone->nr_reserved_highatomic >= max_managed)
  1753. return;
  1754. spin_lock_irqsave(&zone->lock, flags);
  1755. /* Recheck the nr_reserved_highatomic limit under the lock */
  1756. if (zone->nr_reserved_highatomic >= max_managed)
  1757. goto out_unlock;
  1758. /* Yoink! */
  1759. mt = get_pageblock_migratetype(page);
  1760. /* Only reserve normal pageblocks (i.e., they can merge with others) */
  1761. if (!migratetype_is_mergeable(mt))
  1762. goto out_unlock;
  1763. if (order < pageblock_order) {
  1764. if (move_freepages_block(zone, page, mt, MIGRATE_HIGHATOMIC) == -1)
  1765. goto out_unlock;
  1766. zone->nr_reserved_highatomic += pageblock_nr_pages;
  1767. } else {
  1768. change_pageblock_range(page, order, MIGRATE_HIGHATOMIC);
  1769. zone->nr_reserved_highatomic += 1 << order;
  1770. }
  1771. out_unlock:
  1772. spin_unlock_irqrestore(&zone->lock, flags);
  1773. }
  1774. /*
  1775. * Used when an allocation is about to fail under memory pressure. This
  1776. * potentially hurts the reliability of high-order allocations when under
  1777. * intense memory pressure but failed atomic allocations should be easier
  1778. * to recover from than an OOM.
  1779. *
  1780. * If @force is true, try to unreserve pageblocks even though highatomic
  1781. * pageblock is exhausted.
  1782. */
  1783. static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
  1784. bool force)
  1785. {
  1786. struct zonelist *zonelist = ac->zonelist;
  1787. unsigned long flags;
  1788. struct zoneref *z;
  1789. struct zone *zone;
  1790. struct page *page;
  1791. int order;
  1792. int ret;
  1793. for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
  1794. ac->nodemask) {
  1795. /*
  1796. * Preserve at least one pageblock unless memory pressure
  1797. * is really high.
  1798. */
  1799. if (!force && zone->nr_reserved_highatomic <=
  1800. pageblock_nr_pages)
  1801. continue;
  1802. spin_lock_irqsave(&zone->lock, flags);
  1803. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  1804. struct free_area *area = &(zone->free_area[order]);
  1805. int mt;
  1806. page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
  1807. if (!page)
  1808. continue;
  1809. mt = get_pageblock_migratetype(page);
  1810. /*
  1811. * In page freeing path, migratetype change is racy so
  1812. * we can counter several free pages in a pageblock
  1813. * in this loop although we changed the pageblock type
  1814. * from highatomic to ac->migratetype. So we should
  1815. * adjust the count once.
  1816. */
  1817. if (is_migrate_highatomic(mt)) {
  1818. unsigned long size;
  1819. /*
  1820. * It should never happen but changes to
  1821. * locking could inadvertently allow a per-cpu
  1822. * drain to add pages to MIGRATE_HIGHATOMIC
  1823. * while unreserving so be safe and watch for
  1824. * underflows.
  1825. */
  1826. size = max(pageblock_nr_pages, 1UL << order);
  1827. size = min(size, zone->nr_reserved_highatomic);
  1828. zone->nr_reserved_highatomic -= size;
  1829. }
  1830. /*
  1831. * Convert to ac->migratetype and avoid the normal
  1832. * pageblock stealing heuristics. Minimally, the caller
  1833. * is doing the work and needs the pages. More
  1834. * importantly, if the block was always converted to
  1835. * MIGRATE_UNMOVABLE or another type then the number
  1836. * of pageblocks that cannot be completely freed
  1837. * may increase.
  1838. */
  1839. if (order < pageblock_order)
  1840. ret = move_freepages_block(zone, page, mt,
  1841. ac->migratetype);
  1842. else {
  1843. move_to_free_list(page, zone, order, mt,
  1844. ac->migratetype);
  1845. change_pageblock_range(page, order,
  1846. ac->migratetype);
  1847. ret = 1;
  1848. }
  1849. /*
  1850. * Reserving the block(s) already succeeded,
  1851. * so this should not fail on zone boundaries.
  1852. */
  1853. WARN_ON_ONCE(ret == -1);
  1854. if (ret > 0) {
  1855. spin_unlock_irqrestore(&zone->lock, flags);
  1856. return ret;
  1857. }
  1858. }
  1859. spin_unlock_irqrestore(&zone->lock, flags);
  1860. }
  1861. return false;
  1862. }
  1863. /*
  1864. * Try to allocate from some fallback migratetype by claiming the entire block,
  1865. * i.e. converting it to the allocation's start migratetype.
  1866. *
  1867. * The use of signed ints for order and current_order is a deliberate
  1868. * deviation from the rest of this file, to make the for loop
  1869. * condition simpler.
  1870. */
  1871. static __always_inline struct page *
  1872. __rmqueue_claim(struct zone *zone, int order, int start_migratetype,
  1873. unsigned int alloc_flags)
  1874. {
  1875. struct free_area *area;
  1876. int current_order;
  1877. int min_order = order;
  1878. struct page *page;
  1879. int fallback_mt;
  1880. bool can_steal;
  1881. /*
  1882. * Do not steal pages from freelists belonging to other pageblocks
  1883. * i.e. orders < pageblock_order. If there are no local zones free,
  1884. * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
  1885. */
  1886. if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT)
  1887. min_order = pageblock_order;
  1888. /*
  1889. * Find the largest available free page in the other list. This roughly
  1890. * approximates finding the pageblock with the most free pages, which
  1891. * would be too costly to do exactly.
  1892. */
  1893. for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
  1894. --current_order) {
  1895. area = &(zone->free_area[current_order]);
  1896. fallback_mt = find_suitable_fallback(area, current_order,
  1897. start_migratetype, false, &can_steal);
  1898. if (fallback_mt == -1)
  1899. continue;
  1900. if (!can_steal)
  1901. break;
  1902. page = get_page_from_free_area(area, fallback_mt);
  1903. page = try_to_steal_block(zone, page, current_order, order,
  1904. start_migratetype, alloc_flags);
  1905. if (page) {
  1906. trace_mm_page_alloc_extfrag(page, order, current_order,
  1907. start_migratetype, fallback_mt);
  1908. return page;
  1909. }
  1910. }
  1911. return NULL;
  1912. }
  1913. /*
  1914. * Try to steal a single page from some fallback migratetype. Leave the rest of
  1915. * the block as its current migratetype, potentially causing fragmentation.
  1916. */
  1917. static __always_inline struct page *
  1918. __rmqueue_steal(struct zone *zone, int order, int start_migratetype)
  1919. {
  1920. struct free_area *area;
  1921. int current_order;
  1922. struct page *page;
  1923. int fallback_mt;
  1924. bool can_steal;
  1925. for (current_order = order; current_order < NR_PAGE_ORDERS; current_order++) {
  1926. area = &(zone->free_area[current_order]);
  1927. fallback_mt = find_suitable_fallback(area, current_order,
  1928. start_migratetype, false, &can_steal);
  1929. if (fallback_mt == -1)
  1930. continue;
  1931. page = get_page_from_free_area(area, fallback_mt);
  1932. page_del_and_expand(zone, page, order, current_order, fallback_mt);
  1933. trace_mm_page_alloc_extfrag(page, order, current_order,
  1934. start_migratetype, fallback_mt);
  1935. return page;
  1936. }
  1937. return NULL;
  1938. }
  1939. enum rmqueue_mode {
  1940. RMQUEUE_NORMAL,
  1941. RMQUEUE_CMA,
  1942. RMQUEUE_CLAIM,
  1943. RMQUEUE_STEAL,
  1944. };
  1945. /*
  1946. * Do the hard work of removing an element from the buddy allocator.
  1947. * Call me with the zone->lock already held.
  1948. */
  1949. static __always_inline struct page *
  1950. __rmqueue(struct zone *zone, unsigned int order, int migratetype,
  1951. unsigned int alloc_flags, enum rmqueue_mode *mode)
  1952. {
  1953. struct page *page;
  1954. if (IS_ENABLED(CONFIG_CMA)) {
  1955. /*
  1956. * Balance movable allocations between regular and CMA areas by
  1957. * allocating from CMA when over half of the zone's free memory
  1958. * is in the CMA area.
  1959. */
  1960. if (alloc_flags & ALLOC_CMA &&
  1961. zone_page_state(zone, NR_FREE_CMA_PAGES) >
  1962. zone_page_state(zone, NR_FREE_PAGES) / 2) {
  1963. page = __rmqueue_cma_fallback(zone, order);
  1964. if (page)
  1965. return page;
  1966. }
  1967. }
  1968. /*
  1969. * First try the freelists of the requested migratetype, then try
  1970. * fallbacks modes with increasing levels of fragmentation risk.
  1971. *
  1972. * The fallback logic is expensive and rmqueue_bulk() calls in
  1973. * a loop with the zone->lock held, meaning the freelists are
  1974. * not subject to any outside changes. Remember in *mode where
  1975. * we found pay dirt, to save us the search on the next call.
  1976. */
  1977. switch (*mode) {
  1978. case RMQUEUE_NORMAL:
  1979. page = __rmqueue_smallest(zone, order, migratetype);
  1980. if (page)
  1981. return page;
  1982. fallthrough;
  1983. case RMQUEUE_CMA:
  1984. if (alloc_flags & ALLOC_CMA) {
  1985. page = __rmqueue_cma_fallback(zone, order);
  1986. if (page) {
  1987. *mode = RMQUEUE_CMA;
  1988. return page;
  1989. }
  1990. }
  1991. fallthrough;
  1992. case RMQUEUE_CLAIM:
  1993. page = __rmqueue_claim(zone, order, migratetype, alloc_flags);
  1994. if (page) {
  1995. /* Replenished preferred freelist, back to normal mode. */
  1996. *mode = RMQUEUE_NORMAL;
  1997. return page;
  1998. }
  1999. fallthrough;
  2000. case RMQUEUE_STEAL:
  2001. if (!(alloc_flags & ALLOC_NOFRAGMENT)) {
  2002. page = __rmqueue_steal(zone, order, migratetype);
  2003. if (page) {
  2004. *mode = RMQUEUE_STEAL;
  2005. return page;
  2006. }
  2007. }
  2008. }
  2009. return NULL;
  2010. }
  2011. /*
  2012. * Obtain a specified number of elements from the buddy allocator, all under
  2013. * a single hold of the lock, for efficiency. Add them to the supplied list.
  2014. * Returns the number of new pages which were placed at *list.
  2015. */
  2016. static int rmqueue_bulk(struct zone *zone, unsigned int order,
  2017. unsigned long count, struct list_head *list,
  2018. int migratetype, unsigned int alloc_flags)
  2019. {
  2020. enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
  2021. unsigned long flags;
  2022. int i;
  2023. spin_lock_irqsave(&zone->lock, flags);
  2024. for (i = 0; i < count; ++i) {
  2025. struct page *page = __rmqueue(zone, order, migratetype,
  2026. alloc_flags, &rmqm);
  2027. if (unlikely(page == NULL))
  2028. break;
  2029. /*
  2030. * Split buddy pages returned by expand() are received here in
  2031. * physical page order. The page is added to the tail of
  2032. * caller's list. From the callers perspective, the linked list
  2033. * is ordered by page number under some conditions. This is
  2034. * useful for IO devices that can forward direction from the
  2035. * head, thus also in the physical page order. This is useful
  2036. * for IO devices that can merge IO requests if the physical
  2037. * pages are ordered properly.
  2038. */
  2039. list_add_tail(&page->pcp_list, list);
  2040. }
  2041. spin_unlock_irqrestore(&zone->lock, flags);
  2042. return i;
  2043. }
  2044. /*
  2045. * Called from the vmstat counter updater to decay the PCP high.
  2046. * Return whether there are addition works to do.
  2047. */
  2048. int decay_pcp_high(struct zone *zone, struct per_cpu_pages *pcp)
  2049. {
  2050. int high_min, to_drain, batch;
  2051. int todo = 0;
  2052. high_min = READ_ONCE(pcp->high_min);
  2053. batch = READ_ONCE(pcp->batch);
  2054. /*
  2055. * Decrease pcp->high periodically to try to free possible
  2056. * idle PCP pages. And, avoid to free too many pages to
  2057. * control latency. This caps pcp->high decrement too.
  2058. */
  2059. if (pcp->high > high_min) {
  2060. pcp->high = max3(pcp->count - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
  2061. pcp->high - (pcp->high >> 3), high_min);
  2062. if (pcp->high > high_min)
  2063. todo++;
  2064. }
  2065. to_drain = pcp->count - pcp->high;
  2066. if (to_drain > 0) {
  2067. spin_lock(&pcp->lock);
  2068. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2069. spin_unlock(&pcp->lock);
  2070. todo++;
  2071. }
  2072. return todo;
  2073. }
  2074. #ifdef CONFIG_NUMA
  2075. /*
  2076. * Called from the vmstat counter updater to drain pagesets of this
  2077. * currently executing processor on remote nodes after they have
  2078. * expired.
  2079. */
  2080. void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
  2081. {
  2082. int to_drain, batch;
  2083. batch = READ_ONCE(pcp->batch);
  2084. to_drain = min(pcp->count, batch);
  2085. if (to_drain > 0) {
  2086. spin_lock(&pcp->lock);
  2087. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2088. spin_unlock(&pcp->lock);
  2089. }
  2090. }
  2091. #endif
  2092. /*
  2093. * Drain pcplists of the indicated processor and zone.
  2094. */
  2095. static void drain_pages_zone(unsigned int cpu, struct zone *zone)
  2096. {
  2097. struct per_cpu_pages *pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  2098. int count;
  2099. do {
  2100. spin_lock(&pcp->lock);
  2101. count = pcp->count;
  2102. if (count) {
  2103. int to_drain = min(count,
  2104. pcp->batch << CONFIG_PCP_BATCH_SCALE_MAX);
  2105. free_pcppages_bulk(zone, to_drain, pcp, 0);
  2106. count -= to_drain;
  2107. }
  2108. spin_unlock(&pcp->lock);
  2109. } while (count);
  2110. }
  2111. /*
  2112. * Drain pcplists of all zones on the indicated processor.
  2113. */
  2114. static void drain_pages(unsigned int cpu)
  2115. {
  2116. struct zone *zone;
  2117. for_each_populated_zone(zone) {
  2118. drain_pages_zone(cpu, zone);
  2119. }
  2120. }
  2121. /*
  2122. * Spill all of this CPU's per-cpu pages back into the buddy allocator.
  2123. */
  2124. void drain_local_pages(struct zone *zone)
  2125. {
  2126. int cpu = smp_processor_id();
  2127. if (zone)
  2128. drain_pages_zone(cpu, zone);
  2129. else
  2130. drain_pages(cpu);
  2131. }
  2132. /*
  2133. * The implementation of drain_all_pages(), exposing an extra parameter to
  2134. * drain on all cpus.
  2135. *
  2136. * drain_all_pages() is optimized to only execute on cpus where pcplists are
  2137. * not empty. The check for non-emptiness can however race with a free to
  2138. * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
  2139. * that need the guarantee that every CPU has drained can disable the
  2140. * optimizing racy check.
  2141. */
  2142. static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
  2143. {
  2144. int cpu;
  2145. /*
  2146. * Allocate in the BSS so we won't require allocation in
  2147. * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
  2148. */
  2149. static cpumask_t cpus_with_pcps;
  2150. /*
  2151. * Do not drain if one is already in progress unless it's specific to
  2152. * a zone. Such callers are primarily CMA and memory hotplug and need
  2153. * the drain to be complete when the call returns.
  2154. */
  2155. if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
  2156. if (!zone)
  2157. return;
  2158. mutex_lock(&pcpu_drain_mutex);
  2159. }
  2160. /*
  2161. * We don't care about racing with CPU hotplug event
  2162. * as offline notification will cause the notified
  2163. * cpu to drain that CPU pcps and on_each_cpu_mask
  2164. * disables preemption as part of its processing
  2165. */
  2166. for_each_online_cpu(cpu) {
  2167. struct per_cpu_pages *pcp;
  2168. struct zone *z;
  2169. bool has_pcps = false;
  2170. if (force_all_cpus) {
  2171. /*
  2172. * The pcp.count check is racy, some callers need a
  2173. * guarantee that no cpu is missed.
  2174. */
  2175. has_pcps = true;
  2176. } else if (zone) {
  2177. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  2178. if (pcp->count)
  2179. has_pcps = true;
  2180. } else {
  2181. for_each_populated_zone(z) {
  2182. pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
  2183. if (pcp->count) {
  2184. has_pcps = true;
  2185. break;
  2186. }
  2187. }
  2188. }
  2189. if (has_pcps)
  2190. cpumask_set_cpu(cpu, &cpus_with_pcps);
  2191. else
  2192. cpumask_clear_cpu(cpu, &cpus_with_pcps);
  2193. }
  2194. for_each_cpu(cpu, &cpus_with_pcps) {
  2195. if (zone)
  2196. drain_pages_zone(cpu, zone);
  2197. else
  2198. drain_pages(cpu);
  2199. }
  2200. mutex_unlock(&pcpu_drain_mutex);
  2201. }
  2202. /*
  2203. * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
  2204. *
  2205. * When zone parameter is non-NULL, spill just the single zone's pages.
  2206. */
  2207. void drain_all_pages(struct zone *zone)
  2208. {
  2209. __drain_all_pages(zone, false);
  2210. }
  2211. static int nr_pcp_free(struct per_cpu_pages *pcp, int batch, int high, bool free_high)
  2212. {
  2213. int min_nr_free, max_nr_free;
  2214. /* Free as much as possible if batch freeing high-order pages. */
  2215. if (unlikely(free_high))
  2216. return min(pcp->count, batch << CONFIG_PCP_BATCH_SCALE_MAX);
  2217. /* Check for PCP disabled or boot pageset */
  2218. if (unlikely(high < batch))
  2219. return 1;
  2220. /* Leave at least pcp->batch pages on the list */
  2221. min_nr_free = batch;
  2222. max_nr_free = high - batch;
  2223. /*
  2224. * Increase the batch number to the number of the consecutive
  2225. * freed pages to reduce zone lock contention.
  2226. */
  2227. batch = clamp_t(int, pcp->free_count, min_nr_free, max_nr_free);
  2228. return batch;
  2229. }
  2230. static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone,
  2231. int batch, bool free_high)
  2232. {
  2233. int high, high_min, high_max;
  2234. high_min = READ_ONCE(pcp->high_min);
  2235. high_max = READ_ONCE(pcp->high_max);
  2236. high = pcp->high = clamp(pcp->high, high_min, high_max);
  2237. if (unlikely(!high))
  2238. return 0;
  2239. if (unlikely(free_high)) {
  2240. pcp->high = max(high - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
  2241. high_min);
  2242. return 0;
  2243. }
  2244. /*
  2245. * If reclaim is active, limit the number of pages that can be
  2246. * stored on pcp lists
  2247. */
  2248. if (test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) {
  2249. int free_count = max_t(int, pcp->free_count, batch);
  2250. pcp->high = max(high - free_count, high_min);
  2251. return min(batch << 2, pcp->high);
  2252. }
  2253. if (high_min == high_max)
  2254. return high;
  2255. if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) {
  2256. int free_count = max_t(int, pcp->free_count, batch);
  2257. pcp->high = max(high - free_count, high_min);
  2258. high = max(pcp->count, high_min);
  2259. } else if (pcp->count >= high) {
  2260. int need_high = pcp->free_count + batch;
  2261. /* pcp->high should be large enough to hold batch freed pages */
  2262. if (pcp->high < need_high)
  2263. pcp->high = clamp(need_high, high_min, high_max);
  2264. }
  2265. return high;
  2266. }
  2267. static void free_unref_page_commit(struct zone *zone, struct per_cpu_pages *pcp,
  2268. struct page *page, int migratetype,
  2269. unsigned int order)
  2270. {
  2271. int high, batch;
  2272. int pindex;
  2273. bool free_high = false;
  2274. /*
  2275. * On freeing, reduce the number of pages that are batch allocated.
  2276. * See nr_pcp_alloc() where alloc_factor is increased for subsequent
  2277. * allocations.
  2278. */
  2279. pcp->alloc_factor >>= 1;
  2280. __count_vm_events(PGFREE, 1 << order);
  2281. pindex = order_to_pindex(migratetype, order);
  2282. list_add(&page->pcp_list, &pcp->lists[pindex]);
  2283. pcp->count += 1 << order;
  2284. batch = READ_ONCE(pcp->batch);
  2285. /*
  2286. * As high-order pages other than THP's stored on PCP can contribute
  2287. * to fragmentation, limit the number stored when PCP is heavily
  2288. * freeing without allocation. The remainder after bulk freeing
  2289. * stops will be drained from vmstat refresh context.
  2290. */
  2291. if (order && order <= PAGE_ALLOC_COSTLY_ORDER) {
  2292. free_high = (pcp->free_count >= batch &&
  2293. (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) &&
  2294. (!(pcp->flags & PCPF_FREE_HIGH_BATCH) ||
  2295. pcp->count >= READ_ONCE(batch)));
  2296. pcp->flags |= PCPF_PREV_FREE_HIGH_ORDER;
  2297. } else if (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) {
  2298. pcp->flags &= ~PCPF_PREV_FREE_HIGH_ORDER;
  2299. }
  2300. if (pcp->free_count < (batch << CONFIG_PCP_BATCH_SCALE_MAX))
  2301. pcp->free_count += (1 << order);
  2302. high = nr_pcp_high(pcp, zone, batch, free_high);
  2303. if (pcp->count >= high) {
  2304. free_pcppages_bulk(zone, nr_pcp_free(pcp, batch, high, free_high),
  2305. pcp, pindex);
  2306. if (test_bit(ZONE_BELOW_HIGH, &zone->flags) &&
  2307. zone_watermark_ok(zone, 0, high_wmark_pages(zone),
  2308. ZONE_MOVABLE, 0))
  2309. clear_bit(ZONE_BELOW_HIGH, &zone->flags);
  2310. }
  2311. }
  2312. /*
  2313. * Free a pcp page
  2314. */
  2315. void free_unref_page(struct page *page, unsigned int order)
  2316. {
  2317. unsigned long __maybe_unused UP_flags;
  2318. struct per_cpu_pages *pcp;
  2319. struct zone *zone;
  2320. unsigned long pfn = page_to_pfn(page);
  2321. int migratetype;
  2322. if (!pcp_allowed_order(order)) {
  2323. __free_pages_ok(page, order, FPI_NONE);
  2324. return;
  2325. }
  2326. if (!free_pages_prepare(page, order))
  2327. return;
  2328. /*
  2329. * We only track unmovable, reclaimable and movable on pcp lists.
  2330. * Place ISOLATE pages on the isolated list because they are being
  2331. * offlined but treat HIGHATOMIC and CMA as movable pages so we can
  2332. * get those areas back if necessary. Otherwise, we may have to free
  2333. * excessively into the page allocator
  2334. */
  2335. migratetype = get_pfnblock_migratetype(page, pfn);
  2336. if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
  2337. if (unlikely(is_migrate_isolate(migratetype))) {
  2338. free_one_page(page_zone(page), page, pfn, order, FPI_NONE);
  2339. return;
  2340. }
  2341. migratetype = MIGRATE_MOVABLE;
  2342. }
  2343. zone = page_zone(page);
  2344. pcp_trylock_prepare(UP_flags);
  2345. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2346. if (pcp) {
  2347. free_unref_page_commit(zone, pcp, page, migratetype, order);
  2348. pcp_spin_unlock(pcp);
  2349. } else {
  2350. free_one_page(zone, page, pfn, order, FPI_NONE);
  2351. }
  2352. pcp_trylock_finish(UP_flags);
  2353. }
  2354. /*
  2355. * Free a batch of folios
  2356. */
  2357. void free_unref_folios(struct folio_batch *folios)
  2358. {
  2359. unsigned long __maybe_unused UP_flags;
  2360. struct per_cpu_pages *pcp = NULL;
  2361. struct zone *locked_zone = NULL;
  2362. int i, j;
  2363. /* Prepare folios for freeing */
  2364. for (i = 0, j = 0; i < folios->nr; i++) {
  2365. struct folio *folio = folios->folios[i];
  2366. unsigned long pfn = folio_pfn(folio);
  2367. unsigned int order = folio_order(folio);
  2368. if (!free_pages_prepare(&folio->page, order))
  2369. continue;
  2370. /*
  2371. * Free orders not handled on the PCP directly to the
  2372. * allocator.
  2373. */
  2374. if (!pcp_allowed_order(order)) {
  2375. free_one_page(folio_zone(folio), &folio->page,
  2376. pfn, order, FPI_NONE);
  2377. continue;
  2378. }
  2379. folio->private = (void *)(unsigned long)order;
  2380. if (j != i)
  2381. folios->folios[j] = folio;
  2382. j++;
  2383. }
  2384. folios->nr = j;
  2385. for (i = 0; i < folios->nr; i++) {
  2386. struct folio *folio = folios->folios[i];
  2387. struct zone *zone = folio_zone(folio);
  2388. unsigned long pfn = folio_pfn(folio);
  2389. unsigned int order = (unsigned long)folio->private;
  2390. int migratetype;
  2391. folio->private = NULL;
  2392. migratetype = get_pfnblock_migratetype(&folio->page, pfn);
  2393. /* Different zone requires a different pcp lock */
  2394. if (zone != locked_zone ||
  2395. is_migrate_isolate(migratetype)) {
  2396. if (pcp) {
  2397. pcp_spin_unlock(pcp);
  2398. pcp_trylock_finish(UP_flags);
  2399. locked_zone = NULL;
  2400. pcp = NULL;
  2401. }
  2402. /*
  2403. * Free isolated pages directly to the
  2404. * allocator, see comment in free_unref_page.
  2405. */
  2406. if (is_migrate_isolate(migratetype)) {
  2407. free_one_page(zone, &folio->page, pfn,
  2408. order, FPI_NONE);
  2409. continue;
  2410. }
  2411. /*
  2412. * trylock is necessary as folios may be getting freed
  2413. * from IRQ or SoftIRQ context after an IO completion.
  2414. */
  2415. pcp_trylock_prepare(UP_flags);
  2416. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2417. if (unlikely(!pcp)) {
  2418. pcp_trylock_finish(UP_flags);
  2419. free_one_page(zone, &folio->page, pfn,
  2420. order, FPI_NONE);
  2421. continue;
  2422. }
  2423. locked_zone = zone;
  2424. }
  2425. /*
  2426. * Non-isolated types over MIGRATE_PCPTYPES get added
  2427. * to the MIGRATE_MOVABLE pcp list.
  2428. */
  2429. if (unlikely(migratetype >= MIGRATE_PCPTYPES))
  2430. migratetype = MIGRATE_MOVABLE;
  2431. trace_mm_page_free_batched(&folio->page);
  2432. free_unref_page_commit(zone, pcp, &folio->page, migratetype,
  2433. order);
  2434. }
  2435. if (pcp) {
  2436. pcp_spin_unlock(pcp);
  2437. pcp_trylock_finish(UP_flags);
  2438. }
  2439. folio_batch_reinit(folios);
  2440. }
  2441. /*
  2442. * split_page takes a non-compound higher-order page, and splits it into
  2443. * n (1<<order) sub-pages: page[0..n]
  2444. * Each sub-page must be freed individually.
  2445. *
  2446. * Note: this is probably too low level an operation for use in drivers.
  2447. * Please consult with lkml before using this in your driver.
  2448. */
  2449. void split_page(struct page *page, unsigned int order)
  2450. {
  2451. int i;
  2452. VM_BUG_ON_PAGE(PageCompound(page), page);
  2453. VM_BUG_ON_PAGE(!page_count(page), page);
  2454. for (i = 1; i < (1 << order); i++)
  2455. set_page_refcounted(page + i);
  2456. split_page_owner(page, order, 0);
  2457. pgalloc_tag_split(page_folio(page), order, 0);
  2458. split_page_memcg(page, order, 0);
  2459. }
  2460. EXPORT_SYMBOL_GPL(split_page);
  2461. int __isolate_free_page(struct page *page, unsigned int order)
  2462. {
  2463. struct zone *zone = page_zone(page);
  2464. int mt = get_pageblock_migratetype(page);
  2465. if (!is_migrate_isolate(mt)) {
  2466. unsigned long watermark;
  2467. /*
  2468. * Obey watermarks as if the page was being allocated. We can
  2469. * emulate a high-order watermark check with a raised order-0
  2470. * watermark, because we already know our high-order page
  2471. * exists.
  2472. */
  2473. watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
  2474. if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
  2475. return 0;
  2476. }
  2477. del_page_from_free_list(page, zone, order, mt);
  2478. /*
  2479. * Set the pageblock if the isolated page is at least half of a
  2480. * pageblock
  2481. */
  2482. if (order >= pageblock_order - 1) {
  2483. struct page *endpage = page + (1 << order) - 1;
  2484. for (; page < endpage; page += pageblock_nr_pages) {
  2485. int mt = get_pageblock_migratetype(page);
  2486. /*
  2487. * Only change normal pageblocks (i.e., they can merge
  2488. * with others)
  2489. */
  2490. if (migratetype_is_mergeable(mt))
  2491. move_freepages_block(zone, page, mt,
  2492. MIGRATE_MOVABLE);
  2493. }
  2494. }
  2495. return 1UL << order;
  2496. }
  2497. /**
  2498. * __putback_isolated_page - Return a now-isolated page back where we got it
  2499. * @page: Page that was isolated
  2500. * @order: Order of the isolated page
  2501. * @mt: The page's pageblock's migratetype
  2502. *
  2503. * This function is meant to return a page pulled from the free lists via
  2504. * __isolate_free_page back to the free lists they were pulled from.
  2505. */
  2506. void __putback_isolated_page(struct page *page, unsigned int order, int mt)
  2507. {
  2508. struct zone *zone = page_zone(page);
  2509. /* zone lock should be held when this function is called */
  2510. lockdep_assert_held(&zone->lock);
  2511. /* Return isolated page to tail of freelist. */
  2512. __free_one_page(page, page_to_pfn(page), zone, order, mt,
  2513. FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
  2514. }
  2515. /*
  2516. * Update NUMA hit/miss statistics
  2517. */
  2518. static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
  2519. long nr_account)
  2520. {
  2521. #ifdef CONFIG_NUMA
  2522. enum numa_stat_item local_stat = NUMA_LOCAL;
  2523. /* skip numa counters update if numa stats is disabled */
  2524. if (!static_branch_likely(&vm_numa_stat_key))
  2525. return;
  2526. if (zone_to_nid(z) != numa_node_id())
  2527. local_stat = NUMA_OTHER;
  2528. if (zone_to_nid(z) == zone_to_nid(preferred_zone))
  2529. __count_numa_events(z, NUMA_HIT, nr_account);
  2530. else {
  2531. __count_numa_events(z, NUMA_MISS, nr_account);
  2532. __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
  2533. }
  2534. __count_numa_events(z, local_stat, nr_account);
  2535. #endif
  2536. }
  2537. static __always_inline
  2538. struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,
  2539. unsigned int order, unsigned int alloc_flags,
  2540. int migratetype)
  2541. {
  2542. struct page *page;
  2543. unsigned long flags;
  2544. do {
  2545. page = NULL;
  2546. spin_lock_irqsave(&zone->lock, flags);
  2547. if (alloc_flags & ALLOC_HIGHATOMIC)
  2548. page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
  2549. if (!page) {
  2550. enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
  2551. page = __rmqueue(zone, order, migratetype, alloc_flags, &rmqm);
  2552. /*
  2553. * If the allocation fails, allow OOM handling and
  2554. * order-0 (atomic) allocs access to HIGHATOMIC
  2555. * reserves as failing now is worse than failing a
  2556. * high-order atomic allocation in the future.
  2557. */
  2558. if (!page && (alloc_flags & (ALLOC_OOM|ALLOC_NON_BLOCK)))
  2559. page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
  2560. if (!page) {
  2561. spin_unlock_irqrestore(&zone->lock, flags);
  2562. return NULL;
  2563. }
  2564. }
  2565. spin_unlock_irqrestore(&zone->lock, flags);
  2566. } while (check_new_pages(page, order));
  2567. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2568. zone_statistics(preferred_zone, zone, 1);
  2569. return page;
  2570. }
  2571. static int nr_pcp_alloc(struct per_cpu_pages *pcp, struct zone *zone, int order)
  2572. {
  2573. int high, base_batch, batch, max_nr_alloc;
  2574. int high_max, high_min;
  2575. base_batch = READ_ONCE(pcp->batch);
  2576. high_min = READ_ONCE(pcp->high_min);
  2577. high_max = READ_ONCE(pcp->high_max);
  2578. high = pcp->high = clamp(pcp->high, high_min, high_max);
  2579. /* Check for PCP disabled or boot pageset */
  2580. if (unlikely(high < base_batch))
  2581. return 1;
  2582. if (order)
  2583. batch = base_batch;
  2584. else
  2585. batch = (base_batch << pcp->alloc_factor);
  2586. /*
  2587. * If we had larger pcp->high, we could avoid to allocate from
  2588. * zone.
  2589. */
  2590. if (high_min != high_max && !test_bit(ZONE_BELOW_HIGH, &zone->flags))
  2591. high = pcp->high = min(high + batch, high_max);
  2592. if (!order) {
  2593. max_nr_alloc = max(high - pcp->count - base_batch, base_batch);
  2594. /*
  2595. * Double the number of pages allocated each time there is
  2596. * subsequent allocation of order-0 pages without any freeing.
  2597. */
  2598. if (batch <= max_nr_alloc &&
  2599. pcp->alloc_factor < CONFIG_PCP_BATCH_SCALE_MAX)
  2600. pcp->alloc_factor++;
  2601. batch = min(batch, max_nr_alloc);
  2602. }
  2603. /*
  2604. * Scale batch relative to order if batch implies free pages
  2605. * can be stored on the PCP. Batch can be 1 for small zones or
  2606. * for boot pagesets which should never store free pages as
  2607. * the pages may belong to arbitrary zones.
  2608. */
  2609. if (batch > 1)
  2610. batch = max(batch >> order, 2);
  2611. return batch;
  2612. }
  2613. /* Remove page from the per-cpu list, caller must protect the list */
  2614. static inline
  2615. struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order,
  2616. int migratetype,
  2617. unsigned int alloc_flags,
  2618. struct per_cpu_pages *pcp,
  2619. struct list_head *list)
  2620. {
  2621. struct page *page;
  2622. do {
  2623. if (list_empty(list)) {
  2624. int batch = nr_pcp_alloc(pcp, zone, order);
  2625. int alloced;
  2626. alloced = rmqueue_bulk(zone, order,
  2627. batch, list,
  2628. migratetype, alloc_flags);
  2629. pcp->count += alloced << order;
  2630. if (unlikely(list_empty(list)))
  2631. return NULL;
  2632. }
  2633. page = list_first_entry(list, struct page, pcp_list);
  2634. list_del(&page->pcp_list);
  2635. pcp->count -= 1 << order;
  2636. } while (check_new_pages(page, order));
  2637. return page;
  2638. }
  2639. /* Lock and remove page from the per-cpu list */
  2640. static struct page *rmqueue_pcplist(struct zone *preferred_zone,
  2641. struct zone *zone, unsigned int order,
  2642. int migratetype, unsigned int alloc_flags)
  2643. {
  2644. struct per_cpu_pages *pcp;
  2645. struct list_head *list;
  2646. struct page *page;
  2647. unsigned long __maybe_unused UP_flags;
  2648. /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
  2649. pcp_trylock_prepare(UP_flags);
  2650. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  2651. if (!pcp) {
  2652. pcp_trylock_finish(UP_flags);
  2653. return NULL;
  2654. }
  2655. /*
  2656. * On allocation, reduce the number of pages that are batch freed.
  2657. * See nr_pcp_free() where free_factor is increased for subsequent
  2658. * frees.
  2659. */
  2660. pcp->free_count >>= 1;
  2661. list = &pcp->lists[order_to_pindex(migratetype, order)];
  2662. page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list);
  2663. pcp_spin_unlock(pcp);
  2664. pcp_trylock_finish(UP_flags);
  2665. if (page) {
  2666. __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
  2667. zone_statistics(preferred_zone, zone, 1);
  2668. }
  2669. return page;
  2670. }
  2671. /*
  2672. * Allocate a page from the given zone.
  2673. * Use pcplists for THP or "cheap" high-order allocations.
  2674. */
  2675. /*
  2676. * Do not instrument rmqueue() with KMSAN. This function may call
  2677. * __msan_poison_alloca() through a call to set_pfnblock_flags_mask().
  2678. * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it
  2679. * may call rmqueue() again, which will result in a deadlock.
  2680. */
  2681. __no_sanitize_memory
  2682. static inline
  2683. struct page *rmqueue(struct zone *preferred_zone,
  2684. struct zone *zone, unsigned int order,
  2685. gfp_t gfp_flags, unsigned int alloc_flags,
  2686. int migratetype)
  2687. {
  2688. struct page *page;
  2689. if (likely(pcp_allowed_order(order))) {
  2690. page = rmqueue_pcplist(preferred_zone, zone, order,
  2691. migratetype, alloc_flags);
  2692. if (likely(page))
  2693. goto out;
  2694. }
  2695. page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags,
  2696. migratetype);
  2697. out:
  2698. /* Separate test+clear to avoid unnecessary atomics */
  2699. if ((alloc_flags & ALLOC_KSWAPD) &&
  2700. unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) {
  2701. clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
  2702. wakeup_kswapd(zone, 0, 0, zone_idx(zone));
  2703. }
  2704. VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
  2705. return page;
  2706. }
  2707. static inline long __zone_watermark_unusable_free(struct zone *z,
  2708. unsigned int order, unsigned int alloc_flags)
  2709. {
  2710. long unusable_free = (1 << order) - 1;
  2711. /*
  2712. * If the caller does not have rights to reserves below the min
  2713. * watermark then subtract the free pages reserved for highatomic.
  2714. */
  2715. if (likely(!(alloc_flags & ALLOC_RESERVES)))
  2716. unusable_free += READ_ONCE(z->nr_free_highatomic);
  2717. #ifdef CONFIG_CMA
  2718. /* If allocation can't use CMA areas don't use free CMA pages */
  2719. if (!(alloc_flags & ALLOC_CMA))
  2720. unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
  2721. #endif
  2722. return unusable_free;
  2723. }
  2724. /*
  2725. * Return true if free base pages are above 'mark'. For high-order checks it
  2726. * will return true of the order-0 watermark is reached and there is at least
  2727. * one free page of a suitable size. Checking now avoids taking the zone lock
  2728. * to check in the allocation paths if no pages are free.
  2729. */
  2730. bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2731. int highest_zoneidx, unsigned int alloc_flags,
  2732. long free_pages)
  2733. {
  2734. long min = mark;
  2735. int o;
  2736. /* free_pages may go negative - that's OK */
  2737. free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
  2738. if (unlikely(alloc_flags & ALLOC_RESERVES)) {
  2739. /*
  2740. * __GFP_HIGH allows access to 50% of the min reserve as well
  2741. * as OOM.
  2742. */
  2743. if (alloc_flags & ALLOC_MIN_RESERVE) {
  2744. min -= min / 2;
  2745. /*
  2746. * Non-blocking allocations (e.g. GFP_ATOMIC) can
  2747. * access more reserves than just __GFP_HIGH. Other
  2748. * non-blocking allocations requests such as GFP_NOWAIT
  2749. * or (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) do not get
  2750. * access to the min reserve.
  2751. */
  2752. if (alloc_flags & ALLOC_NON_BLOCK)
  2753. min -= min / 4;
  2754. }
  2755. /*
  2756. * OOM victims can try even harder than the normal reserve
  2757. * users on the grounds that it's definitely going to be in
  2758. * the exit path shortly and free memory. Any allocation it
  2759. * makes during the free path will be small and short-lived.
  2760. */
  2761. if (alloc_flags & ALLOC_OOM)
  2762. min -= min / 2;
  2763. }
  2764. /*
  2765. * Check watermarks for an order-0 allocation request. If these
  2766. * are not met, then a high-order request also cannot go ahead
  2767. * even if a suitable page happened to be free.
  2768. */
  2769. if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
  2770. return false;
  2771. /* If this is an order-0 request then the watermark is fine */
  2772. if (!order)
  2773. return true;
  2774. /* For a high-order request, check at least one suitable page is free */
  2775. for (o = order; o < NR_PAGE_ORDERS; o++) {
  2776. struct free_area *area = &z->free_area[o];
  2777. int mt;
  2778. if (!area->nr_free)
  2779. continue;
  2780. for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
  2781. if (!free_area_empty(area, mt))
  2782. return true;
  2783. }
  2784. #ifdef CONFIG_CMA
  2785. if ((alloc_flags & ALLOC_CMA) &&
  2786. !free_area_empty(area, MIGRATE_CMA)) {
  2787. return true;
  2788. }
  2789. #endif
  2790. if ((alloc_flags & (ALLOC_HIGHATOMIC|ALLOC_OOM)) &&
  2791. !free_area_empty(area, MIGRATE_HIGHATOMIC)) {
  2792. return true;
  2793. }
  2794. }
  2795. return false;
  2796. }
  2797. bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
  2798. int highest_zoneidx, unsigned int alloc_flags)
  2799. {
  2800. return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
  2801. zone_page_state(z, NR_FREE_PAGES));
  2802. }
  2803. static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
  2804. unsigned long mark, int highest_zoneidx,
  2805. unsigned int alloc_flags, gfp_t gfp_mask)
  2806. {
  2807. long free_pages;
  2808. free_pages = zone_page_state(z, NR_FREE_PAGES);
  2809. /*
  2810. * Fast check for order-0 only. If this fails then the reserves
  2811. * need to be calculated.
  2812. */
  2813. if (!order) {
  2814. long usable_free;
  2815. long reserved;
  2816. usable_free = free_pages;
  2817. reserved = __zone_watermark_unusable_free(z, 0, alloc_flags);
  2818. /* reserved may over estimate high-atomic reserves. */
  2819. usable_free -= min(usable_free, reserved);
  2820. if (usable_free > mark + z->lowmem_reserve[highest_zoneidx])
  2821. return true;
  2822. }
  2823. if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
  2824. free_pages))
  2825. return true;
  2826. /*
  2827. * Ignore watermark boosting for __GFP_HIGH order-0 allocations
  2828. * when checking the min watermark. The min watermark is the
  2829. * point where boosting is ignored so that kswapd is woken up
  2830. * when below the low watermark.
  2831. */
  2832. if (unlikely(!order && (alloc_flags & ALLOC_MIN_RESERVE) && z->watermark_boost
  2833. && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
  2834. mark = z->_watermark[WMARK_MIN];
  2835. return __zone_watermark_ok(z, order, mark, highest_zoneidx,
  2836. alloc_flags, free_pages);
  2837. }
  2838. return false;
  2839. }
  2840. bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
  2841. unsigned long mark, int highest_zoneidx)
  2842. {
  2843. long free_pages = zone_page_state(z, NR_FREE_PAGES);
  2844. if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
  2845. free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
  2846. return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
  2847. free_pages);
  2848. }
  2849. #ifdef CONFIG_NUMA
  2850. int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
  2851. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2852. {
  2853. return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
  2854. node_reclaim_distance;
  2855. }
  2856. #else /* CONFIG_NUMA */
  2857. static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
  2858. {
  2859. return true;
  2860. }
  2861. #endif /* CONFIG_NUMA */
  2862. /*
  2863. * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
  2864. * fragmentation is subtle. If the preferred zone was HIGHMEM then
  2865. * premature use of a lower zone may cause lowmem pressure problems that
  2866. * are worse than fragmentation. If the next zone is ZONE_DMA then it is
  2867. * probably too small. It only makes sense to spread allocations to avoid
  2868. * fragmentation between the Normal and DMA32 zones.
  2869. */
  2870. static inline unsigned int
  2871. alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
  2872. {
  2873. unsigned int alloc_flags;
  2874. /*
  2875. * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
  2876. * to save a branch.
  2877. */
  2878. alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
  2879. #ifdef CONFIG_ZONE_DMA32
  2880. if (!zone)
  2881. return alloc_flags;
  2882. if (zone_idx(zone) != ZONE_NORMAL)
  2883. return alloc_flags;
  2884. /*
  2885. * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
  2886. * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
  2887. * on UMA that if Normal is populated then so is DMA32.
  2888. */
  2889. BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
  2890. if (nr_online_nodes > 1 && !populated_zone(--zone))
  2891. return alloc_flags;
  2892. alloc_flags |= ALLOC_NOFRAGMENT;
  2893. #endif /* CONFIG_ZONE_DMA32 */
  2894. return alloc_flags;
  2895. }
  2896. /* Must be called after current_gfp_context() which can change gfp_mask */
  2897. static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
  2898. unsigned int alloc_flags)
  2899. {
  2900. #ifdef CONFIG_CMA
  2901. if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
  2902. alloc_flags |= ALLOC_CMA;
  2903. #endif
  2904. return alloc_flags;
  2905. }
  2906. /*
  2907. * get_page_from_freelist goes through the zonelist trying to allocate
  2908. * a page.
  2909. */
  2910. static struct page *
  2911. get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
  2912. const struct alloc_context *ac)
  2913. {
  2914. struct zoneref *z;
  2915. struct zone *zone;
  2916. struct pglist_data *last_pgdat = NULL;
  2917. bool last_pgdat_dirty_ok = false;
  2918. bool no_fallback;
  2919. retry:
  2920. /*
  2921. * Scan zonelist, looking for a zone with enough free.
  2922. * See also cpuset_node_allowed() comment in kernel/cgroup/cpuset.c.
  2923. */
  2924. no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
  2925. z = ac->preferred_zoneref;
  2926. for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
  2927. ac->nodemask) {
  2928. struct page *page;
  2929. unsigned long mark;
  2930. if (cpusets_enabled() &&
  2931. (alloc_flags & ALLOC_CPUSET) &&
  2932. !__cpuset_zone_allowed(zone, gfp_mask))
  2933. continue;
  2934. /*
  2935. * When allocating a page cache page for writing, we
  2936. * want to get it from a node that is within its dirty
  2937. * limit, such that no single node holds more than its
  2938. * proportional share of globally allowed dirty pages.
  2939. * The dirty limits take into account the node's
  2940. * lowmem reserves and high watermark so that kswapd
  2941. * should be able to balance it without having to
  2942. * write pages from its LRU list.
  2943. *
  2944. * XXX: For now, allow allocations to potentially
  2945. * exceed the per-node dirty limit in the slowpath
  2946. * (spread_dirty_pages unset) before going into reclaim,
  2947. * which is important when on a NUMA setup the allowed
  2948. * nodes are together not big enough to reach the
  2949. * global limit. The proper fix for these situations
  2950. * will require awareness of nodes in the
  2951. * dirty-throttling and the flusher threads.
  2952. */
  2953. if (ac->spread_dirty_pages) {
  2954. if (last_pgdat != zone->zone_pgdat) {
  2955. last_pgdat = zone->zone_pgdat;
  2956. last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
  2957. }
  2958. if (!last_pgdat_dirty_ok)
  2959. continue;
  2960. }
  2961. if (no_fallback && nr_online_nodes > 1 &&
  2962. zone != zonelist_zone(ac->preferred_zoneref)) {
  2963. int local_nid;
  2964. /*
  2965. * If moving to a remote node, retry but allow
  2966. * fragmenting fallbacks. Locality is more important
  2967. * than fragmentation avoidance.
  2968. */
  2969. local_nid = zonelist_node_idx(ac->preferred_zoneref);
  2970. if (zone_to_nid(zone) != local_nid) {
  2971. alloc_flags &= ~ALLOC_NOFRAGMENT;
  2972. goto retry;
  2973. }
  2974. }
  2975. cond_accept_memory(zone, order);
  2976. /*
  2977. * Detect whether the number of free pages is below high
  2978. * watermark. If so, we will decrease pcp->high and free
  2979. * PCP pages in free path to reduce the possibility of
  2980. * premature page reclaiming. Detection is done here to
  2981. * avoid to do that in hotter free path.
  2982. */
  2983. if (test_bit(ZONE_BELOW_HIGH, &zone->flags))
  2984. goto check_alloc_wmark;
  2985. mark = high_wmark_pages(zone);
  2986. if (zone_watermark_fast(zone, order, mark,
  2987. ac->highest_zoneidx, alloc_flags,
  2988. gfp_mask))
  2989. goto try_this_zone;
  2990. else
  2991. set_bit(ZONE_BELOW_HIGH, &zone->flags);
  2992. check_alloc_wmark:
  2993. mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
  2994. if (!zone_watermark_fast(zone, order, mark,
  2995. ac->highest_zoneidx, alloc_flags,
  2996. gfp_mask)) {
  2997. int ret;
  2998. if (cond_accept_memory(zone, order))
  2999. goto try_this_zone;
  3000. /*
  3001. * Watermark failed for this zone, but see if we can
  3002. * grow this zone if it contains deferred pages.
  3003. */
  3004. if (deferred_pages_enabled()) {
  3005. if (_deferred_grow_zone(zone, order))
  3006. goto try_this_zone;
  3007. }
  3008. /* Checked here to keep the fast path fast */
  3009. BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
  3010. if (alloc_flags & ALLOC_NO_WATERMARKS)
  3011. goto try_this_zone;
  3012. if (!node_reclaim_enabled() ||
  3013. !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
  3014. continue;
  3015. ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
  3016. switch (ret) {
  3017. case NODE_RECLAIM_NOSCAN:
  3018. /* did not scan */
  3019. continue;
  3020. case NODE_RECLAIM_FULL:
  3021. /* scanned but unreclaimable */
  3022. continue;
  3023. default:
  3024. /* did we reclaim enough */
  3025. if (zone_watermark_ok(zone, order, mark,
  3026. ac->highest_zoneidx, alloc_flags))
  3027. goto try_this_zone;
  3028. continue;
  3029. }
  3030. }
  3031. try_this_zone:
  3032. page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
  3033. gfp_mask, alloc_flags, ac->migratetype);
  3034. if (page) {
  3035. prep_new_page(page, order, gfp_mask, alloc_flags);
  3036. /*
  3037. * If this is a high-order atomic allocation then check
  3038. * if the pageblock should be reserved for the future
  3039. */
  3040. if (unlikely(alloc_flags & ALLOC_HIGHATOMIC))
  3041. reserve_highatomic_pageblock(page, order, zone);
  3042. return page;
  3043. } else {
  3044. if (cond_accept_memory(zone, order))
  3045. goto try_this_zone;
  3046. /* Try again if zone has deferred pages */
  3047. if (deferred_pages_enabled()) {
  3048. if (_deferred_grow_zone(zone, order))
  3049. goto try_this_zone;
  3050. }
  3051. }
  3052. }
  3053. /*
  3054. * It's possible on a UMA machine to get through all zones that are
  3055. * fragmented. If avoiding fragmentation, reset and try again.
  3056. */
  3057. if (no_fallback) {
  3058. alloc_flags &= ~ALLOC_NOFRAGMENT;
  3059. goto retry;
  3060. }
  3061. return NULL;
  3062. }
  3063. static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
  3064. {
  3065. unsigned int filter = SHOW_MEM_FILTER_NODES;
  3066. /*
  3067. * This documents exceptions given to allocations in certain
  3068. * contexts that are allowed to allocate outside current's set
  3069. * of allowed nodes.
  3070. */
  3071. if (!(gfp_mask & __GFP_NOMEMALLOC))
  3072. if (tsk_is_oom_victim(current) ||
  3073. (current->flags & (PF_MEMALLOC | PF_EXITING)))
  3074. filter &= ~SHOW_MEM_FILTER_NODES;
  3075. if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
  3076. filter &= ~SHOW_MEM_FILTER_NODES;
  3077. __show_mem(filter, nodemask, gfp_zone(gfp_mask));
  3078. }
  3079. void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
  3080. {
  3081. struct va_format vaf;
  3082. va_list args;
  3083. static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
  3084. if ((gfp_mask & __GFP_NOWARN) ||
  3085. !__ratelimit(&nopage_rs) ||
  3086. ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
  3087. return;
  3088. va_start(args, fmt);
  3089. vaf.fmt = fmt;
  3090. vaf.va = &args;
  3091. pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
  3092. current->comm, &vaf, gfp_mask, &gfp_mask,
  3093. nodemask_pr_args(nodemask));
  3094. va_end(args);
  3095. cpuset_print_current_mems_allowed();
  3096. pr_cont("\n");
  3097. dump_stack();
  3098. warn_alloc_show_mem(gfp_mask, nodemask);
  3099. }
  3100. static inline struct page *
  3101. __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
  3102. unsigned int alloc_flags,
  3103. const struct alloc_context *ac)
  3104. {
  3105. struct page *page;
  3106. page = get_page_from_freelist(gfp_mask, order,
  3107. alloc_flags|ALLOC_CPUSET, ac);
  3108. /*
  3109. * fallback to ignore cpuset restriction if our nodes
  3110. * are depleted
  3111. */
  3112. if (!page)
  3113. page = get_page_from_freelist(gfp_mask, order,
  3114. alloc_flags, ac);
  3115. return page;
  3116. }
  3117. static inline struct page *
  3118. __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
  3119. const struct alloc_context *ac, unsigned long *did_some_progress)
  3120. {
  3121. struct oom_control oc = {
  3122. .zonelist = ac->zonelist,
  3123. .nodemask = ac->nodemask,
  3124. .memcg = NULL,
  3125. .gfp_mask = gfp_mask,
  3126. .order = order,
  3127. };
  3128. struct page *page;
  3129. *did_some_progress = 0;
  3130. /*
  3131. * Acquire the oom lock. If that fails, somebody else is
  3132. * making progress for us.
  3133. */
  3134. if (!mutex_trylock(&oom_lock)) {
  3135. *did_some_progress = 1;
  3136. schedule_timeout_uninterruptible(1);
  3137. return NULL;
  3138. }
  3139. /*
  3140. * Go through the zonelist yet one more time, keep very high watermark
  3141. * here, this is only to catch a parallel oom killing, we must fail if
  3142. * we're still under heavy pressure. But make sure that this reclaim
  3143. * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
  3144. * allocation which will never fail due to oom_lock already held.
  3145. */
  3146. page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
  3147. ~__GFP_DIRECT_RECLAIM, order,
  3148. ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
  3149. if (page)
  3150. goto out;
  3151. /* Coredumps can quickly deplete all memory reserves */
  3152. if (current->flags & PF_DUMPCORE)
  3153. goto out;
  3154. /* The OOM killer will not help higher order allocs */
  3155. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3156. goto out;
  3157. /*
  3158. * We have already exhausted all our reclaim opportunities without any
  3159. * success so it is time to admit defeat. We will skip the OOM killer
  3160. * because it is very likely that the caller has a more reasonable
  3161. * fallback than shooting a random task.
  3162. *
  3163. * The OOM killer may not free memory on a specific node.
  3164. */
  3165. if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
  3166. goto out;
  3167. /* The OOM killer does not needlessly kill tasks for lowmem */
  3168. if (ac->highest_zoneidx < ZONE_NORMAL)
  3169. goto out;
  3170. if (pm_suspended_storage())
  3171. goto out;
  3172. /*
  3173. * XXX: GFP_NOFS allocations should rather fail than rely on
  3174. * other request to make a forward progress.
  3175. * We are in an unfortunate situation where out_of_memory cannot
  3176. * do much for this context but let's try it to at least get
  3177. * access to memory reserved if the current task is killed (see
  3178. * out_of_memory). Once filesystems are ready to handle allocation
  3179. * failures more gracefully we should just bail out here.
  3180. */
  3181. /* Exhausted what can be done so it's blame time */
  3182. if (out_of_memory(&oc) ||
  3183. WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) {
  3184. *did_some_progress = 1;
  3185. /*
  3186. * Help non-failing allocations by giving them access to memory
  3187. * reserves
  3188. */
  3189. if (gfp_mask & __GFP_NOFAIL)
  3190. page = __alloc_pages_cpuset_fallback(gfp_mask, order,
  3191. ALLOC_NO_WATERMARKS, ac);
  3192. }
  3193. out:
  3194. mutex_unlock(&oom_lock);
  3195. return page;
  3196. }
  3197. /*
  3198. * Maximum number of compaction retries with a progress before OOM
  3199. * killer is consider as the only way to move forward.
  3200. */
  3201. #define MAX_COMPACT_RETRIES 16
  3202. #ifdef CONFIG_COMPACTION
  3203. /* Try memory compaction for high-order allocations before reclaim */
  3204. static struct page *
  3205. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3206. unsigned int alloc_flags, const struct alloc_context *ac,
  3207. enum compact_priority prio, enum compact_result *compact_result)
  3208. {
  3209. struct page *page = NULL;
  3210. unsigned long pflags;
  3211. unsigned int noreclaim_flag;
  3212. if (!order)
  3213. return NULL;
  3214. psi_memstall_enter(&pflags);
  3215. delayacct_compact_start();
  3216. noreclaim_flag = memalloc_noreclaim_save();
  3217. *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
  3218. prio, &page);
  3219. memalloc_noreclaim_restore(noreclaim_flag);
  3220. psi_memstall_leave(&pflags);
  3221. delayacct_compact_end();
  3222. if (*compact_result == COMPACT_SKIPPED)
  3223. return NULL;
  3224. /*
  3225. * At least in one zone compaction wasn't deferred or skipped, so let's
  3226. * count a compaction stall
  3227. */
  3228. count_vm_event(COMPACTSTALL);
  3229. /* Prep a captured page if available */
  3230. if (page)
  3231. prep_new_page(page, order, gfp_mask, alloc_flags);
  3232. /* Try get a page from the freelist if available */
  3233. if (!page)
  3234. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3235. if (page) {
  3236. struct zone *zone = page_zone(page);
  3237. zone->compact_blockskip_flush = false;
  3238. compaction_defer_reset(zone, order, true);
  3239. count_vm_event(COMPACTSUCCESS);
  3240. return page;
  3241. }
  3242. /*
  3243. * It's bad if compaction run occurs and fails. The most likely reason
  3244. * is that pages exist, but not enough to satisfy watermarks.
  3245. */
  3246. count_vm_event(COMPACTFAIL);
  3247. cond_resched();
  3248. return NULL;
  3249. }
  3250. static inline bool
  3251. should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
  3252. enum compact_result compact_result,
  3253. enum compact_priority *compact_priority,
  3254. int *compaction_retries)
  3255. {
  3256. int max_retries = MAX_COMPACT_RETRIES;
  3257. int min_priority;
  3258. bool ret = false;
  3259. int retries = *compaction_retries;
  3260. enum compact_priority priority = *compact_priority;
  3261. if (!order)
  3262. return false;
  3263. if (fatal_signal_pending(current))
  3264. return false;
  3265. /*
  3266. * Compaction was skipped due to a lack of free order-0
  3267. * migration targets. Continue if reclaim can help.
  3268. */
  3269. if (compact_result == COMPACT_SKIPPED) {
  3270. ret = compaction_zonelist_suitable(ac, order, alloc_flags);
  3271. goto out;
  3272. }
  3273. /*
  3274. * Compaction managed to coalesce some page blocks, but the
  3275. * allocation failed presumably due to a race. Retry some.
  3276. */
  3277. if (compact_result == COMPACT_SUCCESS) {
  3278. /*
  3279. * !costly requests are much more important than
  3280. * __GFP_RETRY_MAYFAIL costly ones because they are de
  3281. * facto nofail and invoke OOM killer to move on while
  3282. * costly can fail and users are ready to cope with
  3283. * that. 1/4 retries is rather arbitrary but we would
  3284. * need much more detailed feedback from compaction to
  3285. * make a better decision.
  3286. */
  3287. if (order > PAGE_ALLOC_COSTLY_ORDER)
  3288. max_retries /= 4;
  3289. if (++(*compaction_retries) <= max_retries) {
  3290. ret = true;
  3291. goto out;
  3292. }
  3293. }
  3294. /*
  3295. * Compaction failed. Retry with increasing priority.
  3296. */
  3297. min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
  3298. MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
  3299. if (*compact_priority > min_priority) {
  3300. (*compact_priority)--;
  3301. *compaction_retries = 0;
  3302. ret = true;
  3303. }
  3304. out:
  3305. trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
  3306. return ret;
  3307. }
  3308. #else
  3309. static inline struct page *
  3310. __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
  3311. unsigned int alloc_flags, const struct alloc_context *ac,
  3312. enum compact_priority prio, enum compact_result *compact_result)
  3313. {
  3314. *compact_result = COMPACT_SKIPPED;
  3315. return NULL;
  3316. }
  3317. static inline bool
  3318. should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
  3319. enum compact_result compact_result,
  3320. enum compact_priority *compact_priority,
  3321. int *compaction_retries)
  3322. {
  3323. struct zone *zone;
  3324. struct zoneref *z;
  3325. if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
  3326. return false;
  3327. /*
  3328. * There are setups with compaction disabled which would prefer to loop
  3329. * inside the allocator rather than hit the oom killer prematurely.
  3330. * Let's give them a good hope and keep retrying while the order-0
  3331. * watermarks are OK.
  3332. */
  3333. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  3334. ac->highest_zoneidx, ac->nodemask) {
  3335. if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
  3336. ac->highest_zoneidx, alloc_flags))
  3337. return true;
  3338. }
  3339. return false;
  3340. }
  3341. #endif /* CONFIG_COMPACTION */
  3342. #ifdef CONFIG_LOCKDEP
  3343. static struct lockdep_map __fs_reclaim_map =
  3344. STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
  3345. static bool __need_reclaim(gfp_t gfp_mask)
  3346. {
  3347. /* no reclaim without waiting on it */
  3348. if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
  3349. return false;
  3350. /* this guy won't enter reclaim */
  3351. if (current->flags & PF_MEMALLOC)
  3352. return false;
  3353. if (gfp_mask & __GFP_NOLOCKDEP)
  3354. return false;
  3355. return true;
  3356. }
  3357. void __fs_reclaim_acquire(unsigned long ip)
  3358. {
  3359. lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
  3360. }
  3361. void __fs_reclaim_release(unsigned long ip)
  3362. {
  3363. lock_release(&__fs_reclaim_map, ip);
  3364. }
  3365. void fs_reclaim_acquire(gfp_t gfp_mask)
  3366. {
  3367. gfp_mask = current_gfp_context(gfp_mask);
  3368. if (__need_reclaim(gfp_mask)) {
  3369. if (gfp_mask & __GFP_FS)
  3370. __fs_reclaim_acquire(_RET_IP_);
  3371. #ifdef CONFIG_MMU_NOTIFIER
  3372. lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
  3373. lock_map_release(&__mmu_notifier_invalidate_range_start_map);
  3374. #endif
  3375. }
  3376. }
  3377. EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
  3378. void fs_reclaim_release(gfp_t gfp_mask)
  3379. {
  3380. gfp_mask = current_gfp_context(gfp_mask);
  3381. if (__need_reclaim(gfp_mask)) {
  3382. if (gfp_mask & __GFP_FS)
  3383. __fs_reclaim_release(_RET_IP_);
  3384. }
  3385. }
  3386. EXPORT_SYMBOL_GPL(fs_reclaim_release);
  3387. #endif
  3388. /*
  3389. * Zonelists may change due to hotplug during allocation. Detect when zonelists
  3390. * have been rebuilt so allocation retries. Reader side does not lock and
  3391. * retries the allocation if zonelist changes. Writer side is protected by the
  3392. * embedded spin_lock.
  3393. */
  3394. static DEFINE_SEQLOCK(zonelist_update_seq);
  3395. static unsigned int zonelist_iter_begin(void)
  3396. {
  3397. if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
  3398. return read_seqbegin(&zonelist_update_seq);
  3399. return 0;
  3400. }
  3401. static unsigned int check_retry_zonelist(unsigned int seq)
  3402. {
  3403. if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
  3404. return read_seqretry(&zonelist_update_seq, seq);
  3405. return seq;
  3406. }
  3407. /* Perform direct synchronous page reclaim */
  3408. static unsigned long
  3409. __perform_reclaim(gfp_t gfp_mask, unsigned int order,
  3410. const struct alloc_context *ac)
  3411. {
  3412. unsigned int noreclaim_flag;
  3413. unsigned long progress;
  3414. cond_resched();
  3415. /* We now go into synchronous reclaim */
  3416. cpuset_memory_pressure_bump();
  3417. fs_reclaim_acquire(gfp_mask);
  3418. noreclaim_flag = memalloc_noreclaim_save();
  3419. progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
  3420. ac->nodemask);
  3421. memalloc_noreclaim_restore(noreclaim_flag);
  3422. fs_reclaim_release(gfp_mask);
  3423. cond_resched();
  3424. return progress;
  3425. }
  3426. /* The really slow allocator path where we enter direct reclaim */
  3427. static inline struct page *
  3428. __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
  3429. unsigned int alloc_flags, const struct alloc_context *ac,
  3430. unsigned long *did_some_progress)
  3431. {
  3432. struct page *page = NULL;
  3433. unsigned long pflags;
  3434. bool drained = false;
  3435. psi_memstall_enter(&pflags);
  3436. *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
  3437. if (unlikely(!(*did_some_progress)))
  3438. goto out;
  3439. retry:
  3440. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3441. /*
  3442. * If an allocation failed after direct reclaim, it could be because
  3443. * pages are pinned on the per-cpu lists or in high alloc reserves.
  3444. * Shrink them and try again
  3445. */
  3446. if (!page && !drained) {
  3447. unreserve_highatomic_pageblock(ac, false);
  3448. drain_all_pages(NULL);
  3449. drained = true;
  3450. goto retry;
  3451. }
  3452. out:
  3453. psi_memstall_leave(&pflags);
  3454. return page;
  3455. }
  3456. static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
  3457. const struct alloc_context *ac)
  3458. {
  3459. struct zoneref *z;
  3460. struct zone *zone;
  3461. pg_data_t *last_pgdat = NULL;
  3462. enum zone_type highest_zoneidx = ac->highest_zoneidx;
  3463. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
  3464. ac->nodemask) {
  3465. if (!managed_zone(zone))
  3466. continue;
  3467. if (last_pgdat != zone->zone_pgdat) {
  3468. wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
  3469. last_pgdat = zone->zone_pgdat;
  3470. }
  3471. }
  3472. }
  3473. static inline unsigned int
  3474. gfp_to_alloc_flags(gfp_t gfp_mask, unsigned int order)
  3475. {
  3476. unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
  3477. /*
  3478. * __GFP_HIGH is assumed to be the same as ALLOC_MIN_RESERVE
  3479. * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
  3480. * to save two branches.
  3481. */
  3482. BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_MIN_RESERVE);
  3483. BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
  3484. /*
  3485. * The caller may dip into page reserves a bit more if the caller
  3486. * cannot run direct reclaim, or if the caller has realtime scheduling
  3487. * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
  3488. * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH).
  3489. */
  3490. alloc_flags |= (__force int)
  3491. (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
  3492. if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
  3493. /*
  3494. * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
  3495. * if it can't schedule.
  3496. */
  3497. if (!(gfp_mask & __GFP_NOMEMALLOC)) {
  3498. alloc_flags |= ALLOC_NON_BLOCK;
  3499. if (order > 0 && (alloc_flags & ALLOC_MIN_RESERVE))
  3500. alloc_flags |= ALLOC_HIGHATOMIC;
  3501. }
  3502. /*
  3503. * Ignore cpuset mems for non-blocking __GFP_HIGH (probably
  3504. * GFP_ATOMIC) rather than fail, see the comment for
  3505. * cpuset_node_allowed().
  3506. */
  3507. if (alloc_flags & ALLOC_MIN_RESERVE)
  3508. alloc_flags &= ~ALLOC_CPUSET;
  3509. } else if (unlikely(rt_or_dl_task(current)) && in_task())
  3510. alloc_flags |= ALLOC_MIN_RESERVE;
  3511. alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
  3512. return alloc_flags;
  3513. }
  3514. static bool oom_reserves_allowed(struct task_struct *tsk)
  3515. {
  3516. if (!tsk_is_oom_victim(tsk))
  3517. return false;
  3518. /*
  3519. * !MMU doesn't have oom reaper so give access to memory reserves
  3520. * only to the thread with TIF_MEMDIE set
  3521. */
  3522. if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
  3523. return false;
  3524. return true;
  3525. }
  3526. /*
  3527. * Distinguish requests which really need access to full memory
  3528. * reserves from oom victims which can live with a portion of it
  3529. */
  3530. static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
  3531. {
  3532. if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
  3533. return 0;
  3534. if (gfp_mask & __GFP_MEMALLOC)
  3535. return ALLOC_NO_WATERMARKS;
  3536. if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
  3537. return ALLOC_NO_WATERMARKS;
  3538. if (!in_interrupt()) {
  3539. if (current->flags & PF_MEMALLOC)
  3540. return ALLOC_NO_WATERMARKS;
  3541. else if (oom_reserves_allowed(current))
  3542. return ALLOC_OOM;
  3543. }
  3544. return 0;
  3545. }
  3546. bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
  3547. {
  3548. return !!__gfp_pfmemalloc_flags(gfp_mask);
  3549. }
  3550. /*
  3551. * Checks whether it makes sense to retry the reclaim to make a forward progress
  3552. * for the given allocation request.
  3553. *
  3554. * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
  3555. * without success, or when we couldn't even meet the watermark if we
  3556. * reclaimed all remaining pages on the LRU lists.
  3557. *
  3558. * Returns true if a retry is viable or false to enter the oom path.
  3559. */
  3560. static inline bool
  3561. should_reclaim_retry(gfp_t gfp_mask, unsigned order,
  3562. struct alloc_context *ac, int alloc_flags,
  3563. bool did_some_progress, int *no_progress_loops)
  3564. {
  3565. struct zone *zone;
  3566. struct zoneref *z;
  3567. bool ret = false;
  3568. /*
  3569. * Costly allocations might have made a progress but this doesn't mean
  3570. * their order will become available due to high fragmentation so
  3571. * always increment the no progress counter for them
  3572. */
  3573. if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
  3574. *no_progress_loops = 0;
  3575. else
  3576. (*no_progress_loops)++;
  3577. if (*no_progress_loops > MAX_RECLAIM_RETRIES)
  3578. goto out;
  3579. /*
  3580. * Keep reclaiming pages while there is a chance this will lead
  3581. * somewhere. If none of the target zones can satisfy our allocation
  3582. * request even if all reclaimable pages are considered then we are
  3583. * screwed and have to go OOM.
  3584. */
  3585. for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
  3586. ac->highest_zoneidx, ac->nodemask) {
  3587. unsigned long available;
  3588. unsigned long reclaimable;
  3589. unsigned long min_wmark = min_wmark_pages(zone);
  3590. bool wmark;
  3591. if (cpusets_enabled() &&
  3592. (alloc_flags & ALLOC_CPUSET) &&
  3593. !__cpuset_zone_allowed(zone, gfp_mask))
  3594. continue;
  3595. available = reclaimable = zone_reclaimable_pages(zone);
  3596. available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
  3597. /*
  3598. * Would the allocation succeed if we reclaimed all
  3599. * reclaimable pages?
  3600. */
  3601. wmark = __zone_watermark_ok(zone, order, min_wmark,
  3602. ac->highest_zoneidx, alloc_flags, available);
  3603. trace_reclaim_retry_zone(z, order, reclaimable,
  3604. available, min_wmark, *no_progress_loops, wmark);
  3605. if (wmark) {
  3606. ret = true;
  3607. break;
  3608. }
  3609. }
  3610. /*
  3611. * Memory allocation/reclaim might be called from a WQ context and the
  3612. * current implementation of the WQ concurrency control doesn't
  3613. * recognize that a particular WQ is congested if the worker thread is
  3614. * looping without ever sleeping. Therefore we have to do a short sleep
  3615. * here rather than calling cond_resched().
  3616. */
  3617. if (current->flags & PF_WQ_WORKER)
  3618. schedule_timeout_uninterruptible(1);
  3619. else
  3620. cond_resched();
  3621. out:
  3622. /* Before OOM, exhaust highatomic_reserve */
  3623. if (!ret)
  3624. return unreserve_highatomic_pageblock(ac, true);
  3625. return ret;
  3626. }
  3627. static inline bool
  3628. check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
  3629. {
  3630. /*
  3631. * It's possible that cpuset's mems_allowed and the nodemask from
  3632. * mempolicy don't intersect. This should be normally dealt with by
  3633. * policy_nodemask(), but it's possible to race with cpuset update in
  3634. * such a way the check therein was true, and then it became false
  3635. * before we got our cpuset_mems_cookie here.
  3636. * This assumes that for all allocations, ac->nodemask can come only
  3637. * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
  3638. * when it does not intersect with the cpuset restrictions) or the
  3639. * caller can deal with a violated nodemask.
  3640. */
  3641. if (cpusets_enabled() && ac->nodemask &&
  3642. !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
  3643. ac->nodemask = NULL;
  3644. return true;
  3645. }
  3646. /*
  3647. * When updating a task's mems_allowed or mempolicy nodemask, it is
  3648. * possible to race with parallel threads in such a way that our
  3649. * allocation can fail while the mask is being updated. If we are about
  3650. * to fail, check if the cpuset changed during allocation and if so,
  3651. * retry.
  3652. */
  3653. if (read_mems_allowed_retry(cpuset_mems_cookie))
  3654. return true;
  3655. return false;
  3656. }
  3657. static inline struct page *
  3658. __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
  3659. struct alloc_context *ac)
  3660. {
  3661. bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
  3662. bool can_compact = gfp_compaction_allowed(gfp_mask);
  3663. bool nofail = gfp_mask & __GFP_NOFAIL;
  3664. const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
  3665. struct page *page = NULL;
  3666. unsigned int alloc_flags;
  3667. unsigned long did_some_progress;
  3668. enum compact_priority compact_priority;
  3669. enum compact_result compact_result;
  3670. int compaction_retries;
  3671. int no_progress_loops;
  3672. unsigned int cpuset_mems_cookie;
  3673. unsigned int zonelist_iter_cookie;
  3674. int reserve_flags;
  3675. if (unlikely(nofail)) {
  3676. /*
  3677. * We most definitely don't want callers attempting to
  3678. * allocate greater than order-1 page units with __GFP_NOFAIL.
  3679. */
  3680. WARN_ON_ONCE(order > 1);
  3681. /*
  3682. * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM,
  3683. * otherwise, we may result in lockup.
  3684. */
  3685. WARN_ON_ONCE(!can_direct_reclaim);
  3686. /*
  3687. * PF_MEMALLOC request from this context is rather bizarre
  3688. * because we cannot reclaim anything and only can loop waiting
  3689. * for somebody to do a work for us.
  3690. */
  3691. WARN_ON_ONCE(current->flags & PF_MEMALLOC);
  3692. }
  3693. restart:
  3694. compaction_retries = 0;
  3695. no_progress_loops = 0;
  3696. compact_result = COMPACT_SKIPPED;
  3697. compact_priority = DEF_COMPACT_PRIORITY;
  3698. cpuset_mems_cookie = read_mems_allowed_begin();
  3699. zonelist_iter_cookie = zonelist_iter_begin();
  3700. /*
  3701. * The fast path uses conservative alloc_flags to succeed only until
  3702. * kswapd needs to be woken up, and to avoid the cost of setting up
  3703. * alloc_flags precisely. So we do that now.
  3704. */
  3705. alloc_flags = gfp_to_alloc_flags(gfp_mask, order);
  3706. /*
  3707. * We need to recalculate the starting point for the zonelist iterator
  3708. * because we might have used different nodemask in the fast path, or
  3709. * there was a cpuset modification and we are retrying - otherwise we
  3710. * could end up iterating over non-eligible zones endlessly.
  3711. */
  3712. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3713. ac->highest_zoneidx, ac->nodemask);
  3714. if (!zonelist_zone(ac->preferred_zoneref))
  3715. goto nopage;
  3716. /*
  3717. * Check for insane configurations where the cpuset doesn't contain
  3718. * any suitable zone to satisfy the request - e.g. non-movable
  3719. * GFP_HIGHUSER allocations from MOVABLE nodes only.
  3720. */
  3721. if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
  3722. struct zoneref *z = first_zones_zonelist(ac->zonelist,
  3723. ac->highest_zoneidx,
  3724. &cpuset_current_mems_allowed);
  3725. if (!zonelist_zone(z))
  3726. goto nopage;
  3727. }
  3728. if (alloc_flags & ALLOC_KSWAPD)
  3729. wake_all_kswapds(order, gfp_mask, ac);
  3730. /*
  3731. * The adjusted alloc_flags might result in immediate success, so try
  3732. * that first
  3733. */
  3734. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3735. if (page)
  3736. goto got_pg;
  3737. /*
  3738. * For costly allocations, try direct compaction first, as it's likely
  3739. * that we have enough base pages and don't need to reclaim. For non-
  3740. * movable high-order allocations, do that as well, as compaction will
  3741. * try prevent permanent fragmentation by migrating from blocks of the
  3742. * same migratetype.
  3743. * Don't try this for allocations that are allowed to ignore
  3744. * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
  3745. */
  3746. if (can_direct_reclaim && can_compact &&
  3747. (costly_order ||
  3748. (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
  3749. && !gfp_pfmemalloc_allowed(gfp_mask)) {
  3750. page = __alloc_pages_direct_compact(gfp_mask, order,
  3751. alloc_flags, ac,
  3752. INIT_COMPACT_PRIORITY,
  3753. &compact_result);
  3754. if (page)
  3755. goto got_pg;
  3756. /*
  3757. * Checks for costly allocations with __GFP_NORETRY, which
  3758. * includes some THP page fault allocations
  3759. */
  3760. if (costly_order && (gfp_mask & __GFP_NORETRY)) {
  3761. /*
  3762. * If allocating entire pageblock(s) and compaction
  3763. * failed because all zones are below low watermarks
  3764. * or is prohibited because it recently failed at this
  3765. * order, fail immediately unless the allocator has
  3766. * requested compaction and reclaim retry.
  3767. *
  3768. * Reclaim is
  3769. * - potentially very expensive because zones are far
  3770. * below their low watermarks or this is part of very
  3771. * bursty high order allocations,
  3772. * - not guaranteed to help because isolate_freepages()
  3773. * may not iterate over freed pages as part of its
  3774. * linear scan, and
  3775. * - unlikely to make entire pageblocks free on its
  3776. * own.
  3777. */
  3778. if (compact_result == COMPACT_SKIPPED ||
  3779. compact_result == COMPACT_DEFERRED)
  3780. goto nopage;
  3781. /*
  3782. * Looks like reclaim/compaction is worth trying, but
  3783. * sync compaction could be very expensive, so keep
  3784. * using async compaction.
  3785. */
  3786. compact_priority = INIT_COMPACT_PRIORITY;
  3787. }
  3788. }
  3789. retry:
  3790. /*
  3791. * Deal with possible cpuset update races or zonelist updates to avoid
  3792. * infinite retries.
  3793. */
  3794. if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
  3795. check_retry_zonelist(zonelist_iter_cookie))
  3796. goto restart;
  3797. /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
  3798. if (alloc_flags & ALLOC_KSWAPD)
  3799. wake_all_kswapds(order, gfp_mask, ac);
  3800. reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
  3801. if (reserve_flags)
  3802. alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) |
  3803. (alloc_flags & ALLOC_KSWAPD);
  3804. /*
  3805. * Reset the nodemask and zonelist iterators if memory policies can be
  3806. * ignored. These allocations are high priority and system rather than
  3807. * user oriented.
  3808. */
  3809. if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
  3810. ac->nodemask = NULL;
  3811. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3812. ac->highest_zoneidx, ac->nodemask);
  3813. }
  3814. /* Attempt with potentially adjusted zonelist and alloc_flags */
  3815. page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
  3816. if (page)
  3817. goto got_pg;
  3818. /* Caller is not willing to reclaim, we can't balance anything */
  3819. if (!can_direct_reclaim)
  3820. goto nopage;
  3821. /* Avoid recursion of direct reclaim */
  3822. if (current->flags & PF_MEMALLOC)
  3823. goto nopage;
  3824. /* Try direct reclaim and then allocating */
  3825. page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
  3826. &did_some_progress);
  3827. if (page)
  3828. goto got_pg;
  3829. /* Try direct compaction and then allocating */
  3830. page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
  3831. compact_priority, &compact_result);
  3832. if (page)
  3833. goto got_pg;
  3834. /* Do not loop if specifically requested */
  3835. if (gfp_mask & __GFP_NORETRY)
  3836. goto nopage;
  3837. /*
  3838. * Do not retry costly high order allocations unless they are
  3839. * __GFP_RETRY_MAYFAIL and we can compact
  3840. */
  3841. if (costly_order && (!can_compact ||
  3842. !(gfp_mask & __GFP_RETRY_MAYFAIL)))
  3843. goto nopage;
  3844. if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
  3845. did_some_progress > 0, &no_progress_loops))
  3846. goto retry;
  3847. /*
  3848. * It doesn't make any sense to retry for the compaction if the order-0
  3849. * reclaim is not able to make any progress because the current
  3850. * implementation of the compaction depends on the sufficient amount
  3851. * of free memory (see __compaction_suitable)
  3852. */
  3853. if (did_some_progress > 0 && can_compact &&
  3854. should_compact_retry(ac, order, alloc_flags,
  3855. compact_result, &compact_priority,
  3856. &compaction_retries))
  3857. goto retry;
  3858. /*
  3859. * Deal with possible cpuset update races or zonelist updates to avoid
  3860. * a unnecessary OOM kill.
  3861. */
  3862. if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
  3863. check_retry_zonelist(zonelist_iter_cookie))
  3864. goto restart;
  3865. /* Reclaim has failed us, start killing things */
  3866. page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
  3867. if (page)
  3868. goto got_pg;
  3869. /* Avoid allocations with no watermarks from looping endlessly */
  3870. if (tsk_is_oom_victim(current) &&
  3871. (alloc_flags & ALLOC_OOM ||
  3872. (gfp_mask & __GFP_NOMEMALLOC)))
  3873. goto nopage;
  3874. /* Retry as long as the OOM killer is making progress */
  3875. if (did_some_progress) {
  3876. no_progress_loops = 0;
  3877. goto retry;
  3878. }
  3879. nopage:
  3880. /*
  3881. * Deal with possible cpuset update races or zonelist updates to avoid
  3882. * a unnecessary OOM kill.
  3883. */
  3884. if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
  3885. check_retry_zonelist(zonelist_iter_cookie))
  3886. goto restart;
  3887. /*
  3888. * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
  3889. * we always retry
  3890. */
  3891. if (unlikely(nofail)) {
  3892. /*
  3893. * Lacking direct_reclaim we can't do anything to reclaim memory,
  3894. * we disregard these unreasonable nofail requests and still
  3895. * return NULL
  3896. */
  3897. if (!can_direct_reclaim)
  3898. goto fail;
  3899. /*
  3900. * Help non-failing allocations by giving some access to memory
  3901. * reserves normally used for high priority non-blocking
  3902. * allocations but do not use ALLOC_NO_WATERMARKS because this
  3903. * could deplete whole memory reserves which would just make
  3904. * the situation worse.
  3905. */
  3906. page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac);
  3907. if (page)
  3908. goto got_pg;
  3909. cond_resched();
  3910. goto retry;
  3911. }
  3912. fail:
  3913. warn_alloc(gfp_mask, ac->nodemask,
  3914. "page allocation failure: order:%u", order);
  3915. got_pg:
  3916. return page;
  3917. }
  3918. static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
  3919. int preferred_nid, nodemask_t *nodemask,
  3920. struct alloc_context *ac, gfp_t *alloc_gfp,
  3921. unsigned int *alloc_flags)
  3922. {
  3923. ac->highest_zoneidx = gfp_zone(gfp_mask);
  3924. ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
  3925. ac->nodemask = nodemask;
  3926. ac->migratetype = gfp_migratetype(gfp_mask);
  3927. if (cpusets_enabled()) {
  3928. *alloc_gfp |= __GFP_HARDWALL;
  3929. /*
  3930. * When we are in the interrupt context, it is irrelevant
  3931. * to the current task context. It means that any node ok.
  3932. */
  3933. if (in_task() && !ac->nodemask)
  3934. ac->nodemask = &cpuset_current_mems_allowed;
  3935. else
  3936. *alloc_flags |= ALLOC_CPUSET;
  3937. }
  3938. might_alloc(gfp_mask);
  3939. if (should_fail_alloc_page(gfp_mask, order))
  3940. return false;
  3941. *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
  3942. /* Dirty zone balancing only done in the fast path */
  3943. ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
  3944. /*
  3945. * The preferred zone is used for statistics but crucially it is
  3946. * also used as the starting point for the zonelist iterator. It
  3947. * may get reset for allocations that ignore memory policies.
  3948. */
  3949. ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
  3950. ac->highest_zoneidx, ac->nodemask);
  3951. return true;
  3952. }
  3953. /*
  3954. * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array
  3955. * @gfp: GFP flags for the allocation
  3956. * @preferred_nid: The preferred NUMA node ID to allocate from
  3957. * @nodemask: Set of nodes to allocate from, may be NULL
  3958. * @nr_pages: The number of pages desired on the list or array
  3959. * @page_list: Optional list to store the allocated pages
  3960. * @page_array: Optional array to store the pages
  3961. *
  3962. * This is a batched version of the page allocator that attempts to
  3963. * allocate nr_pages quickly. Pages are added to page_list if page_list
  3964. * is not NULL, otherwise it is assumed that the page_array is valid.
  3965. *
  3966. * For lists, nr_pages is the number of pages that should be allocated.
  3967. *
  3968. * For arrays, only NULL elements are populated with pages and nr_pages
  3969. * is the maximum number of pages that will be stored in the array.
  3970. *
  3971. * Returns the number of pages on the list or array.
  3972. */
  3973. unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
  3974. nodemask_t *nodemask, int nr_pages,
  3975. struct list_head *page_list,
  3976. struct page **page_array)
  3977. {
  3978. struct page *page;
  3979. unsigned long __maybe_unused UP_flags;
  3980. struct zone *zone;
  3981. struct zoneref *z;
  3982. struct per_cpu_pages *pcp;
  3983. struct list_head *pcp_list;
  3984. struct alloc_context ac;
  3985. gfp_t alloc_gfp;
  3986. unsigned int alloc_flags = ALLOC_WMARK_LOW;
  3987. int nr_populated = 0, nr_account = 0;
  3988. /*
  3989. * Skip populated array elements to determine if any pages need
  3990. * to be allocated before disabling IRQs.
  3991. */
  3992. while (page_array && nr_populated < nr_pages && page_array[nr_populated])
  3993. nr_populated++;
  3994. /* No pages requested? */
  3995. if (unlikely(nr_pages <= 0))
  3996. goto out;
  3997. /* Already populated array? */
  3998. if (unlikely(page_array && nr_pages - nr_populated == 0))
  3999. goto out;
  4000. /* Bulk allocator does not support memcg accounting. */
  4001. if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
  4002. goto failed;
  4003. /* Use the single page allocator for one page. */
  4004. if (nr_pages - nr_populated == 1)
  4005. goto failed;
  4006. #ifdef CONFIG_PAGE_OWNER
  4007. /*
  4008. * PAGE_OWNER may recurse into the allocator to allocate space to
  4009. * save the stack with pagesets.lock held. Releasing/reacquiring
  4010. * removes much of the performance benefit of bulk allocation so
  4011. * force the caller to allocate one page at a time as it'll have
  4012. * similar performance to added complexity to the bulk allocator.
  4013. */
  4014. if (static_branch_unlikely(&page_owner_inited))
  4015. goto failed;
  4016. #endif
  4017. /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
  4018. gfp &= gfp_allowed_mask;
  4019. alloc_gfp = gfp;
  4020. if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
  4021. goto out;
  4022. gfp = alloc_gfp;
  4023. /* Find an allowed local zone that meets the low watermark. */
  4024. z = ac.preferred_zoneref;
  4025. for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
  4026. unsigned long mark;
  4027. if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
  4028. !__cpuset_zone_allowed(zone, gfp)) {
  4029. continue;
  4030. }
  4031. if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
  4032. zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
  4033. goto failed;
  4034. }
  4035. cond_accept_memory(zone, 0);
  4036. retry_this_zone:
  4037. mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
  4038. if (zone_watermark_fast(zone, 0, mark,
  4039. zonelist_zone_idx(ac.preferred_zoneref),
  4040. alloc_flags, gfp)) {
  4041. break;
  4042. }
  4043. if (cond_accept_memory(zone, 0))
  4044. goto retry_this_zone;
  4045. /* Try again if zone has deferred pages */
  4046. if (deferred_pages_enabled()) {
  4047. if (_deferred_grow_zone(zone, 0))
  4048. goto retry_this_zone;
  4049. }
  4050. }
  4051. /*
  4052. * If there are no allowed local zones that meets the watermarks then
  4053. * try to allocate a single page and reclaim if necessary.
  4054. */
  4055. if (unlikely(!zone))
  4056. goto failed;
  4057. /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
  4058. pcp_trylock_prepare(UP_flags);
  4059. pcp = pcp_spin_trylock(zone->per_cpu_pageset);
  4060. if (!pcp)
  4061. goto failed_irq;
  4062. /* Attempt the batch allocation */
  4063. pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
  4064. while (nr_populated < nr_pages) {
  4065. /* Skip existing pages */
  4066. if (page_array && page_array[nr_populated]) {
  4067. nr_populated++;
  4068. continue;
  4069. }
  4070. page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
  4071. pcp, pcp_list);
  4072. if (unlikely(!page)) {
  4073. /* Try and allocate at least one page */
  4074. if (!nr_account) {
  4075. pcp_spin_unlock(pcp);
  4076. goto failed_irq;
  4077. }
  4078. break;
  4079. }
  4080. nr_account++;
  4081. prep_new_page(page, 0, gfp, 0);
  4082. if (page_list)
  4083. list_add(&page->lru, page_list);
  4084. else
  4085. page_array[nr_populated] = page;
  4086. nr_populated++;
  4087. }
  4088. pcp_spin_unlock(pcp);
  4089. pcp_trylock_finish(UP_flags);
  4090. __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
  4091. zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
  4092. out:
  4093. return nr_populated;
  4094. failed_irq:
  4095. pcp_trylock_finish(UP_flags);
  4096. failed:
  4097. page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask);
  4098. if (page) {
  4099. if (page_list)
  4100. list_add(&page->lru, page_list);
  4101. else
  4102. page_array[nr_populated] = page;
  4103. nr_populated++;
  4104. }
  4105. goto out;
  4106. }
  4107. EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof);
  4108. /*
  4109. * This is the 'heart' of the zoned buddy allocator.
  4110. */
  4111. struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
  4112. int preferred_nid, nodemask_t *nodemask)
  4113. {
  4114. struct page *page;
  4115. unsigned int alloc_flags = ALLOC_WMARK_LOW;
  4116. gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
  4117. struct alloc_context ac = { };
  4118. /*
  4119. * There are several places where we assume that the order value is sane
  4120. * so bail out early if the request is out of bound.
  4121. */
  4122. if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp))
  4123. return NULL;
  4124. gfp &= gfp_allowed_mask;
  4125. /*
  4126. * Apply scoped allocation constraints. This is mainly about GFP_NOFS
  4127. * resp. GFP_NOIO which has to be inherited for all allocation requests
  4128. * from a particular context which has been marked by
  4129. * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
  4130. * movable zones are not used during allocation.
  4131. */
  4132. gfp = current_gfp_context(gfp);
  4133. alloc_gfp = gfp;
  4134. if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
  4135. &alloc_gfp, &alloc_flags))
  4136. return NULL;
  4137. /*
  4138. * Forbid the first pass from falling back to types that fragment
  4139. * memory until all local zones are considered.
  4140. */
  4141. alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp);
  4142. /* First allocation attempt */
  4143. page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
  4144. if (likely(page))
  4145. goto out;
  4146. alloc_gfp = gfp;
  4147. ac.spread_dirty_pages = false;
  4148. /*
  4149. * Restore the original nodemask if it was potentially replaced with
  4150. * &cpuset_current_mems_allowed to optimize the fast-path attempt.
  4151. */
  4152. ac.nodemask = nodemask;
  4153. page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
  4154. out:
  4155. if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page &&
  4156. unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
  4157. __free_pages(page, order);
  4158. page = NULL;
  4159. }
  4160. trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
  4161. kmsan_alloc_page(page, order, alloc_gfp);
  4162. return page;
  4163. }
  4164. EXPORT_SYMBOL(__alloc_pages_noprof);
  4165. struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid,
  4166. nodemask_t *nodemask)
  4167. {
  4168. struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order,
  4169. preferred_nid, nodemask);
  4170. return page_rmappable_folio(page);
  4171. }
  4172. EXPORT_SYMBOL(__folio_alloc_noprof);
  4173. /*
  4174. * Common helper functions. Never use with __GFP_HIGHMEM because the returned
  4175. * address cannot represent highmem pages. Use alloc_pages and then kmap if
  4176. * you need to access high mem.
  4177. */
  4178. unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order)
  4179. {
  4180. struct page *page;
  4181. page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order);
  4182. if (!page)
  4183. return 0;
  4184. return (unsigned long) page_address(page);
  4185. }
  4186. EXPORT_SYMBOL(get_free_pages_noprof);
  4187. unsigned long get_zeroed_page_noprof(gfp_t gfp_mask)
  4188. {
  4189. return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0);
  4190. }
  4191. EXPORT_SYMBOL(get_zeroed_page_noprof);
  4192. /**
  4193. * __free_pages - Free pages allocated with alloc_pages().
  4194. * @page: The page pointer returned from alloc_pages().
  4195. * @order: The order of the allocation.
  4196. *
  4197. * This function can free multi-page allocations that are not compound
  4198. * pages. It does not check that the @order passed in matches that of
  4199. * the allocation, so it is easy to leak memory. Freeing more memory
  4200. * than was allocated will probably emit a warning.
  4201. *
  4202. * If the last reference to this page is speculative, it will be released
  4203. * by put_page() which only frees the first page of a non-compound
  4204. * allocation. To prevent the remaining pages from being leaked, we free
  4205. * the subsequent pages here. If you want to use the page's reference
  4206. * count to decide when to free the allocation, you should allocate a
  4207. * compound page, and use put_page() instead of __free_pages().
  4208. *
  4209. * Context: May be called in interrupt context or while holding a normal
  4210. * spinlock, but not in NMI context or while holding a raw spinlock.
  4211. */
  4212. void __free_pages(struct page *page, unsigned int order)
  4213. {
  4214. /* get PageHead before we drop reference */
  4215. int head = PageHead(page);
  4216. struct alloc_tag *tag = pgalloc_tag_get(page);
  4217. if (put_page_testzero(page))
  4218. free_unref_page(page, order);
  4219. else if (!head) {
  4220. pgalloc_tag_sub_pages(tag, (1 << order) - 1);
  4221. while (order-- > 0)
  4222. free_unref_page(page + (1 << order), order);
  4223. }
  4224. }
  4225. EXPORT_SYMBOL(__free_pages);
  4226. void free_pages(unsigned long addr, unsigned int order)
  4227. {
  4228. if (addr != 0) {
  4229. VM_BUG_ON(!virt_addr_valid((void *)addr));
  4230. __free_pages(virt_to_page((void *)addr), order);
  4231. }
  4232. }
  4233. EXPORT_SYMBOL(free_pages);
  4234. /*
  4235. * Page Fragment:
  4236. * An arbitrary-length arbitrary-offset area of memory which resides
  4237. * within a 0 or higher order page. Multiple fragments within that page
  4238. * are individually refcounted, in the page's reference counter.
  4239. *
  4240. * The page_frag functions below provide a simple allocation framework for
  4241. * page fragments. This is used by the network stack and network device
  4242. * drivers to provide a backing region of memory for use as either an
  4243. * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
  4244. */
  4245. static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
  4246. gfp_t gfp_mask)
  4247. {
  4248. struct page *page = NULL;
  4249. gfp_t gfp = gfp_mask;
  4250. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4251. gfp_mask = (gfp_mask & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP |
  4252. __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC;
  4253. page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
  4254. PAGE_FRAG_CACHE_MAX_ORDER);
  4255. nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
  4256. #endif
  4257. if (unlikely(!page))
  4258. page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
  4259. nc->va = page ? page_address(page) : NULL;
  4260. return page;
  4261. }
  4262. void page_frag_cache_drain(struct page_frag_cache *nc)
  4263. {
  4264. if (!nc->va)
  4265. return;
  4266. __page_frag_cache_drain(virt_to_head_page(nc->va), nc->pagecnt_bias);
  4267. nc->va = NULL;
  4268. }
  4269. EXPORT_SYMBOL(page_frag_cache_drain);
  4270. void __page_frag_cache_drain(struct page *page, unsigned int count)
  4271. {
  4272. VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
  4273. if (page_ref_sub_and_test(page, count))
  4274. free_unref_page(page, compound_order(page));
  4275. }
  4276. EXPORT_SYMBOL(__page_frag_cache_drain);
  4277. void *__page_frag_alloc_align(struct page_frag_cache *nc,
  4278. unsigned int fragsz, gfp_t gfp_mask,
  4279. unsigned int align_mask)
  4280. {
  4281. unsigned int size = PAGE_SIZE;
  4282. struct page *page;
  4283. int offset;
  4284. if (unlikely(!nc->va)) {
  4285. refill:
  4286. page = __page_frag_cache_refill(nc, gfp_mask);
  4287. if (!page)
  4288. return NULL;
  4289. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4290. /* if size can vary use size else just use PAGE_SIZE */
  4291. size = nc->size;
  4292. #endif
  4293. /* Even if we own the page, we do not use atomic_set().
  4294. * This would break get_page_unless_zero() users.
  4295. */
  4296. page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
  4297. /* reset page count bias and offset to start of new frag */
  4298. nc->pfmemalloc = page_is_pfmemalloc(page);
  4299. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  4300. nc->offset = size;
  4301. }
  4302. offset = nc->offset - fragsz;
  4303. if (unlikely(offset < 0)) {
  4304. page = virt_to_page(nc->va);
  4305. if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
  4306. goto refill;
  4307. if (unlikely(nc->pfmemalloc)) {
  4308. free_unref_page(page, compound_order(page));
  4309. goto refill;
  4310. }
  4311. #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
  4312. /* if size can vary use size else just use PAGE_SIZE */
  4313. size = nc->size;
  4314. #endif
  4315. /* OK, page count is 0, we can safely set it */
  4316. set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
  4317. /* reset page count bias and offset to start of new frag */
  4318. nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
  4319. offset = size - fragsz;
  4320. if (unlikely(offset < 0)) {
  4321. /*
  4322. * The caller is trying to allocate a fragment
  4323. * with fragsz > PAGE_SIZE but the cache isn't big
  4324. * enough to satisfy the request, this may
  4325. * happen in low memory conditions.
  4326. * We don't release the cache page because
  4327. * it could make memory pressure worse
  4328. * so we simply return NULL here.
  4329. */
  4330. return NULL;
  4331. }
  4332. }
  4333. nc->pagecnt_bias--;
  4334. offset &= align_mask;
  4335. nc->offset = offset;
  4336. return nc->va + offset;
  4337. }
  4338. EXPORT_SYMBOL(__page_frag_alloc_align);
  4339. /*
  4340. * Frees a page fragment allocated out of either a compound or order 0 page.
  4341. */
  4342. void page_frag_free(void *addr)
  4343. {
  4344. struct page *page = virt_to_head_page(addr);
  4345. if (unlikely(put_page_testzero(page)))
  4346. free_unref_page(page, compound_order(page));
  4347. }
  4348. EXPORT_SYMBOL(page_frag_free);
  4349. static void *make_alloc_exact(unsigned long addr, unsigned int order,
  4350. size_t size)
  4351. {
  4352. if (addr) {
  4353. unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE);
  4354. struct page *page = virt_to_page((void *)addr);
  4355. struct page *last = page + nr;
  4356. split_page_owner(page, order, 0);
  4357. pgalloc_tag_split(page_folio(page), order, 0);
  4358. split_page_memcg(page, order, 0);
  4359. while (page < --last)
  4360. set_page_refcounted(last);
  4361. last = page + (1UL << order);
  4362. for (page += nr; page < last; page++)
  4363. __free_pages_ok(page, 0, FPI_TO_TAIL);
  4364. }
  4365. return (void *)addr;
  4366. }
  4367. /**
  4368. * alloc_pages_exact - allocate an exact number physically-contiguous pages.
  4369. * @size: the number of bytes to allocate
  4370. * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
  4371. *
  4372. * This function is similar to alloc_pages(), except that it allocates the
  4373. * minimum number of pages to satisfy the request. alloc_pages() can only
  4374. * allocate memory in power-of-two pages.
  4375. *
  4376. * This function is also limited by MAX_PAGE_ORDER.
  4377. *
  4378. * Memory allocated by this function must be released by free_pages_exact().
  4379. *
  4380. * Return: pointer to the allocated area or %NULL in case of error.
  4381. */
  4382. void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
  4383. {
  4384. unsigned int order = get_order(size);
  4385. unsigned long addr;
  4386. if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
  4387. gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
  4388. addr = get_free_pages_noprof(gfp_mask, order);
  4389. return make_alloc_exact(addr, order, size);
  4390. }
  4391. EXPORT_SYMBOL(alloc_pages_exact_noprof);
  4392. /**
  4393. * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
  4394. * pages on a node.
  4395. * @nid: the preferred node ID where memory should be allocated
  4396. * @size: the number of bytes to allocate
  4397. * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
  4398. *
  4399. * Like alloc_pages_exact(), but try to allocate on node nid first before falling
  4400. * back.
  4401. *
  4402. * Return: pointer to the allocated area or %NULL in case of error.
  4403. */
  4404. void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
  4405. {
  4406. unsigned int order = get_order(size);
  4407. struct page *p;
  4408. if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
  4409. gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
  4410. p = alloc_pages_node_noprof(nid, gfp_mask, order);
  4411. if (!p)
  4412. return NULL;
  4413. return make_alloc_exact((unsigned long)page_address(p), order, size);
  4414. }
  4415. /**
  4416. * free_pages_exact - release memory allocated via alloc_pages_exact()
  4417. * @virt: the value returned by alloc_pages_exact.
  4418. * @size: size of allocation, same value as passed to alloc_pages_exact().
  4419. *
  4420. * Release the memory allocated by a previous call to alloc_pages_exact.
  4421. */
  4422. void free_pages_exact(void *virt, size_t size)
  4423. {
  4424. unsigned long addr = (unsigned long)virt;
  4425. unsigned long end = addr + PAGE_ALIGN(size);
  4426. while (addr < end) {
  4427. free_page(addr);
  4428. addr += PAGE_SIZE;
  4429. }
  4430. }
  4431. EXPORT_SYMBOL(free_pages_exact);
  4432. /**
  4433. * nr_free_zone_pages - count number of pages beyond high watermark
  4434. * @offset: The zone index of the highest zone
  4435. *
  4436. * nr_free_zone_pages() counts the number of pages which are beyond the
  4437. * high watermark within all zones at or below a given zone index. For each
  4438. * zone, the number of pages is calculated as:
  4439. *
  4440. * nr_free_zone_pages = managed_pages - high_pages
  4441. *
  4442. * Return: number of pages beyond high watermark.
  4443. */
  4444. static unsigned long nr_free_zone_pages(int offset)
  4445. {
  4446. struct zoneref *z;
  4447. struct zone *zone;
  4448. /* Just pick one node, since fallback list is circular */
  4449. unsigned long sum = 0;
  4450. struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
  4451. for_each_zone_zonelist(zone, z, zonelist, offset) {
  4452. unsigned long size = zone_managed_pages(zone);
  4453. unsigned long high = high_wmark_pages(zone);
  4454. if (size > high)
  4455. sum += size - high;
  4456. }
  4457. return sum;
  4458. }
  4459. /**
  4460. * nr_free_buffer_pages - count number of pages beyond high watermark
  4461. *
  4462. * nr_free_buffer_pages() counts the number of pages which are beyond the high
  4463. * watermark within ZONE_DMA and ZONE_NORMAL.
  4464. *
  4465. * Return: number of pages beyond high watermark within ZONE_DMA and
  4466. * ZONE_NORMAL.
  4467. */
  4468. unsigned long nr_free_buffer_pages(void)
  4469. {
  4470. return nr_free_zone_pages(gfp_zone(GFP_USER));
  4471. }
  4472. EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
  4473. static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
  4474. {
  4475. zoneref->zone = zone;
  4476. zoneref->zone_idx = zone_idx(zone);
  4477. }
  4478. /*
  4479. * Builds allocation fallback zone lists.
  4480. *
  4481. * Add all populated zones of a node to the zonelist.
  4482. */
  4483. static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
  4484. {
  4485. struct zone *zone;
  4486. enum zone_type zone_type = MAX_NR_ZONES;
  4487. int nr_zones = 0;
  4488. do {
  4489. zone_type--;
  4490. zone = pgdat->node_zones + zone_type;
  4491. if (populated_zone(zone)) {
  4492. zoneref_set_zone(zone, &zonerefs[nr_zones++]);
  4493. check_highest_zone(zone_type);
  4494. }
  4495. } while (zone_type);
  4496. return nr_zones;
  4497. }
  4498. #ifdef CONFIG_NUMA
  4499. static int __parse_numa_zonelist_order(char *s)
  4500. {
  4501. /*
  4502. * We used to support different zonelists modes but they turned
  4503. * out to be just not useful. Let's keep the warning in place
  4504. * if somebody still use the cmd line parameter so that we do
  4505. * not fail it silently
  4506. */
  4507. if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
  4508. pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
  4509. return -EINVAL;
  4510. }
  4511. return 0;
  4512. }
  4513. static char numa_zonelist_order[] = "Node";
  4514. #define NUMA_ZONELIST_ORDER_LEN 16
  4515. /*
  4516. * sysctl handler for numa_zonelist_order
  4517. */
  4518. static int numa_zonelist_order_handler(const struct ctl_table *table, int write,
  4519. void *buffer, size_t *length, loff_t *ppos)
  4520. {
  4521. if (write)
  4522. return __parse_numa_zonelist_order(buffer);
  4523. return proc_dostring(table, write, buffer, length, ppos);
  4524. }
  4525. static int node_load[MAX_NUMNODES];
  4526. /**
  4527. * find_next_best_node - find the next node that should appear in a given node's fallback list
  4528. * @node: node whose fallback list we're appending
  4529. * @used_node_mask: nodemask_t of already used nodes
  4530. *
  4531. * We use a number of factors to determine which is the next node that should
  4532. * appear on a given node's fallback list. The node should not have appeared
  4533. * already in @node's fallback list, and it should be the next closest node
  4534. * according to the distance array (which contains arbitrary distance values
  4535. * from each node to each node in the system), and should also prefer nodes
  4536. * with no CPUs, since presumably they'll have very little allocation pressure
  4537. * on them otherwise.
  4538. *
  4539. * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
  4540. */
  4541. int find_next_best_node(int node, nodemask_t *used_node_mask)
  4542. {
  4543. int n, val;
  4544. int min_val = INT_MAX;
  4545. int best_node = NUMA_NO_NODE;
  4546. /*
  4547. * Use the local node if we haven't already, but for memoryless local
  4548. * node, we should skip it and fall back to other nodes.
  4549. */
  4550. if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) {
  4551. node_set(node, *used_node_mask);
  4552. return node;
  4553. }
  4554. for_each_node_state(n, N_MEMORY) {
  4555. /* Don't want a node to appear more than once */
  4556. if (node_isset(n, *used_node_mask))
  4557. continue;
  4558. /* Use the distance array to find the distance */
  4559. val = node_distance(node, n);
  4560. /* Penalize nodes under us ("prefer the next node") */
  4561. val += (n < node);
  4562. /* Give preference to headless and unused nodes */
  4563. if (!cpumask_empty(cpumask_of_node(n)))
  4564. val += PENALTY_FOR_NODE_WITH_CPUS;
  4565. /* Slight preference for less loaded node */
  4566. val *= MAX_NUMNODES;
  4567. val += node_load[n];
  4568. if (val < min_val) {
  4569. min_val = val;
  4570. best_node = n;
  4571. }
  4572. }
  4573. if (best_node >= 0)
  4574. node_set(best_node, *used_node_mask);
  4575. return best_node;
  4576. }
  4577. /*
  4578. * Build zonelists ordered by node and zones within node.
  4579. * This results in maximum locality--normal zone overflows into local
  4580. * DMA zone, if any--but risks exhausting DMA zone.
  4581. */
  4582. static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
  4583. unsigned nr_nodes)
  4584. {
  4585. struct zoneref *zonerefs;
  4586. int i;
  4587. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4588. for (i = 0; i < nr_nodes; i++) {
  4589. int nr_zones;
  4590. pg_data_t *node = NODE_DATA(node_order[i]);
  4591. nr_zones = build_zonerefs_node(node, zonerefs);
  4592. zonerefs += nr_zones;
  4593. }
  4594. zonerefs->zone = NULL;
  4595. zonerefs->zone_idx = 0;
  4596. }
  4597. /*
  4598. * Build __GFP_THISNODE zonelists
  4599. */
  4600. static void build_thisnode_zonelists(pg_data_t *pgdat)
  4601. {
  4602. struct zoneref *zonerefs;
  4603. int nr_zones;
  4604. zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
  4605. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4606. zonerefs += nr_zones;
  4607. zonerefs->zone = NULL;
  4608. zonerefs->zone_idx = 0;
  4609. }
  4610. /*
  4611. * Build zonelists ordered by zone and nodes within zones.
  4612. * This results in conserving DMA zone[s] until all Normal memory is
  4613. * exhausted, but results in overflowing to remote node while memory
  4614. * may still exist in local DMA zone.
  4615. */
  4616. static void build_zonelists(pg_data_t *pgdat)
  4617. {
  4618. static int node_order[MAX_NUMNODES];
  4619. int node, nr_nodes = 0;
  4620. nodemask_t used_mask = NODE_MASK_NONE;
  4621. int local_node, prev_node;
  4622. /* NUMA-aware ordering of nodes */
  4623. local_node = pgdat->node_id;
  4624. prev_node = local_node;
  4625. memset(node_order, 0, sizeof(node_order));
  4626. while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
  4627. /*
  4628. * We don't want to pressure a particular node.
  4629. * So adding penalty to the first node in same
  4630. * distance group to make it round-robin.
  4631. */
  4632. if (node_distance(local_node, node) !=
  4633. node_distance(local_node, prev_node))
  4634. node_load[node] += 1;
  4635. node_order[nr_nodes++] = node;
  4636. prev_node = node;
  4637. }
  4638. build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
  4639. build_thisnode_zonelists(pgdat);
  4640. pr_info("Fallback order for Node %d: ", local_node);
  4641. for (node = 0; node < nr_nodes; node++)
  4642. pr_cont("%d ", node_order[node]);
  4643. pr_cont("\n");
  4644. }
  4645. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4646. /*
  4647. * Return node id of node used for "local" allocations.
  4648. * I.e., first node id of first zone in arg node's generic zonelist.
  4649. * Used for initializing percpu 'numa_mem', which is used primarily
  4650. * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
  4651. */
  4652. int local_memory_node(int node)
  4653. {
  4654. struct zoneref *z;
  4655. z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
  4656. gfp_zone(GFP_KERNEL),
  4657. NULL);
  4658. return zonelist_node_idx(z);
  4659. }
  4660. #endif
  4661. static void setup_min_unmapped_ratio(void);
  4662. static void setup_min_slab_ratio(void);
  4663. #else /* CONFIG_NUMA */
  4664. static void build_zonelists(pg_data_t *pgdat)
  4665. {
  4666. struct zoneref *zonerefs;
  4667. int nr_zones;
  4668. zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
  4669. nr_zones = build_zonerefs_node(pgdat, zonerefs);
  4670. zonerefs += nr_zones;
  4671. zonerefs->zone = NULL;
  4672. zonerefs->zone_idx = 0;
  4673. }
  4674. #endif /* CONFIG_NUMA */
  4675. /*
  4676. * Boot pageset table. One per cpu which is going to be used for all
  4677. * zones and all nodes. The parameters will be set in such a way
  4678. * that an item put on a list will immediately be handed over to
  4679. * the buddy list. This is safe since pageset manipulation is done
  4680. * with interrupts disabled.
  4681. *
  4682. * The boot_pagesets must be kept even after bootup is complete for
  4683. * unused processors and/or zones. They do play a role for bootstrapping
  4684. * hotplugged processors.
  4685. *
  4686. * zoneinfo_show() and maybe other functions do
  4687. * not check if the processor is online before following the pageset pointer.
  4688. * Other parts of the kernel may not check if the zone is available.
  4689. */
  4690. static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
  4691. /* These effectively disable the pcplists in the boot pageset completely */
  4692. #define BOOT_PAGESET_HIGH 0
  4693. #define BOOT_PAGESET_BATCH 1
  4694. static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
  4695. static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
  4696. static void __build_all_zonelists(void *data)
  4697. {
  4698. int nid;
  4699. int __maybe_unused cpu;
  4700. pg_data_t *self = data;
  4701. unsigned long flags;
  4702. /*
  4703. * The zonelist_update_seq must be acquired with irqsave because the
  4704. * reader can be invoked from IRQ with GFP_ATOMIC.
  4705. */
  4706. write_seqlock_irqsave(&zonelist_update_seq, flags);
  4707. /*
  4708. * Also disable synchronous printk() to prevent any printk() from
  4709. * trying to hold port->lock, for
  4710. * tty_insert_flip_string_and_push_buffer() on other CPU might be
  4711. * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held.
  4712. */
  4713. printk_deferred_enter();
  4714. #ifdef CONFIG_NUMA
  4715. memset(node_load, 0, sizeof(node_load));
  4716. #endif
  4717. /*
  4718. * This node is hotadded and no memory is yet present. So just
  4719. * building zonelists is fine - no need to touch other nodes.
  4720. */
  4721. if (self && !node_online(self->node_id)) {
  4722. build_zonelists(self);
  4723. } else {
  4724. /*
  4725. * All possible nodes have pgdat preallocated
  4726. * in free_area_init
  4727. */
  4728. for_each_node(nid) {
  4729. pg_data_t *pgdat = NODE_DATA(nid);
  4730. build_zonelists(pgdat);
  4731. }
  4732. #ifdef CONFIG_HAVE_MEMORYLESS_NODES
  4733. /*
  4734. * We now know the "local memory node" for each node--
  4735. * i.e., the node of the first zone in the generic zonelist.
  4736. * Set up numa_mem percpu variable for on-line cpus. During
  4737. * boot, only the boot cpu should be on-line; we'll init the
  4738. * secondary cpus' numa_mem as they come on-line. During
  4739. * node/memory hotplug, we'll fixup all on-line cpus.
  4740. */
  4741. for_each_online_cpu(cpu)
  4742. set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
  4743. #endif
  4744. }
  4745. printk_deferred_exit();
  4746. write_sequnlock_irqrestore(&zonelist_update_seq, flags);
  4747. }
  4748. static noinline void __init
  4749. build_all_zonelists_init(void)
  4750. {
  4751. int cpu;
  4752. __build_all_zonelists(NULL);
  4753. /*
  4754. * Initialize the boot_pagesets that are going to be used
  4755. * for bootstrapping processors. The real pagesets for
  4756. * each zone will be allocated later when the per cpu
  4757. * allocator is available.
  4758. *
  4759. * boot_pagesets are used also for bootstrapping offline
  4760. * cpus if the system is already booted because the pagesets
  4761. * are needed to initialize allocators on a specific cpu too.
  4762. * F.e. the percpu allocator needs the page allocator which
  4763. * needs the percpu allocator in order to allocate its pagesets
  4764. * (a chicken-egg dilemma).
  4765. */
  4766. for_each_possible_cpu(cpu)
  4767. per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
  4768. mminit_verify_zonelist();
  4769. cpuset_init_current_mems_allowed();
  4770. }
  4771. /*
  4772. * unless system_state == SYSTEM_BOOTING.
  4773. *
  4774. * __ref due to call of __init annotated helper build_all_zonelists_init
  4775. * [protected by SYSTEM_BOOTING].
  4776. */
  4777. void __ref build_all_zonelists(pg_data_t *pgdat)
  4778. {
  4779. unsigned long vm_total_pages;
  4780. if (system_state == SYSTEM_BOOTING) {
  4781. build_all_zonelists_init();
  4782. } else {
  4783. __build_all_zonelists(pgdat);
  4784. /* cpuset refresh routine should be here */
  4785. }
  4786. /* Get the number of free pages beyond high watermark in all zones. */
  4787. vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
  4788. /*
  4789. * Disable grouping by mobility if the number of pages in the
  4790. * system is too low to allow the mechanism to work. It would be
  4791. * more accurate, but expensive to check per-zone. This check is
  4792. * made on memory-hotadd so a system can start with mobility
  4793. * disabled and enable it later
  4794. */
  4795. if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
  4796. page_group_by_mobility_disabled = 1;
  4797. else
  4798. page_group_by_mobility_disabled = 0;
  4799. pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
  4800. nr_online_nodes,
  4801. page_group_by_mobility_disabled ? "off" : "on",
  4802. vm_total_pages);
  4803. #ifdef CONFIG_NUMA
  4804. pr_info("Policy zone: %s\n", zone_names[policy_zone]);
  4805. #endif
  4806. }
  4807. static int zone_batchsize(struct zone *zone)
  4808. {
  4809. #ifdef CONFIG_MMU
  4810. int batch;
  4811. /*
  4812. * The number of pages to batch allocate is either ~0.1%
  4813. * of the zone or 1MB, whichever is smaller. The batch
  4814. * size is striking a balance between allocation latency
  4815. * and zone lock contention.
  4816. */
  4817. batch = min(zone_managed_pages(zone) >> 10, SZ_1M / PAGE_SIZE);
  4818. batch /= 4; /* We effectively *= 4 below */
  4819. if (batch < 1)
  4820. batch = 1;
  4821. /*
  4822. * Clamp the batch to a 2^n - 1 value. Having a power
  4823. * of 2 value was found to be more likely to have
  4824. * suboptimal cache aliasing properties in some cases.
  4825. *
  4826. * For example if 2 tasks are alternately allocating
  4827. * batches of pages, one task can end up with a lot
  4828. * of pages of one half of the possible page colors
  4829. * and the other with pages of the other colors.
  4830. */
  4831. batch = rounddown_pow_of_two(batch + batch/2) - 1;
  4832. return batch;
  4833. #else
  4834. /* The deferral and batching of frees should be suppressed under NOMMU
  4835. * conditions.
  4836. *
  4837. * The problem is that NOMMU needs to be able to allocate large chunks
  4838. * of contiguous memory as there's no hardware page translation to
  4839. * assemble apparent contiguous memory from discontiguous pages.
  4840. *
  4841. * Queueing large contiguous runs of pages for batching, however,
  4842. * causes the pages to actually be freed in smaller chunks. As there
  4843. * can be a significant delay between the individual batches being
  4844. * recycled, this leads to the once large chunks of space being
  4845. * fragmented and becoming unavailable for high-order allocations.
  4846. */
  4847. return 0;
  4848. #endif
  4849. }
  4850. static int percpu_pagelist_high_fraction;
  4851. static int zone_highsize(struct zone *zone, int batch, int cpu_online,
  4852. int high_fraction)
  4853. {
  4854. #ifdef CONFIG_MMU
  4855. int high;
  4856. int nr_split_cpus;
  4857. unsigned long total_pages;
  4858. if (!high_fraction) {
  4859. /*
  4860. * By default, the high value of the pcp is based on the zone
  4861. * low watermark so that if they are full then background
  4862. * reclaim will not be started prematurely.
  4863. */
  4864. total_pages = low_wmark_pages(zone);
  4865. } else {
  4866. /*
  4867. * If percpu_pagelist_high_fraction is configured, the high
  4868. * value is based on a fraction of the managed pages in the
  4869. * zone.
  4870. */
  4871. total_pages = zone_managed_pages(zone) / high_fraction;
  4872. }
  4873. /*
  4874. * Split the high value across all online CPUs local to the zone. Note
  4875. * that early in boot that CPUs may not be online yet and that during
  4876. * CPU hotplug that the cpumask is not yet updated when a CPU is being
  4877. * onlined. For memory nodes that have no CPUs, split the high value
  4878. * across all online CPUs to mitigate the risk that reclaim is triggered
  4879. * prematurely due to pages stored on pcp lists.
  4880. */
  4881. nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
  4882. if (!nr_split_cpus)
  4883. nr_split_cpus = num_online_cpus();
  4884. high = total_pages / nr_split_cpus;
  4885. /*
  4886. * Ensure high is at least batch*4. The multiple is based on the
  4887. * historical relationship between high and batch.
  4888. */
  4889. high = max(high, batch << 2);
  4890. return high;
  4891. #else
  4892. return 0;
  4893. #endif
  4894. }
  4895. /*
  4896. * pcp->high and pcp->batch values are related and generally batch is lower
  4897. * than high. They are also related to pcp->count such that count is lower
  4898. * than high, and as soon as it reaches high, the pcplist is flushed.
  4899. *
  4900. * However, guaranteeing these relations at all times would require e.g. write
  4901. * barriers here but also careful usage of read barriers at the read side, and
  4902. * thus be prone to error and bad for performance. Thus the update only prevents
  4903. * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max
  4904. * should ensure they can cope with those fields changing asynchronously, and
  4905. * fully trust only the pcp->count field on the local CPU with interrupts
  4906. * disabled.
  4907. *
  4908. * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
  4909. * outside of boot time (or some other assurance that no concurrent updaters
  4910. * exist).
  4911. */
  4912. static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min,
  4913. unsigned long high_max, unsigned long batch)
  4914. {
  4915. WRITE_ONCE(pcp->batch, batch);
  4916. WRITE_ONCE(pcp->high_min, high_min);
  4917. WRITE_ONCE(pcp->high_max, high_max);
  4918. }
  4919. static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
  4920. {
  4921. int pindex;
  4922. memset(pcp, 0, sizeof(*pcp));
  4923. memset(pzstats, 0, sizeof(*pzstats));
  4924. spin_lock_init(&pcp->lock);
  4925. for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
  4926. INIT_LIST_HEAD(&pcp->lists[pindex]);
  4927. /*
  4928. * Set batch and high values safe for a boot pageset. A true percpu
  4929. * pageset's initialization will update them subsequently. Here we don't
  4930. * need to be as careful as pageset_update() as nobody can access the
  4931. * pageset yet.
  4932. */
  4933. pcp->high_min = BOOT_PAGESET_HIGH;
  4934. pcp->high_max = BOOT_PAGESET_HIGH;
  4935. pcp->batch = BOOT_PAGESET_BATCH;
  4936. pcp->free_count = 0;
  4937. }
  4938. static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min,
  4939. unsigned long high_max, unsigned long batch)
  4940. {
  4941. struct per_cpu_pages *pcp;
  4942. int cpu;
  4943. for_each_possible_cpu(cpu) {
  4944. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  4945. pageset_update(pcp, high_min, high_max, batch);
  4946. }
  4947. }
  4948. /*
  4949. * Calculate and set new high and batch values for all per-cpu pagesets of a
  4950. * zone based on the zone's size.
  4951. */
  4952. static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
  4953. {
  4954. int new_high_min, new_high_max, new_batch;
  4955. new_batch = max(1, zone_batchsize(zone));
  4956. if (percpu_pagelist_high_fraction) {
  4957. new_high_min = zone_highsize(zone, new_batch, cpu_online,
  4958. percpu_pagelist_high_fraction);
  4959. /*
  4960. * PCP high is tuned manually, disable auto-tuning via
  4961. * setting high_min and high_max to the manual value.
  4962. */
  4963. new_high_max = new_high_min;
  4964. } else {
  4965. new_high_min = zone_highsize(zone, new_batch, cpu_online, 0);
  4966. new_high_max = zone_highsize(zone, new_batch, cpu_online,
  4967. MIN_PERCPU_PAGELIST_HIGH_FRACTION);
  4968. }
  4969. if (zone->pageset_high_min == new_high_min &&
  4970. zone->pageset_high_max == new_high_max &&
  4971. zone->pageset_batch == new_batch)
  4972. return;
  4973. zone->pageset_high_min = new_high_min;
  4974. zone->pageset_high_max = new_high_max;
  4975. zone->pageset_batch = new_batch;
  4976. __zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max,
  4977. new_batch);
  4978. }
  4979. void __meminit setup_zone_pageset(struct zone *zone)
  4980. {
  4981. int cpu;
  4982. /* Size may be 0 on !SMP && !NUMA */
  4983. if (sizeof(struct per_cpu_zonestat) > 0)
  4984. zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
  4985. zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
  4986. for_each_possible_cpu(cpu) {
  4987. struct per_cpu_pages *pcp;
  4988. struct per_cpu_zonestat *pzstats;
  4989. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  4990. pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
  4991. per_cpu_pages_init(pcp, pzstats);
  4992. }
  4993. zone_set_pageset_high_and_batch(zone, 0);
  4994. }
  4995. /*
  4996. * The zone indicated has a new number of managed_pages; batch sizes and percpu
  4997. * page high values need to be recalculated.
  4998. */
  4999. static void zone_pcp_update(struct zone *zone, int cpu_online)
  5000. {
  5001. mutex_lock(&pcp_batch_high_lock);
  5002. zone_set_pageset_high_and_batch(zone, cpu_online);
  5003. mutex_unlock(&pcp_batch_high_lock);
  5004. }
  5005. static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu)
  5006. {
  5007. struct per_cpu_pages *pcp;
  5008. struct cpu_cacheinfo *cci;
  5009. pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
  5010. cci = get_cpu_cacheinfo(cpu);
  5011. /*
  5012. * If data cache slice of CPU is large enough, "pcp->batch"
  5013. * pages can be preserved in PCP before draining PCP for
  5014. * consecutive high-order pages freeing without allocation.
  5015. * This can reduce zone lock contention without hurting
  5016. * cache-hot pages sharing.
  5017. */
  5018. spin_lock(&pcp->lock);
  5019. if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch)
  5020. pcp->flags |= PCPF_FREE_HIGH_BATCH;
  5021. else
  5022. pcp->flags &= ~PCPF_FREE_HIGH_BATCH;
  5023. spin_unlock(&pcp->lock);
  5024. }
  5025. void setup_pcp_cacheinfo(unsigned int cpu)
  5026. {
  5027. struct zone *zone;
  5028. for_each_populated_zone(zone)
  5029. zone_pcp_update_cacheinfo(zone, cpu);
  5030. }
  5031. /*
  5032. * Allocate per cpu pagesets and initialize them.
  5033. * Before this call only boot pagesets were available.
  5034. */
  5035. void __init setup_per_cpu_pageset(void)
  5036. {
  5037. struct pglist_data *pgdat;
  5038. struct zone *zone;
  5039. int __maybe_unused cpu;
  5040. for_each_populated_zone(zone)
  5041. setup_zone_pageset(zone);
  5042. #ifdef CONFIG_NUMA
  5043. /*
  5044. * Unpopulated zones continue using the boot pagesets.
  5045. * The numa stats for these pagesets need to be reset.
  5046. * Otherwise, they will end up skewing the stats of
  5047. * the nodes these zones are associated with.
  5048. */
  5049. for_each_possible_cpu(cpu) {
  5050. struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
  5051. memset(pzstats->vm_numa_event, 0,
  5052. sizeof(pzstats->vm_numa_event));
  5053. }
  5054. #endif
  5055. for_each_online_pgdat(pgdat)
  5056. pgdat->per_cpu_nodestats =
  5057. alloc_percpu(struct per_cpu_nodestat);
  5058. }
  5059. __meminit void zone_pcp_init(struct zone *zone)
  5060. {
  5061. /*
  5062. * per cpu subsystem is not up at this point. The following code
  5063. * relies on the ability of the linker to provide the
  5064. * offset of a (static) per cpu variable into the per cpu area.
  5065. */
  5066. zone->per_cpu_pageset = &boot_pageset;
  5067. zone->per_cpu_zonestats = &boot_zonestats;
  5068. zone->pageset_high_min = BOOT_PAGESET_HIGH;
  5069. zone->pageset_high_max = BOOT_PAGESET_HIGH;
  5070. zone->pageset_batch = BOOT_PAGESET_BATCH;
  5071. if (populated_zone(zone))
  5072. pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name,
  5073. zone->present_pages, zone_batchsize(zone));
  5074. }
  5075. void adjust_managed_page_count(struct page *page, long count)
  5076. {
  5077. atomic_long_add(count, &page_zone(page)->managed_pages);
  5078. totalram_pages_add(count);
  5079. }
  5080. EXPORT_SYMBOL(adjust_managed_page_count);
  5081. unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
  5082. {
  5083. void *pos;
  5084. unsigned long pages = 0;
  5085. start = (void *)PAGE_ALIGN((unsigned long)start);
  5086. end = (void *)((unsigned long)end & PAGE_MASK);
  5087. for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
  5088. struct page *page = virt_to_page(pos);
  5089. void *direct_map_addr;
  5090. /*
  5091. * 'direct_map_addr' might be different from 'pos'
  5092. * because some architectures' virt_to_page()
  5093. * work with aliases. Getting the direct map
  5094. * address ensures that we get a _writeable_
  5095. * alias for the memset().
  5096. */
  5097. direct_map_addr = page_address(page);
  5098. /*
  5099. * Perform a kasan-unchecked memset() since this memory
  5100. * has not been initialized.
  5101. */
  5102. direct_map_addr = kasan_reset_tag(direct_map_addr);
  5103. if ((unsigned int)poison <= 0xFF)
  5104. memset(direct_map_addr, poison, PAGE_SIZE);
  5105. free_reserved_page(page);
  5106. }
  5107. if (pages && s)
  5108. pr_info("Freeing %s memory: %ldK\n", s, K(pages));
  5109. return pages;
  5110. }
  5111. void free_reserved_page(struct page *page)
  5112. {
  5113. clear_page_tag_ref(page);
  5114. ClearPageReserved(page);
  5115. init_page_count(page);
  5116. __free_page(page);
  5117. adjust_managed_page_count(page, 1);
  5118. }
  5119. EXPORT_SYMBOL(free_reserved_page);
  5120. static int page_alloc_cpu_dead(unsigned int cpu)
  5121. {
  5122. struct zone *zone;
  5123. lru_add_drain_cpu(cpu);
  5124. mlock_drain_remote(cpu);
  5125. drain_pages(cpu);
  5126. /*
  5127. * Spill the event counters of the dead processor
  5128. * into the current processors event counters.
  5129. * This artificially elevates the count of the current
  5130. * processor.
  5131. */
  5132. vm_events_fold_cpu(cpu);
  5133. /*
  5134. * Zero the differential counters of the dead processor
  5135. * so that the vm statistics are consistent.
  5136. *
  5137. * This is only okay since the processor is dead and cannot
  5138. * race with what we are doing.
  5139. */
  5140. cpu_vm_stats_fold(cpu);
  5141. for_each_populated_zone(zone)
  5142. zone_pcp_update(zone, 0);
  5143. return 0;
  5144. }
  5145. static int page_alloc_cpu_online(unsigned int cpu)
  5146. {
  5147. struct zone *zone;
  5148. for_each_populated_zone(zone)
  5149. zone_pcp_update(zone, 1);
  5150. return 0;
  5151. }
  5152. void __init page_alloc_init_cpuhp(void)
  5153. {
  5154. int ret;
  5155. ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
  5156. "mm/page_alloc:pcp",
  5157. page_alloc_cpu_online,
  5158. page_alloc_cpu_dead);
  5159. WARN_ON(ret < 0);
  5160. }
  5161. /*
  5162. * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
  5163. * or min_free_kbytes changes.
  5164. */
  5165. static void calculate_totalreserve_pages(void)
  5166. {
  5167. struct pglist_data *pgdat;
  5168. unsigned long reserve_pages = 0;
  5169. enum zone_type i, j;
  5170. for_each_online_pgdat(pgdat) {
  5171. pgdat->totalreserve_pages = 0;
  5172. for (i = 0; i < MAX_NR_ZONES; i++) {
  5173. struct zone *zone = pgdat->node_zones + i;
  5174. long max = 0;
  5175. unsigned long managed_pages = zone_managed_pages(zone);
  5176. /* Find valid and maximum lowmem_reserve in the zone */
  5177. for (j = i; j < MAX_NR_ZONES; j++) {
  5178. if (zone->lowmem_reserve[j] > max)
  5179. max = zone->lowmem_reserve[j];
  5180. }
  5181. /* we treat the high watermark as reserved pages. */
  5182. max += high_wmark_pages(zone);
  5183. if (max > managed_pages)
  5184. max = managed_pages;
  5185. pgdat->totalreserve_pages += max;
  5186. reserve_pages += max;
  5187. }
  5188. }
  5189. totalreserve_pages = reserve_pages;
  5190. }
  5191. /*
  5192. * setup_per_zone_lowmem_reserve - called whenever
  5193. * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
  5194. * has a correct pages reserved value, so an adequate number of
  5195. * pages are left in the zone after a successful __alloc_pages().
  5196. */
  5197. static void setup_per_zone_lowmem_reserve(void)
  5198. {
  5199. struct pglist_data *pgdat;
  5200. enum zone_type i, j;
  5201. for_each_online_pgdat(pgdat) {
  5202. for (i = 0; i < MAX_NR_ZONES - 1; i++) {
  5203. struct zone *zone = &pgdat->node_zones[i];
  5204. int ratio = sysctl_lowmem_reserve_ratio[i];
  5205. bool clear = !ratio || !zone_managed_pages(zone);
  5206. unsigned long managed_pages = 0;
  5207. for (j = i + 1; j < MAX_NR_ZONES; j++) {
  5208. struct zone *upper_zone = &pgdat->node_zones[j];
  5209. managed_pages += zone_managed_pages(upper_zone);
  5210. if (clear)
  5211. zone->lowmem_reserve[j] = 0;
  5212. else
  5213. zone->lowmem_reserve[j] = managed_pages / ratio;
  5214. }
  5215. }
  5216. }
  5217. /* update totalreserve_pages */
  5218. calculate_totalreserve_pages();
  5219. }
  5220. static void __setup_per_zone_wmarks(void)
  5221. {
  5222. unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
  5223. unsigned long lowmem_pages = 0;
  5224. struct zone *zone;
  5225. unsigned long flags;
  5226. /* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */
  5227. for_each_zone(zone) {
  5228. if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE)
  5229. lowmem_pages += zone_managed_pages(zone);
  5230. }
  5231. for_each_zone(zone) {
  5232. u64 tmp;
  5233. spin_lock_irqsave(&zone->lock, flags);
  5234. tmp = (u64)pages_min * zone_managed_pages(zone);
  5235. tmp = div64_ul(tmp, lowmem_pages);
  5236. if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) {
  5237. /*
  5238. * __GFP_HIGH and PF_MEMALLOC allocations usually don't
  5239. * need highmem and movable zones pages, so cap pages_min
  5240. * to a small value here.
  5241. *
  5242. * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
  5243. * deltas control async page reclaim, and so should
  5244. * not be capped for highmem and movable zones.
  5245. */
  5246. unsigned long min_pages;
  5247. min_pages = zone_managed_pages(zone) / 1024;
  5248. min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
  5249. zone->_watermark[WMARK_MIN] = min_pages;
  5250. } else {
  5251. /*
  5252. * If it's a lowmem zone, reserve a number of pages
  5253. * proportionate to the zone's size.
  5254. */
  5255. zone->_watermark[WMARK_MIN] = tmp;
  5256. }
  5257. /*
  5258. * Set the kswapd watermarks distance according to the
  5259. * scale factor in proportion to available memory, but
  5260. * ensure a minimum size on small systems.
  5261. */
  5262. tmp = max_t(u64, tmp >> 2,
  5263. mult_frac(zone_managed_pages(zone),
  5264. watermark_scale_factor, 10000));
  5265. zone->watermark_boost = 0;
  5266. zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
  5267. zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
  5268. zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
  5269. spin_unlock_irqrestore(&zone->lock, flags);
  5270. }
  5271. /* update totalreserve_pages */
  5272. calculate_totalreserve_pages();
  5273. }
  5274. /**
  5275. * setup_per_zone_wmarks - called when min_free_kbytes changes
  5276. * or when memory is hot-{added|removed}
  5277. *
  5278. * Ensures that the watermark[min,low,high] values for each zone are set
  5279. * correctly with respect to min_free_kbytes.
  5280. */
  5281. void setup_per_zone_wmarks(void)
  5282. {
  5283. struct zone *zone;
  5284. static DEFINE_SPINLOCK(lock);
  5285. spin_lock(&lock);
  5286. __setup_per_zone_wmarks();
  5287. spin_unlock(&lock);
  5288. /*
  5289. * The watermark size have changed so update the pcpu batch
  5290. * and high limits or the limits may be inappropriate.
  5291. */
  5292. for_each_zone(zone)
  5293. zone_pcp_update(zone, 0);
  5294. }
  5295. /*
  5296. * Initialise min_free_kbytes.
  5297. *
  5298. * For small machines we want it small (128k min). For large machines
  5299. * we want it large (256MB max). But it is not linear, because network
  5300. * bandwidth does not increase linearly with machine size. We use
  5301. *
  5302. * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
  5303. * min_free_kbytes = sqrt(lowmem_kbytes * 16)
  5304. *
  5305. * which yields
  5306. *
  5307. * 16MB: 512k
  5308. * 32MB: 724k
  5309. * 64MB: 1024k
  5310. * 128MB: 1448k
  5311. * 256MB: 2048k
  5312. * 512MB: 2896k
  5313. * 1024MB: 4096k
  5314. * 2048MB: 5792k
  5315. * 4096MB: 8192k
  5316. * 8192MB: 11584k
  5317. * 16384MB: 16384k
  5318. */
  5319. void calculate_min_free_kbytes(void)
  5320. {
  5321. unsigned long lowmem_kbytes;
  5322. int new_min_free_kbytes;
  5323. lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
  5324. new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
  5325. if (new_min_free_kbytes > user_min_free_kbytes)
  5326. min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
  5327. else
  5328. pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
  5329. new_min_free_kbytes, user_min_free_kbytes);
  5330. }
  5331. int __meminit init_per_zone_wmark_min(void)
  5332. {
  5333. calculate_min_free_kbytes();
  5334. setup_per_zone_wmarks();
  5335. refresh_zone_stat_thresholds();
  5336. setup_per_zone_lowmem_reserve();
  5337. #ifdef CONFIG_NUMA
  5338. setup_min_unmapped_ratio();
  5339. setup_min_slab_ratio();
  5340. #endif
  5341. khugepaged_min_free_kbytes_update();
  5342. return 0;
  5343. }
  5344. postcore_initcall(init_per_zone_wmark_min)
  5345. /*
  5346. * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
  5347. * that we can call two helper functions whenever min_free_kbytes
  5348. * changes.
  5349. */
  5350. static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write,
  5351. void *buffer, size_t *length, loff_t *ppos)
  5352. {
  5353. int rc;
  5354. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5355. if (rc)
  5356. return rc;
  5357. if (write) {
  5358. user_min_free_kbytes = min_free_kbytes;
  5359. setup_per_zone_wmarks();
  5360. }
  5361. return 0;
  5362. }
  5363. static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write,
  5364. void *buffer, size_t *length, loff_t *ppos)
  5365. {
  5366. int rc;
  5367. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5368. if (rc)
  5369. return rc;
  5370. if (write)
  5371. setup_per_zone_wmarks();
  5372. return 0;
  5373. }
  5374. #ifdef CONFIG_NUMA
  5375. static void setup_min_unmapped_ratio(void)
  5376. {
  5377. pg_data_t *pgdat;
  5378. struct zone *zone;
  5379. for_each_online_pgdat(pgdat)
  5380. pgdat->min_unmapped_pages = 0;
  5381. for_each_zone(zone)
  5382. zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
  5383. sysctl_min_unmapped_ratio) / 100;
  5384. }
  5385. static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write,
  5386. void *buffer, size_t *length, loff_t *ppos)
  5387. {
  5388. int rc;
  5389. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5390. if (rc)
  5391. return rc;
  5392. setup_min_unmapped_ratio();
  5393. return 0;
  5394. }
  5395. static void setup_min_slab_ratio(void)
  5396. {
  5397. pg_data_t *pgdat;
  5398. struct zone *zone;
  5399. for_each_online_pgdat(pgdat)
  5400. pgdat->min_slab_pages = 0;
  5401. for_each_zone(zone)
  5402. zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
  5403. sysctl_min_slab_ratio) / 100;
  5404. }
  5405. static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write,
  5406. void *buffer, size_t *length, loff_t *ppos)
  5407. {
  5408. int rc;
  5409. rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5410. if (rc)
  5411. return rc;
  5412. setup_min_slab_ratio();
  5413. return 0;
  5414. }
  5415. #endif
  5416. /*
  5417. * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
  5418. * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
  5419. * whenever sysctl_lowmem_reserve_ratio changes.
  5420. *
  5421. * The reserve ratio obviously has absolutely no relation with the
  5422. * minimum watermarks. The lowmem reserve ratio can only make sense
  5423. * if in function of the boot time zone sizes.
  5424. */
  5425. static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table,
  5426. int write, void *buffer, size_t *length, loff_t *ppos)
  5427. {
  5428. int i;
  5429. proc_dointvec_minmax(table, write, buffer, length, ppos);
  5430. for (i = 0; i < MAX_NR_ZONES; i++) {
  5431. if (sysctl_lowmem_reserve_ratio[i] < 1)
  5432. sysctl_lowmem_reserve_ratio[i] = 0;
  5433. }
  5434. setup_per_zone_lowmem_reserve();
  5435. return 0;
  5436. }
  5437. /*
  5438. * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
  5439. * cpu. It is the fraction of total pages in each zone that a hot per cpu
  5440. * pagelist can have before it gets flushed back to buddy allocator.
  5441. */
  5442. static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table,
  5443. int write, void *buffer, size_t *length, loff_t *ppos)
  5444. {
  5445. struct zone *zone;
  5446. int old_percpu_pagelist_high_fraction;
  5447. int ret;
  5448. mutex_lock(&pcp_batch_high_lock);
  5449. old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
  5450. ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
  5451. if (!write || ret < 0)
  5452. goto out;
  5453. /* Sanity checking to avoid pcp imbalance */
  5454. if (percpu_pagelist_high_fraction &&
  5455. percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
  5456. percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
  5457. ret = -EINVAL;
  5458. goto out;
  5459. }
  5460. /* No change? */
  5461. if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
  5462. goto out;
  5463. for_each_populated_zone(zone)
  5464. zone_set_pageset_high_and_batch(zone, 0);
  5465. out:
  5466. mutex_unlock(&pcp_batch_high_lock);
  5467. return ret;
  5468. }
  5469. static struct ctl_table page_alloc_sysctl_table[] = {
  5470. {
  5471. .procname = "min_free_kbytes",
  5472. .data = &min_free_kbytes,
  5473. .maxlen = sizeof(min_free_kbytes),
  5474. .mode = 0644,
  5475. .proc_handler = min_free_kbytes_sysctl_handler,
  5476. .extra1 = SYSCTL_ZERO,
  5477. },
  5478. {
  5479. .procname = "watermark_boost_factor",
  5480. .data = &watermark_boost_factor,
  5481. .maxlen = sizeof(watermark_boost_factor),
  5482. .mode = 0644,
  5483. .proc_handler = proc_dointvec_minmax,
  5484. .extra1 = SYSCTL_ZERO,
  5485. },
  5486. {
  5487. .procname = "watermark_scale_factor",
  5488. .data = &watermark_scale_factor,
  5489. .maxlen = sizeof(watermark_scale_factor),
  5490. .mode = 0644,
  5491. .proc_handler = watermark_scale_factor_sysctl_handler,
  5492. .extra1 = SYSCTL_ONE,
  5493. .extra2 = SYSCTL_THREE_THOUSAND,
  5494. },
  5495. {
  5496. .procname = "percpu_pagelist_high_fraction",
  5497. .data = &percpu_pagelist_high_fraction,
  5498. .maxlen = sizeof(percpu_pagelist_high_fraction),
  5499. .mode = 0644,
  5500. .proc_handler = percpu_pagelist_high_fraction_sysctl_handler,
  5501. .extra1 = SYSCTL_ZERO,
  5502. },
  5503. {
  5504. .procname = "lowmem_reserve_ratio",
  5505. .data = &sysctl_lowmem_reserve_ratio,
  5506. .maxlen = sizeof(sysctl_lowmem_reserve_ratio),
  5507. .mode = 0644,
  5508. .proc_handler = lowmem_reserve_ratio_sysctl_handler,
  5509. },
  5510. #ifdef CONFIG_NUMA
  5511. {
  5512. .procname = "numa_zonelist_order",
  5513. .data = &numa_zonelist_order,
  5514. .maxlen = NUMA_ZONELIST_ORDER_LEN,
  5515. .mode = 0644,
  5516. .proc_handler = numa_zonelist_order_handler,
  5517. },
  5518. {
  5519. .procname = "min_unmapped_ratio",
  5520. .data = &sysctl_min_unmapped_ratio,
  5521. .maxlen = sizeof(sysctl_min_unmapped_ratio),
  5522. .mode = 0644,
  5523. .proc_handler = sysctl_min_unmapped_ratio_sysctl_handler,
  5524. .extra1 = SYSCTL_ZERO,
  5525. .extra2 = SYSCTL_ONE_HUNDRED,
  5526. },
  5527. {
  5528. .procname = "min_slab_ratio",
  5529. .data = &sysctl_min_slab_ratio,
  5530. .maxlen = sizeof(sysctl_min_slab_ratio),
  5531. .mode = 0644,
  5532. .proc_handler = sysctl_min_slab_ratio_sysctl_handler,
  5533. .extra1 = SYSCTL_ZERO,
  5534. .extra2 = SYSCTL_ONE_HUNDRED,
  5535. },
  5536. #endif
  5537. };
  5538. void __init page_alloc_sysctl_init(void)
  5539. {
  5540. register_sysctl_init("vm", page_alloc_sysctl_table);
  5541. }
  5542. #ifdef CONFIG_CONTIG_ALLOC
  5543. /* Usage: See admin-guide/dynamic-debug-howto.rst */
  5544. static void alloc_contig_dump_pages(struct list_head *page_list)
  5545. {
  5546. DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
  5547. if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
  5548. struct page *page;
  5549. dump_stack();
  5550. list_for_each_entry(page, page_list, lru)
  5551. dump_page(page, "migration failure");
  5552. }
  5553. }
  5554. /*
  5555. * [start, end) must belong to a single zone.
  5556. * @migratetype: using migratetype to filter the type of migration in
  5557. * trace_mm_alloc_contig_migrate_range_info.
  5558. */
  5559. int __alloc_contig_migrate_range(struct compact_control *cc,
  5560. unsigned long start, unsigned long end,
  5561. int migratetype)
  5562. {
  5563. /* This function is based on compact_zone() from compaction.c. */
  5564. unsigned int nr_reclaimed;
  5565. unsigned long pfn = start;
  5566. unsigned int tries = 0;
  5567. int ret = 0;
  5568. struct migration_target_control mtc = {
  5569. .nid = zone_to_nid(cc->zone),
  5570. .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
  5571. .reason = MR_CONTIG_RANGE,
  5572. };
  5573. struct page *page;
  5574. unsigned long total_mapped = 0;
  5575. unsigned long total_migrated = 0;
  5576. unsigned long total_reclaimed = 0;
  5577. lru_cache_disable();
  5578. while (pfn < end || !list_empty(&cc->migratepages)) {
  5579. if (fatal_signal_pending(current)) {
  5580. ret = -EINTR;
  5581. break;
  5582. }
  5583. if (list_empty(&cc->migratepages)) {
  5584. cc->nr_migratepages = 0;
  5585. ret = isolate_migratepages_range(cc, pfn, end);
  5586. if (ret && ret != -EAGAIN)
  5587. break;
  5588. pfn = cc->migrate_pfn;
  5589. tries = 0;
  5590. } else if (++tries == 5) {
  5591. ret = -EBUSY;
  5592. break;
  5593. }
  5594. nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
  5595. &cc->migratepages);
  5596. cc->nr_migratepages -= nr_reclaimed;
  5597. if (trace_mm_alloc_contig_migrate_range_info_enabled()) {
  5598. total_reclaimed += nr_reclaimed;
  5599. list_for_each_entry(page, &cc->migratepages, lru) {
  5600. struct folio *folio = page_folio(page);
  5601. total_mapped += folio_mapped(folio) *
  5602. folio_nr_pages(folio);
  5603. }
  5604. }
  5605. ret = migrate_pages(&cc->migratepages, alloc_migration_target,
  5606. NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
  5607. if (trace_mm_alloc_contig_migrate_range_info_enabled() && !ret)
  5608. total_migrated += cc->nr_migratepages;
  5609. /*
  5610. * On -ENOMEM, migrate_pages() bails out right away. It is pointless
  5611. * to retry again over this error, so do the same here.
  5612. */
  5613. if (ret == -ENOMEM)
  5614. break;
  5615. }
  5616. lru_cache_enable();
  5617. if (ret < 0) {
  5618. if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY)
  5619. alloc_contig_dump_pages(&cc->migratepages);
  5620. putback_movable_pages(&cc->migratepages);
  5621. }
  5622. trace_mm_alloc_contig_migrate_range_info(start, end, migratetype,
  5623. total_migrated,
  5624. total_reclaimed,
  5625. total_mapped);
  5626. return (ret < 0) ? ret : 0;
  5627. }
  5628. static void split_free_pages(struct list_head *list)
  5629. {
  5630. int order;
  5631. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  5632. struct page *page, *next;
  5633. int nr_pages = 1 << order;
  5634. list_for_each_entry_safe(page, next, &list[order], lru) {
  5635. int i;
  5636. post_alloc_hook(page, order, __GFP_MOVABLE);
  5637. if (!order)
  5638. continue;
  5639. split_page(page, order);
  5640. /* Add all subpages to the order-0 head, in sequence. */
  5641. list_del(&page->lru);
  5642. for (i = 0; i < nr_pages; i++)
  5643. list_add_tail(&page[i].lru, &list[0]);
  5644. }
  5645. }
  5646. }
  5647. /**
  5648. * alloc_contig_range() -- tries to allocate given range of pages
  5649. * @start: start PFN to allocate
  5650. * @end: one-past-the-last PFN to allocate
  5651. * @migratetype: migratetype of the underlying pageblocks (either
  5652. * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
  5653. * in range must have the same migratetype and it must
  5654. * be either of the two.
  5655. * @gfp_mask: GFP mask to use during compaction
  5656. *
  5657. * The PFN range does not have to be pageblock aligned. The PFN range must
  5658. * belong to a single zone.
  5659. *
  5660. * The first thing this routine does is attempt to MIGRATE_ISOLATE all
  5661. * pageblocks in the range. Once isolated, the pageblocks should not
  5662. * be modified by others.
  5663. *
  5664. * Return: zero on success or negative error code. On success all
  5665. * pages which PFN is in [start, end) are allocated for the caller and
  5666. * need to be freed with free_contig_range().
  5667. */
  5668. int alloc_contig_range_noprof(unsigned long start, unsigned long end,
  5669. unsigned migratetype, gfp_t gfp_mask)
  5670. {
  5671. unsigned long outer_start, outer_end;
  5672. int ret = 0;
  5673. struct compact_control cc = {
  5674. .nr_migratepages = 0,
  5675. .order = -1,
  5676. .zone = page_zone(pfn_to_page(start)),
  5677. .mode = MIGRATE_SYNC,
  5678. .ignore_skip_hint = true,
  5679. .no_set_skip_hint = true,
  5680. .gfp_mask = current_gfp_context(gfp_mask),
  5681. .alloc_contig = true,
  5682. };
  5683. INIT_LIST_HEAD(&cc.migratepages);
  5684. /*
  5685. * What we do here is we mark all pageblocks in range as
  5686. * MIGRATE_ISOLATE. Because pageblock and max order pages may
  5687. * have different sizes, and due to the way page allocator
  5688. * work, start_isolate_page_range() has special handlings for this.
  5689. *
  5690. * Once the pageblocks are marked as MIGRATE_ISOLATE, we
  5691. * migrate the pages from an unaligned range (ie. pages that
  5692. * we are interested in). This will put all the pages in
  5693. * range back to page allocator as MIGRATE_ISOLATE.
  5694. *
  5695. * When this is done, we take the pages in range from page
  5696. * allocator removing them from the buddy system. This way
  5697. * page allocator will never consider using them.
  5698. *
  5699. * This lets us mark the pageblocks back as
  5700. * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
  5701. * aligned range but not in the unaligned, original range are
  5702. * put back to page allocator so that buddy can use them.
  5703. */
  5704. ret = start_isolate_page_range(start, end, migratetype, 0, gfp_mask);
  5705. if (ret)
  5706. goto done;
  5707. drain_all_pages(cc.zone);
  5708. /*
  5709. * In case of -EBUSY, we'd like to know which page causes problem.
  5710. * So, just fall through. test_pages_isolated() has a tracepoint
  5711. * which will report the busy page.
  5712. *
  5713. * It is possible that busy pages could become available before
  5714. * the call to test_pages_isolated, and the range will actually be
  5715. * allocated. So, if we fall through be sure to clear ret so that
  5716. * -EBUSY is not accidentally used or returned to caller.
  5717. */
  5718. ret = __alloc_contig_migrate_range(&cc, start, end, migratetype);
  5719. if (ret && ret != -EBUSY)
  5720. goto done;
  5721. ret = 0;
  5722. /*
  5723. * Pages from [start, end) are within a pageblock_nr_pages
  5724. * aligned blocks that are marked as MIGRATE_ISOLATE. What's
  5725. * more, all pages in [start, end) are free in page allocator.
  5726. * What we are going to do is to allocate all pages from
  5727. * [start, end) (that is remove them from page allocator).
  5728. *
  5729. * The only problem is that pages at the beginning and at the
  5730. * end of interesting range may be not aligned with pages that
  5731. * page allocator holds, ie. they can be part of higher order
  5732. * pages. Because of this, we reserve the bigger range and
  5733. * once this is done free the pages we are not interested in.
  5734. *
  5735. * We don't have to hold zone->lock here because the pages are
  5736. * isolated thus they won't get removed from buddy.
  5737. */
  5738. outer_start = find_large_buddy(start);
  5739. /* Make sure the range is really isolated. */
  5740. if (test_pages_isolated(outer_start, end, 0)) {
  5741. ret = -EBUSY;
  5742. goto done;
  5743. }
  5744. /* Grab isolated pages from freelists. */
  5745. outer_end = isolate_freepages_range(&cc, outer_start, end);
  5746. if (!outer_end) {
  5747. ret = -EBUSY;
  5748. goto done;
  5749. }
  5750. if (!(gfp_mask & __GFP_COMP)) {
  5751. split_free_pages(cc.freepages);
  5752. /* Free head and tail (if any) */
  5753. if (start != outer_start)
  5754. free_contig_range(outer_start, start - outer_start);
  5755. if (end != outer_end)
  5756. free_contig_range(end, outer_end - end);
  5757. } else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) {
  5758. struct page *head = pfn_to_page(start);
  5759. int order = ilog2(end - start);
  5760. check_new_pages(head, order);
  5761. prep_new_page(head, order, gfp_mask, 0);
  5762. } else {
  5763. ret = -EINVAL;
  5764. WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n",
  5765. start, end, outer_start, outer_end);
  5766. }
  5767. done:
  5768. undo_isolate_page_range(start, end, migratetype);
  5769. return ret;
  5770. }
  5771. EXPORT_SYMBOL(alloc_contig_range_noprof);
  5772. static int __alloc_contig_pages(unsigned long start_pfn,
  5773. unsigned long nr_pages, gfp_t gfp_mask)
  5774. {
  5775. unsigned long end_pfn = start_pfn + nr_pages;
  5776. return alloc_contig_range_noprof(start_pfn, end_pfn, MIGRATE_MOVABLE,
  5777. gfp_mask);
  5778. }
  5779. static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
  5780. unsigned long nr_pages)
  5781. {
  5782. unsigned long i, end_pfn = start_pfn + nr_pages;
  5783. struct page *page;
  5784. for (i = start_pfn; i < end_pfn; i++) {
  5785. page = pfn_to_online_page(i);
  5786. if (!page)
  5787. return false;
  5788. if (page_zone(page) != z)
  5789. return false;
  5790. if (PageReserved(page))
  5791. return false;
  5792. if (PageHuge(page))
  5793. return false;
  5794. }
  5795. return true;
  5796. }
  5797. static bool zone_spans_last_pfn(const struct zone *zone,
  5798. unsigned long start_pfn, unsigned long nr_pages)
  5799. {
  5800. unsigned long last_pfn = start_pfn + nr_pages - 1;
  5801. return zone_spans_pfn(zone, last_pfn);
  5802. }
  5803. /**
  5804. * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
  5805. * @nr_pages: Number of contiguous pages to allocate
  5806. * @gfp_mask: GFP mask to limit search and used during compaction
  5807. * @nid: Target node
  5808. * @nodemask: Mask for other possible nodes
  5809. *
  5810. * This routine is a wrapper around alloc_contig_range(). It scans over zones
  5811. * on an applicable zonelist to find a contiguous pfn range which can then be
  5812. * tried for allocation with alloc_contig_range(). This routine is intended
  5813. * for allocation requests which can not be fulfilled with the buddy allocator.
  5814. *
  5815. * The allocated memory is always aligned to a page boundary. If nr_pages is a
  5816. * power of two, then allocated range is also guaranteed to be aligned to same
  5817. * nr_pages (e.g. 1GB request would be aligned to 1GB).
  5818. *
  5819. * Allocated pages can be freed with free_contig_range() or by manually calling
  5820. * __free_page() on each allocated page.
  5821. *
  5822. * Return: pointer to contiguous pages on success, or NULL if not successful.
  5823. */
  5824. struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask,
  5825. int nid, nodemask_t *nodemask)
  5826. {
  5827. unsigned long ret, pfn, flags;
  5828. struct zonelist *zonelist;
  5829. struct zone *zone;
  5830. struct zoneref *z;
  5831. zonelist = node_zonelist(nid, gfp_mask);
  5832. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  5833. gfp_zone(gfp_mask), nodemask) {
  5834. spin_lock_irqsave(&zone->lock, flags);
  5835. pfn = ALIGN(zone->zone_start_pfn, nr_pages);
  5836. while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
  5837. if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
  5838. /*
  5839. * We release the zone lock here because
  5840. * alloc_contig_range() will also lock the zone
  5841. * at some point. If there's an allocation
  5842. * spinning on this lock, it may win the race
  5843. * and cause alloc_contig_range() to fail...
  5844. */
  5845. spin_unlock_irqrestore(&zone->lock, flags);
  5846. ret = __alloc_contig_pages(pfn, nr_pages,
  5847. gfp_mask);
  5848. if (!ret)
  5849. return pfn_to_page(pfn);
  5850. spin_lock_irqsave(&zone->lock, flags);
  5851. }
  5852. pfn += nr_pages;
  5853. }
  5854. spin_unlock_irqrestore(&zone->lock, flags);
  5855. }
  5856. return NULL;
  5857. }
  5858. #endif /* CONFIG_CONTIG_ALLOC */
  5859. void free_contig_range(unsigned long pfn, unsigned long nr_pages)
  5860. {
  5861. unsigned long count = 0;
  5862. struct folio *folio = pfn_folio(pfn);
  5863. if (folio_test_large(folio)) {
  5864. int expected = folio_nr_pages(folio);
  5865. if (nr_pages == expected)
  5866. folio_put(folio);
  5867. else
  5868. WARN(true, "PFN %lu: nr_pages %lu != expected %d\n",
  5869. pfn, nr_pages, expected);
  5870. return;
  5871. }
  5872. for (; nr_pages--; pfn++) {
  5873. struct page *page = pfn_to_page(pfn);
  5874. count += page_count(page) != 1;
  5875. __free_page(page);
  5876. }
  5877. WARN(count != 0, "%lu pages are still in use!\n", count);
  5878. }
  5879. EXPORT_SYMBOL(free_contig_range);
  5880. /*
  5881. * Effectively disable pcplists for the zone by setting the high limit to 0
  5882. * and draining all cpus. A concurrent page freeing on another CPU that's about
  5883. * to put the page on pcplist will either finish before the drain and the page
  5884. * will be drained, or observe the new high limit and skip the pcplist.
  5885. *
  5886. * Must be paired with a call to zone_pcp_enable().
  5887. */
  5888. void zone_pcp_disable(struct zone *zone)
  5889. {
  5890. mutex_lock(&pcp_batch_high_lock);
  5891. __zone_set_pageset_high_and_batch(zone, 0, 0, 1);
  5892. __drain_all_pages(zone, true);
  5893. }
  5894. void zone_pcp_enable(struct zone *zone)
  5895. {
  5896. __zone_set_pageset_high_and_batch(zone, zone->pageset_high_min,
  5897. zone->pageset_high_max, zone->pageset_batch);
  5898. mutex_unlock(&pcp_batch_high_lock);
  5899. }
  5900. void zone_pcp_reset(struct zone *zone)
  5901. {
  5902. int cpu;
  5903. struct per_cpu_zonestat *pzstats;
  5904. if (zone->per_cpu_pageset != &boot_pageset) {
  5905. for_each_online_cpu(cpu) {
  5906. pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
  5907. drain_zonestat(zone, pzstats);
  5908. }
  5909. free_percpu(zone->per_cpu_pageset);
  5910. zone->per_cpu_pageset = &boot_pageset;
  5911. if (zone->per_cpu_zonestats != &boot_zonestats) {
  5912. free_percpu(zone->per_cpu_zonestats);
  5913. zone->per_cpu_zonestats = &boot_zonestats;
  5914. }
  5915. }
  5916. }
  5917. #ifdef CONFIG_MEMORY_HOTREMOVE
  5918. /*
  5919. * All pages in the range must be in a single zone, must not contain holes,
  5920. * must span full sections, and must be isolated before calling this function.
  5921. *
  5922. * Returns the number of managed (non-PageOffline()) pages in the range: the
  5923. * number of pages for which memory offlining code must adjust managed page
  5924. * counters using adjust_managed_page_count().
  5925. */
  5926. unsigned long __offline_isolated_pages(unsigned long start_pfn,
  5927. unsigned long end_pfn)
  5928. {
  5929. unsigned long already_offline = 0, flags;
  5930. unsigned long pfn = start_pfn;
  5931. struct page *page;
  5932. struct zone *zone;
  5933. unsigned int order;
  5934. offline_mem_sections(pfn, end_pfn);
  5935. zone = page_zone(pfn_to_page(pfn));
  5936. spin_lock_irqsave(&zone->lock, flags);
  5937. while (pfn < end_pfn) {
  5938. page = pfn_to_page(pfn);
  5939. /*
  5940. * The HWPoisoned page may be not in buddy system, and
  5941. * page_count() is not 0.
  5942. */
  5943. if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
  5944. pfn++;
  5945. continue;
  5946. }
  5947. /*
  5948. * At this point all remaining PageOffline() pages have a
  5949. * reference count of 0 and can simply be skipped.
  5950. */
  5951. if (PageOffline(page)) {
  5952. BUG_ON(page_count(page));
  5953. BUG_ON(PageBuddy(page));
  5954. already_offline++;
  5955. pfn++;
  5956. continue;
  5957. }
  5958. BUG_ON(page_count(page));
  5959. BUG_ON(!PageBuddy(page));
  5960. VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE);
  5961. order = buddy_order(page);
  5962. del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE);
  5963. pfn += (1 << order);
  5964. }
  5965. spin_unlock_irqrestore(&zone->lock, flags);
  5966. return end_pfn - start_pfn - already_offline;
  5967. }
  5968. #endif
  5969. /*
  5970. * This function returns a stable result only if called under zone lock.
  5971. */
  5972. bool is_free_buddy_page(const struct page *page)
  5973. {
  5974. unsigned long pfn = page_to_pfn(page);
  5975. unsigned int order;
  5976. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  5977. const struct page *head = page - (pfn & ((1 << order) - 1));
  5978. if (PageBuddy(head) &&
  5979. buddy_order_unsafe(head) >= order)
  5980. break;
  5981. }
  5982. return order <= MAX_PAGE_ORDER;
  5983. }
  5984. EXPORT_SYMBOL(is_free_buddy_page);
  5985. #ifdef CONFIG_MEMORY_FAILURE
  5986. static inline void add_to_free_list(struct page *page, struct zone *zone,
  5987. unsigned int order, int migratetype,
  5988. bool tail)
  5989. {
  5990. __add_to_free_list(page, zone, order, migratetype, tail);
  5991. account_freepages(zone, 1 << order, migratetype);
  5992. }
  5993. /*
  5994. * Break down a higher-order page in sub-pages, and keep our target out of
  5995. * buddy allocator.
  5996. */
  5997. static void break_down_buddy_pages(struct zone *zone, struct page *page,
  5998. struct page *target, int low, int high,
  5999. int migratetype)
  6000. {
  6001. unsigned long size = 1 << high;
  6002. struct page *current_buddy;
  6003. while (high > low) {
  6004. high--;
  6005. size >>= 1;
  6006. if (target >= &page[size]) {
  6007. current_buddy = page;
  6008. page = page + size;
  6009. } else {
  6010. current_buddy = page + size;
  6011. }
  6012. if (set_page_guard(zone, current_buddy, high))
  6013. continue;
  6014. add_to_free_list(current_buddy, zone, high, migratetype, false);
  6015. set_buddy_order(current_buddy, high);
  6016. }
  6017. }
  6018. /*
  6019. * Take a page that will be marked as poisoned off the buddy allocator.
  6020. */
  6021. bool take_page_off_buddy(struct page *page)
  6022. {
  6023. struct zone *zone = page_zone(page);
  6024. unsigned long pfn = page_to_pfn(page);
  6025. unsigned long flags;
  6026. unsigned int order;
  6027. bool ret = false;
  6028. spin_lock_irqsave(&zone->lock, flags);
  6029. for (order = 0; order < NR_PAGE_ORDERS; order++) {
  6030. struct page *page_head = page - (pfn & ((1 << order) - 1));
  6031. int page_order = buddy_order(page_head);
  6032. if (PageBuddy(page_head) && page_order >= order) {
  6033. unsigned long pfn_head = page_to_pfn(page_head);
  6034. int migratetype = get_pfnblock_migratetype(page_head,
  6035. pfn_head);
  6036. del_page_from_free_list(page_head, zone, page_order,
  6037. migratetype);
  6038. break_down_buddy_pages(zone, page_head, page, 0,
  6039. page_order, migratetype);
  6040. SetPageHWPoisonTakenOff(page);
  6041. ret = true;
  6042. break;
  6043. }
  6044. if (page_count(page_head) > 0)
  6045. break;
  6046. }
  6047. spin_unlock_irqrestore(&zone->lock, flags);
  6048. return ret;
  6049. }
  6050. /*
  6051. * Cancel takeoff done by take_page_off_buddy().
  6052. */
  6053. bool put_page_back_buddy(struct page *page)
  6054. {
  6055. struct zone *zone = page_zone(page);
  6056. unsigned long flags;
  6057. bool ret = false;
  6058. spin_lock_irqsave(&zone->lock, flags);
  6059. if (put_page_testzero(page)) {
  6060. unsigned long pfn = page_to_pfn(page);
  6061. int migratetype = get_pfnblock_migratetype(page, pfn);
  6062. ClearPageHWPoisonTakenOff(page);
  6063. __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
  6064. if (TestClearPageHWPoison(page)) {
  6065. ret = true;
  6066. }
  6067. }
  6068. spin_unlock_irqrestore(&zone->lock, flags);
  6069. return ret;
  6070. }
  6071. #endif
  6072. #ifdef CONFIG_ZONE_DMA
  6073. bool has_managed_dma(void)
  6074. {
  6075. struct pglist_data *pgdat;
  6076. for_each_online_pgdat(pgdat) {
  6077. struct zone *zone = &pgdat->node_zones[ZONE_DMA];
  6078. if (managed_zone(zone))
  6079. return true;
  6080. }
  6081. return false;
  6082. }
  6083. #endif /* CONFIG_ZONE_DMA */
  6084. #ifdef CONFIG_UNACCEPTED_MEMORY
  6085. static bool lazy_accept = true;
  6086. static int __init accept_memory_parse(char *p)
  6087. {
  6088. if (!strcmp(p, "lazy")) {
  6089. lazy_accept = true;
  6090. return 0;
  6091. } else if (!strcmp(p, "eager")) {
  6092. lazy_accept = false;
  6093. return 0;
  6094. } else {
  6095. return -EINVAL;
  6096. }
  6097. }
  6098. early_param("accept_memory", accept_memory_parse);
  6099. static bool page_contains_unaccepted(struct page *page, unsigned int order)
  6100. {
  6101. phys_addr_t start = page_to_phys(page);
  6102. return range_contains_unaccepted_memory(start, PAGE_SIZE << order);
  6103. }
  6104. static void __accept_page(struct zone *zone, unsigned long *flags,
  6105. struct page *page)
  6106. {
  6107. list_del(&page->lru);
  6108. account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
  6109. __mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES);
  6110. __ClearPageUnaccepted(page);
  6111. spin_unlock_irqrestore(&zone->lock, *flags);
  6112. accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
  6113. __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
  6114. }
  6115. void accept_page(struct page *page)
  6116. {
  6117. struct zone *zone = page_zone(page);
  6118. unsigned long flags;
  6119. spin_lock_irqsave(&zone->lock, flags);
  6120. if (!PageUnaccepted(page)) {
  6121. spin_unlock_irqrestore(&zone->lock, flags);
  6122. return;
  6123. }
  6124. /* Unlocks zone->lock */
  6125. __accept_page(zone, &flags, page);
  6126. }
  6127. static bool try_to_accept_memory_one(struct zone *zone)
  6128. {
  6129. unsigned long flags;
  6130. struct page *page;
  6131. spin_lock_irqsave(&zone->lock, flags);
  6132. page = list_first_entry_or_null(&zone->unaccepted_pages,
  6133. struct page, lru);
  6134. if (!page) {
  6135. spin_unlock_irqrestore(&zone->lock, flags);
  6136. return false;
  6137. }
  6138. /* Unlocks zone->lock */
  6139. __accept_page(zone, &flags, page);
  6140. return true;
  6141. }
  6142. static bool cond_accept_memory(struct zone *zone, unsigned int order)
  6143. {
  6144. long to_accept, wmark;
  6145. bool ret = false;
  6146. if (list_empty(&zone->unaccepted_pages))
  6147. return false;
  6148. wmark = promo_wmark_pages(zone);
  6149. /*
  6150. * Watermarks have not been initialized yet.
  6151. *
  6152. * Accepting one MAX_ORDER page to ensure progress.
  6153. */
  6154. if (!wmark)
  6155. return try_to_accept_memory_one(zone);
  6156. /* How much to accept to get to promo watermark? */
  6157. to_accept = wmark -
  6158. (zone_page_state(zone, NR_FREE_PAGES) -
  6159. __zone_watermark_unusable_free(zone, order, 0) -
  6160. zone_page_state(zone, NR_UNACCEPTED));
  6161. while (to_accept > 0) {
  6162. if (!try_to_accept_memory_one(zone))
  6163. break;
  6164. ret = true;
  6165. to_accept -= MAX_ORDER_NR_PAGES;
  6166. }
  6167. return ret;
  6168. }
  6169. static bool __free_unaccepted(struct page *page)
  6170. {
  6171. struct zone *zone = page_zone(page);
  6172. unsigned long flags;
  6173. if (!lazy_accept)
  6174. return false;
  6175. spin_lock_irqsave(&zone->lock, flags);
  6176. list_add_tail(&page->lru, &zone->unaccepted_pages);
  6177. account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
  6178. __mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES);
  6179. __SetPageUnaccepted(page);
  6180. spin_unlock_irqrestore(&zone->lock, flags);
  6181. return true;
  6182. }
  6183. #else
  6184. static bool page_contains_unaccepted(struct page *page, unsigned int order)
  6185. {
  6186. return false;
  6187. }
  6188. static bool cond_accept_memory(struct zone *zone, unsigned int order)
  6189. {
  6190. return false;
  6191. }
  6192. static bool __free_unaccepted(struct page *page)
  6193. {
  6194. BUILD_BUG();
  6195. return false;
  6196. }
  6197. #endif /* CONFIG_UNACCEPTED_MEMORY */