slub.c 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * SLUB: A slab allocator that limits cache line use instead of queuing
  4. * objects in per cpu and per node lists.
  5. *
  6. * The allocator synchronizes using per slab locks or atomic operations
  7. * and only uses a centralized lock to manage a pool of partial slabs.
  8. *
  9. * (C) 2007 SGI, Christoph Lameter
  10. * (C) 2011 Linux Foundation, Christoph Lameter
  11. */
  12. #include <linux/mm.h>
  13. #include <linux/swap.h> /* mm_account_reclaimed_pages() */
  14. #include <linux/module.h>
  15. #include <linux/bit_spinlock.h>
  16. #include <linux/interrupt.h>
  17. #include <linux/swab.h>
  18. #include <linux/bitops.h>
  19. #include <linux/slab.h>
  20. #include "slab.h"
  21. #include <linux/proc_fs.h>
  22. #include <linux/seq_file.h>
  23. #include <linux/kasan.h>
  24. #include <linux/kmsan.h>
  25. #include <linux/cpu.h>
  26. #include <linux/cpuset.h>
  27. #include <linux/mempolicy.h>
  28. #include <linux/ctype.h>
  29. #include <linux/stackdepot.h>
  30. #include <linux/debugobjects.h>
  31. #include <linux/kallsyms.h>
  32. #include <linux/kfence.h>
  33. #include <linux/memory.h>
  34. #include <linux/math64.h>
  35. #include <linux/fault-inject.h>
  36. #include <linux/kmemleak.h>
  37. #include <linux/stacktrace.h>
  38. #include <linux/prefetch.h>
  39. #include <linux/memcontrol.h>
  40. #include <linux/random.h>
  41. #include <kunit/test.h>
  42. #include <kunit/test-bug.h>
  43. #include <linux/sort.h>
  44. #include <linux/debugfs.h>
  45. #include <trace/events/kmem.h>
  46. #include "internal.h"
  47. /*
  48. * Lock order:
  49. * 1. slab_mutex (Global Mutex)
  50. * 2. node->list_lock (Spinlock)
  51. * 3. kmem_cache->cpu_slab->lock (Local lock)
  52. * 4. slab_lock(slab) (Only on some arches)
  53. * 5. object_map_lock (Only for debugging)
  54. *
  55. * slab_mutex
  56. *
  57. * The role of the slab_mutex is to protect the list of all the slabs
  58. * and to synchronize major metadata changes to slab cache structures.
  59. * Also synchronizes memory hotplug callbacks.
  60. *
  61. * slab_lock
  62. *
  63. * The slab_lock is a wrapper around the page lock, thus it is a bit
  64. * spinlock.
  65. *
  66. * The slab_lock is only used on arches that do not have the ability
  67. * to do a cmpxchg_double. It only protects:
  68. *
  69. * A. slab->freelist -> List of free objects in a slab
  70. * B. slab->inuse -> Number of objects in use
  71. * C. slab->objects -> Number of objects in slab
  72. * D. slab->frozen -> frozen state
  73. *
  74. * Frozen slabs
  75. *
  76. * If a slab is frozen then it is exempt from list management. It is
  77. * the cpu slab which is actively allocated from by the processor that
  78. * froze it and it is not on any list. The processor that froze the
  79. * slab is the one who can perform list operations on the slab. Other
  80. * processors may put objects onto the freelist but the processor that
  81. * froze the slab is the only one that can retrieve the objects from the
  82. * slab's freelist.
  83. *
  84. * CPU partial slabs
  85. *
  86. * The partially empty slabs cached on the CPU partial list are used
  87. * for performance reasons, which speeds up the allocation process.
  88. * These slabs are not frozen, but are also exempt from list management,
  89. * by clearing the PG_workingset flag when moving out of the node
  90. * partial list. Please see __slab_free() for more details.
  91. *
  92. * To sum up, the current scheme is:
  93. * - node partial slab: PG_Workingset && !frozen
  94. * - cpu partial slab: !PG_Workingset && !frozen
  95. * - cpu slab: !PG_Workingset && frozen
  96. * - full slab: !PG_Workingset && !frozen
  97. *
  98. * list_lock
  99. *
  100. * The list_lock protects the partial and full list on each node and
  101. * the partial slab counter. If taken then no new slabs may be added or
  102. * removed from the lists nor make the number of partial slabs be modified.
  103. * (Note that the total number of slabs is an atomic value that may be
  104. * modified without taking the list lock).
  105. *
  106. * The list_lock is a centralized lock and thus we avoid taking it as
  107. * much as possible. As long as SLUB does not have to handle partial
  108. * slabs, operations can continue without any centralized lock. F.e.
  109. * allocating a long series of objects that fill up slabs does not require
  110. * the list lock.
  111. *
  112. * For debug caches, all allocations are forced to go through a list_lock
  113. * protected region to serialize against concurrent validation.
  114. *
  115. * cpu_slab->lock local lock
  116. *
  117. * This locks protect slowpath manipulation of all kmem_cache_cpu fields
  118. * except the stat counters. This is a percpu structure manipulated only by
  119. * the local cpu, so the lock protects against being preempted or interrupted
  120. * by an irq. Fast path operations rely on lockless operations instead.
  121. *
  122. * On PREEMPT_RT, the local lock neither disables interrupts nor preemption
  123. * which means the lockless fastpath cannot be used as it might interfere with
  124. * an in-progress slow path operations. In this case the local lock is always
  125. * taken but it still utilizes the freelist for the common operations.
  126. *
  127. * lockless fastpaths
  128. *
  129. * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
  130. * are fully lockless when satisfied from the percpu slab (and when
  131. * cmpxchg_double is possible to use, otherwise slab_lock is taken).
  132. * They also don't disable preemption or migration or irqs. They rely on
  133. * the transaction id (tid) field to detect being preempted or moved to
  134. * another cpu.
  135. *
  136. * irq, preemption, migration considerations
  137. *
  138. * Interrupts are disabled as part of list_lock or local_lock operations, or
  139. * around the slab_lock operation, in order to make the slab allocator safe
  140. * to use in the context of an irq.
  141. *
  142. * In addition, preemption (or migration on PREEMPT_RT) is disabled in the
  143. * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
  144. * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
  145. * doesn't have to be revalidated in each section protected by the local lock.
  146. *
  147. * SLUB assigns one slab for allocation to each processor.
  148. * Allocations only occur from these slabs called cpu slabs.
  149. *
  150. * Slabs with free elements are kept on a partial list and during regular
  151. * operations no list for full slabs is used. If an object in a full slab is
  152. * freed then the slab will show up again on the partial lists.
  153. * We track full slabs for debugging purposes though because otherwise we
  154. * cannot scan all objects.
  155. *
  156. * Slabs are freed when they become empty. Teardown and setup is
  157. * minimal so we rely on the page allocators per cpu caches for
  158. * fast frees and allocs.
  159. *
  160. * slab->frozen The slab is frozen and exempt from list processing.
  161. * This means that the slab is dedicated to a purpose
  162. * such as satisfying allocations for a specific
  163. * processor. Objects may be freed in the slab while
  164. * it is frozen but slab_free will then skip the usual
  165. * list operations. It is up to the processor holding
  166. * the slab to integrate the slab into the slab lists
  167. * when the slab is no longer needed.
  168. *
  169. * One use of this flag is to mark slabs that are
  170. * used for allocations. Then such a slab becomes a cpu
  171. * slab. The cpu slab may be equipped with an additional
  172. * freelist that allows lockless access to
  173. * free objects in addition to the regular freelist
  174. * that requires the slab lock.
  175. *
  176. * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
  177. * options set. This moves slab handling out of
  178. * the fast path and disables lockless freelists.
  179. */
  180. /*
  181. * We could simply use migrate_disable()/enable() but as long as it's a
  182. * function call even on !PREEMPT_RT, use inline preempt_disable() there.
  183. */
  184. #ifndef CONFIG_PREEMPT_RT
  185. #define slub_get_cpu_ptr(var) get_cpu_ptr(var)
  186. #define slub_put_cpu_ptr(var) put_cpu_ptr(var)
  187. #define USE_LOCKLESS_FAST_PATH() (true)
  188. #else
  189. #define slub_get_cpu_ptr(var) \
  190. ({ \
  191. migrate_disable(); \
  192. this_cpu_ptr(var); \
  193. })
  194. #define slub_put_cpu_ptr(var) \
  195. do { \
  196. (void)(var); \
  197. migrate_enable(); \
  198. } while (0)
  199. #define USE_LOCKLESS_FAST_PATH() (false)
  200. #endif
  201. #ifndef CONFIG_SLUB_TINY
  202. #define __fastpath_inline __always_inline
  203. #else
  204. #define __fastpath_inline
  205. #endif
  206. #ifdef CONFIG_SLUB_DEBUG
  207. #ifdef CONFIG_SLUB_DEBUG_ON
  208. DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
  209. #else
  210. DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
  211. #endif
  212. #endif /* CONFIG_SLUB_DEBUG */
  213. /* Structure holding parameters for get_partial() call chain */
  214. struct partial_context {
  215. gfp_t flags;
  216. unsigned int orig_size;
  217. void *object;
  218. };
  219. static inline bool kmem_cache_debug(struct kmem_cache *s)
  220. {
  221. return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
  222. }
  223. static inline bool slub_debug_orig_size(struct kmem_cache *s)
  224. {
  225. return (kmem_cache_debug_flags(s, SLAB_STORE_USER) &&
  226. (s->flags & SLAB_KMALLOC));
  227. }
  228. void *fixup_red_left(struct kmem_cache *s, void *p)
  229. {
  230. if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
  231. p += s->red_left_pad;
  232. return p;
  233. }
  234. static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
  235. {
  236. #ifdef CONFIG_SLUB_CPU_PARTIAL
  237. return !kmem_cache_debug(s);
  238. #else
  239. return false;
  240. #endif
  241. }
  242. /*
  243. * Issues still to be resolved:
  244. *
  245. * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
  246. *
  247. * - Variable sizing of the per node arrays
  248. */
  249. /* Enable to log cmpxchg failures */
  250. #undef SLUB_DEBUG_CMPXCHG
  251. #ifndef CONFIG_SLUB_TINY
  252. /*
  253. * Minimum number of partial slabs. These will be left on the partial
  254. * lists even if they are empty. kmem_cache_shrink may reclaim them.
  255. */
  256. #define MIN_PARTIAL 5
  257. /*
  258. * Maximum number of desirable partial slabs.
  259. * The existence of more partial slabs makes kmem_cache_shrink
  260. * sort the partial list by the number of objects in use.
  261. */
  262. #define MAX_PARTIAL 10
  263. #else
  264. #define MIN_PARTIAL 0
  265. #define MAX_PARTIAL 0
  266. #endif
  267. #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
  268. SLAB_POISON | SLAB_STORE_USER)
  269. /*
  270. * These debug flags cannot use CMPXCHG because there might be consistency
  271. * issues when checking or reading debug information
  272. */
  273. #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
  274. SLAB_TRACE)
  275. /*
  276. * Debugging flags that require metadata to be stored in the slab. These get
  277. * disabled when slab_debug=O is used and a cache's min order increases with
  278. * metadata.
  279. */
  280. #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
  281. #define OO_SHIFT 16
  282. #define OO_MASK ((1 << OO_SHIFT) - 1)
  283. #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
  284. /* Internal SLUB flags */
  285. /* Poison object */
  286. #define __OBJECT_POISON __SLAB_FLAG_BIT(_SLAB_OBJECT_POISON)
  287. /* Use cmpxchg_double */
  288. #ifdef system_has_freelist_aba
  289. #define __CMPXCHG_DOUBLE __SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE)
  290. #else
  291. #define __CMPXCHG_DOUBLE __SLAB_FLAG_UNUSED
  292. #endif
  293. /*
  294. * Tracking user of a slab.
  295. */
  296. #define TRACK_ADDRS_COUNT 16
  297. struct track {
  298. unsigned long addr; /* Called from address */
  299. #ifdef CONFIG_STACKDEPOT
  300. depot_stack_handle_t handle;
  301. #endif
  302. int cpu; /* Was running on cpu */
  303. int pid; /* Pid context */
  304. unsigned long when; /* When did the operation occur */
  305. };
  306. enum track_item { TRACK_ALLOC, TRACK_FREE };
  307. #ifdef SLAB_SUPPORTS_SYSFS
  308. static int sysfs_slab_add(struct kmem_cache *);
  309. static int sysfs_slab_alias(struct kmem_cache *, const char *);
  310. #else
  311. static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
  312. static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
  313. { return 0; }
  314. #endif
  315. #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
  316. static void debugfs_slab_add(struct kmem_cache *);
  317. #else
  318. static inline void debugfs_slab_add(struct kmem_cache *s) { }
  319. #endif
  320. enum stat_item {
  321. ALLOC_FASTPATH, /* Allocation from cpu slab */
  322. ALLOC_SLOWPATH, /* Allocation by getting a new cpu slab */
  323. FREE_FASTPATH, /* Free to cpu slab */
  324. FREE_SLOWPATH, /* Freeing not to cpu slab */
  325. FREE_FROZEN, /* Freeing to frozen slab */
  326. FREE_ADD_PARTIAL, /* Freeing moves slab to partial list */
  327. FREE_REMOVE_PARTIAL, /* Freeing removes last object */
  328. ALLOC_FROM_PARTIAL, /* Cpu slab acquired from node partial list */
  329. ALLOC_SLAB, /* Cpu slab acquired from page allocator */
  330. ALLOC_REFILL, /* Refill cpu slab from slab freelist */
  331. ALLOC_NODE_MISMATCH, /* Switching cpu slab */
  332. FREE_SLAB, /* Slab freed to the page allocator */
  333. CPUSLAB_FLUSH, /* Abandoning of the cpu slab */
  334. DEACTIVATE_FULL, /* Cpu slab was full when deactivated */
  335. DEACTIVATE_EMPTY, /* Cpu slab was empty when deactivated */
  336. DEACTIVATE_TO_HEAD, /* Cpu slab was moved to the head of partials */
  337. DEACTIVATE_TO_TAIL, /* Cpu slab was moved to the tail of partials */
  338. DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */
  339. DEACTIVATE_BYPASS, /* Implicit deactivation */
  340. ORDER_FALLBACK, /* Number of times fallback was necessary */
  341. CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */
  342. CMPXCHG_DOUBLE_FAIL, /* Failures of slab freelist update */
  343. CPU_PARTIAL_ALLOC, /* Used cpu partial on alloc */
  344. CPU_PARTIAL_FREE, /* Refill cpu partial on free */
  345. CPU_PARTIAL_NODE, /* Refill cpu partial from node partial */
  346. CPU_PARTIAL_DRAIN, /* Drain cpu partial to node partial */
  347. NR_SLUB_STAT_ITEMS
  348. };
  349. #ifndef CONFIG_SLUB_TINY
  350. /*
  351. * When changing the layout, make sure freelist and tid are still compatible
  352. * with this_cpu_cmpxchg_double() alignment requirements.
  353. */
  354. struct kmem_cache_cpu {
  355. union {
  356. struct {
  357. void **freelist; /* Pointer to next available object */
  358. unsigned long tid; /* Globally unique transaction id */
  359. };
  360. freelist_aba_t freelist_tid;
  361. };
  362. struct slab *slab; /* The slab from which we are allocating */
  363. #ifdef CONFIG_SLUB_CPU_PARTIAL
  364. struct slab *partial; /* Partially allocated slabs */
  365. #endif
  366. local_lock_t lock; /* Protects the fields above */
  367. #ifdef CONFIG_SLUB_STATS
  368. unsigned int stat[NR_SLUB_STAT_ITEMS];
  369. #endif
  370. };
  371. #endif /* CONFIG_SLUB_TINY */
  372. static inline void stat(const struct kmem_cache *s, enum stat_item si)
  373. {
  374. #ifdef CONFIG_SLUB_STATS
  375. /*
  376. * The rmw is racy on a preemptible kernel but this is acceptable, so
  377. * avoid this_cpu_add()'s irq-disable overhead.
  378. */
  379. raw_cpu_inc(s->cpu_slab->stat[si]);
  380. #endif
  381. }
  382. static inline
  383. void stat_add(const struct kmem_cache *s, enum stat_item si, int v)
  384. {
  385. #ifdef CONFIG_SLUB_STATS
  386. raw_cpu_add(s->cpu_slab->stat[si], v);
  387. #endif
  388. }
  389. /*
  390. * The slab lists for all objects.
  391. */
  392. struct kmem_cache_node {
  393. spinlock_t list_lock;
  394. unsigned long nr_partial;
  395. struct list_head partial;
  396. #ifdef CONFIG_SLUB_DEBUG
  397. atomic_long_t nr_slabs;
  398. atomic_long_t total_objects;
  399. struct list_head full;
  400. #endif
  401. };
  402. static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
  403. {
  404. return s->node[node];
  405. }
  406. /*
  407. * Iterator over all nodes. The body will be executed for each node that has
  408. * a kmem_cache_node structure allocated (which is true for all online nodes)
  409. */
  410. #define for_each_kmem_cache_node(__s, __node, __n) \
  411. for (__node = 0; __node < nr_node_ids; __node++) \
  412. if ((__n = get_node(__s, __node)))
  413. /*
  414. * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
  415. * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
  416. * differ during memory hotplug/hotremove operations.
  417. * Protected by slab_mutex.
  418. */
  419. static nodemask_t slab_nodes;
  420. #ifndef CONFIG_SLUB_TINY
  421. /*
  422. * Workqueue used for flush_cpu_slab().
  423. */
  424. static struct workqueue_struct *flushwq;
  425. #endif
  426. /********************************************************************
  427. * Core slab cache functions
  428. *******************************************************************/
  429. /*
  430. * Returns freelist pointer (ptr). With hardening, this is obfuscated
  431. * with an XOR of the address where the pointer is held and a per-cache
  432. * random number.
  433. */
  434. static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
  435. void *ptr, unsigned long ptr_addr)
  436. {
  437. unsigned long encoded;
  438. #ifdef CONFIG_SLAB_FREELIST_HARDENED
  439. encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
  440. #else
  441. encoded = (unsigned long)ptr;
  442. #endif
  443. return (freeptr_t){.v = encoded};
  444. }
  445. static inline void *freelist_ptr_decode(const struct kmem_cache *s,
  446. freeptr_t ptr, unsigned long ptr_addr)
  447. {
  448. void *decoded;
  449. #ifdef CONFIG_SLAB_FREELIST_HARDENED
  450. decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
  451. #else
  452. decoded = (void *)ptr.v;
  453. #endif
  454. return decoded;
  455. }
  456. static inline void *get_freepointer(struct kmem_cache *s, void *object)
  457. {
  458. unsigned long ptr_addr;
  459. freeptr_t p;
  460. object = kasan_reset_tag(object);
  461. ptr_addr = (unsigned long)object + s->offset;
  462. p = *(freeptr_t *)(ptr_addr);
  463. return freelist_ptr_decode(s, p, ptr_addr);
  464. }
  465. #ifndef CONFIG_SLUB_TINY
  466. static void prefetch_freepointer(const struct kmem_cache *s, void *object)
  467. {
  468. prefetchw(object + s->offset);
  469. }
  470. #endif
  471. /*
  472. * When running under KMSAN, get_freepointer_safe() may return an uninitialized
  473. * pointer value in the case the current thread loses the race for the next
  474. * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
  475. * slab_alloc_node() will fail, so the uninitialized value won't be used, but
  476. * KMSAN will still check all arguments of cmpxchg because of imperfect
  477. * handling of inline assembly.
  478. * To work around this problem, we apply __no_kmsan_checks to ensure that
  479. * get_freepointer_safe() returns initialized memory.
  480. */
  481. __no_kmsan_checks
  482. static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
  483. {
  484. unsigned long freepointer_addr;
  485. freeptr_t p;
  486. if (!debug_pagealloc_enabled_static())
  487. return get_freepointer(s, object);
  488. object = kasan_reset_tag(object);
  489. freepointer_addr = (unsigned long)object + s->offset;
  490. copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p));
  491. return freelist_ptr_decode(s, p, freepointer_addr);
  492. }
  493. static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
  494. {
  495. unsigned long freeptr_addr = (unsigned long)object + s->offset;
  496. #ifdef CONFIG_SLAB_FREELIST_HARDENED
  497. BUG_ON(object == fp); /* naive detection of double free or corruption */
  498. #endif
  499. freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
  500. *(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
  501. }
  502. /*
  503. * See comment in calculate_sizes().
  504. */
  505. static inline bool freeptr_outside_object(struct kmem_cache *s)
  506. {
  507. return s->offset >= s->inuse;
  508. }
  509. /*
  510. * Return offset of the end of info block which is inuse + free pointer if
  511. * not overlapping with object.
  512. */
  513. static inline unsigned int get_info_end(struct kmem_cache *s)
  514. {
  515. if (freeptr_outside_object(s))
  516. return s->inuse + sizeof(void *);
  517. else
  518. return s->inuse;
  519. }
  520. /* Loop over all objects in a slab */
  521. #define for_each_object(__p, __s, __addr, __objects) \
  522. for (__p = fixup_red_left(__s, __addr); \
  523. __p < (__addr) + (__objects) * (__s)->size; \
  524. __p += (__s)->size)
  525. static inline unsigned int order_objects(unsigned int order, unsigned int size)
  526. {
  527. return ((unsigned int)PAGE_SIZE << order) / size;
  528. }
  529. static inline struct kmem_cache_order_objects oo_make(unsigned int order,
  530. unsigned int size)
  531. {
  532. struct kmem_cache_order_objects x = {
  533. (order << OO_SHIFT) + order_objects(order, size)
  534. };
  535. return x;
  536. }
  537. static inline unsigned int oo_order(struct kmem_cache_order_objects x)
  538. {
  539. return x.x >> OO_SHIFT;
  540. }
  541. static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
  542. {
  543. return x.x & OO_MASK;
  544. }
  545. #ifdef CONFIG_SLUB_CPU_PARTIAL
  546. static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
  547. {
  548. unsigned int nr_slabs;
  549. s->cpu_partial = nr_objects;
  550. /*
  551. * We take the number of objects but actually limit the number of
  552. * slabs on the per cpu partial list, in order to limit excessive
  553. * growth of the list. For simplicity we assume that the slabs will
  554. * be half-full.
  555. */
  556. nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
  557. s->cpu_partial_slabs = nr_slabs;
  558. }
  559. static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
  560. {
  561. return s->cpu_partial_slabs;
  562. }
  563. #else
  564. static inline void
  565. slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
  566. {
  567. }
  568. static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
  569. {
  570. return 0;
  571. }
  572. #endif /* CONFIG_SLUB_CPU_PARTIAL */
  573. /*
  574. * Per slab locking using the pagelock
  575. */
  576. static __always_inline void slab_lock(struct slab *slab)
  577. {
  578. bit_spin_lock(PG_locked, &slab->__page_flags);
  579. }
  580. static __always_inline void slab_unlock(struct slab *slab)
  581. {
  582. bit_spin_unlock(PG_locked, &slab->__page_flags);
  583. }
  584. static inline bool
  585. __update_freelist_fast(struct slab *slab,
  586. void *freelist_old, unsigned long counters_old,
  587. void *freelist_new, unsigned long counters_new)
  588. {
  589. #ifdef system_has_freelist_aba
  590. freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old };
  591. freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new };
  592. return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full);
  593. #else
  594. return false;
  595. #endif
  596. }
  597. static inline bool
  598. __update_freelist_slow(struct slab *slab,
  599. void *freelist_old, unsigned long counters_old,
  600. void *freelist_new, unsigned long counters_new)
  601. {
  602. bool ret = false;
  603. slab_lock(slab);
  604. if (slab->freelist == freelist_old &&
  605. slab->counters == counters_old) {
  606. slab->freelist = freelist_new;
  607. slab->counters = counters_new;
  608. ret = true;
  609. }
  610. slab_unlock(slab);
  611. return ret;
  612. }
  613. /*
  614. * Interrupts must be disabled (for the fallback code to work right), typically
  615. * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
  616. * part of bit_spin_lock(), is sufficient because the policy is not to allow any
  617. * allocation/ free operation in hardirq context. Therefore nothing can
  618. * interrupt the operation.
  619. */
  620. static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
  621. void *freelist_old, unsigned long counters_old,
  622. void *freelist_new, unsigned long counters_new,
  623. const char *n)
  624. {
  625. bool ret;
  626. if (USE_LOCKLESS_FAST_PATH())
  627. lockdep_assert_irqs_disabled();
  628. if (s->flags & __CMPXCHG_DOUBLE) {
  629. ret = __update_freelist_fast(slab, freelist_old, counters_old,
  630. freelist_new, counters_new);
  631. } else {
  632. ret = __update_freelist_slow(slab, freelist_old, counters_old,
  633. freelist_new, counters_new);
  634. }
  635. if (likely(ret))
  636. return true;
  637. cpu_relax();
  638. stat(s, CMPXCHG_DOUBLE_FAIL);
  639. #ifdef SLUB_DEBUG_CMPXCHG
  640. pr_info("%s %s: cmpxchg double redo ", n, s->name);
  641. #endif
  642. return false;
  643. }
  644. static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
  645. void *freelist_old, unsigned long counters_old,
  646. void *freelist_new, unsigned long counters_new,
  647. const char *n)
  648. {
  649. bool ret;
  650. if (s->flags & __CMPXCHG_DOUBLE) {
  651. ret = __update_freelist_fast(slab, freelist_old, counters_old,
  652. freelist_new, counters_new);
  653. } else {
  654. unsigned long flags;
  655. local_irq_save(flags);
  656. ret = __update_freelist_slow(slab, freelist_old, counters_old,
  657. freelist_new, counters_new);
  658. local_irq_restore(flags);
  659. }
  660. if (likely(ret))
  661. return true;
  662. cpu_relax();
  663. stat(s, CMPXCHG_DOUBLE_FAIL);
  664. #ifdef SLUB_DEBUG_CMPXCHG
  665. pr_info("%s %s: cmpxchg double redo ", n, s->name);
  666. #endif
  667. return false;
  668. }
  669. /*
  670. * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
  671. * family will round up the real request size to these fixed ones, so
  672. * there could be an extra area than what is requested. Save the original
  673. * request size in the meta data area, for better debug and sanity check.
  674. */
  675. static inline void set_orig_size(struct kmem_cache *s,
  676. void *object, unsigned int orig_size)
  677. {
  678. void *p = kasan_reset_tag(object);
  679. unsigned int kasan_meta_size;
  680. if (!slub_debug_orig_size(s))
  681. return;
  682. /*
  683. * KASAN can save its free meta data inside of the object at offset 0.
  684. * If this meta data size is larger than 'orig_size', it will overlap
  685. * the data redzone in [orig_size+1, object_size]. Thus, we adjust
  686. * 'orig_size' to be as at least as big as KASAN's meta data.
  687. */
  688. kasan_meta_size = kasan_metadata_size(s, true);
  689. if (kasan_meta_size > orig_size)
  690. orig_size = kasan_meta_size;
  691. p += get_info_end(s);
  692. p += sizeof(struct track) * 2;
  693. *(unsigned int *)p = orig_size;
  694. }
  695. static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
  696. {
  697. void *p = kasan_reset_tag(object);
  698. if (!slub_debug_orig_size(s))
  699. return s->object_size;
  700. p += get_info_end(s);
  701. p += sizeof(struct track) * 2;
  702. return *(unsigned int *)p;
  703. }
  704. #ifdef CONFIG_SLUB_DEBUG
  705. static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
  706. static DEFINE_SPINLOCK(object_map_lock);
  707. static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
  708. struct slab *slab)
  709. {
  710. void *addr = slab_address(slab);
  711. void *p;
  712. bitmap_zero(obj_map, slab->objects);
  713. for (p = slab->freelist; p; p = get_freepointer(s, p))
  714. set_bit(__obj_to_index(s, addr, p), obj_map);
  715. }
  716. #if IS_ENABLED(CONFIG_KUNIT)
  717. static bool slab_add_kunit_errors(void)
  718. {
  719. struct kunit_resource *resource;
  720. if (!kunit_get_current_test())
  721. return false;
  722. resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
  723. if (!resource)
  724. return false;
  725. (*(int *)resource->data)++;
  726. kunit_put_resource(resource);
  727. return true;
  728. }
  729. bool slab_in_kunit_test(void)
  730. {
  731. struct kunit_resource *resource;
  732. if (!kunit_get_current_test())
  733. return false;
  734. resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
  735. if (!resource)
  736. return false;
  737. kunit_put_resource(resource);
  738. return true;
  739. }
  740. #else
  741. static inline bool slab_add_kunit_errors(void) { return false; }
  742. #endif
  743. static inline unsigned int size_from_object(struct kmem_cache *s)
  744. {
  745. if (s->flags & SLAB_RED_ZONE)
  746. return s->size - s->red_left_pad;
  747. return s->size;
  748. }
  749. static inline void *restore_red_left(struct kmem_cache *s, void *p)
  750. {
  751. if (s->flags & SLAB_RED_ZONE)
  752. p -= s->red_left_pad;
  753. return p;
  754. }
  755. /*
  756. * Debug settings:
  757. */
  758. #if defined(CONFIG_SLUB_DEBUG_ON)
  759. static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
  760. #else
  761. static slab_flags_t slub_debug;
  762. #endif
  763. static char *slub_debug_string;
  764. static int disable_higher_order_debug;
  765. /*
  766. * slub is about to manipulate internal object metadata. This memory lies
  767. * outside the range of the allocated object, so accessing it would normally
  768. * be reported by kasan as a bounds error. metadata_access_enable() is used
  769. * to tell kasan that these accesses are OK.
  770. */
  771. static inline void metadata_access_enable(void)
  772. {
  773. kasan_disable_current();
  774. kmsan_disable_current();
  775. }
  776. static inline void metadata_access_disable(void)
  777. {
  778. kmsan_enable_current();
  779. kasan_enable_current();
  780. }
  781. /*
  782. * Object debugging
  783. */
  784. /* Verify that a pointer has an address that is valid within a slab page */
  785. static inline int check_valid_pointer(struct kmem_cache *s,
  786. struct slab *slab, void *object)
  787. {
  788. void *base;
  789. if (!object)
  790. return 1;
  791. base = slab_address(slab);
  792. object = kasan_reset_tag(object);
  793. object = restore_red_left(s, object);
  794. if (object < base || object >= base + slab->objects * s->size ||
  795. (object - base) % s->size) {
  796. return 0;
  797. }
  798. return 1;
  799. }
  800. static void print_section(char *level, char *text, u8 *addr,
  801. unsigned int length)
  802. {
  803. metadata_access_enable();
  804. print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
  805. 16, 1, kasan_reset_tag((void *)addr), length, 1);
  806. metadata_access_disable();
  807. }
  808. static struct track *get_track(struct kmem_cache *s, void *object,
  809. enum track_item alloc)
  810. {
  811. struct track *p;
  812. p = object + get_info_end(s);
  813. return kasan_reset_tag(p + alloc);
  814. }
  815. #ifdef CONFIG_STACKDEPOT
  816. static noinline depot_stack_handle_t set_track_prepare(void)
  817. {
  818. depot_stack_handle_t handle;
  819. unsigned long entries[TRACK_ADDRS_COUNT];
  820. unsigned int nr_entries;
  821. nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
  822. handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT);
  823. return handle;
  824. }
  825. #else
  826. static inline depot_stack_handle_t set_track_prepare(void)
  827. {
  828. return 0;
  829. }
  830. #endif
  831. static void set_track_update(struct kmem_cache *s, void *object,
  832. enum track_item alloc, unsigned long addr,
  833. depot_stack_handle_t handle)
  834. {
  835. struct track *p = get_track(s, object, alloc);
  836. #ifdef CONFIG_STACKDEPOT
  837. p->handle = handle;
  838. #endif
  839. p->addr = addr;
  840. p->cpu = smp_processor_id();
  841. p->pid = current->pid;
  842. p->when = jiffies;
  843. }
  844. static __always_inline void set_track(struct kmem_cache *s, void *object,
  845. enum track_item alloc, unsigned long addr)
  846. {
  847. depot_stack_handle_t handle = set_track_prepare();
  848. set_track_update(s, object, alloc, addr, handle);
  849. }
  850. static void init_tracking(struct kmem_cache *s, void *object)
  851. {
  852. struct track *p;
  853. if (!(s->flags & SLAB_STORE_USER))
  854. return;
  855. p = get_track(s, object, TRACK_ALLOC);
  856. memset(p, 0, 2*sizeof(struct track));
  857. }
  858. static void print_track(const char *s, struct track *t, unsigned long pr_time)
  859. {
  860. depot_stack_handle_t handle __maybe_unused;
  861. if (!t->addr)
  862. return;
  863. pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
  864. s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
  865. #ifdef CONFIG_STACKDEPOT
  866. handle = READ_ONCE(t->handle);
  867. if (handle)
  868. stack_depot_print(handle);
  869. else
  870. pr_err("object allocation/free stack trace missing\n");
  871. #endif
  872. }
  873. void print_tracking(struct kmem_cache *s, void *object)
  874. {
  875. unsigned long pr_time = jiffies;
  876. if (!(s->flags & SLAB_STORE_USER))
  877. return;
  878. print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
  879. print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
  880. }
  881. static void print_slab_info(const struct slab *slab)
  882. {
  883. pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
  884. slab, slab->objects, slab->inuse, slab->freelist,
  885. &slab->__page_flags);
  886. }
  887. void skip_orig_size_check(struct kmem_cache *s, const void *object)
  888. {
  889. set_orig_size(s, (void *)object, s->object_size);
  890. }
  891. static void slab_bug(struct kmem_cache *s, char *fmt, ...)
  892. {
  893. struct va_format vaf;
  894. va_list args;
  895. va_start(args, fmt);
  896. vaf.fmt = fmt;
  897. vaf.va = &args;
  898. pr_err("=============================================================================\n");
  899. pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
  900. pr_err("-----------------------------------------------------------------------------\n\n");
  901. va_end(args);
  902. }
  903. __printf(2, 3)
  904. static void slab_fix(struct kmem_cache *s, char *fmt, ...)
  905. {
  906. struct va_format vaf;
  907. va_list args;
  908. if (slab_add_kunit_errors())
  909. return;
  910. va_start(args, fmt);
  911. vaf.fmt = fmt;
  912. vaf.va = &args;
  913. pr_err("FIX %s: %pV\n", s->name, &vaf);
  914. va_end(args);
  915. }
  916. static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
  917. {
  918. unsigned int off; /* Offset of last byte */
  919. u8 *addr = slab_address(slab);
  920. print_tracking(s, p);
  921. print_slab_info(slab);
  922. pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
  923. p, p - addr, get_freepointer(s, p));
  924. if (s->flags & SLAB_RED_ZONE)
  925. print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
  926. s->red_left_pad);
  927. else if (p > addr + 16)
  928. print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
  929. print_section(KERN_ERR, "Object ", p,
  930. min_t(unsigned int, s->object_size, PAGE_SIZE));
  931. if (s->flags & SLAB_RED_ZONE)
  932. print_section(KERN_ERR, "Redzone ", p + s->object_size,
  933. s->inuse - s->object_size);
  934. off = get_info_end(s);
  935. if (s->flags & SLAB_STORE_USER)
  936. off += 2 * sizeof(struct track);
  937. if (slub_debug_orig_size(s))
  938. off += sizeof(unsigned int);
  939. off += kasan_metadata_size(s, false);
  940. if (off != size_from_object(s))
  941. /* Beginning of the filler is the free pointer */
  942. print_section(KERN_ERR, "Padding ", p + off,
  943. size_from_object(s) - off);
  944. dump_stack();
  945. }
  946. static void object_err(struct kmem_cache *s, struct slab *slab,
  947. u8 *object, char *reason)
  948. {
  949. if (slab_add_kunit_errors())
  950. return;
  951. slab_bug(s, "%s", reason);
  952. print_trailer(s, slab, object);
  953. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  954. }
  955. static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
  956. void **freelist, void *nextfree)
  957. {
  958. if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
  959. !check_valid_pointer(s, slab, nextfree) && freelist) {
  960. object_err(s, slab, *freelist, "Freechain corrupt");
  961. *freelist = NULL;
  962. slab_fix(s, "Isolate corrupted freechain");
  963. return true;
  964. }
  965. return false;
  966. }
  967. static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
  968. const char *fmt, ...)
  969. {
  970. va_list args;
  971. char buf[100];
  972. if (slab_add_kunit_errors())
  973. return;
  974. va_start(args, fmt);
  975. vsnprintf(buf, sizeof(buf), fmt, args);
  976. va_end(args);
  977. slab_bug(s, "%s", buf);
  978. print_slab_info(slab);
  979. dump_stack();
  980. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  981. }
  982. static void init_object(struct kmem_cache *s, void *object, u8 val)
  983. {
  984. u8 *p = kasan_reset_tag(object);
  985. unsigned int poison_size = s->object_size;
  986. if (s->flags & SLAB_RED_ZONE) {
  987. /*
  988. * Here and below, avoid overwriting the KMSAN shadow. Keeping
  989. * the shadow makes it possible to distinguish uninit-value
  990. * from use-after-free.
  991. */
  992. memset_no_sanitize_memory(p - s->red_left_pad, val,
  993. s->red_left_pad);
  994. if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
  995. /*
  996. * Redzone the extra allocated space by kmalloc than
  997. * requested, and the poison size will be limited to
  998. * the original request size accordingly.
  999. */
  1000. poison_size = get_orig_size(s, object);
  1001. }
  1002. }
  1003. if (s->flags & __OBJECT_POISON) {
  1004. memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1);
  1005. memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1);
  1006. }
  1007. if (s->flags & SLAB_RED_ZONE)
  1008. memset_no_sanitize_memory(p + poison_size, val,
  1009. s->inuse - poison_size);
  1010. }
  1011. static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
  1012. void *from, void *to)
  1013. {
  1014. slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
  1015. memset(from, data, to - from);
  1016. }
  1017. #ifdef CONFIG_KMSAN
  1018. #define pad_check_attributes noinline __no_kmsan_checks
  1019. #else
  1020. #define pad_check_attributes
  1021. #endif
  1022. static pad_check_attributes int
  1023. check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
  1024. u8 *object, char *what,
  1025. u8 *start, unsigned int value, unsigned int bytes)
  1026. {
  1027. u8 *fault;
  1028. u8 *end;
  1029. u8 *addr = slab_address(slab);
  1030. metadata_access_enable();
  1031. fault = memchr_inv(kasan_reset_tag(start), value, bytes);
  1032. metadata_access_disable();
  1033. if (!fault)
  1034. return 1;
  1035. end = start + bytes;
  1036. while (end > fault && end[-1] == value)
  1037. end--;
  1038. if (slab_add_kunit_errors())
  1039. goto skip_bug_print;
  1040. slab_bug(s, "%s overwritten", what);
  1041. pr_err("0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
  1042. fault, end - 1, fault - addr,
  1043. fault[0], value);
  1044. skip_bug_print:
  1045. restore_bytes(s, what, value, fault, end);
  1046. return 0;
  1047. }
  1048. /*
  1049. * Object layout:
  1050. *
  1051. * object address
  1052. * Bytes of the object to be managed.
  1053. * If the freepointer may overlay the object then the free
  1054. * pointer is at the middle of the object.
  1055. *
  1056. * Poisoning uses 0x6b (POISON_FREE) and the last byte is
  1057. * 0xa5 (POISON_END)
  1058. *
  1059. * object + s->object_size
  1060. * Padding to reach word boundary. This is also used for Redzoning.
  1061. * Padding is extended by another word if Redzoning is enabled and
  1062. * object_size == inuse.
  1063. *
  1064. * We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with
  1065. * 0xcc (SLUB_RED_ACTIVE) for objects in use.
  1066. *
  1067. * object + s->inuse
  1068. * Meta data starts here.
  1069. *
  1070. * A. Free pointer (if we cannot overwrite object on free)
  1071. * B. Tracking data for SLAB_STORE_USER
  1072. * C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
  1073. * D. Padding to reach required alignment boundary or at minimum
  1074. * one word if debugging is on to be able to detect writes
  1075. * before the word boundary.
  1076. *
  1077. * Padding is done using 0x5a (POISON_INUSE)
  1078. *
  1079. * object + s->size
  1080. * Nothing is used beyond s->size.
  1081. *
  1082. * If slabcaches are merged then the object_size and inuse boundaries are mostly
  1083. * ignored. And therefore no slab options that rely on these boundaries
  1084. * may be used with merged slabcaches.
  1085. */
  1086. static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
  1087. {
  1088. unsigned long off = get_info_end(s); /* The end of info */
  1089. if (s->flags & SLAB_STORE_USER) {
  1090. /* We also have user information there */
  1091. off += 2 * sizeof(struct track);
  1092. if (s->flags & SLAB_KMALLOC)
  1093. off += sizeof(unsigned int);
  1094. }
  1095. off += kasan_metadata_size(s, false);
  1096. if (size_from_object(s) == off)
  1097. return 1;
  1098. return check_bytes_and_report(s, slab, p, "Object padding",
  1099. p + off, POISON_INUSE, size_from_object(s) - off);
  1100. }
  1101. /* Check the pad bytes at the end of a slab page */
  1102. static pad_check_attributes void
  1103. slab_pad_check(struct kmem_cache *s, struct slab *slab)
  1104. {
  1105. u8 *start;
  1106. u8 *fault;
  1107. u8 *end;
  1108. u8 *pad;
  1109. int length;
  1110. int remainder;
  1111. if (!(s->flags & SLAB_POISON))
  1112. return;
  1113. start = slab_address(slab);
  1114. length = slab_size(slab);
  1115. end = start + length;
  1116. remainder = length % s->size;
  1117. if (!remainder)
  1118. return;
  1119. pad = end - remainder;
  1120. metadata_access_enable();
  1121. fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
  1122. metadata_access_disable();
  1123. if (!fault)
  1124. return;
  1125. while (end > fault && end[-1] == POISON_INUSE)
  1126. end--;
  1127. slab_err(s, slab, "Padding overwritten. 0x%p-0x%p @offset=%tu",
  1128. fault, end - 1, fault - start);
  1129. print_section(KERN_ERR, "Padding ", pad, remainder);
  1130. restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
  1131. }
  1132. static int check_object(struct kmem_cache *s, struct slab *slab,
  1133. void *object, u8 val)
  1134. {
  1135. u8 *p = object;
  1136. u8 *endobject = object + s->object_size;
  1137. unsigned int orig_size, kasan_meta_size;
  1138. int ret = 1;
  1139. if (s->flags & SLAB_RED_ZONE) {
  1140. if (!check_bytes_and_report(s, slab, object, "Left Redzone",
  1141. object - s->red_left_pad, val, s->red_left_pad))
  1142. ret = 0;
  1143. if (!check_bytes_and_report(s, slab, object, "Right Redzone",
  1144. endobject, val, s->inuse - s->object_size))
  1145. ret = 0;
  1146. if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
  1147. orig_size = get_orig_size(s, object);
  1148. if (s->object_size > orig_size &&
  1149. !check_bytes_and_report(s, slab, object,
  1150. "kmalloc Redzone", p + orig_size,
  1151. val, s->object_size - orig_size)) {
  1152. ret = 0;
  1153. }
  1154. }
  1155. } else {
  1156. if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
  1157. if (!check_bytes_and_report(s, slab, p, "Alignment padding",
  1158. endobject, POISON_INUSE,
  1159. s->inuse - s->object_size))
  1160. ret = 0;
  1161. }
  1162. }
  1163. if (s->flags & SLAB_POISON) {
  1164. if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) {
  1165. /*
  1166. * KASAN can save its free meta data inside of the
  1167. * object at offset 0. Thus, skip checking the part of
  1168. * the redzone that overlaps with the meta data.
  1169. */
  1170. kasan_meta_size = kasan_metadata_size(s, true);
  1171. if (kasan_meta_size < s->object_size - 1 &&
  1172. !check_bytes_and_report(s, slab, p, "Poison",
  1173. p + kasan_meta_size, POISON_FREE,
  1174. s->object_size - kasan_meta_size - 1))
  1175. ret = 0;
  1176. if (kasan_meta_size < s->object_size &&
  1177. !check_bytes_and_report(s, slab, p, "End Poison",
  1178. p + s->object_size - 1, POISON_END, 1))
  1179. ret = 0;
  1180. }
  1181. /*
  1182. * check_pad_bytes cleans up on its own.
  1183. */
  1184. if (!check_pad_bytes(s, slab, p))
  1185. ret = 0;
  1186. }
  1187. /*
  1188. * Cannot check freepointer while object is allocated if
  1189. * object and freepointer overlap.
  1190. */
  1191. if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
  1192. !check_valid_pointer(s, slab, get_freepointer(s, p))) {
  1193. object_err(s, slab, p, "Freepointer corrupt");
  1194. /*
  1195. * No choice but to zap it and thus lose the remainder
  1196. * of the free objects in this slab. May cause
  1197. * another error because the object count is now wrong.
  1198. */
  1199. set_freepointer(s, p, NULL);
  1200. ret = 0;
  1201. }
  1202. if (!ret && !slab_in_kunit_test()) {
  1203. print_trailer(s, slab, object);
  1204. add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
  1205. }
  1206. return ret;
  1207. }
  1208. static int check_slab(struct kmem_cache *s, struct slab *slab)
  1209. {
  1210. int maxobj;
  1211. if (!folio_test_slab(slab_folio(slab))) {
  1212. slab_err(s, slab, "Not a valid slab page");
  1213. return 0;
  1214. }
  1215. maxobj = order_objects(slab_order(slab), s->size);
  1216. if (slab->objects > maxobj) {
  1217. slab_err(s, slab, "objects %u > max %u",
  1218. slab->objects, maxobj);
  1219. return 0;
  1220. }
  1221. if (slab->inuse > slab->objects) {
  1222. slab_err(s, slab, "inuse %u > max %u",
  1223. slab->inuse, slab->objects);
  1224. return 0;
  1225. }
  1226. if (slab->frozen) {
  1227. slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
  1228. return 0;
  1229. }
  1230. /* Slab_pad_check fixes things up after itself */
  1231. slab_pad_check(s, slab);
  1232. return 1;
  1233. }
  1234. /*
  1235. * Determine if a certain object in a slab is on the freelist. Must hold the
  1236. * slab lock to guarantee that the chains are in a consistent state.
  1237. */
  1238. static int on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
  1239. {
  1240. int nr = 0;
  1241. void *fp;
  1242. void *object = NULL;
  1243. int max_objects;
  1244. fp = slab->freelist;
  1245. while (fp && nr <= slab->objects) {
  1246. if (fp == search)
  1247. return 1;
  1248. if (!check_valid_pointer(s, slab, fp)) {
  1249. if (object) {
  1250. object_err(s, slab, object,
  1251. "Freechain corrupt");
  1252. set_freepointer(s, object, NULL);
  1253. } else {
  1254. slab_err(s, slab, "Freepointer corrupt");
  1255. slab->freelist = NULL;
  1256. slab->inuse = slab->objects;
  1257. slab_fix(s, "Freelist cleared");
  1258. return 0;
  1259. }
  1260. break;
  1261. }
  1262. object = fp;
  1263. fp = get_freepointer(s, object);
  1264. nr++;
  1265. }
  1266. max_objects = order_objects(slab_order(slab), s->size);
  1267. if (max_objects > MAX_OBJS_PER_PAGE)
  1268. max_objects = MAX_OBJS_PER_PAGE;
  1269. if (slab->objects != max_objects) {
  1270. slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
  1271. slab->objects, max_objects);
  1272. slab->objects = max_objects;
  1273. slab_fix(s, "Number of objects adjusted");
  1274. }
  1275. if (slab->inuse != slab->objects - nr) {
  1276. slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
  1277. slab->inuse, slab->objects - nr);
  1278. slab->inuse = slab->objects - nr;
  1279. slab_fix(s, "Object count adjusted");
  1280. }
  1281. return search == NULL;
  1282. }
  1283. static void trace(struct kmem_cache *s, struct slab *slab, void *object,
  1284. int alloc)
  1285. {
  1286. if (s->flags & SLAB_TRACE) {
  1287. pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
  1288. s->name,
  1289. alloc ? "alloc" : "free",
  1290. object, slab->inuse,
  1291. slab->freelist);
  1292. if (!alloc)
  1293. print_section(KERN_INFO, "Object ", (void *)object,
  1294. s->object_size);
  1295. dump_stack();
  1296. }
  1297. }
  1298. /*
  1299. * Tracking of fully allocated slabs for debugging purposes.
  1300. */
  1301. static void add_full(struct kmem_cache *s,
  1302. struct kmem_cache_node *n, struct slab *slab)
  1303. {
  1304. if (!(s->flags & SLAB_STORE_USER))
  1305. return;
  1306. lockdep_assert_held(&n->list_lock);
  1307. list_add(&slab->slab_list, &n->full);
  1308. }
  1309. static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
  1310. {
  1311. if (!(s->flags & SLAB_STORE_USER))
  1312. return;
  1313. lockdep_assert_held(&n->list_lock);
  1314. list_del(&slab->slab_list);
  1315. }
  1316. static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
  1317. {
  1318. return atomic_long_read(&n->nr_slabs);
  1319. }
  1320. static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
  1321. {
  1322. struct kmem_cache_node *n = get_node(s, node);
  1323. atomic_long_inc(&n->nr_slabs);
  1324. atomic_long_add(objects, &n->total_objects);
  1325. }
  1326. static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
  1327. {
  1328. struct kmem_cache_node *n = get_node(s, node);
  1329. atomic_long_dec(&n->nr_slabs);
  1330. atomic_long_sub(objects, &n->total_objects);
  1331. }
  1332. /* Object debug checks for alloc/free paths */
  1333. static void setup_object_debug(struct kmem_cache *s, void *object)
  1334. {
  1335. if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
  1336. return;
  1337. init_object(s, object, SLUB_RED_INACTIVE);
  1338. init_tracking(s, object);
  1339. }
  1340. static
  1341. void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
  1342. {
  1343. if (!kmem_cache_debug_flags(s, SLAB_POISON))
  1344. return;
  1345. metadata_access_enable();
  1346. memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
  1347. metadata_access_disable();
  1348. }
  1349. static inline int alloc_consistency_checks(struct kmem_cache *s,
  1350. struct slab *slab, void *object)
  1351. {
  1352. if (!check_slab(s, slab))
  1353. return 0;
  1354. if (!check_valid_pointer(s, slab, object)) {
  1355. object_err(s, slab, object, "Freelist Pointer check fails");
  1356. return 0;
  1357. }
  1358. if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
  1359. return 0;
  1360. return 1;
  1361. }
  1362. static noinline bool alloc_debug_processing(struct kmem_cache *s,
  1363. struct slab *slab, void *object, int orig_size)
  1364. {
  1365. if (s->flags & SLAB_CONSISTENCY_CHECKS) {
  1366. if (!alloc_consistency_checks(s, slab, object))
  1367. goto bad;
  1368. }
  1369. /* Success. Perform special debug activities for allocs */
  1370. trace(s, slab, object, 1);
  1371. set_orig_size(s, object, orig_size);
  1372. init_object(s, object, SLUB_RED_ACTIVE);
  1373. return true;
  1374. bad:
  1375. if (folio_test_slab(slab_folio(slab))) {
  1376. /*
  1377. * If this is a slab page then lets do the best we can
  1378. * to avoid issues in the future. Marking all objects
  1379. * as used avoids touching the remaining objects.
  1380. */
  1381. slab_fix(s, "Marking all objects used");
  1382. slab->inuse = slab->objects;
  1383. slab->freelist = NULL;
  1384. slab->frozen = 1; /* mark consistency-failed slab as frozen */
  1385. }
  1386. return false;
  1387. }
  1388. static inline int free_consistency_checks(struct kmem_cache *s,
  1389. struct slab *slab, void *object, unsigned long addr)
  1390. {
  1391. if (!check_valid_pointer(s, slab, object)) {
  1392. slab_err(s, slab, "Invalid object pointer 0x%p", object);
  1393. return 0;
  1394. }
  1395. if (on_freelist(s, slab, object)) {
  1396. object_err(s, slab, object, "Object already free");
  1397. return 0;
  1398. }
  1399. if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
  1400. return 0;
  1401. if (unlikely(s != slab->slab_cache)) {
  1402. if (!folio_test_slab(slab_folio(slab))) {
  1403. slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
  1404. object);
  1405. } else if (!slab->slab_cache) {
  1406. pr_err("SLUB <none>: no slab for object 0x%p.\n",
  1407. object);
  1408. dump_stack();
  1409. } else
  1410. object_err(s, slab, object,
  1411. "page slab pointer corrupt.");
  1412. return 0;
  1413. }
  1414. return 1;
  1415. }
  1416. /*
  1417. * Parse a block of slab_debug options. Blocks are delimited by ';'
  1418. *
  1419. * @str: start of block
  1420. * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
  1421. * @slabs: return start of list of slabs, or NULL when there's no list
  1422. * @init: assume this is initial parsing and not per-kmem-create parsing
  1423. *
  1424. * returns the start of next block if there's any, or NULL
  1425. */
  1426. static char *
  1427. parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
  1428. {
  1429. bool higher_order_disable = false;
  1430. /* Skip any completely empty blocks */
  1431. while (*str && *str == ';')
  1432. str++;
  1433. if (*str == ',') {
  1434. /*
  1435. * No options but restriction on slabs. This means full
  1436. * debugging for slabs matching a pattern.
  1437. */
  1438. *flags = DEBUG_DEFAULT_FLAGS;
  1439. goto check_slabs;
  1440. }
  1441. *flags = 0;
  1442. /* Determine which debug features should be switched on */
  1443. for (; *str && *str != ',' && *str != ';'; str++) {
  1444. switch (tolower(*str)) {
  1445. case '-':
  1446. *flags = 0;
  1447. break;
  1448. case 'f':
  1449. *flags |= SLAB_CONSISTENCY_CHECKS;
  1450. break;
  1451. case 'z':
  1452. *flags |= SLAB_RED_ZONE;
  1453. break;
  1454. case 'p':
  1455. *flags |= SLAB_POISON;
  1456. break;
  1457. case 'u':
  1458. *flags |= SLAB_STORE_USER;
  1459. break;
  1460. case 't':
  1461. *flags |= SLAB_TRACE;
  1462. break;
  1463. case 'a':
  1464. *flags |= SLAB_FAILSLAB;
  1465. break;
  1466. case 'o':
  1467. /*
  1468. * Avoid enabling debugging on caches if its minimum
  1469. * order would increase as a result.
  1470. */
  1471. higher_order_disable = true;
  1472. break;
  1473. default:
  1474. if (init)
  1475. pr_err("slab_debug option '%c' unknown. skipped\n", *str);
  1476. }
  1477. }
  1478. check_slabs:
  1479. if (*str == ',')
  1480. *slabs = ++str;
  1481. else
  1482. *slabs = NULL;
  1483. /* Skip over the slab list */
  1484. while (*str && *str != ';')
  1485. str++;
  1486. /* Skip any completely empty blocks */
  1487. while (*str && *str == ';')
  1488. str++;
  1489. if (init && higher_order_disable)
  1490. disable_higher_order_debug = 1;
  1491. if (*str)
  1492. return str;
  1493. else
  1494. return NULL;
  1495. }
  1496. static int __init setup_slub_debug(char *str)
  1497. {
  1498. slab_flags_t flags;
  1499. slab_flags_t global_flags;
  1500. char *saved_str;
  1501. char *slab_list;
  1502. bool global_slub_debug_changed = false;
  1503. bool slab_list_specified = false;
  1504. global_flags = DEBUG_DEFAULT_FLAGS;
  1505. if (*str++ != '=' || !*str)
  1506. /*
  1507. * No options specified. Switch on full debugging.
  1508. */
  1509. goto out;
  1510. saved_str = str;
  1511. while (str) {
  1512. str = parse_slub_debug_flags(str, &flags, &slab_list, true);
  1513. if (!slab_list) {
  1514. global_flags = flags;
  1515. global_slub_debug_changed = true;
  1516. } else {
  1517. slab_list_specified = true;
  1518. if (flags & SLAB_STORE_USER)
  1519. stack_depot_request_early_init();
  1520. }
  1521. }
  1522. /*
  1523. * For backwards compatibility, a single list of flags with list of
  1524. * slabs means debugging is only changed for those slabs, so the global
  1525. * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
  1526. * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
  1527. * long as there is no option specifying flags without a slab list.
  1528. */
  1529. if (slab_list_specified) {
  1530. if (!global_slub_debug_changed)
  1531. global_flags = slub_debug;
  1532. slub_debug_string = saved_str;
  1533. }
  1534. out:
  1535. slub_debug = global_flags;
  1536. if (slub_debug & SLAB_STORE_USER)
  1537. stack_depot_request_early_init();
  1538. if (slub_debug != 0 || slub_debug_string)
  1539. static_branch_enable(&slub_debug_enabled);
  1540. else
  1541. static_branch_disable(&slub_debug_enabled);
  1542. if ((static_branch_unlikely(&init_on_alloc) ||
  1543. static_branch_unlikely(&init_on_free)) &&
  1544. (slub_debug & SLAB_POISON))
  1545. pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
  1546. return 1;
  1547. }
  1548. __setup("slab_debug", setup_slub_debug);
  1549. __setup_param("slub_debug", slub_debug, setup_slub_debug, 0);
  1550. /*
  1551. * kmem_cache_flags - apply debugging options to the cache
  1552. * @flags: flags to set
  1553. * @name: name of the cache
  1554. *
  1555. * Debug option(s) are applied to @flags. In addition to the debug
  1556. * option(s), if a slab name (or multiple) is specified i.e.
  1557. * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ...
  1558. * then only the select slabs will receive the debug option(s).
  1559. */
  1560. slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
  1561. {
  1562. char *iter;
  1563. size_t len;
  1564. char *next_block;
  1565. slab_flags_t block_flags;
  1566. slab_flags_t slub_debug_local = slub_debug;
  1567. if (flags & SLAB_NO_USER_FLAGS)
  1568. return flags;
  1569. /*
  1570. * If the slab cache is for debugging (e.g. kmemleak) then
  1571. * don't store user (stack trace) information by default,
  1572. * but let the user enable it via the command line below.
  1573. */
  1574. if (flags & SLAB_NOLEAKTRACE)
  1575. slub_debug_local &= ~SLAB_STORE_USER;
  1576. len = strlen(name);
  1577. next_block = slub_debug_string;
  1578. /* Go through all blocks of debug options, see if any matches our slab's name */
  1579. while (next_block) {
  1580. next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
  1581. if (!iter)
  1582. continue;
  1583. /* Found a block that has a slab list, search it */
  1584. while (*iter) {
  1585. char *end, *glob;
  1586. size_t cmplen;
  1587. end = strchrnul(iter, ',');
  1588. if (next_block && next_block < end)
  1589. end = next_block - 1;
  1590. glob = strnchr(iter, end - iter, '*');
  1591. if (glob)
  1592. cmplen = glob - iter;
  1593. else
  1594. cmplen = max_t(size_t, len, (end - iter));
  1595. if (!strncmp(name, iter, cmplen)) {
  1596. flags |= block_flags;
  1597. return flags;
  1598. }
  1599. if (!*end || *end == ';')
  1600. break;
  1601. iter = end + 1;
  1602. }
  1603. }
  1604. return flags | slub_debug_local;
  1605. }
  1606. #else /* !CONFIG_SLUB_DEBUG */
  1607. static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
  1608. static inline
  1609. void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
  1610. static inline bool alloc_debug_processing(struct kmem_cache *s,
  1611. struct slab *slab, void *object, int orig_size) { return true; }
  1612. static inline bool free_debug_processing(struct kmem_cache *s,
  1613. struct slab *slab, void *head, void *tail, int *bulk_cnt,
  1614. unsigned long addr, depot_stack_handle_t handle) { return true; }
  1615. static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
  1616. static inline int check_object(struct kmem_cache *s, struct slab *slab,
  1617. void *object, u8 val) { return 1; }
  1618. static inline depot_stack_handle_t set_track_prepare(void) { return 0; }
  1619. static inline void set_track(struct kmem_cache *s, void *object,
  1620. enum track_item alloc, unsigned long addr) {}
  1621. static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
  1622. struct slab *slab) {}
  1623. static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
  1624. struct slab *slab) {}
  1625. slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
  1626. {
  1627. return flags;
  1628. }
  1629. #define slub_debug 0
  1630. #define disable_higher_order_debug 0
  1631. static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
  1632. { return 0; }
  1633. static inline void inc_slabs_node(struct kmem_cache *s, int node,
  1634. int objects) {}
  1635. static inline void dec_slabs_node(struct kmem_cache *s, int node,
  1636. int objects) {}
  1637. #ifndef CONFIG_SLUB_TINY
  1638. static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
  1639. void **freelist, void *nextfree)
  1640. {
  1641. return false;
  1642. }
  1643. #endif
  1644. #endif /* CONFIG_SLUB_DEBUG */
  1645. #ifdef CONFIG_SLAB_OBJ_EXT
  1646. #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
  1647. static inline void mark_objexts_empty(struct slabobj_ext *obj_exts)
  1648. {
  1649. struct slabobj_ext *slab_exts;
  1650. struct slab *obj_exts_slab;
  1651. obj_exts_slab = virt_to_slab(obj_exts);
  1652. slab_exts = slab_obj_exts(obj_exts_slab);
  1653. if (slab_exts) {
  1654. unsigned int offs = obj_to_index(obj_exts_slab->slab_cache,
  1655. obj_exts_slab, obj_exts);
  1656. /* codetag should be NULL */
  1657. WARN_ON(slab_exts[offs].ref.ct);
  1658. set_codetag_empty(&slab_exts[offs].ref);
  1659. }
  1660. }
  1661. static inline void mark_failed_objexts_alloc(struct slab *slab)
  1662. {
  1663. slab->obj_exts = OBJEXTS_ALLOC_FAIL;
  1664. }
  1665. static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
  1666. struct slabobj_ext *vec, unsigned int objects)
  1667. {
  1668. /*
  1669. * If vector previously failed to allocate then we have live
  1670. * objects with no tag reference. Mark all references in this
  1671. * vector as empty to avoid warnings later on.
  1672. */
  1673. if (obj_exts & OBJEXTS_ALLOC_FAIL) {
  1674. unsigned int i;
  1675. for (i = 0; i < objects; i++)
  1676. set_codetag_empty(&vec[i].ref);
  1677. }
  1678. }
  1679. #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
  1680. static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) {}
  1681. static inline void mark_failed_objexts_alloc(struct slab *slab) {}
  1682. static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
  1683. struct slabobj_ext *vec, unsigned int objects) {}
  1684. #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
  1685. /*
  1686. * The allocated objcg pointers array is not accounted directly.
  1687. * Moreover, it should not come from DMA buffer and is not readily
  1688. * reclaimable. So those GFP bits should be masked off.
  1689. */
  1690. #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
  1691. __GFP_ACCOUNT | __GFP_NOFAIL)
  1692. int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
  1693. gfp_t gfp, bool new_slab)
  1694. {
  1695. unsigned int objects = objs_per_slab(s, slab);
  1696. unsigned long new_exts;
  1697. unsigned long old_exts;
  1698. struct slabobj_ext *vec;
  1699. gfp &= ~OBJCGS_CLEAR_MASK;
  1700. /* Prevent recursive extension vector allocation */
  1701. gfp |= __GFP_NO_OBJ_EXT;
  1702. vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp,
  1703. slab_nid(slab));
  1704. if (!vec) {
  1705. /* Mark vectors which failed to allocate */
  1706. if (new_slab)
  1707. mark_failed_objexts_alloc(slab);
  1708. return -ENOMEM;
  1709. }
  1710. new_exts = (unsigned long)vec;
  1711. #ifdef CONFIG_MEMCG
  1712. new_exts |= MEMCG_DATA_OBJEXTS;
  1713. #endif
  1714. old_exts = READ_ONCE(slab->obj_exts);
  1715. handle_failed_objexts_alloc(old_exts, vec, objects);
  1716. if (new_slab) {
  1717. /*
  1718. * If the slab is brand new and nobody can yet access its
  1719. * obj_exts, no synchronization is required and obj_exts can
  1720. * be simply assigned.
  1721. */
  1722. slab->obj_exts = new_exts;
  1723. } else if ((old_exts & ~OBJEXTS_FLAGS_MASK) ||
  1724. cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) {
  1725. /*
  1726. * If the slab is already in use, somebody can allocate and
  1727. * assign slabobj_exts in parallel. In this case the existing
  1728. * objcg vector should be reused.
  1729. */
  1730. mark_objexts_empty(vec);
  1731. kfree(vec);
  1732. return 0;
  1733. }
  1734. kmemleak_not_leak(vec);
  1735. return 0;
  1736. }
  1737. static inline void free_slab_obj_exts(struct slab *slab)
  1738. {
  1739. struct slabobj_ext *obj_exts;
  1740. obj_exts = slab_obj_exts(slab);
  1741. if (!obj_exts)
  1742. return;
  1743. /*
  1744. * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its
  1745. * corresponding extension will be NULL. alloc_tag_sub() will throw a
  1746. * warning if slab has extensions but the extension of an object is
  1747. * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that
  1748. * the extension for obj_exts is expected to be NULL.
  1749. */
  1750. mark_objexts_empty(obj_exts);
  1751. kfree(obj_exts);
  1752. slab->obj_exts = 0;
  1753. }
  1754. static inline bool need_slab_obj_ext(void)
  1755. {
  1756. if (mem_alloc_profiling_enabled())
  1757. return true;
  1758. /*
  1759. * CONFIG_MEMCG creates vector of obj_cgroup objects conditionally
  1760. * inside memcg_slab_post_alloc_hook. No other users for now.
  1761. */
  1762. return false;
  1763. }
  1764. #else /* CONFIG_SLAB_OBJ_EXT */
  1765. static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
  1766. gfp_t gfp, bool new_slab)
  1767. {
  1768. return 0;
  1769. }
  1770. static inline void free_slab_obj_exts(struct slab *slab)
  1771. {
  1772. }
  1773. static inline bool need_slab_obj_ext(void)
  1774. {
  1775. return false;
  1776. }
  1777. #endif /* CONFIG_SLAB_OBJ_EXT */
  1778. #ifdef CONFIG_MEM_ALLOC_PROFILING
  1779. static inline struct slabobj_ext *
  1780. prepare_slab_obj_exts_hook(struct kmem_cache *s, gfp_t flags, void *p)
  1781. {
  1782. struct slab *slab;
  1783. if (!p)
  1784. return NULL;
  1785. if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
  1786. return NULL;
  1787. if (flags & __GFP_NO_OBJ_EXT)
  1788. return NULL;
  1789. slab = virt_to_slab(p);
  1790. if (!slab_obj_exts(slab) &&
  1791. WARN(alloc_slab_obj_exts(slab, s, flags, false),
  1792. "%s, %s: Failed to create slab extension vector!\n",
  1793. __func__, s->name))
  1794. return NULL;
  1795. return slab_obj_exts(slab) + obj_to_index(s, slab, p);
  1796. }
  1797. static inline void
  1798. alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
  1799. {
  1800. if (need_slab_obj_ext()) {
  1801. struct slabobj_ext *obj_exts;
  1802. obj_exts = prepare_slab_obj_exts_hook(s, flags, object);
  1803. /*
  1804. * Currently obj_exts is used only for allocation profiling.
  1805. * If other users appear then mem_alloc_profiling_enabled()
  1806. * check should be added before alloc_tag_add().
  1807. */
  1808. if (likely(obj_exts))
  1809. alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size);
  1810. }
  1811. }
  1812. static inline void
  1813. alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
  1814. int objects)
  1815. {
  1816. struct slabobj_ext *obj_exts;
  1817. int i;
  1818. if (!mem_alloc_profiling_enabled())
  1819. return;
  1820. /* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */
  1821. if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
  1822. return;
  1823. obj_exts = slab_obj_exts(slab);
  1824. if (!obj_exts)
  1825. return;
  1826. for (i = 0; i < objects; i++) {
  1827. unsigned int off = obj_to_index(s, slab, p[i]);
  1828. alloc_tag_sub(&obj_exts[off].ref, s->size);
  1829. }
  1830. }
  1831. #else /* CONFIG_MEM_ALLOC_PROFILING */
  1832. static inline void
  1833. alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
  1834. {
  1835. }
  1836. static inline void
  1837. alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
  1838. int objects)
  1839. {
  1840. }
  1841. #endif /* CONFIG_MEM_ALLOC_PROFILING */
  1842. #ifdef CONFIG_MEMCG
  1843. static void memcg_alloc_abort_single(struct kmem_cache *s, void *object);
  1844. static __fastpath_inline
  1845. bool memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
  1846. gfp_t flags, size_t size, void **p)
  1847. {
  1848. if (likely(!memcg_kmem_online()))
  1849. return true;
  1850. if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT)))
  1851. return true;
  1852. if (likely(__memcg_slab_post_alloc_hook(s, lru, flags, size, p)))
  1853. return true;
  1854. if (likely(size == 1)) {
  1855. memcg_alloc_abort_single(s, *p);
  1856. *p = NULL;
  1857. } else {
  1858. kmem_cache_free_bulk(s, size, p);
  1859. }
  1860. return false;
  1861. }
  1862. static __fastpath_inline
  1863. void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
  1864. int objects)
  1865. {
  1866. struct slabobj_ext *obj_exts;
  1867. if (!memcg_kmem_online())
  1868. return;
  1869. obj_exts = slab_obj_exts(slab);
  1870. if (likely(!obj_exts))
  1871. return;
  1872. __memcg_slab_free_hook(s, slab, p, objects, obj_exts);
  1873. }
  1874. static __fastpath_inline
  1875. bool memcg_slab_post_charge(void *p, gfp_t flags)
  1876. {
  1877. struct slabobj_ext *slab_exts;
  1878. struct kmem_cache *s;
  1879. struct folio *folio;
  1880. struct slab *slab;
  1881. unsigned long off;
  1882. folio = virt_to_folio(p);
  1883. if (!folio_test_slab(folio)) {
  1884. int size;
  1885. if (folio_memcg_kmem(folio))
  1886. return true;
  1887. if (__memcg_kmem_charge_page(folio_page(folio, 0), flags,
  1888. folio_order(folio)))
  1889. return false;
  1890. /*
  1891. * This folio has already been accounted in the global stats but
  1892. * not in the memcg stats. So, subtract from the global and use
  1893. * the interface which adds to both global and memcg stats.
  1894. */
  1895. size = folio_size(folio);
  1896. node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size);
  1897. lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size);
  1898. return true;
  1899. }
  1900. slab = folio_slab(folio);
  1901. s = slab->slab_cache;
  1902. /*
  1903. * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency
  1904. * of slab_obj_exts being allocated from the same slab and thus the slab
  1905. * becoming effectively unfreeable.
  1906. */
  1907. if (is_kmalloc_normal(s))
  1908. return true;
  1909. /* Ignore already charged objects. */
  1910. slab_exts = slab_obj_exts(slab);
  1911. if (slab_exts) {
  1912. off = obj_to_index(s, slab, p);
  1913. if (unlikely(slab_exts[off].objcg))
  1914. return true;
  1915. }
  1916. return __memcg_slab_post_alloc_hook(s, NULL, flags, 1, &p);
  1917. }
  1918. #else /* CONFIG_MEMCG */
  1919. static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s,
  1920. struct list_lru *lru,
  1921. gfp_t flags, size_t size,
  1922. void **p)
  1923. {
  1924. return true;
  1925. }
  1926. static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
  1927. void **p, int objects)
  1928. {
  1929. }
  1930. static inline bool memcg_slab_post_charge(void *p, gfp_t flags)
  1931. {
  1932. return true;
  1933. }
  1934. #endif /* CONFIG_MEMCG */
  1935. #ifdef CONFIG_SLUB_RCU_DEBUG
  1936. static void slab_free_after_rcu_debug(struct rcu_head *rcu_head);
  1937. struct rcu_delayed_free {
  1938. struct rcu_head head;
  1939. void *object;
  1940. };
  1941. #endif
  1942. /*
  1943. * Hooks for other subsystems that check memory allocations. In a typical
  1944. * production configuration these hooks all should produce no code at all.
  1945. *
  1946. * Returns true if freeing of the object can proceed, false if its reuse
  1947. * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned
  1948. * to KFENCE.
  1949. */
  1950. static __always_inline
  1951. bool slab_free_hook(struct kmem_cache *s, void *x, bool init,
  1952. bool after_rcu_delay)
  1953. {
  1954. /* Are the object contents still accessible? */
  1955. bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
  1956. kmemleak_free_recursive(x, s->flags);
  1957. kmsan_slab_free(s, x);
  1958. debug_check_no_locks_freed(x, s->object_size);
  1959. if (!(s->flags & SLAB_DEBUG_OBJECTS))
  1960. debug_check_no_obj_freed(x, s->object_size);
  1961. /* Use KCSAN to help debug racy use-after-free. */
  1962. if (!still_accessible)
  1963. __kcsan_check_access(x, s->object_size,
  1964. KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
  1965. if (kfence_free(x))
  1966. return false;
  1967. /*
  1968. * Give KASAN a chance to notice an invalid free operation before we
  1969. * modify the object.
  1970. */
  1971. if (kasan_slab_pre_free(s, x))
  1972. return false;
  1973. #ifdef CONFIG_SLUB_RCU_DEBUG
  1974. if (still_accessible) {
  1975. struct rcu_delayed_free *delayed_free;
  1976. delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT);
  1977. if (delayed_free) {
  1978. /*
  1979. * Let KASAN track our call stack as a "related work
  1980. * creation", just like if the object had been freed
  1981. * normally via kfree_rcu().
  1982. * We have to do this manually because the rcu_head is
  1983. * not located inside the object.
  1984. */
  1985. kasan_record_aux_stack_noalloc(x);
  1986. delayed_free->object = x;
  1987. call_rcu(&delayed_free->head, slab_free_after_rcu_debug);
  1988. return false;
  1989. }
  1990. }
  1991. #endif /* CONFIG_SLUB_RCU_DEBUG */
  1992. /*
  1993. * As memory initialization might be integrated into KASAN,
  1994. * kasan_slab_free and initialization memset's must be
  1995. * kept together to avoid discrepancies in behavior.
  1996. *
  1997. * The initialization memset's clear the object and the metadata,
  1998. * but don't touch the SLAB redzone.
  1999. *
  2000. * The object's freepointer is also avoided if stored outside the
  2001. * object.
  2002. */
  2003. if (unlikely(init)) {
  2004. int rsize;
  2005. unsigned int inuse, orig_size;
  2006. inuse = get_info_end(s);
  2007. orig_size = get_orig_size(s, x);
  2008. if (!kasan_has_integrated_init())
  2009. memset(kasan_reset_tag(x), 0, orig_size);
  2010. rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
  2011. memset((char *)kasan_reset_tag(x) + inuse, 0,
  2012. s->size - inuse - rsize);
  2013. /*
  2014. * Restore orig_size, otherwize kmalloc redzone overwritten
  2015. * would be reported
  2016. */
  2017. set_orig_size(s, x, orig_size);
  2018. }
  2019. /* KASAN might put x into memory quarantine, delaying its reuse. */
  2020. return !kasan_slab_free(s, x, init, still_accessible);
  2021. }
  2022. static __fastpath_inline
  2023. bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail,
  2024. int *cnt)
  2025. {
  2026. void *object;
  2027. void *next = *head;
  2028. void *old_tail = *tail;
  2029. bool init;
  2030. if (is_kfence_address(next)) {
  2031. slab_free_hook(s, next, false, false);
  2032. return false;
  2033. }
  2034. /* Head and tail of the reconstructed freelist */
  2035. *head = NULL;
  2036. *tail = NULL;
  2037. init = slab_want_init_on_free(s);
  2038. do {
  2039. object = next;
  2040. next = get_freepointer(s, object);
  2041. /* If object's reuse doesn't have to be delayed */
  2042. if (likely(slab_free_hook(s, object, init, false))) {
  2043. /* Move object to the new freelist */
  2044. set_freepointer(s, object, *head);
  2045. *head = object;
  2046. if (!*tail)
  2047. *tail = object;
  2048. } else {
  2049. /*
  2050. * Adjust the reconstructed freelist depth
  2051. * accordingly if object's reuse is delayed.
  2052. */
  2053. --(*cnt);
  2054. }
  2055. } while (object != old_tail);
  2056. return *head != NULL;
  2057. }
  2058. static void *setup_object(struct kmem_cache *s, void *object)
  2059. {
  2060. setup_object_debug(s, object);
  2061. object = kasan_init_slab_obj(s, object);
  2062. if (unlikely(s->ctor)) {
  2063. kasan_unpoison_new_object(s, object);
  2064. s->ctor(object);
  2065. kasan_poison_new_object(s, object);
  2066. }
  2067. return object;
  2068. }
  2069. /*
  2070. * Slab allocation and freeing
  2071. */
  2072. static inline struct slab *alloc_slab_page(gfp_t flags, int node,
  2073. struct kmem_cache_order_objects oo)
  2074. {
  2075. struct folio *folio;
  2076. struct slab *slab;
  2077. unsigned int order = oo_order(oo);
  2078. if (node == NUMA_NO_NODE)
  2079. folio = (struct folio *)alloc_pages(flags, order);
  2080. else
  2081. folio = (struct folio *)__alloc_pages_node(node, flags, order);
  2082. if (!folio)
  2083. return NULL;
  2084. slab = folio_slab(folio);
  2085. __folio_set_slab(folio);
  2086. /* Make the flag visible before any changes to folio->mapping */
  2087. smp_wmb();
  2088. if (folio_is_pfmemalloc(folio))
  2089. slab_set_pfmemalloc(slab);
  2090. return slab;
  2091. }
  2092. #ifdef CONFIG_SLAB_FREELIST_RANDOM
  2093. /* Pre-initialize the random sequence cache */
  2094. static int init_cache_random_seq(struct kmem_cache *s)
  2095. {
  2096. unsigned int count = oo_objects(s->oo);
  2097. int err;
  2098. /* Bailout if already initialised */
  2099. if (s->random_seq)
  2100. return 0;
  2101. err = cache_random_seq_create(s, count, GFP_KERNEL);
  2102. if (err) {
  2103. pr_err("SLUB: Unable to initialize free list for %s\n",
  2104. s->name);
  2105. return err;
  2106. }
  2107. /* Transform to an offset on the set of pages */
  2108. if (s->random_seq) {
  2109. unsigned int i;
  2110. for (i = 0; i < count; i++)
  2111. s->random_seq[i] *= s->size;
  2112. }
  2113. return 0;
  2114. }
  2115. /* Initialize each random sequence freelist per cache */
  2116. static void __init init_freelist_randomization(void)
  2117. {
  2118. struct kmem_cache *s;
  2119. mutex_lock(&slab_mutex);
  2120. list_for_each_entry(s, &slab_caches, list)
  2121. init_cache_random_seq(s);
  2122. mutex_unlock(&slab_mutex);
  2123. }
  2124. /* Get the next entry on the pre-computed freelist randomized */
  2125. static void *next_freelist_entry(struct kmem_cache *s,
  2126. unsigned long *pos, void *start,
  2127. unsigned long page_limit,
  2128. unsigned long freelist_count)
  2129. {
  2130. unsigned int idx;
  2131. /*
  2132. * If the target page allocation failed, the number of objects on the
  2133. * page might be smaller than the usual size defined by the cache.
  2134. */
  2135. do {
  2136. idx = s->random_seq[*pos];
  2137. *pos += 1;
  2138. if (*pos >= freelist_count)
  2139. *pos = 0;
  2140. } while (unlikely(idx >= page_limit));
  2141. return (char *)start + idx;
  2142. }
  2143. /* Shuffle the single linked freelist based on a random pre-computed sequence */
  2144. static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
  2145. {
  2146. void *start;
  2147. void *cur;
  2148. void *next;
  2149. unsigned long idx, pos, page_limit, freelist_count;
  2150. if (slab->objects < 2 || !s->random_seq)
  2151. return false;
  2152. freelist_count = oo_objects(s->oo);
  2153. pos = get_random_u32_below(freelist_count);
  2154. page_limit = slab->objects * s->size;
  2155. start = fixup_red_left(s, slab_address(slab));
  2156. /* First entry is used as the base of the freelist */
  2157. cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count);
  2158. cur = setup_object(s, cur);
  2159. slab->freelist = cur;
  2160. for (idx = 1; idx < slab->objects; idx++) {
  2161. next = next_freelist_entry(s, &pos, start, page_limit,
  2162. freelist_count);
  2163. next = setup_object(s, next);
  2164. set_freepointer(s, cur, next);
  2165. cur = next;
  2166. }
  2167. set_freepointer(s, cur, NULL);
  2168. return true;
  2169. }
  2170. #else
  2171. static inline int init_cache_random_seq(struct kmem_cache *s)
  2172. {
  2173. return 0;
  2174. }
  2175. static inline void init_freelist_randomization(void) { }
  2176. static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
  2177. {
  2178. return false;
  2179. }
  2180. #endif /* CONFIG_SLAB_FREELIST_RANDOM */
  2181. static __always_inline void account_slab(struct slab *slab, int order,
  2182. struct kmem_cache *s, gfp_t gfp)
  2183. {
  2184. if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT))
  2185. alloc_slab_obj_exts(slab, s, gfp, true);
  2186. mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
  2187. PAGE_SIZE << order);
  2188. }
  2189. static __always_inline void unaccount_slab(struct slab *slab, int order,
  2190. struct kmem_cache *s)
  2191. {
  2192. if (memcg_kmem_online() || need_slab_obj_ext())
  2193. free_slab_obj_exts(slab);
  2194. mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
  2195. -(PAGE_SIZE << order));
  2196. }
  2197. static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
  2198. {
  2199. struct slab *slab;
  2200. struct kmem_cache_order_objects oo = s->oo;
  2201. gfp_t alloc_gfp;
  2202. void *start, *p, *next;
  2203. int idx;
  2204. bool shuffle;
  2205. flags &= gfp_allowed_mask;
  2206. flags |= s->allocflags;
  2207. /*
  2208. * Let the initial higher-order allocation fail under memory pressure
  2209. * so we fall-back to the minimum order allocation.
  2210. */
  2211. alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
  2212. if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
  2213. alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
  2214. slab = alloc_slab_page(alloc_gfp, node, oo);
  2215. if (unlikely(!slab)) {
  2216. oo = s->min;
  2217. alloc_gfp = flags;
  2218. /*
  2219. * Allocation may have failed due to fragmentation.
  2220. * Try a lower order alloc if possible
  2221. */
  2222. slab = alloc_slab_page(alloc_gfp, node, oo);
  2223. if (unlikely(!slab))
  2224. return NULL;
  2225. stat(s, ORDER_FALLBACK);
  2226. }
  2227. slab->objects = oo_objects(oo);
  2228. slab->inuse = 0;
  2229. slab->frozen = 0;
  2230. account_slab(slab, oo_order(oo), s, flags);
  2231. slab->slab_cache = s;
  2232. kasan_poison_slab(slab);
  2233. start = slab_address(slab);
  2234. setup_slab_debug(s, slab, start);
  2235. shuffle = shuffle_freelist(s, slab);
  2236. if (!shuffle) {
  2237. start = fixup_red_left(s, start);
  2238. start = setup_object(s, start);
  2239. slab->freelist = start;
  2240. for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
  2241. next = p + s->size;
  2242. next = setup_object(s, next);
  2243. set_freepointer(s, p, next);
  2244. p = next;
  2245. }
  2246. set_freepointer(s, p, NULL);
  2247. }
  2248. return slab;
  2249. }
  2250. static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
  2251. {
  2252. if (unlikely(flags & GFP_SLAB_BUG_MASK))
  2253. flags = kmalloc_fix_flags(flags);
  2254. WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
  2255. return allocate_slab(s,
  2256. flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
  2257. }
  2258. static void __free_slab(struct kmem_cache *s, struct slab *slab)
  2259. {
  2260. struct folio *folio = slab_folio(slab);
  2261. int order = folio_order(folio);
  2262. int pages = 1 << order;
  2263. __slab_clear_pfmemalloc(slab);
  2264. folio->mapping = NULL;
  2265. /* Make the mapping reset visible before clearing the flag */
  2266. smp_wmb();
  2267. __folio_clear_slab(folio);
  2268. mm_account_reclaimed_pages(pages);
  2269. unaccount_slab(slab, order, s);
  2270. __free_pages(&folio->page, order);
  2271. }
  2272. static void rcu_free_slab(struct rcu_head *h)
  2273. {
  2274. struct slab *slab = container_of(h, struct slab, rcu_head);
  2275. __free_slab(slab->slab_cache, slab);
  2276. }
  2277. static void free_slab(struct kmem_cache *s, struct slab *slab)
  2278. {
  2279. if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
  2280. void *p;
  2281. slab_pad_check(s, slab);
  2282. for_each_object(p, s, slab_address(slab), slab->objects)
  2283. check_object(s, slab, p, SLUB_RED_INACTIVE);
  2284. }
  2285. if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
  2286. call_rcu(&slab->rcu_head, rcu_free_slab);
  2287. else
  2288. __free_slab(s, slab);
  2289. }
  2290. static void discard_slab(struct kmem_cache *s, struct slab *slab)
  2291. {
  2292. dec_slabs_node(s, slab_nid(slab), slab->objects);
  2293. free_slab(s, slab);
  2294. }
  2295. /*
  2296. * SLUB reuses PG_workingset bit to keep track of whether it's on
  2297. * the per-node partial list.
  2298. */
  2299. static inline bool slab_test_node_partial(const struct slab *slab)
  2300. {
  2301. return folio_test_workingset(slab_folio(slab));
  2302. }
  2303. static inline void slab_set_node_partial(struct slab *slab)
  2304. {
  2305. set_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
  2306. }
  2307. static inline void slab_clear_node_partial(struct slab *slab)
  2308. {
  2309. clear_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
  2310. }
  2311. /*
  2312. * Management of partially allocated slabs.
  2313. */
  2314. static inline void
  2315. __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
  2316. {
  2317. n->nr_partial++;
  2318. if (tail == DEACTIVATE_TO_TAIL)
  2319. list_add_tail(&slab->slab_list, &n->partial);
  2320. else
  2321. list_add(&slab->slab_list, &n->partial);
  2322. slab_set_node_partial(slab);
  2323. }
  2324. static inline void add_partial(struct kmem_cache_node *n,
  2325. struct slab *slab, int tail)
  2326. {
  2327. lockdep_assert_held(&n->list_lock);
  2328. __add_partial(n, slab, tail);
  2329. }
  2330. static inline void remove_partial(struct kmem_cache_node *n,
  2331. struct slab *slab)
  2332. {
  2333. lockdep_assert_held(&n->list_lock);
  2334. list_del(&slab->slab_list);
  2335. slab_clear_node_partial(slab);
  2336. n->nr_partial--;
  2337. }
  2338. /*
  2339. * Called only for kmem_cache_debug() caches instead of remove_partial(), with a
  2340. * slab from the n->partial list. Remove only a single object from the slab, do
  2341. * the alloc_debug_processing() checks and leave the slab on the list, or move
  2342. * it to full list if it was the last free object.
  2343. */
  2344. static void *alloc_single_from_partial(struct kmem_cache *s,
  2345. struct kmem_cache_node *n, struct slab *slab, int orig_size)
  2346. {
  2347. void *object;
  2348. lockdep_assert_held(&n->list_lock);
  2349. object = slab->freelist;
  2350. slab->freelist = get_freepointer(s, object);
  2351. slab->inuse++;
  2352. if (!alloc_debug_processing(s, slab, object, orig_size)) {
  2353. if (folio_test_slab(slab_folio(slab)))
  2354. remove_partial(n, slab);
  2355. return NULL;
  2356. }
  2357. if (slab->inuse == slab->objects) {
  2358. remove_partial(n, slab);
  2359. add_full(s, n, slab);
  2360. }
  2361. return object;
  2362. }
  2363. /*
  2364. * Called only for kmem_cache_debug() caches to allocate from a freshly
  2365. * allocated slab. Allocate a single object instead of whole freelist
  2366. * and put the slab to the partial (or full) list.
  2367. */
  2368. static void *alloc_single_from_new_slab(struct kmem_cache *s,
  2369. struct slab *slab, int orig_size)
  2370. {
  2371. int nid = slab_nid(slab);
  2372. struct kmem_cache_node *n = get_node(s, nid);
  2373. unsigned long flags;
  2374. void *object;
  2375. object = slab->freelist;
  2376. slab->freelist = get_freepointer(s, object);
  2377. slab->inuse = 1;
  2378. if (!alloc_debug_processing(s, slab, object, orig_size))
  2379. /*
  2380. * It's not really expected that this would fail on a
  2381. * freshly allocated slab, but a concurrent memory
  2382. * corruption in theory could cause that.
  2383. */
  2384. return NULL;
  2385. spin_lock_irqsave(&n->list_lock, flags);
  2386. if (slab->inuse == slab->objects)
  2387. add_full(s, n, slab);
  2388. else
  2389. add_partial(n, slab, DEACTIVATE_TO_HEAD);
  2390. inc_slabs_node(s, nid, slab->objects);
  2391. spin_unlock_irqrestore(&n->list_lock, flags);
  2392. return object;
  2393. }
  2394. #ifdef CONFIG_SLUB_CPU_PARTIAL
  2395. static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
  2396. #else
  2397. static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
  2398. int drain) { }
  2399. #endif
  2400. static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
  2401. /*
  2402. * Try to allocate a partial slab from a specific node.
  2403. */
  2404. static struct slab *get_partial_node(struct kmem_cache *s,
  2405. struct kmem_cache_node *n,
  2406. struct partial_context *pc)
  2407. {
  2408. struct slab *slab, *slab2, *partial = NULL;
  2409. unsigned long flags;
  2410. unsigned int partial_slabs = 0;
  2411. /*
  2412. * Racy check. If we mistakenly see no partial slabs then we
  2413. * just allocate an empty slab. If we mistakenly try to get a
  2414. * partial slab and there is none available then get_partial()
  2415. * will return NULL.
  2416. */
  2417. if (!n || !n->nr_partial)
  2418. return NULL;
  2419. spin_lock_irqsave(&n->list_lock, flags);
  2420. list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
  2421. if (!pfmemalloc_match(slab, pc->flags))
  2422. continue;
  2423. if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
  2424. void *object = alloc_single_from_partial(s, n, slab,
  2425. pc->orig_size);
  2426. if (object) {
  2427. partial = slab;
  2428. pc->object = object;
  2429. break;
  2430. }
  2431. continue;
  2432. }
  2433. remove_partial(n, slab);
  2434. if (!partial) {
  2435. partial = slab;
  2436. stat(s, ALLOC_FROM_PARTIAL);
  2437. if ((slub_get_cpu_partial(s) == 0)) {
  2438. break;
  2439. }
  2440. } else {
  2441. put_cpu_partial(s, slab, 0);
  2442. stat(s, CPU_PARTIAL_NODE);
  2443. if (++partial_slabs > slub_get_cpu_partial(s) / 2) {
  2444. break;
  2445. }
  2446. }
  2447. }
  2448. spin_unlock_irqrestore(&n->list_lock, flags);
  2449. return partial;
  2450. }
  2451. /*
  2452. * Get a slab from somewhere. Search in increasing NUMA distances.
  2453. */
  2454. static struct slab *get_any_partial(struct kmem_cache *s,
  2455. struct partial_context *pc)
  2456. {
  2457. #ifdef CONFIG_NUMA
  2458. struct zonelist *zonelist;
  2459. struct zoneref *z;
  2460. struct zone *zone;
  2461. enum zone_type highest_zoneidx = gfp_zone(pc->flags);
  2462. struct slab *slab;
  2463. unsigned int cpuset_mems_cookie;
  2464. /*
  2465. * The defrag ratio allows a configuration of the tradeoffs between
  2466. * inter node defragmentation and node local allocations. A lower
  2467. * defrag_ratio increases the tendency to do local allocations
  2468. * instead of attempting to obtain partial slabs from other nodes.
  2469. *
  2470. * If the defrag_ratio is set to 0 then kmalloc() always
  2471. * returns node local objects. If the ratio is higher then kmalloc()
  2472. * may return off node objects because partial slabs are obtained
  2473. * from other nodes and filled up.
  2474. *
  2475. * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
  2476. * (which makes defrag_ratio = 1000) then every (well almost)
  2477. * allocation will first attempt to defrag slab caches on other nodes.
  2478. * This means scanning over all nodes to look for partial slabs which
  2479. * may be expensive if we do it every time we are trying to find a slab
  2480. * with available objects.
  2481. */
  2482. if (!s->remote_node_defrag_ratio ||
  2483. get_cycles() % 1024 > s->remote_node_defrag_ratio)
  2484. return NULL;
  2485. do {
  2486. cpuset_mems_cookie = read_mems_allowed_begin();
  2487. zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
  2488. for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
  2489. struct kmem_cache_node *n;
  2490. n = get_node(s, zone_to_nid(zone));
  2491. if (n && cpuset_zone_allowed(zone, pc->flags) &&
  2492. n->nr_partial > s->min_partial) {
  2493. slab = get_partial_node(s, n, pc);
  2494. if (slab) {
  2495. /*
  2496. * Don't check read_mems_allowed_retry()
  2497. * here - if mems_allowed was updated in
  2498. * parallel, that was a harmless race
  2499. * between allocation and the cpuset
  2500. * update
  2501. */
  2502. return slab;
  2503. }
  2504. }
  2505. }
  2506. } while (read_mems_allowed_retry(cpuset_mems_cookie));
  2507. #endif /* CONFIG_NUMA */
  2508. return NULL;
  2509. }
  2510. /*
  2511. * Get a partial slab, lock it and return it.
  2512. */
  2513. static struct slab *get_partial(struct kmem_cache *s, int node,
  2514. struct partial_context *pc)
  2515. {
  2516. struct slab *slab;
  2517. int searchnode = node;
  2518. if (node == NUMA_NO_NODE)
  2519. searchnode = numa_mem_id();
  2520. slab = get_partial_node(s, get_node(s, searchnode), pc);
  2521. if (slab || (node != NUMA_NO_NODE && (pc->flags & __GFP_THISNODE)))
  2522. return slab;
  2523. return get_any_partial(s, pc);
  2524. }
  2525. #ifndef CONFIG_SLUB_TINY
  2526. #ifdef CONFIG_PREEMPTION
  2527. /*
  2528. * Calculate the next globally unique transaction for disambiguation
  2529. * during cmpxchg. The transactions start with the cpu number and are then
  2530. * incremented by CONFIG_NR_CPUS.
  2531. */
  2532. #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
  2533. #else
  2534. /*
  2535. * No preemption supported therefore also no need to check for
  2536. * different cpus.
  2537. */
  2538. #define TID_STEP 1
  2539. #endif /* CONFIG_PREEMPTION */
  2540. static inline unsigned long next_tid(unsigned long tid)
  2541. {
  2542. return tid + TID_STEP;
  2543. }
  2544. #ifdef SLUB_DEBUG_CMPXCHG
  2545. static inline unsigned int tid_to_cpu(unsigned long tid)
  2546. {
  2547. return tid % TID_STEP;
  2548. }
  2549. static inline unsigned long tid_to_event(unsigned long tid)
  2550. {
  2551. return tid / TID_STEP;
  2552. }
  2553. #endif
  2554. static inline unsigned int init_tid(int cpu)
  2555. {
  2556. return cpu;
  2557. }
  2558. static inline void note_cmpxchg_failure(const char *n,
  2559. const struct kmem_cache *s, unsigned long tid)
  2560. {
  2561. #ifdef SLUB_DEBUG_CMPXCHG
  2562. unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
  2563. pr_info("%s %s: cmpxchg redo ", n, s->name);
  2564. #ifdef CONFIG_PREEMPTION
  2565. if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
  2566. pr_warn("due to cpu change %d -> %d\n",
  2567. tid_to_cpu(tid), tid_to_cpu(actual_tid));
  2568. else
  2569. #endif
  2570. if (tid_to_event(tid) != tid_to_event(actual_tid))
  2571. pr_warn("due to cpu running other code. Event %ld->%ld\n",
  2572. tid_to_event(tid), tid_to_event(actual_tid));
  2573. else
  2574. pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
  2575. actual_tid, tid, next_tid(tid));
  2576. #endif
  2577. stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
  2578. }
  2579. static void init_kmem_cache_cpus(struct kmem_cache *s)
  2580. {
  2581. int cpu;
  2582. struct kmem_cache_cpu *c;
  2583. for_each_possible_cpu(cpu) {
  2584. c = per_cpu_ptr(s->cpu_slab, cpu);
  2585. local_lock_init(&c->lock);
  2586. c->tid = init_tid(cpu);
  2587. }
  2588. }
  2589. /*
  2590. * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
  2591. * unfreezes the slabs and puts it on the proper list.
  2592. * Assumes the slab has been already safely taken away from kmem_cache_cpu
  2593. * by the caller.
  2594. */
  2595. static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
  2596. void *freelist)
  2597. {
  2598. struct kmem_cache_node *n = get_node(s, slab_nid(slab));
  2599. int free_delta = 0;
  2600. void *nextfree, *freelist_iter, *freelist_tail;
  2601. int tail = DEACTIVATE_TO_HEAD;
  2602. unsigned long flags = 0;
  2603. struct slab new;
  2604. struct slab old;
  2605. if (READ_ONCE(slab->freelist)) {
  2606. stat(s, DEACTIVATE_REMOTE_FREES);
  2607. tail = DEACTIVATE_TO_TAIL;
  2608. }
  2609. /*
  2610. * Stage one: Count the objects on cpu's freelist as free_delta and
  2611. * remember the last object in freelist_tail for later splicing.
  2612. */
  2613. freelist_tail = NULL;
  2614. freelist_iter = freelist;
  2615. while (freelist_iter) {
  2616. nextfree = get_freepointer(s, freelist_iter);
  2617. /*
  2618. * If 'nextfree' is invalid, it is possible that the object at
  2619. * 'freelist_iter' is already corrupted. So isolate all objects
  2620. * starting at 'freelist_iter' by skipping them.
  2621. */
  2622. if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
  2623. break;
  2624. freelist_tail = freelist_iter;
  2625. free_delta++;
  2626. freelist_iter = nextfree;
  2627. }
  2628. /*
  2629. * Stage two: Unfreeze the slab while splicing the per-cpu
  2630. * freelist to the head of slab's freelist.
  2631. */
  2632. do {
  2633. old.freelist = READ_ONCE(slab->freelist);
  2634. old.counters = READ_ONCE(slab->counters);
  2635. VM_BUG_ON(!old.frozen);
  2636. /* Determine target state of the slab */
  2637. new.counters = old.counters;
  2638. new.frozen = 0;
  2639. if (freelist_tail) {
  2640. new.inuse -= free_delta;
  2641. set_freepointer(s, freelist_tail, old.freelist);
  2642. new.freelist = freelist;
  2643. } else {
  2644. new.freelist = old.freelist;
  2645. }
  2646. } while (!slab_update_freelist(s, slab,
  2647. old.freelist, old.counters,
  2648. new.freelist, new.counters,
  2649. "unfreezing slab"));
  2650. /*
  2651. * Stage three: Manipulate the slab list based on the updated state.
  2652. */
  2653. if (!new.inuse && n->nr_partial >= s->min_partial) {
  2654. stat(s, DEACTIVATE_EMPTY);
  2655. discard_slab(s, slab);
  2656. stat(s, FREE_SLAB);
  2657. } else if (new.freelist) {
  2658. spin_lock_irqsave(&n->list_lock, flags);
  2659. add_partial(n, slab, tail);
  2660. spin_unlock_irqrestore(&n->list_lock, flags);
  2661. stat(s, tail);
  2662. } else {
  2663. stat(s, DEACTIVATE_FULL);
  2664. }
  2665. }
  2666. #ifdef CONFIG_SLUB_CPU_PARTIAL
  2667. static void __put_partials(struct kmem_cache *s, struct slab *partial_slab)
  2668. {
  2669. struct kmem_cache_node *n = NULL, *n2 = NULL;
  2670. struct slab *slab, *slab_to_discard = NULL;
  2671. unsigned long flags = 0;
  2672. while (partial_slab) {
  2673. slab = partial_slab;
  2674. partial_slab = slab->next;
  2675. n2 = get_node(s, slab_nid(slab));
  2676. if (n != n2) {
  2677. if (n)
  2678. spin_unlock_irqrestore(&n->list_lock, flags);
  2679. n = n2;
  2680. spin_lock_irqsave(&n->list_lock, flags);
  2681. }
  2682. if (unlikely(!slab->inuse && n->nr_partial >= s->min_partial)) {
  2683. slab->next = slab_to_discard;
  2684. slab_to_discard = slab;
  2685. } else {
  2686. add_partial(n, slab, DEACTIVATE_TO_TAIL);
  2687. stat(s, FREE_ADD_PARTIAL);
  2688. }
  2689. }
  2690. if (n)
  2691. spin_unlock_irqrestore(&n->list_lock, flags);
  2692. while (slab_to_discard) {
  2693. slab = slab_to_discard;
  2694. slab_to_discard = slab_to_discard->next;
  2695. stat(s, DEACTIVATE_EMPTY);
  2696. discard_slab(s, slab);
  2697. stat(s, FREE_SLAB);
  2698. }
  2699. }
  2700. /*
  2701. * Put all the cpu partial slabs to the node partial list.
  2702. */
  2703. static void put_partials(struct kmem_cache *s)
  2704. {
  2705. struct slab *partial_slab;
  2706. unsigned long flags;
  2707. local_lock_irqsave(&s->cpu_slab->lock, flags);
  2708. partial_slab = this_cpu_read(s->cpu_slab->partial);
  2709. this_cpu_write(s->cpu_slab->partial, NULL);
  2710. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  2711. if (partial_slab)
  2712. __put_partials(s, partial_slab);
  2713. }
  2714. static void put_partials_cpu(struct kmem_cache *s,
  2715. struct kmem_cache_cpu *c)
  2716. {
  2717. struct slab *partial_slab;
  2718. partial_slab = slub_percpu_partial(c);
  2719. c->partial = NULL;
  2720. if (partial_slab)
  2721. __put_partials(s, partial_slab);
  2722. }
  2723. /*
  2724. * Put a slab into a partial slab slot if available.
  2725. *
  2726. * If we did not find a slot then simply move all the partials to the
  2727. * per node partial list.
  2728. */
  2729. static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
  2730. {
  2731. struct slab *oldslab;
  2732. struct slab *slab_to_put = NULL;
  2733. unsigned long flags;
  2734. int slabs = 0;
  2735. local_lock_irqsave(&s->cpu_slab->lock, flags);
  2736. oldslab = this_cpu_read(s->cpu_slab->partial);
  2737. if (oldslab) {
  2738. if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
  2739. /*
  2740. * Partial array is full. Move the existing set to the
  2741. * per node partial list. Postpone the actual unfreezing
  2742. * outside of the critical section.
  2743. */
  2744. slab_to_put = oldslab;
  2745. oldslab = NULL;
  2746. } else {
  2747. slabs = oldslab->slabs;
  2748. }
  2749. }
  2750. slabs++;
  2751. slab->slabs = slabs;
  2752. slab->next = oldslab;
  2753. this_cpu_write(s->cpu_slab->partial, slab);
  2754. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  2755. if (slab_to_put) {
  2756. __put_partials(s, slab_to_put);
  2757. stat(s, CPU_PARTIAL_DRAIN);
  2758. }
  2759. }
  2760. #else /* CONFIG_SLUB_CPU_PARTIAL */
  2761. static inline void put_partials(struct kmem_cache *s) { }
  2762. static inline void put_partials_cpu(struct kmem_cache *s,
  2763. struct kmem_cache_cpu *c) { }
  2764. #endif /* CONFIG_SLUB_CPU_PARTIAL */
  2765. static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
  2766. {
  2767. unsigned long flags;
  2768. struct slab *slab;
  2769. void *freelist;
  2770. local_lock_irqsave(&s->cpu_slab->lock, flags);
  2771. slab = c->slab;
  2772. freelist = c->freelist;
  2773. c->slab = NULL;
  2774. c->freelist = NULL;
  2775. c->tid = next_tid(c->tid);
  2776. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  2777. if (slab) {
  2778. deactivate_slab(s, slab, freelist);
  2779. stat(s, CPUSLAB_FLUSH);
  2780. }
  2781. }
  2782. static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
  2783. {
  2784. struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
  2785. void *freelist = c->freelist;
  2786. struct slab *slab = c->slab;
  2787. c->slab = NULL;
  2788. c->freelist = NULL;
  2789. c->tid = next_tid(c->tid);
  2790. if (slab) {
  2791. deactivate_slab(s, slab, freelist);
  2792. stat(s, CPUSLAB_FLUSH);
  2793. }
  2794. put_partials_cpu(s, c);
  2795. }
  2796. struct slub_flush_work {
  2797. struct work_struct work;
  2798. struct kmem_cache *s;
  2799. bool skip;
  2800. };
  2801. /*
  2802. * Flush cpu slab.
  2803. *
  2804. * Called from CPU work handler with migration disabled.
  2805. */
  2806. static void flush_cpu_slab(struct work_struct *w)
  2807. {
  2808. struct kmem_cache *s;
  2809. struct kmem_cache_cpu *c;
  2810. struct slub_flush_work *sfw;
  2811. sfw = container_of(w, struct slub_flush_work, work);
  2812. s = sfw->s;
  2813. c = this_cpu_ptr(s->cpu_slab);
  2814. if (c->slab)
  2815. flush_slab(s, c);
  2816. put_partials(s);
  2817. }
  2818. static bool has_cpu_slab(int cpu, struct kmem_cache *s)
  2819. {
  2820. struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
  2821. return c->slab || slub_percpu_partial(c);
  2822. }
  2823. static DEFINE_MUTEX(flush_lock);
  2824. static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
  2825. static void flush_all_cpus_locked(struct kmem_cache *s)
  2826. {
  2827. struct slub_flush_work *sfw;
  2828. unsigned int cpu;
  2829. lockdep_assert_cpus_held();
  2830. mutex_lock(&flush_lock);
  2831. for_each_online_cpu(cpu) {
  2832. sfw = &per_cpu(slub_flush, cpu);
  2833. if (!has_cpu_slab(cpu, s)) {
  2834. sfw->skip = true;
  2835. continue;
  2836. }
  2837. INIT_WORK(&sfw->work, flush_cpu_slab);
  2838. sfw->skip = false;
  2839. sfw->s = s;
  2840. queue_work_on(cpu, flushwq, &sfw->work);
  2841. }
  2842. for_each_online_cpu(cpu) {
  2843. sfw = &per_cpu(slub_flush, cpu);
  2844. if (sfw->skip)
  2845. continue;
  2846. flush_work(&sfw->work);
  2847. }
  2848. mutex_unlock(&flush_lock);
  2849. }
  2850. static void flush_all(struct kmem_cache *s)
  2851. {
  2852. cpus_read_lock();
  2853. flush_all_cpus_locked(s);
  2854. cpus_read_unlock();
  2855. }
  2856. /*
  2857. * Use the cpu notifier to insure that the cpu slabs are flushed when
  2858. * necessary.
  2859. */
  2860. static int slub_cpu_dead(unsigned int cpu)
  2861. {
  2862. struct kmem_cache *s;
  2863. mutex_lock(&slab_mutex);
  2864. list_for_each_entry(s, &slab_caches, list)
  2865. __flush_cpu_slab(s, cpu);
  2866. mutex_unlock(&slab_mutex);
  2867. return 0;
  2868. }
  2869. #else /* CONFIG_SLUB_TINY */
  2870. static inline void flush_all_cpus_locked(struct kmem_cache *s) { }
  2871. static inline void flush_all(struct kmem_cache *s) { }
  2872. static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { }
  2873. static inline int slub_cpu_dead(unsigned int cpu) { return 0; }
  2874. #endif /* CONFIG_SLUB_TINY */
  2875. /*
  2876. * Check if the objects in a per cpu structure fit numa
  2877. * locality expectations.
  2878. */
  2879. static inline int node_match(struct slab *slab, int node)
  2880. {
  2881. #ifdef CONFIG_NUMA
  2882. if (node != NUMA_NO_NODE && slab_nid(slab) != node)
  2883. return 0;
  2884. #endif
  2885. return 1;
  2886. }
  2887. #ifdef CONFIG_SLUB_DEBUG
  2888. static int count_free(struct slab *slab)
  2889. {
  2890. return slab->objects - slab->inuse;
  2891. }
  2892. static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
  2893. {
  2894. return atomic_long_read(&n->total_objects);
  2895. }
  2896. /* Supports checking bulk free of a constructed freelist */
  2897. static inline bool free_debug_processing(struct kmem_cache *s,
  2898. struct slab *slab, void *head, void *tail, int *bulk_cnt,
  2899. unsigned long addr, depot_stack_handle_t handle)
  2900. {
  2901. bool checks_ok = false;
  2902. void *object = head;
  2903. int cnt = 0;
  2904. if (s->flags & SLAB_CONSISTENCY_CHECKS) {
  2905. if (!check_slab(s, slab))
  2906. goto out;
  2907. }
  2908. if (slab->inuse < *bulk_cnt) {
  2909. slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
  2910. slab->inuse, *bulk_cnt);
  2911. goto out;
  2912. }
  2913. next_object:
  2914. if (++cnt > *bulk_cnt)
  2915. goto out_cnt;
  2916. if (s->flags & SLAB_CONSISTENCY_CHECKS) {
  2917. if (!free_consistency_checks(s, slab, object, addr))
  2918. goto out;
  2919. }
  2920. if (s->flags & SLAB_STORE_USER)
  2921. set_track_update(s, object, TRACK_FREE, addr, handle);
  2922. trace(s, slab, object, 0);
  2923. /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
  2924. init_object(s, object, SLUB_RED_INACTIVE);
  2925. /* Reached end of constructed freelist yet? */
  2926. if (object != tail) {
  2927. object = get_freepointer(s, object);
  2928. goto next_object;
  2929. }
  2930. checks_ok = true;
  2931. out_cnt:
  2932. if (cnt != *bulk_cnt) {
  2933. slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
  2934. *bulk_cnt, cnt);
  2935. *bulk_cnt = cnt;
  2936. }
  2937. out:
  2938. if (!checks_ok)
  2939. slab_fix(s, "Object at 0x%p not freed", object);
  2940. return checks_ok;
  2941. }
  2942. #endif /* CONFIG_SLUB_DEBUG */
  2943. #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
  2944. static unsigned long count_partial(struct kmem_cache_node *n,
  2945. int (*get_count)(struct slab *))
  2946. {
  2947. unsigned long flags;
  2948. unsigned long x = 0;
  2949. struct slab *slab;
  2950. spin_lock_irqsave(&n->list_lock, flags);
  2951. list_for_each_entry(slab, &n->partial, slab_list)
  2952. x += get_count(slab);
  2953. spin_unlock_irqrestore(&n->list_lock, flags);
  2954. return x;
  2955. }
  2956. #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
  2957. #ifdef CONFIG_SLUB_DEBUG
  2958. #define MAX_PARTIAL_TO_SCAN 10000
  2959. static unsigned long count_partial_free_approx(struct kmem_cache_node *n)
  2960. {
  2961. unsigned long flags;
  2962. unsigned long x = 0;
  2963. struct slab *slab;
  2964. spin_lock_irqsave(&n->list_lock, flags);
  2965. if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
  2966. list_for_each_entry(slab, &n->partial, slab_list)
  2967. x += slab->objects - slab->inuse;
  2968. } else {
  2969. /*
  2970. * For a long list, approximate the total count of objects in
  2971. * it to meet the limit on the number of slabs to scan.
  2972. * Scan from both the list's head and tail for better accuracy.
  2973. */
  2974. unsigned long scanned = 0;
  2975. list_for_each_entry(slab, &n->partial, slab_list) {
  2976. x += slab->objects - slab->inuse;
  2977. if (++scanned == MAX_PARTIAL_TO_SCAN / 2)
  2978. break;
  2979. }
  2980. list_for_each_entry_reverse(slab, &n->partial, slab_list) {
  2981. x += slab->objects - slab->inuse;
  2982. if (++scanned == MAX_PARTIAL_TO_SCAN)
  2983. break;
  2984. }
  2985. x = mult_frac(x, n->nr_partial, scanned);
  2986. x = min(x, node_nr_objs(n));
  2987. }
  2988. spin_unlock_irqrestore(&n->list_lock, flags);
  2989. return x;
  2990. }
  2991. static noinline void
  2992. slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
  2993. {
  2994. static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
  2995. DEFAULT_RATELIMIT_BURST);
  2996. int cpu = raw_smp_processor_id();
  2997. int node;
  2998. struct kmem_cache_node *n;
  2999. if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
  3000. return;
  3001. pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
  3002. cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
  3003. pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
  3004. s->name, s->object_size, s->size, oo_order(s->oo),
  3005. oo_order(s->min));
  3006. if (oo_order(s->min) > get_order(s->object_size))
  3007. pr_warn(" %s debugging increased min order, use slab_debug=O to disable.\n",
  3008. s->name);
  3009. for_each_kmem_cache_node(s, node, n) {
  3010. unsigned long nr_slabs;
  3011. unsigned long nr_objs;
  3012. unsigned long nr_free;
  3013. nr_free = count_partial_free_approx(n);
  3014. nr_slabs = node_nr_slabs(n);
  3015. nr_objs = node_nr_objs(n);
  3016. pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
  3017. node, nr_slabs, nr_objs, nr_free);
  3018. }
  3019. }
  3020. #else /* CONFIG_SLUB_DEBUG */
  3021. static inline void
  3022. slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
  3023. #endif
  3024. static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
  3025. {
  3026. if (unlikely(slab_test_pfmemalloc(slab)))
  3027. return gfp_pfmemalloc_allowed(gfpflags);
  3028. return true;
  3029. }
  3030. #ifndef CONFIG_SLUB_TINY
  3031. static inline bool
  3032. __update_cpu_freelist_fast(struct kmem_cache *s,
  3033. void *freelist_old, void *freelist_new,
  3034. unsigned long tid)
  3035. {
  3036. freelist_aba_t old = { .freelist = freelist_old, .counter = tid };
  3037. freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) };
  3038. return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full,
  3039. &old.full, new.full);
  3040. }
  3041. /*
  3042. * Check the slab->freelist and either transfer the freelist to the
  3043. * per cpu freelist or deactivate the slab.
  3044. *
  3045. * The slab is still frozen if the return value is not NULL.
  3046. *
  3047. * If this function returns NULL then the slab has been unfrozen.
  3048. */
  3049. static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
  3050. {
  3051. struct slab new;
  3052. unsigned long counters;
  3053. void *freelist;
  3054. lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
  3055. do {
  3056. freelist = slab->freelist;
  3057. counters = slab->counters;
  3058. new.counters = counters;
  3059. new.inuse = slab->objects;
  3060. new.frozen = freelist != NULL;
  3061. } while (!__slab_update_freelist(s, slab,
  3062. freelist, counters,
  3063. NULL, new.counters,
  3064. "get_freelist"));
  3065. return freelist;
  3066. }
  3067. /*
  3068. * Freeze the partial slab and return the pointer to the freelist.
  3069. */
  3070. static inline void *freeze_slab(struct kmem_cache *s, struct slab *slab)
  3071. {
  3072. struct slab new;
  3073. unsigned long counters;
  3074. void *freelist;
  3075. do {
  3076. freelist = slab->freelist;
  3077. counters = slab->counters;
  3078. new.counters = counters;
  3079. VM_BUG_ON(new.frozen);
  3080. new.inuse = slab->objects;
  3081. new.frozen = 1;
  3082. } while (!slab_update_freelist(s, slab,
  3083. freelist, counters,
  3084. NULL, new.counters,
  3085. "freeze_slab"));
  3086. return freelist;
  3087. }
  3088. /*
  3089. * Slow path. The lockless freelist is empty or we need to perform
  3090. * debugging duties.
  3091. *
  3092. * Processing is still very fast if new objects have been freed to the
  3093. * regular freelist. In that case we simply take over the regular freelist
  3094. * as the lockless freelist and zap the regular freelist.
  3095. *
  3096. * If that is not working then we fall back to the partial lists. We take the
  3097. * first element of the freelist as the object to allocate now and move the
  3098. * rest of the freelist to the lockless freelist.
  3099. *
  3100. * And if we were unable to get a new slab from the partial slab lists then
  3101. * we need to allocate a new slab. This is the slowest path since it involves
  3102. * a call to the page allocator and the setup of a new slab.
  3103. *
  3104. * Version of __slab_alloc to use when we know that preemption is
  3105. * already disabled (which is the case for bulk allocation).
  3106. */
  3107. static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
  3108. unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
  3109. {
  3110. void *freelist;
  3111. struct slab *slab;
  3112. unsigned long flags;
  3113. struct partial_context pc;
  3114. bool try_thisnode = true;
  3115. stat(s, ALLOC_SLOWPATH);
  3116. reread_slab:
  3117. slab = READ_ONCE(c->slab);
  3118. if (!slab) {
  3119. /*
  3120. * if the node is not online or has no normal memory, just
  3121. * ignore the node constraint
  3122. */
  3123. if (unlikely(node != NUMA_NO_NODE &&
  3124. !node_isset(node, slab_nodes)))
  3125. node = NUMA_NO_NODE;
  3126. goto new_slab;
  3127. }
  3128. if (unlikely(!node_match(slab, node))) {
  3129. /*
  3130. * same as above but node_match() being false already
  3131. * implies node != NUMA_NO_NODE
  3132. */
  3133. if (!node_isset(node, slab_nodes)) {
  3134. node = NUMA_NO_NODE;
  3135. } else {
  3136. stat(s, ALLOC_NODE_MISMATCH);
  3137. goto deactivate_slab;
  3138. }
  3139. }
  3140. /*
  3141. * By rights, we should be searching for a slab page that was
  3142. * PFMEMALLOC but right now, we are losing the pfmemalloc
  3143. * information when the page leaves the per-cpu allocator
  3144. */
  3145. if (unlikely(!pfmemalloc_match(slab, gfpflags)))
  3146. goto deactivate_slab;
  3147. /* must check again c->slab in case we got preempted and it changed */
  3148. local_lock_irqsave(&s->cpu_slab->lock, flags);
  3149. if (unlikely(slab != c->slab)) {
  3150. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3151. goto reread_slab;
  3152. }
  3153. freelist = c->freelist;
  3154. if (freelist)
  3155. goto load_freelist;
  3156. freelist = get_freelist(s, slab);
  3157. if (!freelist) {
  3158. c->slab = NULL;
  3159. c->tid = next_tid(c->tid);
  3160. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3161. stat(s, DEACTIVATE_BYPASS);
  3162. goto new_slab;
  3163. }
  3164. stat(s, ALLOC_REFILL);
  3165. load_freelist:
  3166. lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
  3167. /*
  3168. * freelist is pointing to the list of objects to be used.
  3169. * slab is pointing to the slab from which the objects are obtained.
  3170. * That slab must be frozen for per cpu allocations to work.
  3171. */
  3172. VM_BUG_ON(!c->slab->frozen);
  3173. c->freelist = get_freepointer(s, freelist);
  3174. c->tid = next_tid(c->tid);
  3175. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3176. return freelist;
  3177. deactivate_slab:
  3178. local_lock_irqsave(&s->cpu_slab->lock, flags);
  3179. if (slab != c->slab) {
  3180. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3181. goto reread_slab;
  3182. }
  3183. freelist = c->freelist;
  3184. c->slab = NULL;
  3185. c->freelist = NULL;
  3186. c->tid = next_tid(c->tid);
  3187. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3188. deactivate_slab(s, slab, freelist);
  3189. new_slab:
  3190. #ifdef CONFIG_SLUB_CPU_PARTIAL
  3191. while (slub_percpu_partial(c)) {
  3192. local_lock_irqsave(&s->cpu_slab->lock, flags);
  3193. if (unlikely(c->slab)) {
  3194. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3195. goto reread_slab;
  3196. }
  3197. if (unlikely(!slub_percpu_partial(c))) {
  3198. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3199. /* we were preempted and partial list got empty */
  3200. goto new_objects;
  3201. }
  3202. slab = slub_percpu_partial(c);
  3203. slub_set_percpu_partial(c, slab);
  3204. if (likely(node_match(slab, node) &&
  3205. pfmemalloc_match(slab, gfpflags))) {
  3206. c->slab = slab;
  3207. freelist = get_freelist(s, slab);
  3208. VM_BUG_ON(!freelist);
  3209. stat(s, CPU_PARTIAL_ALLOC);
  3210. goto load_freelist;
  3211. }
  3212. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3213. slab->next = NULL;
  3214. __put_partials(s, slab);
  3215. }
  3216. #endif
  3217. new_objects:
  3218. pc.flags = gfpflags;
  3219. /*
  3220. * When a preferred node is indicated but no __GFP_THISNODE
  3221. *
  3222. * 1) try to get a partial slab from target node only by having
  3223. * __GFP_THISNODE in pc.flags for get_partial()
  3224. * 2) if 1) failed, try to allocate a new slab from target node with
  3225. * GPF_NOWAIT | __GFP_THISNODE opportunistically
  3226. * 3) if 2) failed, retry with original gfpflags which will allow
  3227. * get_partial() try partial lists of other nodes before potentially
  3228. * allocating new page from other nodes
  3229. */
  3230. if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
  3231. && try_thisnode))
  3232. pc.flags = GFP_NOWAIT | __GFP_THISNODE;
  3233. pc.orig_size = orig_size;
  3234. slab = get_partial(s, node, &pc);
  3235. if (slab) {
  3236. if (kmem_cache_debug(s)) {
  3237. freelist = pc.object;
  3238. /*
  3239. * For debug caches here we had to go through
  3240. * alloc_single_from_partial() so just store the
  3241. * tracking info and return the object.
  3242. */
  3243. if (s->flags & SLAB_STORE_USER)
  3244. set_track(s, freelist, TRACK_ALLOC, addr);
  3245. return freelist;
  3246. }
  3247. freelist = freeze_slab(s, slab);
  3248. goto retry_load_slab;
  3249. }
  3250. slub_put_cpu_ptr(s->cpu_slab);
  3251. slab = new_slab(s, pc.flags, node);
  3252. c = slub_get_cpu_ptr(s->cpu_slab);
  3253. if (unlikely(!slab)) {
  3254. if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
  3255. && try_thisnode) {
  3256. try_thisnode = false;
  3257. goto new_objects;
  3258. }
  3259. slab_out_of_memory(s, gfpflags, node);
  3260. return NULL;
  3261. }
  3262. stat(s, ALLOC_SLAB);
  3263. if (kmem_cache_debug(s)) {
  3264. freelist = alloc_single_from_new_slab(s, slab, orig_size);
  3265. if (unlikely(!freelist))
  3266. goto new_objects;
  3267. if (s->flags & SLAB_STORE_USER)
  3268. set_track(s, freelist, TRACK_ALLOC, addr);
  3269. return freelist;
  3270. }
  3271. /*
  3272. * No other reference to the slab yet so we can
  3273. * muck around with it freely without cmpxchg
  3274. */
  3275. freelist = slab->freelist;
  3276. slab->freelist = NULL;
  3277. slab->inuse = slab->objects;
  3278. slab->frozen = 1;
  3279. inc_slabs_node(s, slab_nid(slab), slab->objects);
  3280. if (unlikely(!pfmemalloc_match(slab, gfpflags))) {
  3281. /*
  3282. * For !pfmemalloc_match() case we don't load freelist so that
  3283. * we don't make further mismatched allocations easier.
  3284. */
  3285. deactivate_slab(s, slab, get_freepointer(s, freelist));
  3286. return freelist;
  3287. }
  3288. retry_load_slab:
  3289. local_lock_irqsave(&s->cpu_slab->lock, flags);
  3290. if (unlikely(c->slab)) {
  3291. void *flush_freelist = c->freelist;
  3292. struct slab *flush_slab = c->slab;
  3293. c->slab = NULL;
  3294. c->freelist = NULL;
  3295. c->tid = next_tid(c->tid);
  3296. local_unlock_irqrestore(&s->cpu_slab->lock, flags);
  3297. deactivate_slab(s, flush_slab, flush_freelist);
  3298. stat(s, CPUSLAB_FLUSH);
  3299. goto retry_load_slab;
  3300. }
  3301. c->slab = slab;
  3302. goto load_freelist;
  3303. }
  3304. /*
  3305. * A wrapper for ___slab_alloc() for contexts where preemption is not yet
  3306. * disabled. Compensates for possible cpu changes by refetching the per cpu area
  3307. * pointer.
  3308. */
  3309. static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
  3310. unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
  3311. {
  3312. void *p;
  3313. #ifdef CONFIG_PREEMPT_COUNT
  3314. /*
  3315. * We may have been preempted and rescheduled on a different
  3316. * cpu before disabling preemption. Need to reload cpu area
  3317. * pointer.
  3318. */
  3319. c = slub_get_cpu_ptr(s->cpu_slab);
  3320. #endif
  3321. p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
  3322. #ifdef CONFIG_PREEMPT_COUNT
  3323. slub_put_cpu_ptr(s->cpu_slab);
  3324. #endif
  3325. return p;
  3326. }
  3327. static __always_inline void *__slab_alloc_node(struct kmem_cache *s,
  3328. gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
  3329. {
  3330. struct kmem_cache_cpu *c;
  3331. struct slab *slab;
  3332. unsigned long tid;
  3333. void *object;
  3334. redo:
  3335. /*
  3336. * Must read kmem_cache cpu data via this cpu ptr. Preemption is
  3337. * enabled. We may switch back and forth between cpus while
  3338. * reading from one cpu area. That does not matter as long
  3339. * as we end up on the original cpu again when doing the cmpxchg.
  3340. *
  3341. * We must guarantee that tid and kmem_cache_cpu are retrieved on the
  3342. * same cpu. We read first the kmem_cache_cpu pointer and use it to read
  3343. * the tid. If we are preempted and switched to another cpu between the
  3344. * two reads, it's OK as the two are still associated with the same cpu
  3345. * and cmpxchg later will validate the cpu.
  3346. */
  3347. c = raw_cpu_ptr(s->cpu_slab);
  3348. tid = READ_ONCE(c->tid);
  3349. /*
  3350. * Irqless object alloc/free algorithm used here depends on sequence
  3351. * of fetching cpu_slab's data. tid should be fetched before anything
  3352. * on c to guarantee that object and slab associated with previous tid
  3353. * won't be used with current tid. If we fetch tid first, object and
  3354. * slab could be one associated with next tid and our alloc/free
  3355. * request will be failed. In this case, we will retry. So, no problem.
  3356. */
  3357. barrier();
  3358. /*
  3359. * The transaction ids are globally unique per cpu and per operation on
  3360. * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
  3361. * occurs on the right processor and that there was no operation on the
  3362. * linked list in between.
  3363. */
  3364. object = c->freelist;
  3365. slab = c->slab;
  3366. if (!USE_LOCKLESS_FAST_PATH() ||
  3367. unlikely(!object || !slab || !node_match(slab, node))) {
  3368. object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
  3369. } else {
  3370. void *next_object = get_freepointer_safe(s, object);
  3371. /*
  3372. * The cmpxchg will only match if there was no additional
  3373. * operation and if we are on the right processor.
  3374. *
  3375. * The cmpxchg does the following atomically (without lock
  3376. * semantics!)
  3377. * 1. Relocate first pointer to the current per cpu area.
  3378. * 2. Verify that tid and freelist have not been changed
  3379. * 3. If they were not changed replace tid and freelist
  3380. *
  3381. * Since this is without lock semantics the protection is only
  3382. * against code executing on this cpu *not* from access by
  3383. * other cpus.
  3384. */
  3385. if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
  3386. note_cmpxchg_failure("slab_alloc", s, tid);
  3387. goto redo;
  3388. }
  3389. prefetch_freepointer(s, next_object);
  3390. stat(s, ALLOC_FASTPATH);
  3391. }
  3392. return object;
  3393. }
  3394. #else /* CONFIG_SLUB_TINY */
  3395. static void *__slab_alloc_node(struct kmem_cache *s,
  3396. gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
  3397. {
  3398. struct partial_context pc;
  3399. struct slab *slab;
  3400. void *object;
  3401. pc.flags = gfpflags;
  3402. pc.orig_size = orig_size;
  3403. slab = get_partial(s, node, &pc);
  3404. if (slab)
  3405. return pc.object;
  3406. slab = new_slab(s, gfpflags, node);
  3407. if (unlikely(!slab)) {
  3408. slab_out_of_memory(s, gfpflags, node);
  3409. return NULL;
  3410. }
  3411. object = alloc_single_from_new_slab(s, slab, orig_size);
  3412. return object;
  3413. }
  3414. #endif /* CONFIG_SLUB_TINY */
  3415. /*
  3416. * If the object has been wiped upon free, make sure it's fully initialized by
  3417. * zeroing out freelist pointer.
  3418. *
  3419. * Note that we also wipe custom freelist pointers.
  3420. */
  3421. static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
  3422. void *obj)
  3423. {
  3424. if (unlikely(slab_want_init_on_free(s)) && obj &&
  3425. !freeptr_outside_object(s))
  3426. memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
  3427. 0, sizeof(void *));
  3428. }
  3429. static __fastpath_inline
  3430. struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
  3431. {
  3432. flags &= gfp_allowed_mask;
  3433. might_alloc(flags);
  3434. if (unlikely(should_failslab(s, flags)))
  3435. return NULL;
  3436. return s;
  3437. }
  3438. static __fastpath_inline
  3439. bool slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
  3440. gfp_t flags, size_t size, void **p, bool init,
  3441. unsigned int orig_size)
  3442. {
  3443. unsigned int zero_size = s->object_size;
  3444. bool kasan_init = init;
  3445. size_t i;
  3446. gfp_t init_flags = flags & gfp_allowed_mask;
  3447. /*
  3448. * For kmalloc object, the allocated memory size(object_size) is likely
  3449. * larger than the requested size(orig_size). If redzone check is
  3450. * enabled for the extra space, don't zero it, as it will be redzoned
  3451. * soon. The redzone operation for this extra space could be seen as a
  3452. * replacement of current poisoning under certain debug option, and
  3453. * won't break other sanity checks.
  3454. */
  3455. if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) &&
  3456. (s->flags & SLAB_KMALLOC))
  3457. zero_size = orig_size;
  3458. /*
  3459. * When slab_debug is enabled, avoid memory initialization integrated
  3460. * into KASAN and instead zero out the memory via the memset below with
  3461. * the proper size. Otherwise, KASAN might overwrite SLUB redzones and
  3462. * cause false-positive reports. This does not lead to a performance
  3463. * penalty on production builds, as slab_debug is not intended to be
  3464. * enabled there.
  3465. */
  3466. if (__slub_debug_enabled())
  3467. kasan_init = false;
  3468. /*
  3469. * As memory initialization might be integrated into KASAN,
  3470. * kasan_slab_alloc and initialization memset must be
  3471. * kept together to avoid discrepancies in behavior.
  3472. *
  3473. * As p[i] might get tagged, memset and kmemleak hook come after KASAN.
  3474. */
  3475. for (i = 0; i < size; i++) {
  3476. p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init);
  3477. if (p[i] && init && (!kasan_init ||
  3478. !kasan_has_integrated_init()))
  3479. memset(p[i], 0, zero_size);
  3480. kmemleak_alloc_recursive(p[i], s->object_size, 1,
  3481. s->flags, init_flags);
  3482. kmsan_slab_alloc(s, p[i], init_flags);
  3483. alloc_tagging_slab_alloc_hook(s, p[i], flags);
  3484. }
  3485. return memcg_slab_post_alloc_hook(s, lru, flags, size, p);
  3486. }
  3487. /*
  3488. * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
  3489. * have the fastpath folded into their functions. So no function call
  3490. * overhead for requests that can be satisfied on the fastpath.
  3491. *
  3492. * The fastpath works by first checking if the lockless freelist can be used.
  3493. * If not then __slab_alloc is called for slow processing.
  3494. *
  3495. * Otherwise we can simply pick the next object from the lockless free list.
  3496. */
  3497. static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
  3498. gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
  3499. {
  3500. void *object;
  3501. bool init = false;
  3502. s = slab_pre_alloc_hook(s, gfpflags);
  3503. if (unlikely(!s))
  3504. return NULL;
  3505. object = kfence_alloc(s, orig_size, gfpflags);
  3506. if (unlikely(object))
  3507. goto out;
  3508. object = __slab_alloc_node(s, gfpflags, node, addr, orig_size);
  3509. maybe_wipe_obj_freeptr(s, object);
  3510. init = slab_want_init_on_alloc(gfpflags, s);
  3511. out:
  3512. /*
  3513. * When init equals 'true', like for kzalloc() family, only
  3514. * @orig_size bytes might be zeroed instead of s->object_size
  3515. * In case this fails due to memcg_slab_post_alloc_hook(),
  3516. * object is set to NULL
  3517. */
  3518. slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size);
  3519. return object;
  3520. }
  3521. void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)
  3522. {
  3523. void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, _RET_IP_,
  3524. s->object_size);
  3525. trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
  3526. return ret;
  3527. }
  3528. EXPORT_SYMBOL(kmem_cache_alloc_noprof);
  3529. void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,
  3530. gfp_t gfpflags)
  3531. {
  3532. void *ret = slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, _RET_IP_,
  3533. s->object_size);
  3534. trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
  3535. return ret;
  3536. }
  3537. EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);
  3538. bool kmem_cache_charge(void *objp, gfp_t gfpflags)
  3539. {
  3540. if (!memcg_kmem_online())
  3541. return true;
  3542. return memcg_slab_post_charge(objp, gfpflags);
  3543. }
  3544. EXPORT_SYMBOL(kmem_cache_charge);
  3545. /**
  3546. * kmem_cache_alloc_node - Allocate an object on the specified node
  3547. * @s: The cache to allocate from.
  3548. * @gfpflags: See kmalloc().
  3549. * @node: node number of the target node.
  3550. *
  3551. * Identical to kmem_cache_alloc but it will allocate memory on the given
  3552. * node, which can improve the performance for cpu bound structures.
  3553. *
  3554. * Fallback to other node is possible if __GFP_THISNODE is not set.
  3555. *
  3556. * Return: pointer to the new object or %NULL in case of error
  3557. */
  3558. void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
  3559. {
  3560. void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
  3561. trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
  3562. return ret;
  3563. }
  3564. EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
  3565. /*
  3566. * To avoid unnecessary overhead, we pass through large allocation requests
  3567. * directly to the page allocator. We use __GFP_COMP, because we will need to
  3568. * know the allocation order to free the pages properly in kfree.
  3569. */
  3570. static void *___kmalloc_large_node(size_t size, gfp_t flags, int node)
  3571. {
  3572. struct folio *folio;
  3573. void *ptr = NULL;
  3574. unsigned int order = get_order(size);
  3575. if (unlikely(flags & GFP_SLAB_BUG_MASK))
  3576. flags = kmalloc_fix_flags(flags);
  3577. flags |= __GFP_COMP;
  3578. folio = (struct folio *)alloc_pages_node_noprof(node, flags, order);
  3579. if (folio) {
  3580. ptr = folio_address(folio);
  3581. lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
  3582. PAGE_SIZE << order);
  3583. }
  3584. ptr = kasan_kmalloc_large(ptr, size, flags);
  3585. /* As ptr might get tagged, call kmemleak hook after KASAN. */
  3586. kmemleak_alloc(ptr, size, 1, flags);
  3587. kmsan_kmalloc_large(ptr, size, flags);
  3588. return ptr;
  3589. }
  3590. void *__kmalloc_large_noprof(size_t size, gfp_t flags)
  3591. {
  3592. void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE);
  3593. trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
  3594. flags, NUMA_NO_NODE);
  3595. return ret;
  3596. }
  3597. EXPORT_SYMBOL(__kmalloc_large_noprof);
  3598. void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
  3599. {
  3600. void *ret = ___kmalloc_large_node(size, flags, node);
  3601. trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
  3602. flags, node);
  3603. return ret;
  3604. }
  3605. EXPORT_SYMBOL(__kmalloc_large_node_noprof);
  3606. static __always_inline
  3607. void *__do_kmalloc_node(size_t size, kmem_buckets *b, gfp_t flags, int node,
  3608. unsigned long caller)
  3609. {
  3610. struct kmem_cache *s;
  3611. void *ret;
  3612. if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
  3613. ret = __kmalloc_large_node_noprof(size, flags, node);
  3614. trace_kmalloc(caller, ret, size,
  3615. PAGE_SIZE << get_order(size), flags, node);
  3616. return ret;
  3617. }
  3618. if (unlikely(!size))
  3619. return ZERO_SIZE_PTR;
  3620. s = kmalloc_slab(size, b, flags, caller);
  3621. ret = slab_alloc_node(s, NULL, flags, node, caller, size);
  3622. ret = kasan_kmalloc(s, ret, size, flags);
  3623. trace_kmalloc(caller, ret, size, s->size, flags, node);
  3624. return ret;
  3625. }
  3626. void *__kmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
  3627. {
  3628. return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, _RET_IP_);
  3629. }
  3630. EXPORT_SYMBOL(__kmalloc_node_noprof);
  3631. void *__kmalloc_noprof(size_t size, gfp_t flags)
  3632. {
  3633. return __do_kmalloc_node(size, NULL, flags, NUMA_NO_NODE, _RET_IP_);
  3634. }
  3635. EXPORT_SYMBOL(__kmalloc_noprof);
  3636. void *__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags,
  3637. int node, unsigned long caller)
  3638. {
  3639. return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, caller);
  3640. }
  3641. EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof);
  3642. void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size)
  3643. {
  3644. void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE,
  3645. _RET_IP_, size);
  3646. trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
  3647. ret = kasan_kmalloc(s, ret, size, gfpflags);
  3648. return ret;
  3649. }
  3650. EXPORT_SYMBOL(__kmalloc_cache_noprof);
  3651. void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags,
  3652. int node, size_t size)
  3653. {
  3654. void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, size);
  3655. trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
  3656. ret = kasan_kmalloc(s, ret, size, gfpflags);
  3657. return ret;
  3658. }
  3659. EXPORT_SYMBOL(__kmalloc_cache_node_noprof);
  3660. static noinline void free_to_partial_list(
  3661. struct kmem_cache *s, struct slab *slab,
  3662. void *head, void *tail, int bulk_cnt,
  3663. unsigned long addr)
  3664. {
  3665. struct kmem_cache_node *n = get_node(s, slab_nid(slab));
  3666. struct slab *slab_free = NULL;
  3667. int cnt = bulk_cnt;
  3668. unsigned long flags;
  3669. depot_stack_handle_t handle = 0;
  3670. if (s->flags & SLAB_STORE_USER)
  3671. handle = set_track_prepare();
  3672. spin_lock_irqsave(&n->list_lock, flags);
  3673. if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
  3674. void *prior = slab->freelist;
  3675. /* Perform the actual freeing while we still hold the locks */
  3676. slab->inuse -= cnt;
  3677. set_freepointer(s, tail, prior);
  3678. slab->freelist = head;
  3679. /*
  3680. * If the slab is empty, and node's partial list is full,
  3681. * it should be discarded anyway no matter it's on full or
  3682. * partial list.
  3683. */
  3684. if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
  3685. slab_free = slab;
  3686. if (!prior) {
  3687. /* was on full list */
  3688. remove_full(s, n, slab);
  3689. if (!slab_free) {
  3690. add_partial(n, slab, DEACTIVATE_TO_TAIL);
  3691. stat(s, FREE_ADD_PARTIAL);
  3692. }
  3693. } else if (slab_free) {
  3694. remove_partial(n, slab);
  3695. stat(s, FREE_REMOVE_PARTIAL);
  3696. }
  3697. }
  3698. if (slab_free) {
  3699. /*
  3700. * Update the counters while still holding n->list_lock to
  3701. * prevent spurious validation warnings
  3702. */
  3703. dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
  3704. }
  3705. spin_unlock_irqrestore(&n->list_lock, flags);
  3706. if (slab_free) {
  3707. stat(s, FREE_SLAB);
  3708. free_slab(s, slab_free);
  3709. }
  3710. }
  3711. /*
  3712. * Slow path handling. This may still be called frequently since objects
  3713. * have a longer lifetime than the cpu slabs in most processing loads.
  3714. *
  3715. * So we still attempt to reduce cache line usage. Just take the slab
  3716. * lock and free the item. If there is no additional partial slab
  3717. * handling required then we can return immediately.
  3718. */
  3719. static void __slab_free(struct kmem_cache *s, struct slab *slab,
  3720. void *head, void *tail, int cnt,
  3721. unsigned long addr)
  3722. {
  3723. void *prior;
  3724. int was_frozen;
  3725. struct slab new;
  3726. unsigned long counters;
  3727. struct kmem_cache_node *n = NULL;
  3728. unsigned long flags;
  3729. bool on_node_partial;
  3730. stat(s, FREE_SLOWPATH);
  3731. if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
  3732. free_to_partial_list(s, slab, head, tail, cnt, addr);
  3733. return;
  3734. }
  3735. do {
  3736. if (unlikely(n)) {
  3737. spin_unlock_irqrestore(&n->list_lock, flags);
  3738. n = NULL;
  3739. }
  3740. prior = slab->freelist;
  3741. counters = slab->counters;
  3742. set_freepointer(s, tail, prior);
  3743. new.counters = counters;
  3744. was_frozen = new.frozen;
  3745. new.inuse -= cnt;
  3746. if ((!new.inuse || !prior) && !was_frozen) {
  3747. /* Needs to be taken off a list */
  3748. if (!kmem_cache_has_cpu_partial(s) || prior) {
  3749. n = get_node(s, slab_nid(slab));
  3750. /*
  3751. * Speculatively acquire the list_lock.
  3752. * If the cmpxchg does not succeed then we may
  3753. * drop the list_lock without any processing.
  3754. *
  3755. * Otherwise the list_lock will synchronize with
  3756. * other processors updating the list of slabs.
  3757. */
  3758. spin_lock_irqsave(&n->list_lock, flags);
  3759. on_node_partial = slab_test_node_partial(slab);
  3760. }
  3761. }
  3762. } while (!slab_update_freelist(s, slab,
  3763. prior, counters,
  3764. head, new.counters,
  3765. "__slab_free"));
  3766. if (likely(!n)) {
  3767. if (likely(was_frozen)) {
  3768. /*
  3769. * The list lock was not taken therefore no list
  3770. * activity can be necessary.
  3771. */
  3772. stat(s, FREE_FROZEN);
  3773. } else if (kmem_cache_has_cpu_partial(s) && !prior) {
  3774. /*
  3775. * If we started with a full slab then put it onto the
  3776. * per cpu partial list.
  3777. */
  3778. put_cpu_partial(s, slab, 1);
  3779. stat(s, CPU_PARTIAL_FREE);
  3780. }
  3781. return;
  3782. }
  3783. /*
  3784. * This slab was partially empty but not on the per-node partial list,
  3785. * in which case we shouldn't manipulate its list, just return.
  3786. */
  3787. if (prior && !on_node_partial) {
  3788. spin_unlock_irqrestore(&n->list_lock, flags);
  3789. return;
  3790. }
  3791. if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
  3792. goto slab_empty;
  3793. /*
  3794. * Objects left in the slab. If it was not on the partial list before
  3795. * then add it.
  3796. */
  3797. if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
  3798. add_partial(n, slab, DEACTIVATE_TO_TAIL);
  3799. stat(s, FREE_ADD_PARTIAL);
  3800. }
  3801. spin_unlock_irqrestore(&n->list_lock, flags);
  3802. return;
  3803. slab_empty:
  3804. if (prior) {
  3805. /*
  3806. * Slab on the partial list.
  3807. */
  3808. remove_partial(n, slab);
  3809. stat(s, FREE_REMOVE_PARTIAL);
  3810. }
  3811. spin_unlock_irqrestore(&n->list_lock, flags);
  3812. stat(s, FREE_SLAB);
  3813. discard_slab(s, slab);
  3814. }
  3815. #ifndef CONFIG_SLUB_TINY
  3816. /*
  3817. * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
  3818. * can perform fastpath freeing without additional function calls.
  3819. *
  3820. * The fastpath is only possible if we are freeing to the current cpu slab
  3821. * of this processor. This typically the case if we have just allocated
  3822. * the item before.
  3823. *
  3824. * If fastpath is not possible then fall back to __slab_free where we deal
  3825. * with all sorts of special processing.
  3826. *
  3827. * Bulk free of a freelist with several objects (all pointing to the
  3828. * same slab) possible by specifying head and tail ptr, plus objects
  3829. * count (cnt). Bulk free indicated by tail pointer being set.
  3830. */
  3831. static __always_inline void do_slab_free(struct kmem_cache *s,
  3832. struct slab *slab, void *head, void *tail,
  3833. int cnt, unsigned long addr)
  3834. {
  3835. struct kmem_cache_cpu *c;
  3836. unsigned long tid;
  3837. void **freelist;
  3838. redo:
  3839. /*
  3840. * Determine the currently cpus per cpu slab.
  3841. * The cpu may change afterward. However that does not matter since
  3842. * data is retrieved via this pointer. If we are on the same cpu
  3843. * during the cmpxchg then the free will succeed.
  3844. */
  3845. c = raw_cpu_ptr(s->cpu_slab);
  3846. tid = READ_ONCE(c->tid);
  3847. /* Same with comment on barrier() in __slab_alloc_node() */
  3848. barrier();
  3849. if (unlikely(slab != c->slab)) {
  3850. __slab_free(s, slab, head, tail, cnt, addr);
  3851. return;
  3852. }
  3853. if (USE_LOCKLESS_FAST_PATH()) {
  3854. freelist = READ_ONCE(c->freelist);
  3855. set_freepointer(s, tail, freelist);
  3856. if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
  3857. note_cmpxchg_failure("slab_free", s, tid);
  3858. goto redo;
  3859. }
  3860. } else {
  3861. /* Update the free list under the local lock */
  3862. local_lock(&s->cpu_slab->lock);
  3863. c = this_cpu_ptr(s->cpu_slab);
  3864. if (unlikely(slab != c->slab)) {
  3865. local_unlock(&s->cpu_slab->lock);
  3866. goto redo;
  3867. }
  3868. tid = c->tid;
  3869. freelist = c->freelist;
  3870. set_freepointer(s, tail, freelist);
  3871. c->freelist = head;
  3872. c->tid = next_tid(tid);
  3873. local_unlock(&s->cpu_slab->lock);
  3874. }
  3875. stat_add(s, FREE_FASTPATH, cnt);
  3876. }
  3877. #else /* CONFIG_SLUB_TINY */
  3878. static void do_slab_free(struct kmem_cache *s,
  3879. struct slab *slab, void *head, void *tail,
  3880. int cnt, unsigned long addr)
  3881. {
  3882. __slab_free(s, slab, head, tail, cnt, addr);
  3883. }
  3884. #endif /* CONFIG_SLUB_TINY */
  3885. static __fastpath_inline
  3886. void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
  3887. unsigned long addr)
  3888. {
  3889. memcg_slab_free_hook(s, slab, &object, 1);
  3890. alloc_tagging_slab_free_hook(s, slab, &object, 1);
  3891. if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
  3892. do_slab_free(s, slab, object, object, 1, addr);
  3893. }
  3894. #ifdef CONFIG_MEMCG
  3895. /* Do not inline the rare memcg charging failed path into the allocation path */
  3896. static noinline
  3897. void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
  3898. {
  3899. if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
  3900. do_slab_free(s, virt_to_slab(object), object, object, 1, _RET_IP_);
  3901. }
  3902. #endif
  3903. static __fastpath_inline
  3904. void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
  3905. void *tail, void **p, int cnt, unsigned long addr)
  3906. {
  3907. memcg_slab_free_hook(s, slab, p, cnt);
  3908. alloc_tagging_slab_free_hook(s, slab, p, cnt);
  3909. /*
  3910. * With KASAN enabled slab_free_freelist_hook modifies the freelist
  3911. * to remove objects, whose reuse must be delayed.
  3912. */
  3913. if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt)))
  3914. do_slab_free(s, slab, head, tail, cnt, addr);
  3915. }
  3916. #ifdef CONFIG_SLUB_RCU_DEBUG
  3917. static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
  3918. {
  3919. struct rcu_delayed_free *delayed_free =
  3920. container_of(rcu_head, struct rcu_delayed_free, head);
  3921. void *object = delayed_free->object;
  3922. struct slab *slab = virt_to_slab(object);
  3923. struct kmem_cache *s;
  3924. kfree(delayed_free);
  3925. if (WARN_ON(is_kfence_address(object)))
  3926. return;
  3927. /* find the object and the cache again */
  3928. if (WARN_ON(!slab))
  3929. return;
  3930. s = slab->slab_cache;
  3931. if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
  3932. return;
  3933. /* resume freeing */
  3934. if (slab_free_hook(s, object, slab_want_init_on_free(s), true))
  3935. do_slab_free(s, slab, object, object, 1, _THIS_IP_);
  3936. }
  3937. #endif /* CONFIG_SLUB_RCU_DEBUG */
  3938. #ifdef CONFIG_KASAN_GENERIC
  3939. void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
  3940. {
  3941. do_slab_free(cache, virt_to_slab(x), x, x, 1, addr);
  3942. }
  3943. #endif
  3944. static inline struct kmem_cache *virt_to_cache(const void *obj)
  3945. {
  3946. struct slab *slab;
  3947. slab = virt_to_slab(obj);
  3948. if (WARN_ONCE(!slab, "%s: Object is not a Slab page!\n", __func__))
  3949. return NULL;
  3950. return slab->slab_cache;
  3951. }
  3952. static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x)
  3953. {
  3954. struct kmem_cache *cachep;
  3955. if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
  3956. !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS))
  3957. return s;
  3958. cachep = virt_to_cache(x);
  3959. if (WARN(cachep && cachep != s,
  3960. "%s: Wrong slab cache. %s but object is from %s\n",
  3961. __func__, s->name, cachep->name))
  3962. print_tracking(cachep, x);
  3963. return cachep;
  3964. }
  3965. /**
  3966. * kmem_cache_free - Deallocate an object
  3967. * @s: The cache the allocation was from.
  3968. * @x: The previously allocated object.
  3969. *
  3970. * Free an object which was previously allocated from this
  3971. * cache.
  3972. */
  3973. void kmem_cache_free(struct kmem_cache *s, void *x)
  3974. {
  3975. s = cache_from_obj(s, x);
  3976. if (!s)
  3977. return;
  3978. trace_kmem_cache_free(_RET_IP_, x, s);
  3979. slab_free(s, virt_to_slab(x), x, _RET_IP_);
  3980. }
  3981. EXPORT_SYMBOL(kmem_cache_free);
  3982. static void free_large_kmalloc(struct folio *folio, void *object)
  3983. {
  3984. unsigned int order = folio_order(folio);
  3985. if (WARN_ON_ONCE(order == 0))
  3986. pr_warn_once("object pointer: 0x%p\n", object);
  3987. kmemleak_free(object);
  3988. kasan_kfree_large(object);
  3989. kmsan_kfree_large(object);
  3990. lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
  3991. -(PAGE_SIZE << order));
  3992. folio_put(folio);
  3993. }
  3994. /**
  3995. * kfree - free previously allocated memory
  3996. * @object: pointer returned by kmalloc() or kmem_cache_alloc()
  3997. *
  3998. * If @object is NULL, no operation is performed.
  3999. */
  4000. void kfree(const void *object)
  4001. {
  4002. struct folio *folio;
  4003. struct slab *slab;
  4004. struct kmem_cache *s;
  4005. void *x = (void *)object;
  4006. trace_kfree(_RET_IP_, object);
  4007. if (unlikely(ZERO_OR_NULL_PTR(object)))
  4008. return;
  4009. folio = virt_to_folio(object);
  4010. if (unlikely(!folio_test_slab(folio))) {
  4011. free_large_kmalloc(folio, (void *)object);
  4012. return;
  4013. }
  4014. slab = folio_slab(folio);
  4015. s = slab->slab_cache;
  4016. slab_free(s, slab, x, _RET_IP_);
  4017. }
  4018. EXPORT_SYMBOL(kfree);
  4019. struct detached_freelist {
  4020. struct slab *slab;
  4021. void *tail;
  4022. void *freelist;
  4023. int cnt;
  4024. struct kmem_cache *s;
  4025. };
  4026. /*
  4027. * This function progressively scans the array with free objects (with
  4028. * a limited look ahead) and extract objects belonging to the same
  4029. * slab. It builds a detached freelist directly within the given
  4030. * slab/objects. This can happen without any need for
  4031. * synchronization, because the objects are owned by running process.
  4032. * The freelist is build up as a single linked list in the objects.
  4033. * The idea is, that this detached freelist can then be bulk
  4034. * transferred to the real freelist(s), but only requiring a single
  4035. * synchronization primitive. Look ahead in the array is limited due
  4036. * to performance reasons.
  4037. */
  4038. static inline
  4039. int build_detached_freelist(struct kmem_cache *s, size_t size,
  4040. void **p, struct detached_freelist *df)
  4041. {
  4042. int lookahead = 3;
  4043. void *object;
  4044. struct folio *folio;
  4045. size_t same;
  4046. object = p[--size];
  4047. folio = virt_to_folio(object);
  4048. if (!s) {
  4049. /* Handle kalloc'ed objects */
  4050. if (unlikely(!folio_test_slab(folio))) {
  4051. free_large_kmalloc(folio, object);
  4052. df->slab = NULL;
  4053. return size;
  4054. }
  4055. /* Derive kmem_cache from object */
  4056. df->slab = folio_slab(folio);
  4057. df->s = df->slab->slab_cache;
  4058. } else {
  4059. df->slab = folio_slab(folio);
  4060. df->s = cache_from_obj(s, object); /* Support for memcg */
  4061. }
  4062. /* Start new detached freelist */
  4063. df->tail = object;
  4064. df->freelist = object;
  4065. df->cnt = 1;
  4066. if (is_kfence_address(object))
  4067. return size;
  4068. set_freepointer(df->s, object, NULL);
  4069. same = size;
  4070. while (size) {
  4071. object = p[--size];
  4072. /* df->slab is always set at this point */
  4073. if (df->slab == virt_to_slab(object)) {
  4074. /* Opportunity build freelist */
  4075. set_freepointer(df->s, object, df->freelist);
  4076. df->freelist = object;
  4077. df->cnt++;
  4078. same--;
  4079. if (size != same)
  4080. swap(p[size], p[same]);
  4081. continue;
  4082. }
  4083. /* Limit look ahead search */
  4084. if (!--lookahead)
  4085. break;
  4086. }
  4087. return same;
  4088. }
  4089. /*
  4090. * Internal bulk free of objects that were not initialised by the post alloc
  4091. * hooks and thus should not be processed by the free hooks
  4092. */
  4093. static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
  4094. {
  4095. if (!size)
  4096. return;
  4097. do {
  4098. struct detached_freelist df;
  4099. size = build_detached_freelist(s, size, p, &df);
  4100. if (!df.slab)
  4101. continue;
  4102. if (kfence_free(df.freelist))
  4103. continue;
  4104. do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
  4105. _RET_IP_);
  4106. } while (likely(size));
  4107. }
  4108. /* Note that interrupts must be enabled when calling this function. */
  4109. void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
  4110. {
  4111. if (!size)
  4112. return;
  4113. do {
  4114. struct detached_freelist df;
  4115. size = build_detached_freelist(s, size, p, &df);
  4116. if (!df.slab)
  4117. continue;
  4118. slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
  4119. df.cnt, _RET_IP_);
  4120. } while (likely(size));
  4121. }
  4122. EXPORT_SYMBOL(kmem_cache_free_bulk);
  4123. #ifndef CONFIG_SLUB_TINY
  4124. static inline
  4125. int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
  4126. void **p)
  4127. {
  4128. struct kmem_cache_cpu *c;
  4129. unsigned long irqflags;
  4130. int i;
  4131. /*
  4132. * Drain objects in the per cpu slab, while disabling local
  4133. * IRQs, which protects against PREEMPT and interrupts
  4134. * handlers invoking normal fastpath.
  4135. */
  4136. c = slub_get_cpu_ptr(s->cpu_slab);
  4137. local_lock_irqsave(&s->cpu_slab->lock, irqflags);
  4138. for (i = 0; i < size; i++) {
  4139. void *object = kfence_alloc(s, s->object_size, flags);
  4140. if (unlikely(object)) {
  4141. p[i] = object;
  4142. continue;
  4143. }
  4144. object = c->freelist;
  4145. if (unlikely(!object)) {
  4146. /*
  4147. * We may have removed an object from c->freelist using
  4148. * the fastpath in the previous iteration; in that case,
  4149. * c->tid has not been bumped yet.
  4150. * Since ___slab_alloc() may reenable interrupts while
  4151. * allocating memory, we should bump c->tid now.
  4152. */
  4153. c->tid = next_tid(c->tid);
  4154. local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
  4155. /*
  4156. * Invoking slow path likely have side-effect
  4157. * of re-populating per CPU c->freelist
  4158. */
  4159. p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
  4160. _RET_IP_, c, s->object_size);
  4161. if (unlikely(!p[i]))
  4162. goto error;
  4163. c = this_cpu_ptr(s->cpu_slab);
  4164. maybe_wipe_obj_freeptr(s, p[i]);
  4165. local_lock_irqsave(&s->cpu_slab->lock, irqflags);
  4166. continue; /* goto for-loop */
  4167. }
  4168. c->freelist = get_freepointer(s, object);
  4169. p[i] = object;
  4170. maybe_wipe_obj_freeptr(s, p[i]);
  4171. stat(s, ALLOC_FASTPATH);
  4172. }
  4173. c->tid = next_tid(c->tid);
  4174. local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
  4175. slub_put_cpu_ptr(s->cpu_slab);
  4176. return i;
  4177. error:
  4178. slub_put_cpu_ptr(s->cpu_slab);
  4179. __kmem_cache_free_bulk(s, i, p);
  4180. return 0;
  4181. }
  4182. #else /* CONFIG_SLUB_TINY */
  4183. static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
  4184. size_t size, void **p)
  4185. {
  4186. int i;
  4187. for (i = 0; i < size; i++) {
  4188. void *object = kfence_alloc(s, s->object_size, flags);
  4189. if (unlikely(object)) {
  4190. p[i] = object;
  4191. continue;
  4192. }
  4193. p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE,
  4194. _RET_IP_, s->object_size);
  4195. if (unlikely(!p[i]))
  4196. goto error;
  4197. maybe_wipe_obj_freeptr(s, p[i]);
  4198. }
  4199. return i;
  4200. error:
  4201. __kmem_cache_free_bulk(s, i, p);
  4202. return 0;
  4203. }
  4204. #endif /* CONFIG_SLUB_TINY */
  4205. /* Note that interrupts must be enabled when calling this function. */
  4206. int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size,
  4207. void **p)
  4208. {
  4209. int i;
  4210. if (!size)
  4211. return 0;
  4212. s = slab_pre_alloc_hook(s, flags);
  4213. if (unlikely(!s))
  4214. return 0;
  4215. i = __kmem_cache_alloc_bulk(s, flags, size, p);
  4216. if (unlikely(i == 0))
  4217. return 0;
  4218. /*
  4219. * memcg and kmem_cache debug support and memory initialization.
  4220. * Done outside of the IRQ disabled fastpath loop.
  4221. */
  4222. if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p,
  4223. slab_want_init_on_alloc(flags, s), s->object_size))) {
  4224. return 0;
  4225. }
  4226. return i;
  4227. }
  4228. EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
  4229. /*
  4230. * Object placement in a slab is made very easy because we always start at
  4231. * offset 0. If we tune the size of the object to the alignment then we can
  4232. * get the required alignment by putting one properly sized object after
  4233. * another.
  4234. *
  4235. * Notice that the allocation order determines the sizes of the per cpu
  4236. * caches. Each processor has always one slab available for allocations.
  4237. * Increasing the allocation order reduces the number of times that slabs
  4238. * must be moved on and off the partial lists and is therefore a factor in
  4239. * locking overhead.
  4240. */
  4241. /*
  4242. * Minimum / Maximum order of slab pages. This influences locking overhead
  4243. * and slab fragmentation. A higher order reduces the number of partial slabs
  4244. * and increases the number of allocations possible without having to
  4245. * take the list_lock.
  4246. */
  4247. static unsigned int slub_min_order;
  4248. static unsigned int slub_max_order =
  4249. IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
  4250. static unsigned int slub_min_objects;
  4251. /*
  4252. * Calculate the order of allocation given an slab object size.
  4253. *
  4254. * The order of allocation has significant impact on performance and other
  4255. * system components. Generally order 0 allocations should be preferred since
  4256. * order 0 does not cause fragmentation in the page allocator. Larger objects
  4257. * be problematic to put into order 0 slabs because there may be too much
  4258. * unused space left. We go to a higher order if more than 1/16th of the slab
  4259. * would be wasted.
  4260. *
  4261. * In order to reach satisfactory performance we must ensure that a minimum
  4262. * number of objects is in one slab. Otherwise we may generate too much
  4263. * activity on the partial lists which requires taking the list_lock. This is
  4264. * less a concern for large slabs though which are rarely used.
  4265. *
  4266. * slab_max_order specifies the order where we begin to stop considering the
  4267. * number of objects in a slab as critical. If we reach slab_max_order then
  4268. * we try to keep the page order as low as possible. So we accept more waste
  4269. * of space in favor of a small page order.
  4270. *
  4271. * Higher order allocations also allow the placement of more objects in a
  4272. * slab and thereby reduce object handling overhead. If the user has
  4273. * requested a higher minimum order then we start with that one instead of
  4274. * the smallest order which will fit the object.
  4275. */
  4276. static inline unsigned int calc_slab_order(unsigned int size,
  4277. unsigned int min_order, unsigned int max_order,
  4278. unsigned int fract_leftover)
  4279. {
  4280. unsigned int order;
  4281. for (order = min_order; order <= max_order; order++) {
  4282. unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
  4283. unsigned int rem;
  4284. rem = slab_size % size;
  4285. if (rem <= slab_size / fract_leftover)
  4286. break;
  4287. }
  4288. return order;
  4289. }
  4290. static inline int calculate_order(unsigned int size)
  4291. {
  4292. unsigned int order;
  4293. unsigned int min_objects;
  4294. unsigned int max_objects;
  4295. unsigned int min_order;
  4296. min_objects = slub_min_objects;
  4297. if (!min_objects) {
  4298. /*
  4299. * Some architectures will only update present cpus when
  4300. * onlining them, so don't trust the number if it's just 1. But
  4301. * we also don't want to use nr_cpu_ids always, as on some other
  4302. * architectures, there can be many possible cpus, but never
  4303. * onlined. Here we compromise between trying to avoid too high
  4304. * order on systems that appear larger than they are, and too
  4305. * low order on systems that appear smaller than they are.
  4306. */
  4307. unsigned int nr_cpus = num_present_cpus();
  4308. if (nr_cpus <= 1)
  4309. nr_cpus = nr_cpu_ids;
  4310. min_objects = 4 * (fls(nr_cpus) + 1);
  4311. }
  4312. /* min_objects can't be 0 because get_order(0) is undefined */
  4313. max_objects = max(order_objects(slub_max_order, size), 1U);
  4314. min_objects = min(min_objects, max_objects);
  4315. min_order = max_t(unsigned int, slub_min_order,
  4316. get_order(min_objects * size));
  4317. if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
  4318. return get_order(size * MAX_OBJS_PER_PAGE) - 1;
  4319. /*
  4320. * Attempt to find best configuration for a slab. This works by first
  4321. * attempting to generate a layout with the best possible configuration
  4322. * and backing off gradually.
  4323. *
  4324. * We start with accepting at most 1/16 waste and try to find the
  4325. * smallest order from min_objects-derived/slab_min_order up to
  4326. * slab_max_order that will satisfy the constraint. Note that increasing
  4327. * the order can only result in same or less fractional waste, not more.
  4328. *
  4329. * If that fails, we increase the acceptable fraction of waste and try
  4330. * again. The last iteration with fraction of 1/2 would effectively
  4331. * accept any waste and give us the order determined by min_objects, as
  4332. * long as at least single object fits within slab_max_order.
  4333. */
  4334. for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
  4335. order = calc_slab_order(size, min_order, slub_max_order,
  4336. fraction);
  4337. if (order <= slub_max_order)
  4338. return order;
  4339. }
  4340. /*
  4341. * Doh this slab cannot be placed using slab_max_order.
  4342. */
  4343. order = get_order(size);
  4344. if (order <= MAX_PAGE_ORDER)
  4345. return order;
  4346. return -ENOSYS;
  4347. }
  4348. static void
  4349. init_kmem_cache_node(struct kmem_cache_node *n)
  4350. {
  4351. n->nr_partial = 0;
  4352. spin_lock_init(&n->list_lock);
  4353. INIT_LIST_HEAD(&n->partial);
  4354. #ifdef CONFIG_SLUB_DEBUG
  4355. atomic_long_set(&n->nr_slabs, 0);
  4356. atomic_long_set(&n->total_objects, 0);
  4357. INIT_LIST_HEAD(&n->full);
  4358. #endif
  4359. }
  4360. #ifndef CONFIG_SLUB_TINY
  4361. static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
  4362. {
  4363. BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
  4364. NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
  4365. sizeof(struct kmem_cache_cpu));
  4366. /*
  4367. * Must align to double word boundary for the double cmpxchg
  4368. * instructions to work; see __pcpu_double_call_return_bool().
  4369. */
  4370. s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
  4371. 2 * sizeof(void *));
  4372. if (!s->cpu_slab)
  4373. return 0;
  4374. init_kmem_cache_cpus(s);
  4375. return 1;
  4376. }
  4377. #else
  4378. static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
  4379. {
  4380. return 1;
  4381. }
  4382. #endif /* CONFIG_SLUB_TINY */
  4383. static struct kmem_cache *kmem_cache_node;
  4384. /*
  4385. * No kmalloc_node yet so do it by hand. We know that this is the first
  4386. * slab on the node for this slabcache. There are no concurrent accesses
  4387. * possible.
  4388. *
  4389. * Note that this function only works on the kmem_cache_node
  4390. * when allocating for the kmem_cache_node. This is used for bootstrapping
  4391. * memory on a fresh node that has no slab structures yet.
  4392. */
  4393. static void early_kmem_cache_node_alloc(int node)
  4394. {
  4395. struct slab *slab;
  4396. struct kmem_cache_node *n;
  4397. BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
  4398. slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
  4399. BUG_ON(!slab);
  4400. if (slab_nid(slab) != node) {
  4401. pr_err("SLUB: Unable to allocate memory from node %d\n", node);
  4402. pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
  4403. }
  4404. n = slab->freelist;
  4405. BUG_ON(!n);
  4406. #ifdef CONFIG_SLUB_DEBUG
  4407. init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
  4408. #endif
  4409. n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
  4410. slab->freelist = get_freepointer(kmem_cache_node, n);
  4411. slab->inuse = 1;
  4412. kmem_cache_node->node[node] = n;
  4413. init_kmem_cache_node(n);
  4414. inc_slabs_node(kmem_cache_node, node, slab->objects);
  4415. /*
  4416. * No locks need to be taken here as it has just been
  4417. * initialized and there is no concurrent access.
  4418. */
  4419. __add_partial(n, slab, DEACTIVATE_TO_HEAD);
  4420. }
  4421. static void free_kmem_cache_nodes(struct kmem_cache *s)
  4422. {
  4423. int node;
  4424. struct kmem_cache_node *n;
  4425. for_each_kmem_cache_node(s, node, n) {
  4426. s->node[node] = NULL;
  4427. kmem_cache_free(kmem_cache_node, n);
  4428. }
  4429. }
  4430. void __kmem_cache_release(struct kmem_cache *s)
  4431. {
  4432. cache_random_seq_destroy(s);
  4433. #ifndef CONFIG_SLUB_TINY
  4434. free_percpu(s->cpu_slab);
  4435. #endif
  4436. free_kmem_cache_nodes(s);
  4437. }
  4438. static int init_kmem_cache_nodes(struct kmem_cache *s)
  4439. {
  4440. int node;
  4441. for_each_node_mask(node, slab_nodes) {
  4442. struct kmem_cache_node *n;
  4443. if (slab_state == DOWN) {
  4444. early_kmem_cache_node_alloc(node);
  4445. continue;
  4446. }
  4447. n = kmem_cache_alloc_node(kmem_cache_node,
  4448. GFP_KERNEL, node);
  4449. if (!n) {
  4450. free_kmem_cache_nodes(s);
  4451. return 0;
  4452. }
  4453. init_kmem_cache_node(n);
  4454. s->node[node] = n;
  4455. }
  4456. return 1;
  4457. }
  4458. static void set_cpu_partial(struct kmem_cache *s)
  4459. {
  4460. #ifdef CONFIG_SLUB_CPU_PARTIAL
  4461. unsigned int nr_objects;
  4462. /*
  4463. * cpu_partial determined the maximum number of objects kept in the
  4464. * per cpu partial lists of a processor.
  4465. *
  4466. * Per cpu partial lists mainly contain slabs that just have one
  4467. * object freed. If they are used for allocation then they can be
  4468. * filled up again with minimal effort. The slab will never hit the
  4469. * per node partial lists and therefore no locking will be required.
  4470. *
  4471. * For backwards compatibility reasons, this is determined as number
  4472. * of objects, even though we now limit maximum number of pages, see
  4473. * slub_set_cpu_partial()
  4474. */
  4475. if (!kmem_cache_has_cpu_partial(s))
  4476. nr_objects = 0;
  4477. else if (s->size >= PAGE_SIZE)
  4478. nr_objects = 6;
  4479. else if (s->size >= 1024)
  4480. nr_objects = 24;
  4481. else if (s->size >= 256)
  4482. nr_objects = 52;
  4483. else
  4484. nr_objects = 120;
  4485. slub_set_cpu_partial(s, nr_objects);
  4486. #endif
  4487. }
  4488. /*
  4489. * calculate_sizes() determines the order and the distribution of data within
  4490. * a slab object.
  4491. */
  4492. static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
  4493. {
  4494. slab_flags_t flags = s->flags;
  4495. unsigned int size = s->object_size;
  4496. unsigned int order;
  4497. /*
  4498. * Round up object size to the next word boundary. We can only
  4499. * place the free pointer at word boundaries and this determines
  4500. * the possible location of the free pointer.
  4501. */
  4502. size = ALIGN(size, sizeof(void *));
  4503. #ifdef CONFIG_SLUB_DEBUG
  4504. /*
  4505. * Determine if we can poison the object itself. If the user of
  4506. * the slab may touch the object after free or before allocation
  4507. * then we should never poison the object itself.
  4508. */
  4509. if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
  4510. !s->ctor)
  4511. s->flags |= __OBJECT_POISON;
  4512. else
  4513. s->flags &= ~__OBJECT_POISON;
  4514. /*
  4515. * If we are Redzoning then check if there is some space between the
  4516. * end of the object and the free pointer. If not then add an
  4517. * additional word to have some bytes to store Redzone information.
  4518. */
  4519. if ((flags & SLAB_RED_ZONE) && size == s->object_size)
  4520. size += sizeof(void *);
  4521. #endif
  4522. /*
  4523. * With that we have determined the number of bytes in actual use
  4524. * by the object and redzoning.
  4525. */
  4526. s->inuse = size;
  4527. if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
  4528. (flags & SLAB_POISON) || s->ctor ||
  4529. ((flags & SLAB_RED_ZONE) &&
  4530. (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
  4531. /*
  4532. * Relocate free pointer after the object if it is not
  4533. * permitted to overwrite the first word of the object on
  4534. * kmem_cache_free.
  4535. *
  4536. * This is the case if we do RCU, have a constructor or
  4537. * destructor, are poisoning the objects, or are
  4538. * redzoning an object smaller than sizeof(void *) or are
  4539. * redzoning an object with slub_debug_orig_size() enabled,
  4540. * in which case the right redzone may be extended.
  4541. *
  4542. * The assumption that s->offset >= s->inuse means free
  4543. * pointer is outside of the object is used in the
  4544. * freeptr_outside_object() function. If that is no
  4545. * longer true, the function needs to be modified.
  4546. */
  4547. s->offset = size;
  4548. size += sizeof(void *);
  4549. } else if ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) {
  4550. s->offset = args->freeptr_offset;
  4551. } else {
  4552. /*
  4553. * Store freelist pointer near middle of object to keep
  4554. * it away from the edges of the object to avoid small
  4555. * sized over/underflows from neighboring allocations.
  4556. */
  4557. s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
  4558. }
  4559. #ifdef CONFIG_SLUB_DEBUG
  4560. if (flags & SLAB_STORE_USER) {
  4561. /*
  4562. * Need to store information about allocs and frees after
  4563. * the object.
  4564. */
  4565. size += 2 * sizeof(struct track);
  4566. /* Save the original kmalloc request size */
  4567. if (flags & SLAB_KMALLOC)
  4568. size += sizeof(unsigned int);
  4569. }
  4570. #endif
  4571. kasan_cache_create(s, &size, &s->flags);
  4572. #ifdef CONFIG_SLUB_DEBUG
  4573. if (flags & SLAB_RED_ZONE) {
  4574. /*
  4575. * Add some empty padding so that we can catch
  4576. * overwrites from earlier objects rather than let
  4577. * tracking information or the free pointer be
  4578. * corrupted if a user writes before the start
  4579. * of the object.
  4580. */
  4581. size += sizeof(void *);
  4582. s->red_left_pad = sizeof(void *);
  4583. s->red_left_pad = ALIGN(s->red_left_pad, s->align);
  4584. size += s->red_left_pad;
  4585. }
  4586. #endif
  4587. /*
  4588. * SLUB stores one object immediately after another beginning from
  4589. * offset 0. In order to align the objects we have to simply size
  4590. * each object to conform to the alignment.
  4591. */
  4592. size = ALIGN(size, s->align);
  4593. s->size = size;
  4594. s->reciprocal_size = reciprocal_value(size);
  4595. order = calculate_order(size);
  4596. if ((int)order < 0)
  4597. return 0;
  4598. s->allocflags = __GFP_COMP;
  4599. if (s->flags & SLAB_CACHE_DMA)
  4600. s->allocflags |= GFP_DMA;
  4601. if (s->flags & SLAB_CACHE_DMA32)
  4602. s->allocflags |= GFP_DMA32;
  4603. if (s->flags & SLAB_RECLAIM_ACCOUNT)
  4604. s->allocflags |= __GFP_RECLAIMABLE;
  4605. /*
  4606. * Determine the number of objects per slab
  4607. */
  4608. s->oo = oo_make(order, size);
  4609. s->min = oo_make(get_order(size), size);
  4610. return !!oo_objects(s->oo);
  4611. }
  4612. static void list_slab_objects(struct kmem_cache *s, struct slab *slab,
  4613. const char *text)
  4614. {
  4615. #ifdef CONFIG_SLUB_DEBUG
  4616. void *addr = slab_address(slab);
  4617. void *p;
  4618. slab_err(s, slab, text, s->name);
  4619. spin_lock(&object_map_lock);
  4620. __fill_map(object_map, s, slab);
  4621. for_each_object(p, s, addr, slab->objects) {
  4622. if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
  4623. if (slab_add_kunit_errors())
  4624. continue;
  4625. pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
  4626. print_tracking(s, p);
  4627. }
  4628. }
  4629. spin_unlock(&object_map_lock);
  4630. #endif
  4631. }
  4632. /*
  4633. * Attempt to free all partial slabs on a node.
  4634. * This is called from __kmem_cache_shutdown(). We must take list_lock
  4635. * because sysfs file might still access partial list after the shutdowning.
  4636. */
  4637. static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
  4638. {
  4639. LIST_HEAD(discard);
  4640. struct slab *slab, *h;
  4641. BUG_ON(irqs_disabled());
  4642. spin_lock_irq(&n->list_lock);
  4643. list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
  4644. if (!slab->inuse) {
  4645. remove_partial(n, slab);
  4646. list_add(&slab->slab_list, &discard);
  4647. } else {
  4648. list_slab_objects(s, slab,
  4649. "Objects remaining in %s on __kmem_cache_shutdown()");
  4650. }
  4651. }
  4652. spin_unlock_irq(&n->list_lock);
  4653. list_for_each_entry_safe(slab, h, &discard, slab_list)
  4654. discard_slab(s, slab);
  4655. }
  4656. bool __kmem_cache_empty(struct kmem_cache *s)
  4657. {
  4658. int node;
  4659. struct kmem_cache_node *n;
  4660. for_each_kmem_cache_node(s, node, n)
  4661. if (n->nr_partial || node_nr_slabs(n))
  4662. return false;
  4663. return true;
  4664. }
  4665. /*
  4666. * Release all resources used by a slab cache.
  4667. */
  4668. int __kmem_cache_shutdown(struct kmem_cache *s)
  4669. {
  4670. int node;
  4671. struct kmem_cache_node *n;
  4672. flush_all_cpus_locked(s);
  4673. /* Attempt to free all objects */
  4674. for_each_kmem_cache_node(s, node, n) {
  4675. free_partial(s, n);
  4676. if (n->nr_partial || node_nr_slabs(n))
  4677. return 1;
  4678. }
  4679. return 0;
  4680. }
  4681. #ifdef CONFIG_PRINTK
  4682. void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
  4683. {
  4684. void *base;
  4685. int __maybe_unused i;
  4686. unsigned int objnr;
  4687. void *objp;
  4688. void *objp0;
  4689. struct kmem_cache *s = slab->slab_cache;
  4690. struct track __maybe_unused *trackp;
  4691. kpp->kp_ptr = object;
  4692. kpp->kp_slab = slab;
  4693. kpp->kp_slab_cache = s;
  4694. base = slab_address(slab);
  4695. objp0 = kasan_reset_tag(object);
  4696. #ifdef CONFIG_SLUB_DEBUG
  4697. objp = restore_red_left(s, objp0);
  4698. #else
  4699. objp = objp0;
  4700. #endif
  4701. objnr = obj_to_index(s, slab, objp);
  4702. kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
  4703. objp = base + s->size * objnr;
  4704. kpp->kp_objp = objp;
  4705. if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
  4706. || (objp - base) % s->size) ||
  4707. !(s->flags & SLAB_STORE_USER))
  4708. return;
  4709. #ifdef CONFIG_SLUB_DEBUG
  4710. objp = fixup_red_left(s, objp);
  4711. trackp = get_track(s, objp, TRACK_ALLOC);
  4712. kpp->kp_ret = (void *)trackp->addr;
  4713. #ifdef CONFIG_STACKDEPOT
  4714. {
  4715. depot_stack_handle_t handle;
  4716. unsigned long *entries;
  4717. unsigned int nr_entries;
  4718. handle = READ_ONCE(trackp->handle);
  4719. if (handle) {
  4720. nr_entries = stack_depot_fetch(handle, &entries);
  4721. for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
  4722. kpp->kp_stack[i] = (void *)entries[i];
  4723. }
  4724. trackp = get_track(s, objp, TRACK_FREE);
  4725. handle = READ_ONCE(trackp->handle);
  4726. if (handle) {
  4727. nr_entries = stack_depot_fetch(handle, &entries);
  4728. for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
  4729. kpp->kp_free_stack[i] = (void *)entries[i];
  4730. }
  4731. }
  4732. #endif
  4733. #endif
  4734. }
  4735. #endif
  4736. /********************************************************************
  4737. * Kmalloc subsystem
  4738. *******************************************************************/
  4739. static int __init setup_slub_min_order(char *str)
  4740. {
  4741. get_option(&str, (int *)&slub_min_order);
  4742. if (slub_min_order > slub_max_order)
  4743. slub_max_order = slub_min_order;
  4744. return 1;
  4745. }
  4746. __setup("slab_min_order=", setup_slub_min_order);
  4747. __setup_param("slub_min_order=", slub_min_order, setup_slub_min_order, 0);
  4748. static int __init setup_slub_max_order(char *str)
  4749. {
  4750. get_option(&str, (int *)&slub_max_order);
  4751. slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
  4752. if (slub_min_order > slub_max_order)
  4753. slub_min_order = slub_max_order;
  4754. return 1;
  4755. }
  4756. __setup("slab_max_order=", setup_slub_max_order);
  4757. __setup_param("slub_max_order=", slub_max_order, setup_slub_max_order, 0);
  4758. static int __init setup_slub_min_objects(char *str)
  4759. {
  4760. get_option(&str, (int *)&slub_min_objects);
  4761. return 1;
  4762. }
  4763. __setup("slab_min_objects=", setup_slub_min_objects);
  4764. __setup_param("slub_min_objects=", slub_min_objects, setup_slub_min_objects, 0);
  4765. #ifdef CONFIG_HARDENED_USERCOPY
  4766. /*
  4767. * Rejects incorrectly sized objects and objects that are to be copied
  4768. * to/from userspace but do not fall entirely within the containing slab
  4769. * cache's usercopy region.
  4770. *
  4771. * Returns NULL if check passes, otherwise const char * to name of cache
  4772. * to indicate an error.
  4773. */
  4774. void __check_heap_object(const void *ptr, unsigned long n,
  4775. const struct slab *slab, bool to_user)
  4776. {
  4777. struct kmem_cache *s;
  4778. unsigned int offset;
  4779. bool is_kfence = is_kfence_address(ptr);
  4780. ptr = kasan_reset_tag(ptr);
  4781. /* Find object and usable object size. */
  4782. s = slab->slab_cache;
  4783. /* Reject impossible pointers. */
  4784. if (ptr < slab_address(slab))
  4785. usercopy_abort("SLUB object not in SLUB page?!", NULL,
  4786. to_user, 0, n);
  4787. /* Find offset within object. */
  4788. if (is_kfence)
  4789. offset = ptr - kfence_object_start(ptr);
  4790. else
  4791. offset = (ptr - slab_address(slab)) % s->size;
  4792. /* Adjust for redzone and reject if within the redzone. */
  4793. if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
  4794. if (offset < s->red_left_pad)
  4795. usercopy_abort("SLUB object in left red zone",
  4796. s->name, to_user, offset, n);
  4797. offset -= s->red_left_pad;
  4798. }
  4799. /* Allow address range falling entirely within usercopy region. */
  4800. if (offset >= s->useroffset &&
  4801. offset - s->useroffset <= s->usersize &&
  4802. n <= s->useroffset - offset + s->usersize)
  4803. return;
  4804. usercopy_abort("SLUB object", s->name, to_user, offset, n);
  4805. }
  4806. #endif /* CONFIG_HARDENED_USERCOPY */
  4807. #define SHRINK_PROMOTE_MAX 32
  4808. /*
  4809. * kmem_cache_shrink discards empty slabs and promotes the slabs filled
  4810. * up most to the head of the partial lists. New allocations will then
  4811. * fill those up and thus they can be removed from the partial lists.
  4812. *
  4813. * The slabs with the least items are placed last. This results in them
  4814. * being allocated from last increasing the chance that the last objects
  4815. * are freed in them.
  4816. */
  4817. static int __kmem_cache_do_shrink(struct kmem_cache *s)
  4818. {
  4819. int node;
  4820. int i;
  4821. struct kmem_cache_node *n;
  4822. struct slab *slab;
  4823. struct slab *t;
  4824. struct list_head discard;
  4825. struct list_head promote[SHRINK_PROMOTE_MAX];
  4826. unsigned long flags;
  4827. int ret = 0;
  4828. for_each_kmem_cache_node(s, node, n) {
  4829. INIT_LIST_HEAD(&discard);
  4830. for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
  4831. INIT_LIST_HEAD(promote + i);
  4832. spin_lock_irqsave(&n->list_lock, flags);
  4833. /*
  4834. * Build lists of slabs to discard or promote.
  4835. *
  4836. * Note that concurrent frees may occur while we hold the
  4837. * list_lock. slab->inuse here is the upper limit.
  4838. */
  4839. list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
  4840. int free = slab->objects - slab->inuse;
  4841. /* Do not reread slab->inuse */
  4842. barrier();
  4843. /* We do not keep full slabs on the list */
  4844. BUG_ON(free <= 0);
  4845. if (free == slab->objects) {
  4846. list_move(&slab->slab_list, &discard);
  4847. slab_clear_node_partial(slab);
  4848. n->nr_partial--;
  4849. dec_slabs_node(s, node, slab->objects);
  4850. } else if (free <= SHRINK_PROMOTE_MAX)
  4851. list_move(&slab->slab_list, promote + free - 1);
  4852. }
  4853. /*
  4854. * Promote the slabs filled up most to the head of the
  4855. * partial list.
  4856. */
  4857. for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
  4858. list_splice(promote + i, &n->partial);
  4859. spin_unlock_irqrestore(&n->list_lock, flags);
  4860. /* Release empty slabs */
  4861. list_for_each_entry_safe(slab, t, &discard, slab_list)
  4862. free_slab(s, slab);
  4863. if (node_nr_slabs(n))
  4864. ret = 1;
  4865. }
  4866. return ret;
  4867. }
  4868. int __kmem_cache_shrink(struct kmem_cache *s)
  4869. {
  4870. flush_all(s);
  4871. return __kmem_cache_do_shrink(s);
  4872. }
  4873. static int slab_mem_going_offline_callback(void *arg)
  4874. {
  4875. struct kmem_cache *s;
  4876. mutex_lock(&slab_mutex);
  4877. list_for_each_entry(s, &slab_caches, list) {
  4878. flush_all_cpus_locked(s);
  4879. __kmem_cache_do_shrink(s);
  4880. }
  4881. mutex_unlock(&slab_mutex);
  4882. return 0;
  4883. }
  4884. static void slab_mem_offline_callback(void *arg)
  4885. {
  4886. struct memory_notify *marg = arg;
  4887. int offline_node;
  4888. offline_node = marg->status_change_nid_normal;
  4889. /*
  4890. * If the node still has available memory. we need kmem_cache_node
  4891. * for it yet.
  4892. */
  4893. if (offline_node < 0)
  4894. return;
  4895. mutex_lock(&slab_mutex);
  4896. node_clear(offline_node, slab_nodes);
  4897. /*
  4898. * We no longer free kmem_cache_node structures here, as it would be
  4899. * racy with all get_node() users, and infeasible to protect them with
  4900. * slab_mutex.
  4901. */
  4902. mutex_unlock(&slab_mutex);
  4903. }
  4904. static int slab_mem_going_online_callback(void *arg)
  4905. {
  4906. struct kmem_cache_node *n;
  4907. struct kmem_cache *s;
  4908. struct memory_notify *marg = arg;
  4909. int nid = marg->status_change_nid_normal;
  4910. int ret = 0;
  4911. /*
  4912. * If the node's memory is already available, then kmem_cache_node is
  4913. * already created. Nothing to do.
  4914. */
  4915. if (nid < 0)
  4916. return 0;
  4917. /*
  4918. * We are bringing a node online. No memory is available yet. We must
  4919. * allocate a kmem_cache_node structure in order to bring the node
  4920. * online.
  4921. */
  4922. mutex_lock(&slab_mutex);
  4923. list_for_each_entry(s, &slab_caches, list) {
  4924. /*
  4925. * The structure may already exist if the node was previously
  4926. * onlined and offlined.
  4927. */
  4928. if (get_node(s, nid))
  4929. continue;
  4930. /*
  4931. * XXX: kmem_cache_alloc_node will fallback to other nodes
  4932. * since memory is not yet available from the node that
  4933. * is brought up.
  4934. */
  4935. n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
  4936. if (!n) {
  4937. ret = -ENOMEM;
  4938. goto out;
  4939. }
  4940. init_kmem_cache_node(n);
  4941. s->node[nid] = n;
  4942. }
  4943. /*
  4944. * Any cache created after this point will also have kmem_cache_node
  4945. * initialized for the new node.
  4946. */
  4947. node_set(nid, slab_nodes);
  4948. out:
  4949. mutex_unlock(&slab_mutex);
  4950. return ret;
  4951. }
  4952. static int slab_memory_callback(struct notifier_block *self,
  4953. unsigned long action, void *arg)
  4954. {
  4955. int ret = 0;
  4956. switch (action) {
  4957. case MEM_GOING_ONLINE:
  4958. ret = slab_mem_going_online_callback(arg);
  4959. break;
  4960. case MEM_GOING_OFFLINE:
  4961. ret = slab_mem_going_offline_callback(arg);
  4962. break;
  4963. case MEM_OFFLINE:
  4964. case MEM_CANCEL_ONLINE:
  4965. slab_mem_offline_callback(arg);
  4966. break;
  4967. case MEM_ONLINE:
  4968. case MEM_CANCEL_OFFLINE:
  4969. break;
  4970. }
  4971. if (ret)
  4972. ret = notifier_from_errno(ret);
  4973. else
  4974. ret = NOTIFY_OK;
  4975. return ret;
  4976. }
  4977. /********************************************************************
  4978. * Basic setup of slabs
  4979. *******************************************************************/
  4980. /*
  4981. * Used for early kmem_cache structures that were allocated using
  4982. * the page allocator. Allocate them properly then fix up the pointers
  4983. * that may be pointing to the wrong kmem_cache structure.
  4984. */
  4985. static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
  4986. {
  4987. int node;
  4988. struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
  4989. struct kmem_cache_node *n;
  4990. memcpy(s, static_cache, kmem_cache->object_size);
  4991. /*
  4992. * This runs very early, and only the boot processor is supposed to be
  4993. * up. Even if it weren't true, IRQs are not up so we couldn't fire
  4994. * IPIs around.
  4995. */
  4996. __flush_cpu_slab(s, smp_processor_id());
  4997. for_each_kmem_cache_node(s, node, n) {
  4998. struct slab *p;
  4999. list_for_each_entry(p, &n->partial, slab_list)
  5000. p->slab_cache = s;
  5001. #ifdef CONFIG_SLUB_DEBUG
  5002. list_for_each_entry(p, &n->full, slab_list)
  5003. p->slab_cache = s;
  5004. #endif
  5005. }
  5006. list_add(&s->list, &slab_caches);
  5007. return s;
  5008. }
  5009. void __init kmem_cache_init(void)
  5010. {
  5011. static __initdata struct kmem_cache boot_kmem_cache,
  5012. boot_kmem_cache_node;
  5013. int node;
  5014. if (debug_guardpage_minorder())
  5015. slub_max_order = 0;
  5016. /* Print slub debugging pointers without hashing */
  5017. if (__slub_debug_enabled())
  5018. no_hash_pointers_enable(NULL);
  5019. kmem_cache_node = &boot_kmem_cache_node;
  5020. kmem_cache = &boot_kmem_cache;
  5021. /*
  5022. * Initialize the nodemask for which we will allocate per node
  5023. * structures. Here we don't need taking slab_mutex yet.
  5024. */
  5025. for_each_node_state(node, N_NORMAL_MEMORY)
  5026. node_set(node, slab_nodes);
  5027. create_boot_cache(kmem_cache_node, "kmem_cache_node",
  5028. sizeof(struct kmem_cache_node),
  5029. SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
  5030. hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
  5031. /* Able to allocate the per node structures */
  5032. slab_state = PARTIAL;
  5033. create_boot_cache(kmem_cache, "kmem_cache",
  5034. offsetof(struct kmem_cache, node) +
  5035. nr_node_ids * sizeof(struct kmem_cache_node *),
  5036. SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
  5037. kmem_cache = bootstrap(&boot_kmem_cache);
  5038. kmem_cache_node = bootstrap(&boot_kmem_cache_node);
  5039. /* Now we can use the kmem_cache to allocate kmalloc slabs */
  5040. setup_kmalloc_cache_index_table();
  5041. create_kmalloc_caches();
  5042. /* Setup random freelists for each cache */
  5043. init_freelist_randomization();
  5044. cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
  5045. slub_cpu_dead);
  5046. pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
  5047. cache_line_size(),
  5048. slub_min_order, slub_max_order, slub_min_objects,
  5049. nr_cpu_ids, nr_node_ids);
  5050. }
  5051. void __init kmem_cache_init_late(void)
  5052. {
  5053. #ifndef CONFIG_SLUB_TINY
  5054. flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
  5055. WARN_ON(!flushwq);
  5056. #endif
  5057. }
  5058. struct kmem_cache *
  5059. __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
  5060. slab_flags_t flags, void (*ctor)(void *))
  5061. {
  5062. struct kmem_cache *s;
  5063. s = find_mergeable(size, align, flags, name, ctor);
  5064. if (s) {
  5065. if (sysfs_slab_alias(s, name))
  5066. return NULL;
  5067. s->refcount++;
  5068. /*
  5069. * Adjust the object sizes so that we clear
  5070. * the complete object on kzalloc.
  5071. */
  5072. s->object_size = max(s->object_size, size);
  5073. s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
  5074. }
  5075. return s;
  5076. }
  5077. int do_kmem_cache_create(struct kmem_cache *s, const char *name,
  5078. unsigned int size, struct kmem_cache_args *args,
  5079. slab_flags_t flags)
  5080. {
  5081. int err = -EINVAL;
  5082. s->name = name;
  5083. s->size = s->object_size = size;
  5084. s->flags = kmem_cache_flags(flags, s->name);
  5085. #ifdef CONFIG_SLAB_FREELIST_HARDENED
  5086. s->random = get_random_long();
  5087. #endif
  5088. s->align = args->align;
  5089. s->ctor = args->ctor;
  5090. #ifdef CONFIG_HARDENED_USERCOPY
  5091. s->useroffset = args->useroffset;
  5092. s->usersize = args->usersize;
  5093. #endif
  5094. if (!calculate_sizes(args, s))
  5095. goto out;
  5096. if (disable_higher_order_debug) {
  5097. /*
  5098. * Disable debugging flags that store metadata if the min slab
  5099. * order increased.
  5100. */
  5101. if (get_order(s->size) > get_order(s->object_size)) {
  5102. s->flags &= ~DEBUG_METADATA_FLAGS;
  5103. s->offset = 0;
  5104. if (!calculate_sizes(args, s))
  5105. goto out;
  5106. }
  5107. }
  5108. #ifdef system_has_freelist_aba
  5109. if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
  5110. /* Enable fast mode */
  5111. s->flags |= __CMPXCHG_DOUBLE;
  5112. }
  5113. #endif
  5114. /*
  5115. * The larger the object size is, the more slabs we want on the partial
  5116. * list to avoid pounding the page allocator excessively.
  5117. */
  5118. s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
  5119. s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
  5120. set_cpu_partial(s);
  5121. #ifdef CONFIG_NUMA
  5122. s->remote_node_defrag_ratio = 1000;
  5123. #endif
  5124. /* Initialize the pre-computed randomized freelist if slab is up */
  5125. if (slab_state >= UP) {
  5126. if (init_cache_random_seq(s))
  5127. goto out;
  5128. }
  5129. if (!init_kmem_cache_nodes(s))
  5130. goto out;
  5131. if (!alloc_kmem_cache_cpus(s))
  5132. goto out;
  5133. /* Mutex is not taken during early boot */
  5134. if (slab_state <= UP) {
  5135. err = 0;
  5136. goto out;
  5137. }
  5138. err = sysfs_slab_add(s);
  5139. if (err)
  5140. goto out;
  5141. if (s->flags & SLAB_STORE_USER)
  5142. debugfs_slab_add(s);
  5143. out:
  5144. if (err)
  5145. __kmem_cache_release(s);
  5146. return err;
  5147. }
  5148. #ifdef SLAB_SUPPORTS_SYSFS
  5149. static int count_inuse(struct slab *slab)
  5150. {
  5151. return slab->inuse;
  5152. }
  5153. static int count_total(struct slab *slab)
  5154. {
  5155. return slab->objects;
  5156. }
  5157. #endif
  5158. #ifdef CONFIG_SLUB_DEBUG
  5159. static void validate_slab(struct kmem_cache *s, struct slab *slab,
  5160. unsigned long *obj_map)
  5161. {
  5162. void *p;
  5163. void *addr = slab_address(slab);
  5164. if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
  5165. return;
  5166. /* Now we know that a valid freelist exists */
  5167. __fill_map(obj_map, s, slab);
  5168. for_each_object(p, s, addr, slab->objects) {
  5169. u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
  5170. SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
  5171. if (!check_object(s, slab, p, val))
  5172. break;
  5173. }
  5174. }
  5175. static int validate_slab_node(struct kmem_cache *s,
  5176. struct kmem_cache_node *n, unsigned long *obj_map)
  5177. {
  5178. unsigned long count = 0;
  5179. struct slab *slab;
  5180. unsigned long flags;
  5181. spin_lock_irqsave(&n->list_lock, flags);
  5182. list_for_each_entry(slab, &n->partial, slab_list) {
  5183. validate_slab(s, slab, obj_map);
  5184. count++;
  5185. }
  5186. if (count != n->nr_partial) {
  5187. pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
  5188. s->name, count, n->nr_partial);
  5189. slab_add_kunit_errors();
  5190. }
  5191. if (!(s->flags & SLAB_STORE_USER))
  5192. goto out;
  5193. list_for_each_entry(slab, &n->full, slab_list) {
  5194. validate_slab(s, slab, obj_map);
  5195. count++;
  5196. }
  5197. if (count != node_nr_slabs(n)) {
  5198. pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
  5199. s->name, count, node_nr_slabs(n));
  5200. slab_add_kunit_errors();
  5201. }
  5202. out:
  5203. spin_unlock_irqrestore(&n->list_lock, flags);
  5204. return count;
  5205. }
  5206. long validate_slab_cache(struct kmem_cache *s)
  5207. {
  5208. int node;
  5209. unsigned long count = 0;
  5210. struct kmem_cache_node *n;
  5211. unsigned long *obj_map;
  5212. obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
  5213. if (!obj_map)
  5214. return -ENOMEM;
  5215. flush_all(s);
  5216. for_each_kmem_cache_node(s, node, n)
  5217. count += validate_slab_node(s, n, obj_map);
  5218. bitmap_free(obj_map);
  5219. return count;
  5220. }
  5221. EXPORT_SYMBOL(validate_slab_cache);
  5222. #ifdef CONFIG_DEBUG_FS
  5223. /*
  5224. * Generate lists of code addresses where slabcache objects are allocated
  5225. * and freed.
  5226. */
  5227. struct location {
  5228. depot_stack_handle_t handle;
  5229. unsigned long count;
  5230. unsigned long addr;
  5231. unsigned long waste;
  5232. long long sum_time;
  5233. long min_time;
  5234. long max_time;
  5235. long min_pid;
  5236. long max_pid;
  5237. DECLARE_BITMAP(cpus, NR_CPUS);
  5238. nodemask_t nodes;
  5239. };
  5240. struct loc_track {
  5241. unsigned long max;
  5242. unsigned long count;
  5243. struct location *loc;
  5244. loff_t idx;
  5245. };
  5246. static struct dentry *slab_debugfs_root;
  5247. static void free_loc_track(struct loc_track *t)
  5248. {
  5249. if (t->max)
  5250. free_pages((unsigned long)t->loc,
  5251. get_order(sizeof(struct location) * t->max));
  5252. }
  5253. static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
  5254. {
  5255. struct location *l;
  5256. int order;
  5257. order = get_order(sizeof(struct location) * max);
  5258. l = (void *)__get_free_pages(flags, order);
  5259. if (!l)
  5260. return 0;
  5261. if (t->count) {
  5262. memcpy(l, t->loc, sizeof(struct location) * t->count);
  5263. free_loc_track(t);
  5264. }
  5265. t->max = max;
  5266. t->loc = l;
  5267. return 1;
  5268. }
  5269. static int add_location(struct loc_track *t, struct kmem_cache *s,
  5270. const struct track *track,
  5271. unsigned int orig_size)
  5272. {
  5273. long start, end, pos;
  5274. struct location *l;
  5275. unsigned long caddr, chandle, cwaste;
  5276. unsigned long age = jiffies - track->when;
  5277. depot_stack_handle_t handle = 0;
  5278. unsigned int waste = s->object_size - orig_size;
  5279. #ifdef CONFIG_STACKDEPOT
  5280. handle = READ_ONCE(track->handle);
  5281. #endif
  5282. start = -1;
  5283. end = t->count;
  5284. for ( ; ; ) {
  5285. pos = start + (end - start + 1) / 2;
  5286. /*
  5287. * There is nothing at "end". If we end up there
  5288. * we need to add something to before end.
  5289. */
  5290. if (pos == end)
  5291. break;
  5292. l = &t->loc[pos];
  5293. caddr = l->addr;
  5294. chandle = l->handle;
  5295. cwaste = l->waste;
  5296. if ((track->addr == caddr) && (handle == chandle) &&
  5297. (waste == cwaste)) {
  5298. l->count++;
  5299. if (track->when) {
  5300. l->sum_time += age;
  5301. if (age < l->min_time)
  5302. l->min_time = age;
  5303. if (age > l->max_time)
  5304. l->max_time = age;
  5305. if (track->pid < l->min_pid)
  5306. l->min_pid = track->pid;
  5307. if (track->pid > l->max_pid)
  5308. l->max_pid = track->pid;
  5309. cpumask_set_cpu(track->cpu,
  5310. to_cpumask(l->cpus));
  5311. }
  5312. node_set(page_to_nid(virt_to_page(track)), l->nodes);
  5313. return 1;
  5314. }
  5315. if (track->addr < caddr)
  5316. end = pos;
  5317. else if (track->addr == caddr && handle < chandle)
  5318. end = pos;
  5319. else if (track->addr == caddr && handle == chandle &&
  5320. waste < cwaste)
  5321. end = pos;
  5322. else
  5323. start = pos;
  5324. }
  5325. /*
  5326. * Not found. Insert new tracking element.
  5327. */
  5328. if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
  5329. return 0;
  5330. l = t->loc + pos;
  5331. if (pos < t->count)
  5332. memmove(l + 1, l,
  5333. (t->count - pos) * sizeof(struct location));
  5334. t->count++;
  5335. l->count = 1;
  5336. l->addr = track->addr;
  5337. l->sum_time = age;
  5338. l->min_time = age;
  5339. l->max_time = age;
  5340. l->min_pid = track->pid;
  5341. l->max_pid = track->pid;
  5342. l->handle = handle;
  5343. l->waste = waste;
  5344. cpumask_clear(to_cpumask(l->cpus));
  5345. cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
  5346. nodes_clear(l->nodes);
  5347. node_set(page_to_nid(virt_to_page(track)), l->nodes);
  5348. return 1;
  5349. }
  5350. static void process_slab(struct loc_track *t, struct kmem_cache *s,
  5351. struct slab *slab, enum track_item alloc,
  5352. unsigned long *obj_map)
  5353. {
  5354. void *addr = slab_address(slab);
  5355. bool is_alloc = (alloc == TRACK_ALLOC);
  5356. void *p;
  5357. __fill_map(obj_map, s, slab);
  5358. for_each_object(p, s, addr, slab->objects)
  5359. if (!test_bit(__obj_to_index(s, addr, p), obj_map))
  5360. add_location(t, s, get_track(s, p, alloc),
  5361. is_alloc ? get_orig_size(s, p) :
  5362. s->object_size);
  5363. }
  5364. #endif /* CONFIG_DEBUG_FS */
  5365. #endif /* CONFIG_SLUB_DEBUG */
  5366. #ifdef SLAB_SUPPORTS_SYSFS
  5367. enum slab_stat_type {
  5368. SL_ALL, /* All slabs */
  5369. SL_PARTIAL, /* Only partially allocated slabs */
  5370. SL_CPU, /* Only slabs used for cpu caches */
  5371. SL_OBJECTS, /* Determine allocated objects not slabs */
  5372. SL_TOTAL /* Determine object capacity not slabs */
  5373. };
  5374. #define SO_ALL (1 << SL_ALL)
  5375. #define SO_PARTIAL (1 << SL_PARTIAL)
  5376. #define SO_CPU (1 << SL_CPU)
  5377. #define SO_OBJECTS (1 << SL_OBJECTS)
  5378. #define SO_TOTAL (1 << SL_TOTAL)
  5379. static ssize_t show_slab_objects(struct kmem_cache *s,
  5380. char *buf, unsigned long flags)
  5381. {
  5382. unsigned long total = 0;
  5383. int node;
  5384. int x;
  5385. unsigned long *nodes;
  5386. int len = 0;
  5387. nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
  5388. if (!nodes)
  5389. return -ENOMEM;
  5390. if (flags & SO_CPU) {
  5391. int cpu;
  5392. for_each_possible_cpu(cpu) {
  5393. struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
  5394. cpu);
  5395. int node;
  5396. struct slab *slab;
  5397. slab = READ_ONCE(c->slab);
  5398. if (!slab)
  5399. continue;
  5400. node = slab_nid(slab);
  5401. if (flags & SO_TOTAL)
  5402. x = slab->objects;
  5403. else if (flags & SO_OBJECTS)
  5404. x = slab->inuse;
  5405. else
  5406. x = 1;
  5407. total += x;
  5408. nodes[node] += x;
  5409. #ifdef CONFIG_SLUB_CPU_PARTIAL
  5410. slab = slub_percpu_partial_read_once(c);
  5411. if (slab) {
  5412. node = slab_nid(slab);
  5413. if (flags & SO_TOTAL)
  5414. WARN_ON_ONCE(1);
  5415. else if (flags & SO_OBJECTS)
  5416. WARN_ON_ONCE(1);
  5417. else
  5418. x = data_race(slab->slabs);
  5419. total += x;
  5420. nodes[node] += x;
  5421. }
  5422. #endif
  5423. }
  5424. }
  5425. /*
  5426. * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
  5427. * already held which will conflict with an existing lock order:
  5428. *
  5429. * mem_hotplug_lock->slab_mutex->kernfs_mutex
  5430. *
  5431. * We don't really need mem_hotplug_lock (to hold off
  5432. * slab_mem_going_offline_callback) here because slab's memory hot
  5433. * unplug code doesn't destroy the kmem_cache->node[] data.
  5434. */
  5435. #ifdef CONFIG_SLUB_DEBUG
  5436. if (flags & SO_ALL) {
  5437. struct kmem_cache_node *n;
  5438. for_each_kmem_cache_node(s, node, n) {
  5439. if (flags & SO_TOTAL)
  5440. x = node_nr_objs(n);
  5441. else if (flags & SO_OBJECTS)
  5442. x = node_nr_objs(n) - count_partial(n, count_free);
  5443. else
  5444. x = node_nr_slabs(n);
  5445. total += x;
  5446. nodes[node] += x;
  5447. }
  5448. } else
  5449. #endif
  5450. if (flags & SO_PARTIAL) {
  5451. struct kmem_cache_node *n;
  5452. for_each_kmem_cache_node(s, node, n) {
  5453. if (flags & SO_TOTAL)
  5454. x = count_partial(n, count_total);
  5455. else if (flags & SO_OBJECTS)
  5456. x = count_partial(n, count_inuse);
  5457. else
  5458. x = n->nr_partial;
  5459. total += x;
  5460. nodes[node] += x;
  5461. }
  5462. }
  5463. len += sysfs_emit_at(buf, len, "%lu", total);
  5464. #ifdef CONFIG_NUMA
  5465. for (node = 0; node < nr_node_ids; node++) {
  5466. if (nodes[node])
  5467. len += sysfs_emit_at(buf, len, " N%d=%lu",
  5468. node, nodes[node]);
  5469. }
  5470. #endif
  5471. len += sysfs_emit_at(buf, len, "\n");
  5472. kfree(nodes);
  5473. return len;
  5474. }
  5475. #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
  5476. #define to_slab(n) container_of(n, struct kmem_cache, kobj)
  5477. struct slab_attribute {
  5478. struct attribute attr;
  5479. ssize_t (*show)(struct kmem_cache *s, char *buf);
  5480. ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
  5481. };
  5482. #define SLAB_ATTR_RO(_name) \
  5483. static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
  5484. #define SLAB_ATTR(_name) \
  5485. static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
  5486. static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
  5487. {
  5488. return sysfs_emit(buf, "%u\n", s->size);
  5489. }
  5490. SLAB_ATTR_RO(slab_size);
  5491. static ssize_t align_show(struct kmem_cache *s, char *buf)
  5492. {
  5493. return sysfs_emit(buf, "%u\n", s->align);
  5494. }
  5495. SLAB_ATTR_RO(align);
  5496. static ssize_t object_size_show(struct kmem_cache *s, char *buf)
  5497. {
  5498. return sysfs_emit(buf, "%u\n", s->object_size);
  5499. }
  5500. SLAB_ATTR_RO(object_size);
  5501. static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
  5502. {
  5503. return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
  5504. }
  5505. SLAB_ATTR_RO(objs_per_slab);
  5506. static ssize_t order_show(struct kmem_cache *s, char *buf)
  5507. {
  5508. return sysfs_emit(buf, "%u\n", oo_order(s->oo));
  5509. }
  5510. SLAB_ATTR_RO(order);
  5511. static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
  5512. {
  5513. return sysfs_emit(buf, "%lu\n", s->min_partial);
  5514. }
  5515. static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
  5516. size_t length)
  5517. {
  5518. unsigned long min;
  5519. int err;
  5520. err = kstrtoul(buf, 10, &min);
  5521. if (err)
  5522. return err;
  5523. s->min_partial = min;
  5524. return length;
  5525. }
  5526. SLAB_ATTR(min_partial);
  5527. static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
  5528. {
  5529. unsigned int nr_partial = 0;
  5530. #ifdef CONFIG_SLUB_CPU_PARTIAL
  5531. nr_partial = s->cpu_partial;
  5532. #endif
  5533. return sysfs_emit(buf, "%u\n", nr_partial);
  5534. }
  5535. static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
  5536. size_t length)
  5537. {
  5538. unsigned int objects;
  5539. int err;
  5540. err = kstrtouint(buf, 10, &objects);
  5541. if (err)
  5542. return err;
  5543. if (objects && !kmem_cache_has_cpu_partial(s))
  5544. return -EINVAL;
  5545. slub_set_cpu_partial(s, objects);
  5546. flush_all(s);
  5547. return length;
  5548. }
  5549. SLAB_ATTR(cpu_partial);
  5550. static ssize_t ctor_show(struct kmem_cache *s, char *buf)
  5551. {
  5552. if (!s->ctor)
  5553. return 0;
  5554. return sysfs_emit(buf, "%pS\n", s->ctor);
  5555. }
  5556. SLAB_ATTR_RO(ctor);
  5557. static ssize_t aliases_show(struct kmem_cache *s, char *buf)
  5558. {
  5559. return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
  5560. }
  5561. SLAB_ATTR_RO(aliases);
  5562. static ssize_t partial_show(struct kmem_cache *s, char *buf)
  5563. {
  5564. return show_slab_objects(s, buf, SO_PARTIAL);
  5565. }
  5566. SLAB_ATTR_RO(partial);
  5567. static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
  5568. {
  5569. return show_slab_objects(s, buf, SO_CPU);
  5570. }
  5571. SLAB_ATTR_RO(cpu_slabs);
  5572. static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
  5573. {
  5574. return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
  5575. }
  5576. SLAB_ATTR_RO(objects_partial);
  5577. static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
  5578. {
  5579. int objects = 0;
  5580. int slabs = 0;
  5581. int cpu __maybe_unused;
  5582. int len = 0;
  5583. #ifdef CONFIG_SLUB_CPU_PARTIAL
  5584. for_each_online_cpu(cpu) {
  5585. struct slab *slab;
  5586. slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
  5587. if (slab)
  5588. slabs += data_race(slab->slabs);
  5589. }
  5590. #endif
  5591. /* Approximate half-full slabs, see slub_set_cpu_partial() */
  5592. objects = (slabs * oo_objects(s->oo)) / 2;
  5593. len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
  5594. #ifdef CONFIG_SLUB_CPU_PARTIAL
  5595. for_each_online_cpu(cpu) {
  5596. struct slab *slab;
  5597. slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
  5598. if (slab) {
  5599. slabs = data_race(slab->slabs);
  5600. objects = (slabs * oo_objects(s->oo)) / 2;
  5601. len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
  5602. cpu, objects, slabs);
  5603. }
  5604. }
  5605. #endif
  5606. len += sysfs_emit_at(buf, len, "\n");
  5607. return len;
  5608. }
  5609. SLAB_ATTR_RO(slabs_cpu_partial);
  5610. static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
  5611. {
  5612. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
  5613. }
  5614. SLAB_ATTR_RO(reclaim_account);
  5615. static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
  5616. {
  5617. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
  5618. }
  5619. SLAB_ATTR_RO(hwcache_align);
  5620. #ifdef CONFIG_ZONE_DMA
  5621. static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
  5622. {
  5623. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
  5624. }
  5625. SLAB_ATTR_RO(cache_dma);
  5626. #endif
  5627. #ifdef CONFIG_HARDENED_USERCOPY
  5628. static ssize_t usersize_show(struct kmem_cache *s, char *buf)
  5629. {
  5630. return sysfs_emit(buf, "%u\n", s->usersize);
  5631. }
  5632. SLAB_ATTR_RO(usersize);
  5633. #endif
  5634. static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
  5635. {
  5636. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
  5637. }
  5638. SLAB_ATTR_RO(destroy_by_rcu);
  5639. #ifdef CONFIG_SLUB_DEBUG
  5640. static ssize_t slabs_show(struct kmem_cache *s, char *buf)
  5641. {
  5642. return show_slab_objects(s, buf, SO_ALL);
  5643. }
  5644. SLAB_ATTR_RO(slabs);
  5645. static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
  5646. {
  5647. return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
  5648. }
  5649. SLAB_ATTR_RO(total_objects);
  5650. static ssize_t objects_show(struct kmem_cache *s, char *buf)
  5651. {
  5652. return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
  5653. }
  5654. SLAB_ATTR_RO(objects);
  5655. static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
  5656. {
  5657. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
  5658. }
  5659. SLAB_ATTR_RO(sanity_checks);
  5660. static ssize_t trace_show(struct kmem_cache *s, char *buf)
  5661. {
  5662. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
  5663. }
  5664. SLAB_ATTR_RO(trace);
  5665. static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
  5666. {
  5667. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
  5668. }
  5669. SLAB_ATTR_RO(red_zone);
  5670. static ssize_t poison_show(struct kmem_cache *s, char *buf)
  5671. {
  5672. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
  5673. }
  5674. SLAB_ATTR_RO(poison);
  5675. static ssize_t store_user_show(struct kmem_cache *s, char *buf)
  5676. {
  5677. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
  5678. }
  5679. SLAB_ATTR_RO(store_user);
  5680. static ssize_t validate_show(struct kmem_cache *s, char *buf)
  5681. {
  5682. return 0;
  5683. }
  5684. static ssize_t validate_store(struct kmem_cache *s,
  5685. const char *buf, size_t length)
  5686. {
  5687. int ret = -EINVAL;
  5688. if (buf[0] == '1' && kmem_cache_debug(s)) {
  5689. ret = validate_slab_cache(s);
  5690. if (ret >= 0)
  5691. ret = length;
  5692. }
  5693. return ret;
  5694. }
  5695. SLAB_ATTR(validate);
  5696. #endif /* CONFIG_SLUB_DEBUG */
  5697. #ifdef CONFIG_FAILSLAB
  5698. static ssize_t failslab_show(struct kmem_cache *s, char *buf)
  5699. {
  5700. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
  5701. }
  5702. static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
  5703. size_t length)
  5704. {
  5705. if (s->refcount > 1)
  5706. return -EINVAL;
  5707. if (buf[0] == '1')
  5708. WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
  5709. else
  5710. WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
  5711. return length;
  5712. }
  5713. SLAB_ATTR(failslab);
  5714. #endif
  5715. static ssize_t shrink_show(struct kmem_cache *s, char *buf)
  5716. {
  5717. return 0;
  5718. }
  5719. static ssize_t shrink_store(struct kmem_cache *s,
  5720. const char *buf, size_t length)
  5721. {
  5722. if (buf[0] == '1')
  5723. kmem_cache_shrink(s);
  5724. else
  5725. return -EINVAL;
  5726. return length;
  5727. }
  5728. SLAB_ATTR(shrink);
  5729. #ifdef CONFIG_NUMA
  5730. static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
  5731. {
  5732. return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
  5733. }
  5734. static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
  5735. const char *buf, size_t length)
  5736. {
  5737. unsigned int ratio;
  5738. int err;
  5739. err = kstrtouint(buf, 10, &ratio);
  5740. if (err)
  5741. return err;
  5742. if (ratio > 100)
  5743. return -ERANGE;
  5744. s->remote_node_defrag_ratio = ratio * 10;
  5745. return length;
  5746. }
  5747. SLAB_ATTR(remote_node_defrag_ratio);
  5748. #endif
  5749. #ifdef CONFIG_SLUB_STATS
  5750. static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
  5751. {
  5752. unsigned long sum = 0;
  5753. int cpu;
  5754. int len = 0;
  5755. int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
  5756. if (!data)
  5757. return -ENOMEM;
  5758. for_each_online_cpu(cpu) {
  5759. unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
  5760. data[cpu] = x;
  5761. sum += x;
  5762. }
  5763. len += sysfs_emit_at(buf, len, "%lu", sum);
  5764. #ifdef CONFIG_SMP
  5765. for_each_online_cpu(cpu) {
  5766. if (data[cpu])
  5767. len += sysfs_emit_at(buf, len, " C%d=%u",
  5768. cpu, data[cpu]);
  5769. }
  5770. #endif
  5771. kfree(data);
  5772. len += sysfs_emit_at(buf, len, "\n");
  5773. return len;
  5774. }
  5775. static void clear_stat(struct kmem_cache *s, enum stat_item si)
  5776. {
  5777. int cpu;
  5778. for_each_online_cpu(cpu)
  5779. per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
  5780. }
  5781. #define STAT_ATTR(si, text) \
  5782. static ssize_t text##_show(struct kmem_cache *s, char *buf) \
  5783. { \
  5784. return show_stat(s, buf, si); \
  5785. } \
  5786. static ssize_t text##_store(struct kmem_cache *s, \
  5787. const char *buf, size_t length) \
  5788. { \
  5789. if (buf[0] != '0') \
  5790. return -EINVAL; \
  5791. clear_stat(s, si); \
  5792. return length; \
  5793. } \
  5794. SLAB_ATTR(text); \
  5795. STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
  5796. STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
  5797. STAT_ATTR(FREE_FASTPATH, free_fastpath);
  5798. STAT_ATTR(FREE_SLOWPATH, free_slowpath);
  5799. STAT_ATTR(FREE_FROZEN, free_frozen);
  5800. STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
  5801. STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
  5802. STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
  5803. STAT_ATTR(ALLOC_SLAB, alloc_slab);
  5804. STAT_ATTR(ALLOC_REFILL, alloc_refill);
  5805. STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
  5806. STAT_ATTR(FREE_SLAB, free_slab);
  5807. STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
  5808. STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
  5809. STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
  5810. STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
  5811. STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
  5812. STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
  5813. STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
  5814. STAT_ATTR(ORDER_FALLBACK, order_fallback);
  5815. STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
  5816. STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
  5817. STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
  5818. STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
  5819. STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
  5820. STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
  5821. #endif /* CONFIG_SLUB_STATS */
  5822. #ifdef CONFIG_KFENCE
  5823. static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
  5824. {
  5825. return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
  5826. }
  5827. static ssize_t skip_kfence_store(struct kmem_cache *s,
  5828. const char *buf, size_t length)
  5829. {
  5830. int ret = length;
  5831. if (buf[0] == '0')
  5832. s->flags &= ~SLAB_SKIP_KFENCE;
  5833. else if (buf[0] == '1')
  5834. s->flags |= SLAB_SKIP_KFENCE;
  5835. else
  5836. ret = -EINVAL;
  5837. return ret;
  5838. }
  5839. SLAB_ATTR(skip_kfence);
  5840. #endif
  5841. static struct attribute *slab_attrs[] = {
  5842. &slab_size_attr.attr,
  5843. &object_size_attr.attr,
  5844. &objs_per_slab_attr.attr,
  5845. &order_attr.attr,
  5846. &min_partial_attr.attr,
  5847. &cpu_partial_attr.attr,
  5848. &objects_partial_attr.attr,
  5849. &partial_attr.attr,
  5850. &cpu_slabs_attr.attr,
  5851. &ctor_attr.attr,
  5852. &aliases_attr.attr,
  5853. &align_attr.attr,
  5854. &hwcache_align_attr.attr,
  5855. &reclaim_account_attr.attr,
  5856. &destroy_by_rcu_attr.attr,
  5857. &shrink_attr.attr,
  5858. &slabs_cpu_partial_attr.attr,
  5859. #ifdef CONFIG_SLUB_DEBUG
  5860. &total_objects_attr.attr,
  5861. &objects_attr.attr,
  5862. &slabs_attr.attr,
  5863. &sanity_checks_attr.attr,
  5864. &trace_attr.attr,
  5865. &red_zone_attr.attr,
  5866. &poison_attr.attr,
  5867. &store_user_attr.attr,
  5868. &validate_attr.attr,
  5869. #endif
  5870. #ifdef CONFIG_ZONE_DMA
  5871. &cache_dma_attr.attr,
  5872. #endif
  5873. #ifdef CONFIG_NUMA
  5874. &remote_node_defrag_ratio_attr.attr,
  5875. #endif
  5876. #ifdef CONFIG_SLUB_STATS
  5877. &alloc_fastpath_attr.attr,
  5878. &alloc_slowpath_attr.attr,
  5879. &free_fastpath_attr.attr,
  5880. &free_slowpath_attr.attr,
  5881. &free_frozen_attr.attr,
  5882. &free_add_partial_attr.attr,
  5883. &free_remove_partial_attr.attr,
  5884. &alloc_from_partial_attr.attr,
  5885. &alloc_slab_attr.attr,
  5886. &alloc_refill_attr.attr,
  5887. &alloc_node_mismatch_attr.attr,
  5888. &free_slab_attr.attr,
  5889. &cpuslab_flush_attr.attr,
  5890. &deactivate_full_attr.attr,
  5891. &deactivate_empty_attr.attr,
  5892. &deactivate_to_head_attr.attr,
  5893. &deactivate_to_tail_attr.attr,
  5894. &deactivate_remote_frees_attr.attr,
  5895. &deactivate_bypass_attr.attr,
  5896. &order_fallback_attr.attr,
  5897. &cmpxchg_double_fail_attr.attr,
  5898. &cmpxchg_double_cpu_fail_attr.attr,
  5899. &cpu_partial_alloc_attr.attr,
  5900. &cpu_partial_free_attr.attr,
  5901. &cpu_partial_node_attr.attr,
  5902. &cpu_partial_drain_attr.attr,
  5903. #endif
  5904. #ifdef CONFIG_FAILSLAB
  5905. &failslab_attr.attr,
  5906. #endif
  5907. #ifdef CONFIG_HARDENED_USERCOPY
  5908. &usersize_attr.attr,
  5909. #endif
  5910. #ifdef CONFIG_KFENCE
  5911. &skip_kfence_attr.attr,
  5912. #endif
  5913. NULL
  5914. };
  5915. static const struct attribute_group slab_attr_group = {
  5916. .attrs = slab_attrs,
  5917. };
  5918. static ssize_t slab_attr_show(struct kobject *kobj,
  5919. struct attribute *attr,
  5920. char *buf)
  5921. {
  5922. struct slab_attribute *attribute;
  5923. struct kmem_cache *s;
  5924. attribute = to_slab_attr(attr);
  5925. s = to_slab(kobj);
  5926. if (!attribute->show)
  5927. return -EIO;
  5928. return attribute->show(s, buf);
  5929. }
  5930. static ssize_t slab_attr_store(struct kobject *kobj,
  5931. struct attribute *attr,
  5932. const char *buf, size_t len)
  5933. {
  5934. struct slab_attribute *attribute;
  5935. struct kmem_cache *s;
  5936. attribute = to_slab_attr(attr);
  5937. s = to_slab(kobj);
  5938. if (!attribute->store)
  5939. return -EIO;
  5940. return attribute->store(s, buf, len);
  5941. }
  5942. static void kmem_cache_release(struct kobject *k)
  5943. {
  5944. slab_kmem_cache_release(to_slab(k));
  5945. }
  5946. static const struct sysfs_ops slab_sysfs_ops = {
  5947. .show = slab_attr_show,
  5948. .store = slab_attr_store,
  5949. };
  5950. static const struct kobj_type slab_ktype = {
  5951. .sysfs_ops = &slab_sysfs_ops,
  5952. .release = kmem_cache_release,
  5953. };
  5954. static struct kset *slab_kset;
  5955. static inline struct kset *cache_kset(struct kmem_cache *s)
  5956. {
  5957. return slab_kset;
  5958. }
  5959. #define ID_STR_LENGTH 32
  5960. /* Create a unique string id for a slab cache:
  5961. *
  5962. * Format :[flags-]size
  5963. */
  5964. static char *create_unique_id(struct kmem_cache *s)
  5965. {
  5966. char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
  5967. char *p = name;
  5968. if (!name)
  5969. return ERR_PTR(-ENOMEM);
  5970. *p++ = ':';
  5971. /*
  5972. * First flags affecting slabcache operations. We will only
  5973. * get here for aliasable slabs so we do not need to support
  5974. * too many flags. The flags here must cover all flags that
  5975. * are matched during merging to guarantee that the id is
  5976. * unique.
  5977. */
  5978. if (s->flags & SLAB_CACHE_DMA)
  5979. *p++ = 'd';
  5980. if (s->flags & SLAB_CACHE_DMA32)
  5981. *p++ = 'D';
  5982. if (s->flags & SLAB_RECLAIM_ACCOUNT)
  5983. *p++ = 'a';
  5984. if (s->flags & SLAB_CONSISTENCY_CHECKS)
  5985. *p++ = 'F';
  5986. if (s->flags & SLAB_ACCOUNT)
  5987. *p++ = 'A';
  5988. if (p != name + 1)
  5989. *p++ = '-';
  5990. p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
  5991. if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
  5992. kfree(name);
  5993. return ERR_PTR(-EINVAL);
  5994. }
  5995. kmsan_unpoison_memory(name, p - name);
  5996. return name;
  5997. }
  5998. static int sysfs_slab_add(struct kmem_cache *s)
  5999. {
  6000. int err;
  6001. const char *name;
  6002. struct kset *kset = cache_kset(s);
  6003. int unmergeable = slab_unmergeable(s);
  6004. if (!unmergeable && disable_higher_order_debug &&
  6005. (slub_debug & DEBUG_METADATA_FLAGS))
  6006. unmergeable = 1;
  6007. if (unmergeable) {
  6008. /*
  6009. * Slabcache can never be merged so we can use the name proper.
  6010. * This is typically the case for debug situations. In that
  6011. * case we can catch duplicate names easily.
  6012. */
  6013. sysfs_remove_link(&slab_kset->kobj, s->name);
  6014. name = s->name;
  6015. } else {
  6016. /*
  6017. * Create a unique name for the slab as a target
  6018. * for the symlinks.
  6019. */
  6020. name = create_unique_id(s);
  6021. if (IS_ERR(name))
  6022. return PTR_ERR(name);
  6023. }
  6024. s->kobj.kset = kset;
  6025. err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
  6026. if (err)
  6027. goto out;
  6028. err = sysfs_create_group(&s->kobj, &slab_attr_group);
  6029. if (err)
  6030. goto out_del_kobj;
  6031. if (!unmergeable) {
  6032. /* Setup first alias */
  6033. sysfs_slab_alias(s, s->name);
  6034. }
  6035. out:
  6036. if (!unmergeable)
  6037. kfree(name);
  6038. return err;
  6039. out_del_kobj:
  6040. kobject_del(&s->kobj);
  6041. goto out;
  6042. }
  6043. void sysfs_slab_unlink(struct kmem_cache *s)
  6044. {
  6045. kobject_del(&s->kobj);
  6046. }
  6047. void sysfs_slab_release(struct kmem_cache *s)
  6048. {
  6049. kobject_put(&s->kobj);
  6050. }
  6051. /*
  6052. * Need to buffer aliases during bootup until sysfs becomes
  6053. * available lest we lose that information.
  6054. */
  6055. struct saved_alias {
  6056. struct kmem_cache *s;
  6057. const char *name;
  6058. struct saved_alias *next;
  6059. };
  6060. static struct saved_alias *alias_list;
  6061. static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
  6062. {
  6063. struct saved_alias *al;
  6064. if (slab_state == FULL) {
  6065. /*
  6066. * If we have a leftover link then remove it.
  6067. */
  6068. sysfs_remove_link(&slab_kset->kobj, name);
  6069. return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
  6070. }
  6071. al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
  6072. if (!al)
  6073. return -ENOMEM;
  6074. al->s = s;
  6075. al->name = name;
  6076. al->next = alias_list;
  6077. alias_list = al;
  6078. kmsan_unpoison_memory(al, sizeof(*al));
  6079. return 0;
  6080. }
  6081. static int __init slab_sysfs_init(void)
  6082. {
  6083. struct kmem_cache *s;
  6084. int err;
  6085. mutex_lock(&slab_mutex);
  6086. slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
  6087. if (!slab_kset) {
  6088. mutex_unlock(&slab_mutex);
  6089. pr_err("Cannot register slab subsystem.\n");
  6090. return -ENOMEM;
  6091. }
  6092. slab_state = FULL;
  6093. list_for_each_entry(s, &slab_caches, list) {
  6094. err = sysfs_slab_add(s);
  6095. if (err)
  6096. pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
  6097. s->name);
  6098. }
  6099. while (alias_list) {
  6100. struct saved_alias *al = alias_list;
  6101. alias_list = alias_list->next;
  6102. err = sysfs_slab_alias(al->s, al->name);
  6103. if (err)
  6104. pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
  6105. al->name);
  6106. kfree(al);
  6107. }
  6108. mutex_unlock(&slab_mutex);
  6109. return 0;
  6110. }
  6111. late_initcall(slab_sysfs_init);
  6112. #endif /* SLAB_SUPPORTS_SYSFS */
  6113. #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
  6114. static int slab_debugfs_show(struct seq_file *seq, void *v)
  6115. {
  6116. struct loc_track *t = seq->private;
  6117. struct location *l;
  6118. unsigned long idx;
  6119. idx = (unsigned long) t->idx;
  6120. if (idx < t->count) {
  6121. l = &t->loc[idx];
  6122. seq_printf(seq, "%7ld ", l->count);
  6123. if (l->addr)
  6124. seq_printf(seq, "%pS", (void *)l->addr);
  6125. else
  6126. seq_puts(seq, "<not-available>");
  6127. if (l->waste)
  6128. seq_printf(seq, " waste=%lu/%lu",
  6129. l->count * l->waste, l->waste);
  6130. if (l->sum_time != l->min_time) {
  6131. seq_printf(seq, " age=%ld/%llu/%ld",
  6132. l->min_time, div_u64(l->sum_time, l->count),
  6133. l->max_time);
  6134. } else
  6135. seq_printf(seq, " age=%ld", l->min_time);
  6136. if (l->min_pid != l->max_pid)
  6137. seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
  6138. else
  6139. seq_printf(seq, " pid=%ld",
  6140. l->min_pid);
  6141. if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
  6142. seq_printf(seq, " cpus=%*pbl",
  6143. cpumask_pr_args(to_cpumask(l->cpus)));
  6144. if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
  6145. seq_printf(seq, " nodes=%*pbl",
  6146. nodemask_pr_args(&l->nodes));
  6147. #ifdef CONFIG_STACKDEPOT
  6148. {
  6149. depot_stack_handle_t handle;
  6150. unsigned long *entries;
  6151. unsigned int nr_entries, j;
  6152. handle = READ_ONCE(l->handle);
  6153. if (handle) {
  6154. nr_entries = stack_depot_fetch(handle, &entries);
  6155. seq_puts(seq, "\n");
  6156. for (j = 0; j < nr_entries; j++)
  6157. seq_printf(seq, " %pS\n", (void *)entries[j]);
  6158. }
  6159. }
  6160. #endif
  6161. seq_puts(seq, "\n");
  6162. }
  6163. if (!idx && !t->count)
  6164. seq_puts(seq, "No data\n");
  6165. return 0;
  6166. }
  6167. static void slab_debugfs_stop(struct seq_file *seq, void *v)
  6168. {
  6169. }
  6170. static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
  6171. {
  6172. struct loc_track *t = seq->private;
  6173. t->idx = ++(*ppos);
  6174. if (*ppos <= t->count)
  6175. return ppos;
  6176. return NULL;
  6177. }
  6178. static int cmp_loc_by_count(const void *a, const void *b, const void *data)
  6179. {
  6180. struct location *loc1 = (struct location *)a;
  6181. struct location *loc2 = (struct location *)b;
  6182. if (loc1->count > loc2->count)
  6183. return -1;
  6184. else
  6185. return 1;
  6186. }
  6187. static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
  6188. {
  6189. struct loc_track *t = seq->private;
  6190. t->idx = *ppos;
  6191. return ppos;
  6192. }
  6193. static const struct seq_operations slab_debugfs_sops = {
  6194. .start = slab_debugfs_start,
  6195. .next = slab_debugfs_next,
  6196. .stop = slab_debugfs_stop,
  6197. .show = slab_debugfs_show,
  6198. };
  6199. static int slab_debug_trace_open(struct inode *inode, struct file *filep)
  6200. {
  6201. struct kmem_cache_node *n;
  6202. enum track_item alloc;
  6203. int node;
  6204. struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
  6205. sizeof(struct loc_track));
  6206. struct kmem_cache *s = file_inode(filep)->i_private;
  6207. unsigned long *obj_map;
  6208. if (!t)
  6209. return -ENOMEM;
  6210. obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
  6211. if (!obj_map) {
  6212. seq_release_private(inode, filep);
  6213. return -ENOMEM;
  6214. }
  6215. if (strcmp(filep->f_path.dentry->d_name.name, "alloc_traces") == 0)
  6216. alloc = TRACK_ALLOC;
  6217. else
  6218. alloc = TRACK_FREE;
  6219. if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
  6220. bitmap_free(obj_map);
  6221. seq_release_private(inode, filep);
  6222. return -ENOMEM;
  6223. }
  6224. for_each_kmem_cache_node(s, node, n) {
  6225. unsigned long flags;
  6226. struct slab *slab;
  6227. if (!node_nr_slabs(n))
  6228. continue;
  6229. spin_lock_irqsave(&n->list_lock, flags);
  6230. list_for_each_entry(slab, &n->partial, slab_list)
  6231. process_slab(t, s, slab, alloc, obj_map);
  6232. list_for_each_entry(slab, &n->full, slab_list)
  6233. process_slab(t, s, slab, alloc, obj_map);
  6234. spin_unlock_irqrestore(&n->list_lock, flags);
  6235. }
  6236. /* Sort locations by count */
  6237. sort_r(t->loc, t->count, sizeof(struct location),
  6238. cmp_loc_by_count, NULL, NULL);
  6239. bitmap_free(obj_map);
  6240. return 0;
  6241. }
  6242. static int slab_debug_trace_release(struct inode *inode, struct file *file)
  6243. {
  6244. struct seq_file *seq = file->private_data;
  6245. struct loc_track *t = seq->private;
  6246. free_loc_track(t);
  6247. return seq_release_private(inode, file);
  6248. }
  6249. static const struct file_operations slab_debugfs_fops = {
  6250. .open = slab_debug_trace_open,
  6251. .read = seq_read,
  6252. .llseek = seq_lseek,
  6253. .release = slab_debug_trace_release,
  6254. };
  6255. static void debugfs_slab_add(struct kmem_cache *s)
  6256. {
  6257. struct dentry *slab_cache_dir;
  6258. if (unlikely(!slab_debugfs_root))
  6259. return;
  6260. slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
  6261. debugfs_create_file("alloc_traces", 0400,
  6262. slab_cache_dir, s, &slab_debugfs_fops);
  6263. debugfs_create_file("free_traces", 0400,
  6264. slab_cache_dir, s, &slab_debugfs_fops);
  6265. }
  6266. void debugfs_slab_release(struct kmem_cache *s)
  6267. {
  6268. debugfs_lookup_and_remove(s->name, slab_debugfs_root);
  6269. }
  6270. static int __init slab_debugfs_init(void)
  6271. {
  6272. struct kmem_cache *s;
  6273. slab_debugfs_root = debugfs_create_dir("slab", NULL);
  6274. list_for_each_entry(s, &slab_caches, list)
  6275. if (s->flags & SLAB_STORE_USER)
  6276. debugfs_slab_add(s);
  6277. return 0;
  6278. }
  6279. __initcall(slab_debugfs_init);
  6280. #endif
  6281. /*
  6282. * The /proc/slabinfo ABI
  6283. */
  6284. #ifdef CONFIG_SLUB_DEBUG
  6285. void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
  6286. {
  6287. unsigned long nr_slabs = 0;
  6288. unsigned long nr_objs = 0;
  6289. unsigned long nr_free = 0;
  6290. int node;
  6291. struct kmem_cache_node *n;
  6292. for_each_kmem_cache_node(s, node, n) {
  6293. nr_slabs += node_nr_slabs(n);
  6294. nr_objs += node_nr_objs(n);
  6295. nr_free += count_partial_free_approx(n);
  6296. }
  6297. sinfo->active_objs = nr_objs - nr_free;
  6298. sinfo->num_objs = nr_objs;
  6299. sinfo->active_slabs = nr_slabs;
  6300. sinfo->num_slabs = nr_slabs;
  6301. sinfo->objects_per_slab = oo_objects(s->oo);
  6302. sinfo->cache_order = oo_order(s->oo);
  6303. }
  6304. #endif /* CONFIG_SLUB_DEBUG */