cgroup.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532
  1. /*
  2. * Generic process-grouping system.
  3. *
  4. * Based originally on the cpuset system, extracted by Paul Menage
  5. * Copyright (C) 2006 Google, Inc
  6. *
  7. * Notifications support
  8. * Copyright (C) 2009 Nokia Corporation
  9. * Author: Kirill A. Shutemov
  10. *
  11. * Copyright notices from the original cpuset code:
  12. * --------------------------------------------------
  13. * Copyright (C) 2003 BULL SA.
  14. * Copyright (C) 2004-2006 Silicon Graphics, Inc.
  15. *
  16. * Portions derived from Patrick Mochel's sysfs code.
  17. * sysfs is Copyright (c) 2001-3 Patrick Mochel
  18. *
  19. * 2003-10-10 Written by Simon Derr.
  20. * 2003-10-22 Updates by Stephen Hemminger.
  21. * 2004 May-July Rework by Paul Jackson.
  22. * ---------------------------------------------------
  23. *
  24. * This file is subject to the terms and conditions of the GNU General Public
  25. * License. See the file COPYING in the main directory of the Linux
  26. * distribution for more details.
  27. */
  28. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  29. #include <linux/cgroup.h>
  30. #include <linux/cred.h>
  31. #include <linux/ctype.h>
  32. #include <linux/errno.h>
  33. #include <linux/init_task.h>
  34. #include <linux/kernel.h>
  35. #include <linux/list.h>
  36. #include <linux/magic.h>
  37. #include <linux/mm.h>
  38. #include <linux/mutex.h>
  39. #include <linux/mount.h>
  40. #include <linux/pagemap.h>
  41. #include <linux/proc_fs.h>
  42. #include <linux/rcupdate.h>
  43. #include <linux/sched.h>
  44. #include <linux/slab.h>
  45. #include <linux/spinlock.h>
  46. #include <linux/percpu-rwsem.h>
  47. #include <linux/string.h>
  48. #include <linux/sort.h>
  49. #include <linux/kmod.h>
  50. #include <linux/delayacct.h>
  51. #include <linux/cgroupstats.h>
  52. #include <linux/hashtable.h>
  53. #include <linux/pid_namespace.h>
  54. #include <linux/idr.h>
  55. #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
  56. #include <linux/kthread.h>
  57. #include <linux/delay.h>
  58. #include <linux/atomic.h>
  59. #include <linux/cpuset.h>
  60. #include <linux/proc_ns.h>
  61. #include <linux/nsproxy.h>
  62. #include <linux/proc_ns.h>
  63. #include <net/sock.h>
  64. /*
  65. * pidlists linger the following amount before being destroyed. The goal
  66. * is avoiding frequent destruction in the middle of consecutive read calls
  67. * Expiring in the middle is a performance problem not a correctness one.
  68. * 1 sec should be enough.
  69. */
  70. #define CGROUP_PIDLIST_DESTROY_DELAY HZ
  71. #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
  72. MAX_CFTYPE_NAME + 2)
  73. /*
  74. * cgroup_mutex is the master lock. Any modification to cgroup or its
  75. * hierarchy must be performed while holding it.
  76. *
  77. * css_set_lock protects task->cgroups pointer, the list of css_set
  78. * objects, and the chain of tasks off each css_set.
  79. *
  80. * These locks are exported if CONFIG_PROVE_RCU so that accessors in
  81. * cgroup.h can use them for lockdep annotations.
  82. */
  83. #ifdef CONFIG_PROVE_RCU
  84. DEFINE_MUTEX(cgroup_mutex);
  85. DEFINE_SPINLOCK(css_set_lock);
  86. EXPORT_SYMBOL_GPL(cgroup_mutex);
  87. EXPORT_SYMBOL_GPL(css_set_lock);
  88. #else
  89. static DEFINE_MUTEX(cgroup_mutex);
  90. static DEFINE_SPINLOCK(css_set_lock);
  91. #endif
  92. /*
  93. * Protects cgroup_idr and css_idr so that IDs can be released without
  94. * grabbing cgroup_mutex.
  95. */
  96. static DEFINE_SPINLOCK(cgroup_idr_lock);
  97. /*
  98. * Protects cgroup_file->kn for !self csses. It synchronizes notifications
  99. * against file removal/re-creation across css hiding.
  100. */
  101. static DEFINE_SPINLOCK(cgroup_file_kn_lock);
  102. /*
  103. * Protects cgroup_subsys->release_agent_path. Modifying it also requires
  104. * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
  105. */
  106. static DEFINE_SPINLOCK(release_agent_path_lock);
  107. struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
  108. #define cgroup_assert_mutex_or_rcu_locked() \
  109. RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
  110. !lockdep_is_held(&cgroup_mutex), \
  111. "cgroup_mutex or RCU read lock required");
  112. /*
  113. * cgroup destruction makes heavy use of work items and there can be a lot
  114. * of concurrent destructions. Use a separate workqueue so that cgroup
  115. * destruction work items don't end up filling up max_active of system_wq
  116. * which may lead to deadlock.
  117. */
  118. static struct workqueue_struct *cgroup_destroy_wq;
  119. /*
  120. * pidlist destructions need to be flushed on cgroup destruction. Use a
  121. * separate workqueue as flush domain.
  122. */
  123. static struct workqueue_struct *cgroup_pidlist_destroy_wq;
  124. /* generate an array of cgroup subsystem pointers */
  125. #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
  126. static struct cgroup_subsys *cgroup_subsys[] = {
  127. #include <linux/cgroup_subsys.h>
  128. };
  129. #undef SUBSYS
  130. /* array of cgroup subsystem names */
  131. #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
  132. static const char *cgroup_subsys_name[] = {
  133. #include <linux/cgroup_subsys.h>
  134. };
  135. #undef SUBSYS
  136. /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
  137. #define SUBSYS(_x) \
  138. DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
  139. DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
  140. EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
  141. EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
  142. #include <linux/cgroup_subsys.h>
  143. #undef SUBSYS
  144. #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
  145. static struct static_key_true *cgroup_subsys_enabled_key[] = {
  146. #include <linux/cgroup_subsys.h>
  147. };
  148. #undef SUBSYS
  149. #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
  150. static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
  151. #include <linux/cgroup_subsys.h>
  152. };
  153. #undef SUBSYS
  154. /*
  155. * The default hierarchy, reserved for the subsystems that are otherwise
  156. * unattached - it never has more than a single cgroup, and all tasks are
  157. * part of that cgroup.
  158. */
  159. struct cgroup_root cgrp_dfl_root;
  160. EXPORT_SYMBOL_GPL(cgrp_dfl_root);
  161. /*
  162. * The default hierarchy always exists but is hidden until mounted for the
  163. * first time. This is for backward compatibility.
  164. */
  165. static bool cgrp_dfl_visible;
  166. /* Controllers blocked by the commandline in v1 */
  167. static u16 cgroup_no_v1_mask;
  168. /* some controllers are not supported in the default hierarchy */
  169. static u16 cgrp_dfl_inhibit_ss_mask;
  170. /* some controllers are implicitly enabled on the default hierarchy */
  171. static unsigned long cgrp_dfl_implicit_ss_mask;
  172. /* The list of hierarchy roots */
  173. static LIST_HEAD(cgroup_roots);
  174. static int cgroup_root_count;
  175. /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
  176. static DEFINE_IDR(cgroup_hierarchy_idr);
  177. /*
  178. * Assign a monotonically increasing serial number to csses. It guarantees
  179. * cgroups with bigger numbers are newer than those with smaller numbers.
  180. * Also, as csses are always appended to the parent's ->children list, it
  181. * guarantees that sibling csses are always sorted in the ascending serial
  182. * number order on the list. Protected by cgroup_mutex.
  183. */
  184. static u64 css_serial_nr_next = 1;
  185. /*
  186. * These bitmask flags indicate whether tasks in the fork and exit paths have
  187. * fork/exit handlers to call. This avoids us having to do extra work in the
  188. * fork/exit path to check which subsystems have fork/exit callbacks.
  189. */
  190. static u16 have_fork_callback __read_mostly;
  191. static u16 have_exit_callback __read_mostly;
  192. static u16 have_free_callback __read_mostly;
  193. /* cgroup namespace for init task */
  194. struct cgroup_namespace init_cgroup_ns = {
  195. .count = { .counter = 2, },
  196. .user_ns = &init_user_ns,
  197. .ns.ops = &cgroupns_operations,
  198. .ns.inum = PROC_CGROUP_INIT_INO,
  199. .root_cset = &init_css_set,
  200. };
  201. /* Ditto for the can_fork callback. */
  202. static u16 have_canfork_callback __read_mostly;
  203. static struct file_system_type cgroup2_fs_type;
  204. static struct cftype cgroup_dfl_base_files[];
  205. static struct cftype cgroup_legacy_base_files[];
  206. static int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask);
  207. static void cgroup_lock_and_drain_offline(struct cgroup *cgrp);
  208. static int cgroup_apply_control(struct cgroup *cgrp);
  209. static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
  210. static void css_task_iter_advance(struct css_task_iter *it);
  211. static int cgroup_destroy_locked(struct cgroup *cgrp);
  212. static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
  213. struct cgroup_subsys *ss);
  214. static void css_release(struct percpu_ref *ref);
  215. static void kill_css(struct cgroup_subsys_state *css);
  216. static int cgroup_addrm_files(struct cgroup_subsys_state *css,
  217. struct cgroup *cgrp, struct cftype cfts[],
  218. bool is_add);
  219. /**
  220. * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
  221. * @ssid: subsys ID of interest
  222. *
  223. * cgroup_subsys_enabled() can only be used with literal subsys names which
  224. * is fine for individual subsystems but unsuitable for cgroup core. This
  225. * is slower static_key_enabled() based test indexed by @ssid.
  226. */
  227. static bool cgroup_ssid_enabled(int ssid)
  228. {
  229. if (CGROUP_SUBSYS_COUNT == 0)
  230. return false;
  231. return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
  232. }
  233. static bool cgroup_ssid_no_v1(int ssid)
  234. {
  235. return cgroup_no_v1_mask & (1 << ssid);
  236. }
  237. /**
  238. * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
  239. * @cgrp: the cgroup of interest
  240. *
  241. * The default hierarchy is the v2 interface of cgroup and this function
  242. * can be used to test whether a cgroup is on the default hierarchy for
  243. * cases where a subsystem should behave differnetly depending on the
  244. * interface version.
  245. *
  246. * The set of behaviors which change on the default hierarchy are still
  247. * being determined and the mount option is prefixed with __DEVEL__.
  248. *
  249. * List of changed behaviors:
  250. *
  251. * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
  252. * and "name" are disallowed.
  253. *
  254. * - When mounting an existing superblock, mount options should match.
  255. *
  256. * - Remount is disallowed.
  257. *
  258. * - rename(2) is disallowed.
  259. *
  260. * - "tasks" is removed. Everything should be at process granularity. Use
  261. * "cgroup.procs" instead.
  262. *
  263. * - "cgroup.procs" is not sorted. pids will be unique unless they got
  264. * recycled inbetween reads.
  265. *
  266. * - "release_agent" and "notify_on_release" are removed. Replacement
  267. * notification mechanism will be implemented.
  268. *
  269. * - "cgroup.clone_children" is removed.
  270. *
  271. * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
  272. * and its descendants contain no task; otherwise, 1. The file also
  273. * generates kernfs notification which can be monitored through poll and
  274. * [di]notify when the value of the file changes.
  275. *
  276. * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
  277. * take masks of ancestors with non-empty cpus/mems, instead of being
  278. * moved to an ancestor.
  279. *
  280. * - cpuset: a task can be moved into an empty cpuset, and again it takes
  281. * masks of ancestors.
  282. *
  283. * - memcg: use_hierarchy is on by default and the cgroup file for the flag
  284. * is not created.
  285. *
  286. * - blkcg: blk-throttle becomes properly hierarchical.
  287. *
  288. * - debug: disallowed on the default hierarchy.
  289. */
  290. static bool cgroup_on_dfl(const struct cgroup *cgrp)
  291. {
  292. return cgrp->root == &cgrp_dfl_root;
  293. }
  294. /* IDR wrappers which synchronize using cgroup_idr_lock */
  295. static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
  296. gfp_t gfp_mask)
  297. {
  298. int ret;
  299. idr_preload(gfp_mask);
  300. spin_lock_bh(&cgroup_idr_lock);
  301. ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
  302. spin_unlock_bh(&cgroup_idr_lock);
  303. idr_preload_end();
  304. return ret;
  305. }
  306. static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
  307. {
  308. void *ret;
  309. spin_lock_bh(&cgroup_idr_lock);
  310. ret = idr_replace(idr, ptr, id);
  311. spin_unlock_bh(&cgroup_idr_lock);
  312. return ret;
  313. }
  314. static void cgroup_idr_remove(struct idr *idr, int id)
  315. {
  316. spin_lock_bh(&cgroup_idr_lock);
  317. idr_remove(idr, id);
  318. spin_unlock_bh(&cgroup_idr_lock);
  319. }
  320. static struct cgroup *cgroup_parent(struct cgroup *cgrp)
  321. {
  322. struct cgroup_subsys_state *parent_css = cgrp->self.parent;
  323. if (parent_css)
  324. return container_of(parent_css, struct cgroup, self);
  325. return NULL;
  326. }
  327. /* subsystems visibly enabled on a cgroup */
  328. static u16 cgroup_control(struct cgroup *cgrp)
  329. {
  330. struct cgroup *parent = cgroup_parent(cgrp);
  331. u16 root_ss_mask = cgrp->root->subsys_mask;
  332. if (parent)
  333. return parent->subtree_control;
  334. if (cgroup_on_dfl(cgrp))
  335. root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
  336. cgrp_dfl_implicit_ss_mask);
  337. return root_ss_mask;
  338. }
  339. /* subsystems enabled on a cgroup */
  340. static u16 cgroup_ss_mask(struct cgroup *cgrp)
  341. {
  342. struct cgroup *parent = cgroup_parent(cgrp);
  343. if (parent)
  344. return parent->subtree_ss_mask;
  345. return cgrp->root->subsys_mask;
  346. }
  347. /**
  348. * cgroup_css - obtain a cgroup's css for the specified subsystem
  349. * @cgrp: the cgroup of interest
  350. * @ss: the subsystem of interest (%NULL returns @cgrp->self)
  351. *
  352. * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
  353. * function must be called either under cgroup_mutex or rcu_read_lock() and
  354. * the caller is responsible for pinning the returned css if it wants to
  355. * keep accessing it outside the said locks. This function may return
  356. * %NULL if @cgrp doesn't have @subsys_id enabled.
  357. */
  358. static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
  359. struct cgroup_subsys *ss)
  360. {
  361. if (ss)
  362. return rcu_dereference_check(cgrp->subsys[ss->id],
  363. lockdep_is_held(&cgroup_mutex));
  364. else
  365. return &cgrp->self;
  366. }
  367. /**
  368. * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
  369. * @cgrp: the cgroup of interest
  370. * @ss: the subsystem of interest (%NULL returns @cgrp->self)
  371. *
  372. * Similar to cgroup_css() but returns the effective css, which is defined
  373. * as the matching css of the nearest ancestor including self which has @ss
  374. * enabled. If @ss is associated with the hierarchy @cgrp is on, this
  375. * function is guaranteed to return non-NULL css.
  376. */
  377. static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
  378. struct cgroup_subsys *ss)
  379. {
  380. lockdep_assert_held(&cgroup_mutex);
  381. if (!ss)
  382. return &cgrp->self;
  383. /*
  384. * This function is used while updating css associations and thus
  385. * can't test the csses directly. Test ss_mask.
  386. */
  387. while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
  388. cgrp = cgroup_parent(cgrp);
  389. if (!cgrp)
  390. return NULL;
  391. }
  392. return cgroup_css(cgrp, ss);
  393. }
  394. /**
  395. * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
  396. * @cgrp: the cgroup of interest
  397. * @ss: the subsystem of interest
  398. *
  399. * Find and get the effective css of @cgrp for @ss. The effective css is
  400. * defined as the matching css of the nearest ancestor including self which
  401. * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
  402. * the root css is returned, so this function always returns a valid css.
  403. * The returned css must be put using css_put().
  404. */
  405. struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
  406. struct cgroup_subsys *ss)
  407. {
  408. struct cgroup_subsys_state *css;
  409. rcu_read_lock();
  410. do {
  411. css = cgroup_css(cgrp, ss);
  412. if (css && css_tryget_online(css))
  413. goto out_unlock;
  414. cgrp = cgroup_parent(cgrp);
  415. } while (cgrp);
  416. css = init_css_set.subsys[ss->id];
  417. css_get(css);
  418. out_unlock:
  419. rcu_read_unlock();
  420. return css;
  421. }
  422. /* convenient tests for these bits */
  423. static inline bool cgroup_is_dead(const struct cgroup *cgrp)
  424. {
  425. return !(cgrp->self.flags & CSS_ONLINE);
  426. }
  427. static void cgroup_get(struct cgroup *cgrp)
  428. {
  429. WARN_ON_ONCE(cgroup_is_dead(cgrp));
  430. css_get(&cgrp->self);
  431. }
  432. static bool cgroup_tryget(struct cgroup *cgrp)
  433. {
  434. return css_tryget(&cgrp->self);
  435. }
  436. struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
  437. {
  438. struct cgroup *cgrp = of->kn->parent->priv;
  439. struct cftype *cft = of_cft(of);
  440. /*
  441. * This is open and unprotected implementation of cgroup_css().
  442. * seq_css() is only called from a kernfs file operation which has
  443. * an active reference on the file. Because all the subsystem
  444. * files are drained before a css is disassociated with a cgroup,
  445. * the matching css from the cgroup's subsys table is guaranteed to
  446. * be and stay valid until the enclosing operation is complete.
  447. */
  448. if (cft->ss)
  449. return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
  450. else
  451. return &cgrp->self;
  452. }
  453. EXPORT_SYMBOL_GPL(of_css);
  454. static int notify_on_release(const struct cgroup *cgrp)
  455. {
  456. return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
  457. }
  458. /**
  459. * for_each_css - iterate all css's of a cgroup
  460. * @css: the iteration cursor
  461. * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
  462. * @cgrp: the target cgroup to iterate css's of
  463. *
  464. * Should be called under cgroup_[tree_]mutex.
  465. */
  466. #define for_each_css(css, ssid, cgrp) \
  467. for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
  468. if (!((css) = rcu_dereference_check( \
  469. (cgrp)->subsys[(ssid)], \
  470. lockdep_is_held(&cgroup_mutex)))) { } \
  471. else
  472. /**
  473. * for_each_e_css - iterate all effective css's of a cgroup
  474. * @css: the iteration cursor
  475. * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
  476. * @cgrp: the target cgroup to iterate css's of
  477. *
  478. * Should be called under cgroup_[tree_]mutex.
  479. */
  480. #define for_each_e_css(css, ssid, cgrp) \
  481. for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
  482. if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
  483. ; \
  484. else
  485. /**
  486. * for_each_subsys - iterate all enabled cgroup subsystems
  487. * @ss: the iteration cursor
  488. * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
  489. */
  490. #define for_each_subsys(ss, ssid) \
  491. for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
  492. (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
  493. /**
  494. * do_each_subsys_mask - filter for_each_subsys with a bitmask
  495. * @ss: the iteration cursor
  496. * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
  497. * @ss_mask: the bitmask
  498. *
  499. * The block will only run for cases where the ssid-th bit (1 << ssid) of
  500. * @ss_mask is set.
  501. */
  502. #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
  503. unsigned long __ss_mask = (ss_mask); \
  504. if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
  505. (ssid) = 0; \
  506. break; \
  507. } \
  508. for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
  509. (ss) = cgroup_subsys[ssid]; \
  510. {
  511. #define while_each_subsys_mask() \
  512. } \
  513. } \
  514. } while (false)
  515. /* iterate across the hierarchies */
  516. #define for_each_root(root) \
  517. list_for_each_entry((root), &cgroup_roots, root_list)
  518. /* iterate over child cgrps, lock should be held throughout iteration */
  519. #define cgroup_for_each_live_child(child, cgrp) \
  520. list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
  521. if (({ lockdep_assert_held(&cgroup_mutex); \
  522. cgroup_is_dead(child); })) \
  523. ; \
  524. else
  525. /* walk live descendants in preorder */
  526. #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
  527. css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
  528. if (({ lockdep_assert_held(&cgroup_mutex); \
  529. (dsct) = (d_css)->cgroup; \
  530. cgroup_is_dead(dsct); })) \
  531. ; \
  532. else
  533. /* walk live descendants in postorder */
  534. #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
  535. css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
  536. if (({ lockdep_assert_held(&cgroup_mutex); \
  537. (dsct) = (d_css)->cgroup; \
  538. cgroup_is_dead(dsct); })) \
  539. ; \
  540. else
  541. static void cgroup_release_agent(struct work_struct *work);
  542. static void check_for_release(struct cgroup *cgrp);
  543. /*
  544. * A cgroup can be associated with multiple css_sets as different tasks may
  545. * belong to different cgroups on different hierarchies. In the other
  546. * direction, a css_set is naturally associated with multiple cgroups.
  547. * This M:N relationship is represented by the following link structure
  548. * which exists for each association and allows traversing the associations
  549. * from both sides.
  550. */
  551. struct cgrp_cset_link {
  552. /* the cgroup and css_set this link associates */
  553. struct cgroup *cgrp;
  554. struct css_set *cset;
  555. /* list of cgrp_cset_links anchored at cgrp->cset_links */
  556. struct list_head cset_link;
  557. /* list of cgrp_cset_links anchored at css_set->cgrp_links */
  558. struct list_head cgrp_link;
  559. };
  560. /*
  561. * The default css_set - used by init and its children prior to any
  562. * hierarchies being mounted. It contains a pointer to the root state
  563. * for each subsystem. Also used to anchor the list of css_sets. Not
  564. * reference-counted, to improve performance when child cgroups
  565. * haven't been created.
  566. */
  567. struct css_set init_css_set = {
  568. .refcount = ATOMIC_INIT(1),
  569. .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
  570. .tasks = LIST_HEAD_INIT(init_css_set.tasks),
  571. .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
  572. .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
  573. .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
  574. .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
  575. };
  576. static int css_set_count = 1; /* 1 for init_css_set */
  577. /**
  578. * css_set_populated - does a css_set contain any tasks?
  579. * @cset: target css_set
  580. */
  581. static bool css_set_populated(struct css_set *cset)
  582. {
  583. lockdep_assert_held(&css_set_lock);
  584. return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
  585. }
  586. /**
  587. * cgroup_update_populated - updated populated count of a cgroup
  588. * @cgrp: the target cgroup
  589. * @populated: inc or dec populated count
  590. *
  591. * One of the css_sets associated with @cgrp is either getting its first
  592. * task or losing the last. Update @cgrp->populated_cnt accordingly. The
  593. * count is propagated towards root so that a given cgroup's populated_cnt
  594. * is zero iff the cgroup and all its descendants don't contain any tasks.
  595. *
  596. * @cgrp's interface file "cgroup.populated" is zero if
  597. * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
  598. * changes from or to zero, userland is notified that the content of the
  599. * interface file has changed. This can be used to detect when @cgrp and
  600. * its descendants become populated or empty.
  601. */
  602. static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
  603. {
  604. lockdep_assert_held(&css_set_lock);
  605. do {
  606. bool trigger;
  607. if (populated)
  608. trigger = !cgrp->populated_cnt++;
  609. else
  610. trigger = !--cgrp->populated_cnt;
  611. if (!trigger)
  612. break;
  613. check_for_release(cgrp);
  614. cgroup_file_notify(&cgrp->events_file);
  615. cgrp = cgroup_parent(cgrp);
  616. } while (cgrp);
  617. }
  618. /**
  619. * css_set_update_populated - update populated state of a css_set
  620. * @cset: target css_set
  621. * @populated: whether @cset is populated or depopulated
  622. *
  623. * @cset is either getting the first task or losing the last. Update the
  624. * ->populated_cnt of all associated cgroups accordingly.
  625. */
  626. static void css_set_update_populated(struct css_set *cset, bool populated)
  627. {
  628. struct cgrp_cset_link *link;
  629. lockdep_assert_held(&css_set_lock);
  630. list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
  631. cgroup_update_populated(link->cgrp, populated);
  632. }
  633. /**
  634. * css_set_move_task - move a task from one css_set to another
  635. * @task: task being moved
  636. * @from_cset: css_set @task currently belongs to (may be NULL)
  637. * @to_cset: new css_set @task is being moved to (may be NULL)
  638. * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
  639. *
  640. * Move @task from @from_cset to @to_cset. If @task didn't belong to any
  641. * css_set, @from_cset can be NULL. If @task is being disassociated
  642. * instead of moved, @to_cset can be NULL.
  643. *
  644. * This function automatically handles populated_cnt updates and
  645. * css_task_iter adjustments but the caller is responsible for managing
  646. * @from_cset and @to_cset's reference counts.
  647. */
  648. static void css_set_move_task(struct task_struct *task,
  649. struct css_set *from_cset, struct css_set *to_cset,
  650. bool use_mg_tasks)
  651. {
  652. lockdep_assert_held(&css_set_lock);
  653. if (to_cset && !css_set_populated(to_cset))
  654. css_set_update_populated(to_cset, true);
  655. if (from_cset) {
  656. struct css_task_iter *it, *pos;
  657. WARN_ON_ONCE(list_empty(&task->cg_list));
  658. /*
  659. * @task is leaving, advance task iterators which are
  660. * pointing to it so that they can resume at the next
  661. * position. Advancing an iterator might remove it from
  662. * the list, use safe walk. See css_task_iter_advance*()
  663. * for details.
  664. */
  665. list_for_each_entry_safe(it, pos, &from_cset->task_iters,
  666. iters_node)
  667. if (it->task_pos == &task->cg_list)
  668. css_task_iter_advance(it);
  669. list_del_init(&task->cg_list);
  670. if (!css_set_populated(from_cset))
  671. css_set_update_populated(from_cset, false);
  672. } else {
  673. WARN_ON_ONCE(!list_empty(&task->cg_list));
  674. }
  675. if (to_cset) {
  676. /*
  677. * We are synchronized through cgroup_threadgroup_rwsem
  678. * against PF_EXITING setting such that we can't race
  679. * against cgroup_exit() changing the css_set to
  680. * init_css_set and dropping the old one.
  681. */
  682. WARN_ON_ONCE(task->flags & PF_EXITING);
  683. rcu_assign_pointer(task->cgroups, to_cset);
  684. list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
  685. &to_cset->tasks);
  686. }
  687. }
  688. /*
  689. * hash table for cgroup groups. This improves the performance to find
  690. * an existing css_set. This hash doesn't (currently) take into
  691. * account cgroups in empty hierarchies.
  692. */
  693. #define CSS_SET_HASH_BITS 7
  694. static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
  695. static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
  696. {
  697. unsigned long key = 0UL;
  698. struct cgroup_subsys *ss;
  699. int i;
  700. for_each_subsys(ss, i)
  701. key += (unsigned long)css[i];
  702. key = (key >> 16) ^ key;
  703. return key;
  704. }
  705. static void put_css_set_locked(struct css_set *cset)
  706. {
  707. struct cgrp_cset_link *link, *tmp_link;
  708. struct cgroup_subsys *ss;
  709. int ssid;
  710. lockdep_assert_held(&css_set_lock);
  711. if (!atomic_dec_and_test(&cset->refcount))
  712. return;
  713. /* This css_set is dead. unlink it and release cgroup and css refs */
  714. for_each_subsys(ss, ssid) {
  715. list_del(&cset->e_cset_node[ssid]);
  716. css_put(cset->subsys[ssid]);
  717. }
  718. hash_del(&cset->hlist);
  719. css_set_count--;
  720. list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
  721. list_del(&link->cset_link);
  722. list_del(&link->cgrp_link);
  723. if (cgroup_parent(link->cgrp))
  724. cgroup_put(link->cgrp);
  725. kfree(link);
  726. }
  727. kfree_rcu(cset, rcu_head);
  728. }
  729. static void put_css_set(struct css_set *cset)
  730. {
  731. /*
  732. * Ensure that the refcount doesn't hit zero while any readers
  733. * can see it. Similar to atomic_dec_and_lock(), but for an
  734. * rwlock
  735. */
  736. if (atomic_add_unless(&cset->refcount, -1, 1))
  737. return;
  738. spin_lock_bh(&css_set_lock);
  739. put_css_set_locked(cset);
  740. spin_unlock_bh(&css_set_lock);
  741. }
  742. /*
  743. * refcounted get/put for css_set objects
  744. */
  745. static inline void get_css_set(struct css_set *cset)
  746. {
  747. atomic_inc(&cset->refcount);
  748. }
  749. /**
  750. * compare_css_sets - helper function for find_existing_css_set().
  751. * @cset: candidate css_set being tested
  752. * @old_cset: existing css_set for a task
  753. * @new_cgrp: cgroup that's being entered by the task
  754. * @template: desired set of css pointers in css_set (pre-calculated)
  755. *
  756. * Returns true if "cset" matches "old_cset" except for the hierarchy
  757. * which "new_cgrp" belongs to, for which it should match "new_cgrp".
  758. */
  759. static bool compare_css_sets(struct css_set *cset,
  760. struct css_set *old_cset,
  761. struct cgroup *new_cgrp,
  762. struct cgroup_subsys_state *template[])
  763. {
  764. struct list_head *l1, *l2;
  765. /*
  766. * On the default hierarchy, there can be csets which are
  767. * associated with the same set of cgroups but different csses.
  768. * Let's first ensure that csses match.
  769. */
  770. if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
  771. return false;
  772. /*
  773. * Compare cgroup pointers in order to distinguish between
  774. * different cgroups in hierarchies. As different cgroups may
  775. * share the same effective css, this comparison is always
  776. * necessary.
  777. */
  778. l1 = &cset->cgrp_links;
  779. l2 = &old_cset->cgrp_links;
  780. while (1) {
  781. struct cgrp_cset_link *link1, *link2;
  782. struct cgroup *cgrp1, *cgrp2;
  783. l1 = l1->next;
  784. l2 = l2->next;
  785. /* See if we reached the end - both lists are equal length. */
  786. if (l1 == &cset->cgrp_links) {
  787. BUG_ON(l2 != &old_cset->cgrp_links);
  788. break;
  789. } else {
  790. BUG_ON(l2 == &old_cset->cgrp_links);
  791. }
  792. /* Locate the cgroups associated with these links. */
  793. link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
  794. link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
  795. cgrp1 = link1->cgrp;
  796. cgrp2 = link2->cgrp;
  797. /* Hierarchies should be linked in the same order. */
  798. BUG_ON(cgrp1->root != cgrp2->root);
  799. /*
  800. * If this hierarchy is the hierarchy of the cgroup
  801. * that's changing, then we need to check that this
  802. * css_set points to the new cgroup; if it's any other
  803. * hierarchy, then this css_set should point to the
  804. * same cgroup as the old css_set.
  805. */
  806. if (cgrp1->root == new_cgrp->root) {
  807. if (cgrp1 != new_cgrp)
  808. return false;
  809. } else {
  810. if (cgrp1 != cgrp2)
  811. return false;
  812. }
  813. }
  814. return true;
  815. }
  816. /**
  817. * find_existing_css_set - init css array and find the matching css_set
  818. * @old_cset: the css_set that we're using before the cgroup transition
  819. * @cgrp: the cgroup that we're moving into
  820. * @template: out param for the new set of csses, should be clear on entry
  821. */
  822. static struct css_set *find_existing_css_set(struct css_set *old_cset,
  823. struct cgroup *cgrp,
  824. struct cgroup_subsys_state *template[])
  825. {
  826. struct cgroup_root *root = cgrp->root;
  827. struct cgroup_subsys *ss;
  828. struct css_set *cset;
  829. unsigned long key;
  830. int i;
  831. /*
  832. * Build the set of subsystem state objects that we want to see in the
  833. * new css_set. while subsystems can change globally, the entries here
  834. * won't change, so no need for locking.
  835. */
  836. for_each_subsys(ss, i) {
  837. if (root->subsys_mask & (1UL << i)) {
  838. /*
  839. * @ss is in this hierarchy, so we want the
  840. * effective css from @cgrp.
  841. */
  842. template[i] = cgroup_e_css(cgrp, ss);
  843. } else {
  844. /*
  845. * @ss is not in this hierarchy, so we don't want
  846. * to change the css.
  847. */
  848. template[i] = old_cset->subsys[i];
  849. }
  850. }
  851. key = css_set_hash(template);
  852. hash_for_each_possible(css_set_table, cset, hlist, key) {
  853. if (!compare_css_sets(cset, old_cset, cgrp, template))
  854. continue;
  855. /* This css_set matches what we need */
  856. return cset;
  857. }
  858. /* No existing cgroup group matched */
  859. return NULL;
  860. }
  861. static void free_cgrp_cset_links(struct list_head *links_to_free)
  862. {
  863. struct cgrp_cset_link *link, *tmp_link;
  864. list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
  865. list_del(&link->cset_link);
  866. kfree(link);
  867. }
  868. }
  869. /**
  870. * allocate_cgrp_cset_links - allocate cgrp_cset_links
  871. * @count: the number of links to allocate
  872. * @tmp_links: list_head the allocated links are put on
  873. *
  874. * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
  875. * through ->cset_link. Returns 0 on success or -errno.
  876. */
  877. static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
  878. {
  879. struct cgrp_cset_link *link;
  880. int i;
  881. INIT_LIST_HEAD(tmp_links);
  882. for (i = 0; i < count; i++) {
  883. link = kzalloc(sizeof(*link), GFP_KERNEL);
  884. if (!link) {
  885. free_cgrp_cset_links(tmp_links);
  886. return -ENOMEM;
  887. }
  888. list_add(&link->cset_link, tmp_links);
  889. }
  890. return 0;
  891. }
  892. /**
  893. * link_css_set - a helper function to link a css_set to a cgroup
  894. * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
  895. * @cset: the css_set to be linked
  896. * @cgrp: the destination cgroup
  897. */
  898. static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
  899. struct cgroup *cgrp)
  900. {
  901. struct cgrp_cset_link *link;
  902. BUG_ON(list_empty(tmp_links));
  903. if (cgroup_on_dfl(cgrp))
  904. cset->dfl_cgrp = cgrp;
  905. link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
  906. link->cset = cset;
  907. link->cgrp = cgrp;
  908. /*
  909. * Always add links to the tail of the lists so that the lists are
  910. * in choronological order.
  911. */
  912. list_move_tail(&link->cset_link, &cgrp->cset_links);
  913. list_add_tail(&link->cgrp_link, &cset->cgrp_links);
  914. if (cgroup_parent(cgrp))
  915. cgroup_get(cgrp);
  916. }
  917. /**
  918. * find_css_set - return a new css_set with one cgroup updated
  919. * @old_cset: the baseline css_set
  920. * @cgrp: the cgroup to be updated
  921. *
  922. * Return a new css_set that's equivalent to @old_cset, but with @cgrp
  923. * substituted into the appropriate hierarchy.
  924. */
  925. static struct css_set *find_css_set(struct css_set *old_cset,
  926. struct cgroup *cgrp)
  927. {
  928. struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
  929. struct css_set *cset;
  930. struct list_head tmp_links;
  931. struct cgrp_cset_link *link;
  932. struct cgroup_subsys *ss;
  933. unsigned long key;
  934. int ssid;
  935. lockdep_assert_held(&cgroup_mutex);
  936. /* First see if we already have a cgroup group that matches
  937. * the desired set */
  938. spin_lock_bh(&css_set_lock);
  939. cset = find_existing_css_set(old_cset, cgrp, template);
  940. if (cset)
  941. get_css_set(cset);
  942. spin_unlock_bh(&css_set_lock);
  943. if (cset)
  944. return cset;
  945. cset = kzalloc(sizeof(*cset), GFP_KERNEL);
  946. if (!cset)
  947. return NULL;
  948. /* Allocate all the cgrp_cset_link objects that we'll need */
  949. if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
  950. kfree(cset);
  951. return NULL;
  952. }
  953. atomic_set(&cset->refcount, 1);
  954. INIT_LIST_HEAD(&cset->cgrp_links);
  955. INIT_LIST_HEAD(&cset->tasks);
  956. INIT_LIST_HEAD(&cset->mg_tasks);
  957. INIT_LIST_HEAD(&cset->mg_preload_node);
  958. INIT_LIST_HEAD(&cset->mg_node);
  959. INIT_LIST_HEAD(&cset->task_iters);
  960. INIT_HLIST_NODE(&cset->hlist);
  961. /* Copy the set of subsystem state objects generated in
  962. * find_existing_css_set() */
  963. memcpy(cset->subsys, template, sizeof(cset->subsys));
  964. spin_lock_bh(&css_set_lock);
  965. /* Add reference counts and links from the new css_set. */
  966. list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
  967. struct cgroup *c = link->cgrp;
  968. if (c->root == cgrp->root)
  969. c = cgrp;
  970. link_css_set(&tmp_links, cset, c);
  971. }
  972. BUG_ON(!list_empty(&tmp_links));
  973. css_set_count++;
  974. /* Add @cset to the hash table */
  975. key = css_set_hash(cset->subsys);
  976. hash_add(css_set_table, &cset->hlist, key);
  977. for_each_subsys(ss, ssid) {
  978. struct cgroup_subsys_state *css = cset->subsys[ssid];
  979. list_add_tail(&cset->e_cset_node[ssid],
  980. &css->cgroup->e_csets[ssid]);
  981. css_get(css);
  982. }
  983. spin_unlock_bh(&css_set_lock);
  984. return cset;
  985. }
  986. static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
  987. {
  988. struct cgroup *root_cgrp = kf_root->kn->priv;
  989. return root_cgrp->root;
  990. }
  991. static int cgroup_init_root_id(struct cgroup_root *root)
  992. {
  993. int id;
  994. lockdep_assert_held(&cgroup_mutex);
  995. id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
  996. if (id < 0)
  997. return id;
  998. root->hierarchy_id = id;
  999. return 0;
  1000. }
  1001. static void cgroup_exit_root_id(struct cgroup_root *root)
  1002. {
  1003. lockdep_assert_held(&cgroup_mutex);
  1004. if (root->hierarchy_id) {
  1005. idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
  1006. root->hierarchy_id = 0;
  1007. }
  1008. }
  1009. static void cgroup_free_root(struct cgroup_root *root)
  1010. {
  1011. if (root) {
  1012. /* hierarchy ID should already have been released */
  1013. WARN_ON_ONCE(root->hierarchy_id);
  1014. idr_destroy(&root->cgroup_idr);
  1015. kfree(root);
  1016. }
  1017. }
  1018. static void cgroup_destroy_root(struct cgroup_root *root)
  1019. {
  1020. struct cgroup *cgrp = &root->cgrp;
  1021. struct cgrp_cset_link *link, *tmp_link;
  1022. cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
  1023. BUG_ON(atomic_read(&root->nr_cgrps));
  1024. BUG_ON(!list_empty(&cgrp->self.children));
  1025. /* Rebind all subsystems back to the default hierarchy */
  1026. WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
  1027. /*
  1028. * Release all the links from cset_links to this hierarchy's
  1029. * root cgroup
  1030. */
  1031. spin_lock_bh(&css_set_lock);
  1032. list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
  1033. list_del(&link->cset_link);
  1034. list_del(&link->cgrp_link);
  1035. kfree(link);
  1036. }
  1037. spin_unlock_bh(&css_set_lock);
  1038. if (!list_empty(&root->root_list)) {
  1039. list_del(&root->root_list);
  1040. cgroup_root_count--;
  1041. }
  1042. cgroup_exit_root_id(root);
  1043. mutex_unlock(&cgroup_mutex);
  1044. kernfs_destroy_root(root->kf_root);
  1045. cgroup_free_root(root);
  1046. }
  1047. /*
  1048. * look up cgroup associated with current task's cgroup namespace on the
  1049. * specified hierarchy
  1050. */
  1051. static struct cgroup *
  1052. current_cgns_cgroup_from_root(struct cgroup_root *root)
  1053. {
  1054. struct cgroup *res = NULL;
  1055. struct css_set *cset;
  1056. lockdep_assert_held(&css_set_lock);
  1057. rcu_read_lock();
  1058. cset = current->nsproxy->cgroup_ns->root_cset;
  1059. if (cset == &init_css_set) {
  1060. res = &root->cgrp;
  1061. } else {
  1062. struct cgrp_cset_link *link;
  1063. list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
  1064. struct cgroup *c = link->cgrp;
  1065. if (c->root == root) {
  1066. res = c;
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. rcu_read_unlock();
  1072. BUG_ON(!res);
  1073. return res;
  1074. }
  1075. /* look up cgroup associated with given css_set on the specified hierarchy */
  1076. static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
  1077. struct cgroup_root *root)
  1078. {
  1079. struct cgroup *res = NULL;
  1080. lockdep_assert_held(&cgroup_mutex);
  1081. lockdep_assert_held(&css_set_lock);
  1082. if (cset == &init_css_set) {
  1083. res = &root->cgrp;
  1084. } else {
  1085. struct cgrp_cset_link *link;
  1086. list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
  1087. struct cgroup *c = link->cgrp;
  1088. if (c->root == root) {
  1089. res = c;
  1090. break;
  1091. }
  1092. }
  1093. }
  1094. BUG_ON(!res);
  1095. return res;
  1096. }
  1097. /*
  1098. * Return the cgroup for "task" from the given hierarchy. Must be
  1099. * called with cgroup_mutex and css_set_lock held.
  1100. */
  1101. static struct cgroup *task_cgroup_from_root(struct task_struct *task,
  1102. struct cgroup_root *root)
  1103. {
  1104. /*
  1105. * No need to lock the task - since we hold cgroup_mutex the
  1106. * task can't change groups, so the only thing that can happen
  1107. * is that it exits and its css is set back to init_css_set.
  1108. */
  1109. return cset_cgroup_from_root(task_css_set(task), root);
  1110. }
  1111. /*
  1112. * A task must hold cgroup_mutex to modify cgroups.
  1113. *
  1114. * Any task can increment and decrement the count field without lock.
  1115. * So in general, code holding cgroup_mutex can't rely on the count
  1116. * field not changing. However, if the count goes to zero, then only
  1117. * cgroup_attach_task() can increment it again. Because a count of zero
  1118. * means that no tasks are currently attached, therefore there is no
  1119. * way a task attached to that cgroup can fork (the other way to
  1120. * increment the count). So code holding cgroup_mutex can safely
  1121. * assume that if the count is zero, it will stay zero. Similarly, if
  1122. * a task holds cgroup_mutex on a cgroup with zero count, it
  1123. * knows that the cgroup won't be removed, as cgroup_rmdir()
  1124. * needs that mutex.
  1125. *
  1126. * A cgroup can only be deleted if both its 'count' of using tasks
  1127. * is zero, and its list of 'children' cgroups is empty. Since all
  1128. * tasks in the system use _some_ cgroup, and since there is always at
  1129. * least one task in the system (init, pid == 1), therefore, root cgroup
  1130. * always has either children cgroups and/or using tasks. So we don't
  1131. * need a special hack to ensure that root cgroup cannot be deleted.
  1132. *
  1133. * P.S. One more locking exception. RCU is used to guard the
  1134. * update of a tasks cgroup pointer by cgroup_attach_task()
  1135. */
  1136. static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
  1137. static const struct file_operations proc_cgroupstats_operations;
  1138. static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
  1139. char *buf)
  1140. {
  1141. struct cgroup_subsys *ss = cft->ss;
  1142. if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
  1143. !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
  1144. snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
  1145. cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
  1146. cft->name);
  1147. else
  1148. strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
  1149. return buf;
  1150. }
  1151. /**
  1152. * cgroup_file_mode - deduce file mode of a control file
  1153. * @cft: the control file in question
  1154. *
  1155. * S_IRUGO for read, S_IWUSR for write.
  1156. */
  1157. static umode_t cgroup_file_mode(const struct cftype *cft)
  1158. {
  1159. umode_t mode = 0;
  1160. if (cft->read_u64 || cft->read_s64 || cft->seq_show)
  1161. mode |= S_IRUGO;
  1162. if (cft->write_u64 || cft->write_s64 || cft->write) {
  1163. if (cft->flags & CFTYPE_WORLD_WRITABLE)
  1164. mode |= S_IWUGO;
  1165. else
  1166. mode |= S_IWUSR;
  1167. }
  1168. return mode;
  1169. }
  1170. /**
  1171. * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
  1172. * @subtree_control: the new subtree_control mask to consider
  1173. * @this_ss_mask: available subsystems
  1174. *
  1175. * On the default hierarchy, a subsystem may request other subsystems to be
  1176. * enabled together through its ->depends_on mask. In such cases, more
  1177. * subsystems than specified in "cgroup.subtree_control" may be enabled.
  1178. *
  1179. * This function calculates which subsystems need to be enabled if
  1180. * @subtree_control is to be applied while restricted to @this_ss_mask.
  1181. */
  1182. static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
  1183. {
  1184. u16 cur_ss_mask = subtree_control;
  1185. struct cgroup_subsys *ss;
  1186. int ssid;
  1187. lockdep_assert_held(&cgroup_mutex);
  1188. cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
  1189. while (true) {
  1190. u16 new_ss_mask = cur_ss_mask;
  1191. do_each_subsys_mask(ss, ssid, cur_ss_mask) {
  1192. new_ss_mask |= ss->depends_on;
  1193. } while_each_subsys_mask();
  1194. /*
  1195. * Mask out subsystems which aren't available. This can
  1196. * happen only if some depended-upon subsystems were bound
  1197. * to non-default hierarchies.
  1198. */
  1199. new_ss_mask &= this_ss_mask;
  1200. if (new_ss_mask == cur_ss_mask)
  1201. break;
  1202. cur_ss_mask = new_ss_mask;
  1203. }
  1204. return cur_ss_mask;
  1205. }
  1206. /**
  1207. * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
  1208. * @kn: the kernfs_node being serviced
  1209. *
  1210. * This helper undoes cgroup_kn_lock_live() and should be invoked before
  1211. * the method finishes if locking succeeded. Note that once this function
  1212. * returns the cgroup returned by cgroup_kn_lock_live() may become
  1213. * inaccessible any time. If the caller intends to continue to access the
  1214. * cgroup, it should pin it before invoking this function.
  1215. */
  1216. static void cgroup_kn_unlock(struct kernfs_node *kn)
  1217. {
  1218. struct cgroup *cgrp;
  1219. if (kernfs_type(kn) == KERNFS_DIR)
  1220. cgrp = kn->priv;
  1221. else
  1222. cgrp = kn->parent->priv;
  1223. mutex_unlock(&cgroup_mutex);
  1224. kernfs_unbreak_active_protection(kn);
  1225. cgroup_put(cgrp);
  1226. }
  1227. /**
  1228. * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
  1229. * @kn: the kernfs_node being serviced
  1230. * @drain_offline: perform offline draining on the cgroup
  1231. *
  1232. * This helper is to be used by a cgroup kernfs method currently servicing
  1233. * @kn. It breaks the active protection, performs cgroup locking and
  1234. * verifies that the associated cgroup is alive. Returns the cgroup if
  1235. * alive; otherwise, %NULL. A successful return should be undone by a
  1236. * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
  1237. * cgroup is drained of offlining csses before return.
  1238. *
  1239. * Any cgroup kernfs method implementation which requires locking the
  1240. * associated cgroup should use this helper. It avoids nesting cgroup
  1241. * locking under kernfs active protection and allows all kernfs operations
  1242. * including self-removal.
  1243. */
  1244. static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn,
  1245. bool drain_offline)
  1246. {
  1247. struct cgroup *cgrp;
  1248. if (kernfs_type(kn) == KERNFS_DIR)
  1249. cgrp = kn->priv;
  1250. else
  1251. cgrp = kn->parent->priv;
  1252. /*
  1253. * We're gonna grab cgroup_mutex which nests outside kernfs
  1254. * active_ref. cgroup liveliness check alone provides enough
  1255. * protection against removal. Ensure @cgrp stays accessible and
  1256. * break the active_ref protection.
  1257. */
  1258. if (!cgroup_tryget(cgrp))
  1259. return NULL;
  1260. kernfs_break_active_protection(kn);
  1261. if (drain_offline)
  1262. cgroup_lock_and_drain_offline(cgrp);
  1263. else
  1264. mutex_lock(&cgroup_mutex);
  1265. if (!cgroup_is_dead(cgrp))
  1266. return cgrp;
  1267. cgroup_kn_unlock(kn);
  1268. return NULL;
  1269. }
  1270. static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
  1271. {
  1272. char name[CGROUP_FILE_NAME_MAX];
  1273. lockdep_assert_held(&cgroup_mutex);
  1274. if (cft->file_offset) {
  1275. struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
  1276. struct cgroup_file *cfile = (void *)css + cft->file_offset;
  1277. spin_lock_irq(&cgroup_file_kn_lock);
  1278. cfile->kn = NULL;
  1279. spin_unlock_irq(&cgroup_file_kn_lock);
  1280. }
  1281. kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
  1282. }
  1283. /**
  1284. * css_clear_dir - remove subsys files in a cgroup directory
  1285. * @css: taget css
  1286. */
  1287. static void css_clear_dir(struct cgroup_subsys_state *css)
  1288. {
  1289. struct cgroup *cgrp = css->cgroup;
  1290. struct cftype *cfts;
  1291. if (!(css->flags & CSS_VISIBLE))
  1292. return;
  1293. css->flags &= ~CSS_VISIBLE;
  1294. list_for_each_entry(cfts, &css->ss->cfts, node)
  1295. cgroup_addrm_files(css, cgrp, cfts, false);
  1296. }
  1297. /**
  1298. * css_populate_dir - create subsys files in a cgroup directory
  1299. * @css: target css
  1300. *
  1301. * On failure, no file is added.
  1302. */
  1303. static int css_populate_dir(struct cgroup_subsys_state *css)
  1304. {
  1305. struct cgroup *cgrp = css->cgroup;
  1306. struct cftype *cfts, *failed_cfts;
  1307. int ret;
  1308. if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
  1309. return 0;
  1310. if (!css->ss) {
  1311. if (cgroup_on_dfl(cgrp))
  1312. cfts = cgroup_dfl_base_files;
  1313. else
  1314. cfts = cgroup_legacy_base_files;
  1315. return cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
  1316. }
  1317. list_for_each_entry(cfts, &css->ss->cfts, node) {
  1318. ret = cgroup_addrm_files(css, cgrp, cfts, true);
  1319. if (ret < 0) {
  1320. failed_cfts = cfts;
  1321. goto err;
  1322. }
  1323. }
  1324. css->flags |= CSS_VISIBLE;
  1325. return 0;
  1326. err:
  1327. list_for_each_entry(cfts, &css->ss->cfts, node) {
  1328. if (cfts == failed_cfts)
  1329. break;
  1330. cgroup_addrm_files(css, cgrp, cfts, false);
  1331. }
  1332. return ret;
  1333. }
  1334. static int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
  1335. {
  1336. struct cgroup *dcgrp = &dst_root->cgrp;
  1337. struct cgroup_subsys *ss;
  1338. int ssid, i, ret;
  1339. lockdep_assert_held(&cgroup_mutex);
  1340. do_each_subsys_mask(ss, ssid, ss_mask) {
  1341. /*
  1342. * If @ss has non-root csses attached to it, can't move.
  1343. * If @ss is an implicit controller, it is exempt from this
  1344. * rule and can be stolen.
  1345. */
  1346. if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
  1347. !ss->implicit_on_dfl)
  1348. return -EBUSY;
  1349. /* can't move between two non-dummy roots either */
  1350. if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
  1351. return -EBUSY;
  1352. } while_each_subsys_mask();
  1353. do_each_subsys_mask(ss, ssid, ss_mask) {
  1354. struct cgroup_root *src_root = ss->root;
  1355. struct cgroup *scgrp = &src_root->cgrp;
  1356. struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
  1357. struct css_set *cset;
  1358. WARN_ON(!css || cgroup_css(dcgrp, ss));
  1359. /* disable from the source */
  1360. src_root->subsys_mask &= ~(1 << ssid);
  1361. WARN_ON(cgroup_apply_control(scgrp));
  1362. cgroup_finalize_control(scgrp, 0);
  1363. /* rebind */
  1364. RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
  1365. rcu_assign_pointer(dcgrp->subsys[ssid], css);
  1366. ss->root = dst_root;
  1367. css->cgroup = dcgrp;
  1368. spin_lock_bh(&css_set_lock);
  1369. hash_for_each(css_set_table, i, cset, hlist)
  1370. list_move_tail(&cset->e_cset_node[ss->id],
  1371. &dcgrp->e_csets[ss->id]);
  1372. spin_unlock_bh(&css_set_lock);
  1373. /* default hierarchy doesn't enable controllers by default */
  1374. dst_root->subsys_mask |= 1 << ssid;
  1375. if (dst_root == &cgrp_dfl_root) {
  1376. static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
  1377. } else {
  1378. dcgrp->subtree_control |= 1 << ssid;
  1379. static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
  1380. }
  1381. ret = cgroup_apply_control(dcgrp);
  1382. if (ret)
  1383. pr_warn("partial failure to rebind %s controller (err=%d)\n",
  1384. ss->name, ret);
  1385. if (ss->bind)
  1386. ss->bind(css);
  1387. } while_each_subsys_mask();
  1388. kernfs_activate(dcgrp->kn);
  1389. return 0;
  1390. }
  1391. static int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
  1392. struct kernfs_root *kf_root)
  1393. {
  1394. int len = 0;
  1395. char *buf = NULL;
  1396. struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
  1397. struct cgroup *ns_cgroup;
  1398. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  1399. if (!buf)
  1400. return -ENOMEM;
  1401. spin_lock_bh(&css_set_lock);
  1402. ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
  1403. len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
  1404. spin_unlock_bh(&css_set_lock);
  1405. if (len >= PATH_MAX)
  1406. len = -ERANGE;
  1407. else if (len > 0) {
  1408. seq_escape(sf, buf, " \t\n\\");
  1409. len = 0;
  1410. }
  1411. kfree(buf);
  1412. return len;
  1413. }
  1414. static int cgroup_show_options(struct seq_file *seq,
  1415. struct kernfs_root *kf_root)
  1416. {
  1417. struct cgroup_root *root = cgroup_root_from_kf(kf_root);
  1418. struct cgroup_subsys *ss;
  1419. int ssid;
  1420. if (root != &cgrp_dfl_root)
  1421. for_each_subsys(ss, ssid)
  1422. if (root->subsys_mask & (1 << ssid))
  1423. seq_show_option(seq, ss->legacy_name, NULL);
  1424. if (root->flags & CGRP_ROOT_NOPREFIX)
  1425. seq_puts(seq, ",noprefix");
  1426. if (root->flags & CGRP_ROOT_XATTR)
  1427. seq_puts(seq, ",xattr");
  1428. spin_lock(&release_agent_path_lock);
  1429. if (strlen(root->release_agent_path))
  1430. seq_show_option(seq, "release_agent",
  1431. root->release_agent_path);
  1432. spin_unlock(&release_agent_path_lock);
  1433. if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
  1434. seq_puts(seq, ",clone_children");
  1435. if (strlen(root->name))
  1436. seq_show_option(seq, "name", root->name);
  1437. return 0;
  1438. }
  1439. struct cgroup_sb_opts {
  1440. u16 subsys_mask;
  1441. unsigned int flags;
  1442. char *release_agent;
  1443. bool cpuset_clone_children;
  1444. char *name;
  1445. /* User explicitly requested empty subsystem */
  1446. bool none;
  1447. };
  1448. static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
  1449. {
  1450. char *token, *o = data;
  1451. bool all_ss = false, one_ss = false;
  1452. u16 mask = U16_MAX;
  1453. struct cgroup_subsys *ss;
  1454. int nr_opts = 0;
  1455. int i;
  1456. #ifdef CONFIG_CPUSETS
  1457. mask = ~((u16)1 << cpuset_cgrp_id);
  1458. #endif
  1459. memset(opts, 0, sizeof(*opts));
  1460. while ((token = strsep(&o, ",")) != NULL) {
  1461. nr_opts++;
  1462. if (!*token)
  1463. return -EINVAL;
  1464. if (!strcmp(token, "none")) {
  1465. /* Explicitly have no subsystems */
  1466. opts->none = true;
  1467. continue;
  1468. }
  1469. if (!strcmp(token, "all")) {
  1470. /* Mutually exclusive option 'all' + subsystem name */
  1471. if (one_ss)
  1472. return -EINVAL;
  1473. all_ss = true;
  1474. continue;
  1475. }
  1476. if (!strcmp(token, "noprefix")) {
  1477. opts->flags |= CGRP_ROOT_NOPREFIX;
  1478. continue;
  1479. }
  1480. if (!strcmp(token, "clone_children")) {
  1481. opts->cpuset_clone_children = true;
  1482. continue;
  1483. }
  1484. if (!strcmp(token, "xattr")) {
  1485. opts->flags |= CGRP_ROOT_XATTR;
  1486. continue;
  1487. }
  1488. if (!strncmp(token, "release_agent=", 14)) {
  1489. /* Specifying two release agents is forbidden */
  1490. if (opts->release_agent)
  1491. return -EINVAL;
  1492. opts->release_agent =
  1493. kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
  1494. if (!opts->release_agent)
  1495. return -ENOMEM;
  1496. continue;
  1497. }
  1498. if (!strncmp(token, "name=", 5)) {
  1499. const char *name = token + 5;
  1500. /* Can't specify an empty name */
  1501. if (!strlen(name))
  1502. return -EINVAL;
  1503. /* Must match [\w.-]+ */
  1504. for (i = 0; i < strlen(name); i++) {
  1505. char c = name[i];
  1506. if (isalnum(c))
  1507. continue;
  1508. if ((c == '.') || (c == '-') || (c == '_'))
  1509. continue;
  1510. return -EINVAL;
  1511. }
  1512. /* Specifying two names is forbidden */
  1513. if (opts->name)
  1514. return -EINVAL;
  1515. opts->name = kstrndup(name,
  1516. MAX_CGROUP_ROOT_NAMELEN - 1,
  1517. GFP_KERNEL);
  1518. if (!opts->name)
  1519. return -ENOMEM;
  1520. continue;
  1521. }
  1522. for_each_subsys(ss, i) {
  1523. if (strcmp(token, ss->legacy_name))
  1524. continue;
  1525. if (!cgroup_ssid_enabled(i))
  1526. continue;
  1527. if (cgroup_ssid_no_v1(i))
  1528. continue;
  1529. /* Mutually exclusive option 'all' + subsystem name */
  1530. if (all_ss)
  1531. return -EINVAL;
  1532. opts->subsys_mask |= (1 << i);
  1533. one_ss = true;
  1534. break;
  1535. }
  1536. if (i == CGROUP_SUBSYS_COUNT)
  1537. return -ENOENT;
  1538. }
  1539. /*
  1540. * If the 'all' option was specified select all the subsystems,
  1541. * otherwise if 'none', 'name=' and a subsystem name options were
  1542. * not specified, let's default to 'all'
  1543. */
  1544. if (all_ss || (!one_ss && !opts->none && !opts->name))
  1545. for_each_subsys(ss, i)
  1546. if (cgroup_ssid_enabled(i) && !cgroup_ssid_no_v1(i))
  1547. opts->subsys_mask |= (1 << i);
  1548. /*
  1549. * We either have to specify by name or by subsystems. (So all
  1550. * empty hierarchies must have a name).
  1551. */
  1552. if (!opts->subsys_mask && !opts->name)
  1553. return -EINVAL;
  1554. /*
  1555. * Option noprefix was introduced just for backward compatibility
  1556. * with the old cpuset, so we allow noprefix only if mounting just
  1557. * the cpuset subsystem.
  1558. */
  1559. if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
  1560. return -EINVAL;
  1561. /* Can't specify "none" and some subsystems */
  1562. if (opts->subsys_mask && opts->none)
  1563. return -EINVAL;
  1564. return 0;
  1565. }
  1566. static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
  1567. {
  1568. int ret = 0;
  1569. struct cgroup_root *root = cgroup_root_from_kf(kf_root);
  1570. struct cgroup_sb_opts opts;
  1571. u16 added_mask, removed_mask;
  1572. if (root == &cgrp_dfl_root) {
  1573. pr_err("remount is not allowed\n");
  1574. return -EINVAL;
  1575. }
  1576. cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
  1577. /* See what subsystems are wanted */
  1578. ret = parse_cgroupfs_options(data, &opts);
  1579. if (ret)
  1580. goto out_unlock;
  1581. if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
  1582. pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
  1583. task_tgid_nr(current), current->comm);
  1584. added_mask = opts.subsys_mask & ~root->subsys_mask;
  1585. removed_mask = root->subsys_mask & ~opts.subsys_mask;
  1586. /* Don't allow flags or name to change at remount */
  1587. if ((opts.flags ^ root->flags) ||
  1588. (opts.name && strcmp(opts.name, root->name))) {
  1589. pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
  1590. opts.flags, opts.name ?: "", root->flags, root->name);
  1591. ret = -EINVAL;
  1592. goto out_unlock;
  1593. }
  1594. /* remounting is not allowed for populated hierarchies */
  1595. if (!list_empty(&root->cgrp.self.children)) {
  1596. ret = -EBUSY;
  1597. goto out_unlock;
  1598. }
  1599. ret = rebind_subsystems(root, added_mask);
  1600. if (ret)
  1601. goto out_unlock;
  1602. WARN_ON(rebind_subsystems(&cgrp_dfl_root, removed_mask));
  1603. if (opts.release_agent) {
  1604. spin_lock(&release_agent_path_lock);
  1605. strcpy(root->release_agent_path, opts.release_agent);
  1606. spin_unlock(&release_agent_path_lock);
  1607. }
  1608. out_unlock:
  1609. kfree(opts.release_agent);
  1610. kfree(opts.name);
  1611. mutex_unlock(&cgroup_mutex);
  1612. return ret;
  1613. }
  1614. /*
  1615. * To reduce the fork() overhead for systems that are not actually using
  1616. * their cgroups capability, we don't maintain the lists running through
  1617. * each css_set to its tasks until we see the list actually used - in other
  1618. * words after the first mount.
  1619. */
  1620. static bool use_task_css_set_links __read_mostly;
  1621. static void cgroup_enable_task_cg_lists(void)
  1622. {
  1623. struct task_struct *p, *g;
  1624. spin_lock_bh(&css_set_lock);
  1625. if (use_task_css_set_links)
  1626. goto out_unlock;
  1627. use_task_css_set_links = true;
  1628. /*
  1629. * We need tasklist_lock because RCU is not safe against
  1630. * while_each_thread(). Besides, a forking task that has passed
  1631. * cgroup_post_fork() without seeing use_task_css_set_links = 1
  1632. * is not guaranteed to have its child immediately visible in the
  1633. * tasklist if we walk through it with RCU.
  1634. */
  1635. read_lock(&tasklist_lock);
  1636. do_each_thread(g, p) {
  1637. WARN_ON_ONCE(!list_empty(&p->cg_list) ||
  1638. task_css_set(p) != &init_css_set);
  1639. /*
  1640. * We should check if the process is exiting, otherwise
  1641. * it will race with cgroup_exit() in that the list
  1642. * entry won't be deleted though the process has exited.
  1643. * Do it while holding siglock so that we don't end up
  1644. * racing against cgroup_exit().
  1645. */
  1646. spin_lock_irq(&p->sighand->siglock);
  1647. if (!(p->flags & PF_EXITING)) {
  1648. struct css_set *cset = task_css_set(p);
  1649. if (!css_set_populated(cset))
  1650. css_set_update_populated(cset, true);
  1651. list_add_tail(&p->cg_list, &cset->tasks);
  1652. get_css_set(cset);
  1653. }
  1654. spin_unlock_irq(&p->sighand->siglock);
  1655. } while_each_thread(g, p);
  1656. read_unlock(&tasklist_lock);
  1657. out_unlock:
  1658. spin_unlock_bh(&css_set_lock);
  1659. }
  1660. static void init_cgroup_housekeeping(struct cgroup *cgrp)
  1661. {
  1662. struct cgroup_subsys *ss;
  1663. int ssid;
  1664. INIT_LIST_HEAD(&cgrp->self.sibling);
  1665. INIT_LIST_HEAD(&cgrp->self.children);
  1666. INIT_LIST_HEAD(&cgrp->cset_links);
  1667. INIT_LIST_HEAD(&cgrp->pidlists);
  1668. mutex_init(&cgrp->pidlist_mutex);
  1669. cgrp->self.cgroup = cgrp;
  1670. cgrp->self.flags |= CSS_ONLINE;
  1671. for_each_subsys(ss, ssid)
  1672. INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
  1673. init_waitqueue_head(&cgrp->offline_waitq);
  1674. INIT_WORK(&cgrp->release_agent_work, cgroup_release_agent);
  1675. }
  1676. static void init_cgroup_root(struct cgroup_root *root,
  1677. struct cgroup_sb_opts *opts)
  1678. {
  1679. struct cgroup *cgrp = &root->cgrp;
  1680. INIT_LIST_HEAD(&root->root_list);
  1681. atomic_set(&root->nr_cgrps, 1);
  1682. cgrp->root = root;
  1683. init_cgroup_housekeeping(cgrp);
  1684. idr_init(&root->cgroup_idr);
  1685. root->flags = opts->flags;
  1686. if (opts->release_agent)
  1687. strcpy(root->release_agent_path, opts->release_agent);
  1688. if (opts->name)
  1689. strcpy(root->name, opts->name);
  1690. if (opts->cpuset_clone_children)
  1691. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
  1692. }
  1693. static int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
  1694. {
  1695. LIST_HEAD(tmp_links);
  1696. struct cgroup *root_cgrp = &root->cgrp;
  1697. struct css_set *cset;
  1698. int i, ret;
  1699. lockdep_assert_held(&cgroup_mutex);
  1700. ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
  1701. if (ret < 0)
  1702. goto out;
  1703. root_cgrp->id = ret;
  1704. root_cgrp->ancestor_ids[0] = ret;
  1705. ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 0,
  1706. GFP_KERNEL);
  1707. if (ret)
  1708. goto out;
  1709. /*
  1710. * We're accessing css_set_count without locking css_set_lock here,
  1711. * but that's OK - it can only be increased by someone holding
  1712. * cgroup_lock, and that's us. Later rebinding may disable
  1713. * controllers on the default hierarchy and thus create new csets,
  1714. * which can't be more than the existing ones. Allocate 2x.
  1715. */
  1716. ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
  1717. if (ret)
  1718. goto cancel_ref;
  1719. ret = cgroup_init_root_id(root);
  1720. if (ret)
  1721. goto cancel_ref;
  1722. root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
  1723. KERNFS_ROOT_CREATE_DEACTIVATED,
  1724. root_cgrp);
  1725. if (IS_ERR(root->kf_root)) {
  1726. ret = PTR_ERR(root->kf_root);
  1727. goto exit_root_id;
  1728. }
  1729. root_cgrp->kn = root->kf_root->kn;
  1730. ret = css_populate_dir(&root_cgrp->self);
  1731. if (ret)
  1732. goto destroy_root;
  1733. ret = rebind_subsystems(root, ss_mask);
  1734. if (ret)
  1735. goto destroy_root;
  1736. /*
  1737. * There must be no failure case after here, since rebinding takes
  1738. * care of subsystems' refcounts, which are explicitly dropped in
  1739. * the failure exit path.
  1740. */
  1741. list_add(&root->root_list, &cgroup_roots);
  1742. cgroup_root_count++;
  1743. /*
  1744. * Link the root cgroup in this hierarchy into all the css_set
  1745. * objects.
  1746. */
  1747. spin_lock_bh(&css_set_lock);
  1748. hash_for_each(css_set_table, i, cset, hlist) {
  1749. link_css_set(&tmp_links, cset, root_cgrp);
  1750. if (css_set_populated(cset))
  1751. cgroup_update_populated(root_cgrp, true);
  1752. }
  1753. spin_unlock_bh(&css_set_lock);
  1754. BUG_ON(!list_empty(&root_cgrp->self.children));
  1755. BUG_ON(atomic_read(&root->nr_cgrps) != 1);
  1756. kernfs_activate(root_cgrp->kn);
  1757. ret = 0;
  1758. goto out;
  1759. destroy_root:
  1760. kernfs_destroy_root(root->kf_root);
  1761. root->kf_root = NULL;
  1762. exit_root_id:
  1763. cgroup_exit_root_id(root);
  1764. cancel_ref:
  1765. percpu_ref_exit(&root_cgrp->self.refcnt);
  1766. out:
  1767. free_cgrp_cset_links(&tmp_links);
  1768. return ret;
  1769. }
  1770. static struct dentry *cgroup_mount(struct file_system_type *fs_type,
  1771. int flags, const char *unused_dev_name,
  1772. void *data)
  1773. {
  1774. bool is_v2 = fs_type == &cgroup2_fs_type;
  1775. struct super_block *pinned_sb = NULL;
  1776. struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
  1777. struct cgroup_subsys *ss;
  1778. struct cgroup_root *root;
  1779. struct cgroup_sb_opts opts;
  1780. struct dentry *dentry;
  1781. int ret;
  1782. int i;
  1783. bool new_sb;
  1784. get_cgroup_ns(ns);
  1785. /* Check if the caller has permission to mount. */
  1786. if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
  1787. put_cgroup_ns(ns);
  1788. return ERR_PTR(-EPERM);
  1789. }
  1790. /*
  1791. * The first time anyone tries to mount a cgroup, enable the list
  1792. * linking each css_set to its tasks and fix up all existing tasks.
  1793. */
  1794. if (!use_task_css_set_links)
  1795. cgroup_enable_task_cg_lists();
  1796. if (is_v2) {
  1797. if (data) {
  1798. pr_err("cgroup2: unknown option \"%s\"\n", (char *)data);
  1799. put_cgroup_ns(ns);
  1800. return ERR_PTR(-EINVAL);
  1801. }
  1802. cgrp_dfl_visible = true;
  1803. root = &cgrp_dfl_root;
  1804. cgroup_get(&root->cgrp);
  1805. goto out_mount;
  1806. }
  1807. cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
  1808. /* First find the desired set of subsystems */
  1809. ret = parse_cgroupfs_options(data, &opts);
  1810. if (ret)
  1811. goto out_unlock;
  1812. /*
  1813. * Destruction of cgroup root is asynchronous, so subsystems may
  1814. * still be dying after the previous unmount. Let's drain the
  1815. * dying subsystems. We just need to ensure that the ones
  1816. * unmounted previously finish dying and don't care about new ones
  1817. * starting. Testing ref liveliness is good enough.
  1818. */
  1819. for_each_subsys(ss, i) {
  1820. if (!(opts.subsys_mask & (1 << i)) ||
  1821. ss->root == &cgrp_dfl_root)
  1822. continue;
  1823. if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
  1824. mutex_unlock(&cgroup_mutex);
  1825. msleep(10);
  1826. ret = restart_syscall();
  1827. goto out_free;
  1828. }
  1829. cgroup_put(&ss->root->cgrp);
  1830. }
  1831. for_each_root(root) {
  1832. bool name_match = false;
  1833. if (root == &cgrp_dfl_root)
  1834. continue;
  1835. /*
  1836. * If we asked for a name then it must match. Also, if
  1837. * name matches but sybsys_mask doesn't, we should fail.
  1838. * Remember whether name matched.
  1839. */
  1840. if (opts.name) {
  1841. if (strcmp(opts.name, root->name))
  1842. continue;
  1843. name_match = true;
  1844. }
  1845. /*
  1846. * If we asked for subsystems (or explicitly for no
  1847. * subsystems) then they must match.
  1848. */
  1849. if ((opts.subsys_mask || opts.none) &&
  1850. (opts.subsys_mask != root->subsys_mask)) {
  1851. if (!name_match)
  1852. continue;
  1853. ret = -EBUSY;
  1854. goto out_unlock;
  1855. }
  1856. if (root->flags ^ opts.flags)
  1857. pr_warn("new mount options do not match the existing superblock, will be ignored\n");
  1858. /*
  1859. * We want to reuse @root whose lifetime is governed by its
  1860. * ->cgrp. Let's check whether @root is alive and keep it
  1861. * that way. As cgroup_kill_sb() can happen anytime, we
  1862. * want to block it by pinning the sb so that @root doesn't
  1863. * get killed before mount is complete.
  1864. *
  1865. * With the sb pinned, tryget_live can reliably indicate
  1866. * whether @root can be reused. If it's being killed,
  1867. * drain it. We can use wait_queue for the wait but this
  1868. * path is super cold. Let's just sleep a bit and retry.
  1869. */
  1870. pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
  1871. if (IS_ERR(pinned_sb) ||
  1872. !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
  1873. mutex_unlock(&cgroup_mutex);
  1874. if (!IS_ERR_OR_NULL(pinned_sb))
  1875. deactivate_super(pinned_sb);
  1876. msleep(10);
  1877. ret = restart_syscall();
  1878. goto out_free;
  1879. }
  1880. ret = 0;
  1881. goto out_unlock;
  1882. }
  1883. /*
  1884. * No such thing, create a new one. name= matching without subsys
  1885. * specification is allowed for already existing hierarchies but we
  1886. * can't create new one without subsys specification.
  1887. */
  1888. if (!opts.subsys_mask && !opts.none) {
  1889. ret = -EINVAL;
  1890. goto out_unlock;
  1891. }
  1892. /*
  1893. * We know this subsystem has not yet been bound. Users in a non-init
  1894. * user namespace may only mount hierarchies with no bound subsystems,
  1895. * i.e. 'none,name=user1'
  1896. */
  1897. if (!opts.none && !capable(CAP_SYS_ADMIN)) {
  1898. ret = -EPERM;
  1899. goto out_unlock;
  1900. }
  1901. root = kzalloc(sizeof(*root), GFP_KERNEL);
  1902. if (!root) {
  1903. ret = -ENOMEM;
  1904. goto out_unlock;
  1905. }
  1906. init_cgroup_root(root, &opts);
  1907. ret = cgroup_setup_root(root, opts.subsys_mask);
  1908. if (ret)
  1909. cgroup_free_root(root);
  1910. out_unlock:
  1911. mutex_unlock(&cgroup_mutex);
  1912. out_free:
  1913. kfree(opts.release_agent);
  1914. kfree(opts.name);
  1915. if (ret) {
  1916. put_cgroup_ns(ns);
  1917. return ERR_PTR(ret);
  1918. }
  1919. out_mount:
  1920. dentry = kernfs_mount(fs_type, flags, root->kf_root,
  1921. is_v2 ? CGROUP2_SUPER_MAGIC : CGROUP_SUPER_MAGIC,
  1922. &new_sb);
  1923. /*
  1924. * In non-init cgroup namespace, instead of root cgroup's
  1925. * dentry, we return the dentry corresponding to the
  1926. * cgroupns->root_cgrp.
  1927. */
  1928. if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
  1929. struct dentry *nsdentry;
  1930. struct cgroup *cgrp;
  1931. mutex_lock(&cgroup_mutex);
  1932. spin_lock_bh(&css_set_lock);
  1933. cgrp = cset_cgroup_from_root(ns->root_cset, root);
  1934. spin_unlock_bh(&css_set_lock);
  1935. mutex_unlock(&cgroup_mutex);
  1936. nsdentry = kernfs_node_dentry(cgrp->kn, dentry->d_sb);
  1937. dput(dentry);
  1938. dentry = nsdentry;
  1939. }
  1940. if (IS_ERR(dentry) || !new_sb)
  1941. cgroup_put(&root->cgrp);
  1942. /*
  1943. * If @pinned_sb, we're reusing an existing root and holding an
  1944. * extra ref on its sb. Mount is complete. Put the extra ref.
  1945. */
  1946. if (pinned_sb) {
  1947. WARN_ON(new_sb);
  1948. deactivate_super(pinned_sb);
  1949. }
  1950. put_cgroup_ns(ns);
  1951. return dentry;
  1952. }
  1953. static void cgroup_kill_sb(struct super_block *sb)
  1954. {
  1955. struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
  1956. struct cgroup_root *root = cgroup_root_from_kf(kf_root);
  1957. /*
  1958. * If @root doesn't have any mounts or children, start killing it.
  1959. * This prevents new mounts by disabling percpu_ref_tryget_live().
  1960. * cgroup_mount() may wait for @root's release.
  1961. *
  1962. * And don't kill the default root.
  1963. */
  1964. if (!list_empty(&root->cgrp.self.children) ||
  1965. root == &cgrp_dfl_root)
  1966. cgroup_put(&root->cgrp);
  1967. else
  1968. percpu_ref_kill(&root->cgrp.self.refcnt);
  1969. kernfs_kill_sb(sb);
  1970. }
  1971. static struct file_system_type cgroup_fs_type = {
  1972. .name = "cgroup",
  1973. .mount = cgroup_mount,
  1974. .kill_sb = cgroup_kill_sb,
  1975. .fs_flags = FS_USERNS_MOUNT,
  1976. };
  1977. static struct file_system_type cgroup2_fs_type = {
  1978. .name = "cgroup2",
  1979. .mount = cgroup_mount,
  1980. .kill_sb = cgroup_kill_sb,
  1981. .fs_flags = FS_USERNS_MOUNT,
  1982. };
  1983. static char *cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
  1984. struct cgroup_namespace *ns)
  1985. {
  1986. struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
  1987. int ret;
  1988. ret = kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
  1989. if (ret < 0 || ret >= buflen)
  1990. return NULL;
  1991. return buf;
  1992. }
  1993. char *cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
  1994. struct cgroup_namespace *ns)
  1995. {
  1996. char *ret;
  1997. mutex_lock(&cgroup_mutex);
  1998. spin_lock_bh(&css_set_lock);
  1999. ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
  2000. spin_unlock_bh(&css_set_lock);
  2001. mutex_unlock(&cgroup_mutex);
  2002. return ret;
  2003. }
  2004. EXPORT_SYMBOL_GPL(cgroup_path_ns);
  2005. /**
  2006. * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
  2007. * @task: target task
  2008. * @buf: the buffer to write the path into
  2009. * @buflen: the length of the buffer
  2010. *
  2011. * Determine @task's cgroup on the first (the one with the lowest non-zero
  2012. * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
  2013. * function grabs cgroup_mutex and shouldn't be used inside locks used by
  2014. * cgroup controller callbacks.
  2015. *
  2016. * Return value is the same as kernfs_path().
  2017. */
  2018. char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
  2019. {
  2020. struct cgroup_root *root;
  2021. struct cgroup *cgrp;
  2022. int hierarchy_id = 1;
  2023. char *path = NULL;
  2024. mutex_lock(&cgroup_mutex);
  2025. spin_lock_bh(&css_set_lock);
  2026. root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
  2027. if (root) {
  2028. cgrp = task_cgroup_from_root(task, root);
  2029. path = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
  2030. } else {
  2031. /* if no hierarchy exists, everyone is in "/" */
  2032. if (strlcpy(buf, "/", buflen) < buflen)
  2033. path = buf;
  2034. }
  2035. spin_unlock_bh(&css_set_lock);
  2036. mutex_unlock(&cgroup_mutex);
  2037. return path;
  2038. }
  2039. EXPORT_SYMBOL_GPL(task_cgroup_path);
  2040. /* used to track tasks and other necessary states during migration */
  2041. struct cgroup_taskset {
  2042. /* the src and dst cset list running through cset->mg_node */
  2043. struct list_head src_csets;
  2044. struct list_head dst_csets;
  2045. /* the subsys currently being processed */
  2046. int ssid;
  2047. /*
  2048. * Fields for cgroup_taskset_*() iteration.
  2049. *
  2050. * Before migration is committed, the target migration tasks are on
  2051. * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
  2052. * the csets on ->dst_csets. ->csets point to either ->src_csets
  2053. * or ->dst_csets depending on whether migration is committed.
  2054. *
  2055. * ->cur_csets and ->cur_task point to the current task position
  2056. * during iteration.
  2057. */
  2058. struct list_head *csets;
  2059. struct css_set *cur_cset;
  2060. struct task_struct *cur_task;
  2061. };
  2062. #define CGROUP_TASKSET_INIT(tset) (struct cgroup_taskset){ \
  2063. .src_csets = LIST_HEAD_INIT(tset.src_csets), \
  2064. .dst_csets = LIST_HEAD_INIT(tset.dst_csets), \
  2065. .csets = &tset.src_csets, \
  2066. }
  2067. /**
  2068. * cgroup_taskset_add - try to add a migration target task to a taskset
  2069. * @task: target task
  2070. * @tset: target taskset
  2071. *
  2072. * Add @task, which is a migration target, to @tset. This function becomes
  2073. * noop if @task doesn't need to be migrated. @task's css_set should have
  2074. * been added as a migration source and @task->cg_list will be moved from
  2075. * the css_set's tasks list to mg_tasks one.
  2076. */
  2077. static void cgroup_taskset_add(struct task_struct *task,
  2078. struct cgroup_taskset *tset)
  2079. {
  2080. struct css_set *cset;
  2081. lockdep_assert_held(&css_set_lock);
  2082. /* @task either already exited or can't exit until the end */
  2083. if (task->flags & PF_EXITING)
  2084. return;
  2085. /* leave @task alone if post_fork() hasn't linked it yet */
  2086. if (list_empty(&task->cg_list))
  2087. return;
  2088. cset = task_css_set(task);
  2089. if (!cset->mg_src_cgrp)
  2090. return;
  2091. list_move_tail(&task->cg_list, &cset->mg_tasks);
  2092. if (list_empty(&cset->mg_node))
  2093. list_add_tail(&cset->mg_node, &tset->src_csets);
  2094. if (list_empty(&cset->mg_dst_cset->mg_node))
  2095. list_move_tail(&cset->mg_dst_cset->mg_node,
  2096. &tset->dst_csets);
  2097. }
  2098. /**
  2099. * cgroup_taskset_first - reset taskset and return the first task
  2100. * @tset: taskset of interest
  2101. * @dst_cssp: output variable for the destination css
  2102. *
  2103. * @tset iteration is initialized and the first task is returned.
  2104. */
  2105. struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
  2106. struct cgroup_subsys_state **dst_cssp)
  2107. {
  2108. tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
  2109. tset->cur_task = NULL;
  2110. return cgroup_taskset_next(tset, dst_cssp);
  2111. }
  2112. /**
  2113. * cgroup_taskset_next - iterate to the next task in taskset
  2114. * @tset: taskset of interest
  2115. * @dst_cssp: output variable for the destination css
  2116. *
  2117. * Return the next task in @tset. Iteration must have been initialized
  2118. * with cgroup_taskset_first().
  2119. */
  2120. struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
  2121. struct cgroup_subsys_state **dst_cssp)
  2122. {
  2123. struct css_set *cset = tset->cur_cset;
  2124. struct task_struct *task = tset->cur_task;
  2125. while (&cset->mg_node != tset->csets) {
  2126. if (!task)
  2127. task = list_first_entry(&cset->mg_tasks,
  2128. struct task_struct, cg_list);
  2129. else
  2130. task = list_next_entry(task, cg_list);
  2131. if (&task->cg_list != &cset->mg_tasks) {
  2132. tset->cur_cset = cset;
  2133. tset->cur_task = task;
  2134. /*
  2135. * This function may be called both before and
  2136. * after cgroup_taskset_migrate(). The two cases
  2137. * can be distinguished by looking at whether @cset
  2138. * has its ->mg_dst_cset set.
  2139. */
  2140. if (cset->mg_dst_cset)
  2141. *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
  2142. else
  2143. *dst_cssp = cset->subsys[tset->ssid];
  2144. return task;
  2145. }
  2146. cset = list_next_entry(cset, mg_node);
  2147. task = NULL;
  2148. }
  2149. return NULL;
  2150. }
  2151. /**
  2152. * cgroup_taskset_migrate - migrate a taskset
  2153. * @tset: taget taskset
  2154. * @root: cgroup root the migration is taking place on
  2155. *
  2156. * Migrate tasks in @tset as setup by migration preparation functions.
  2157. * This function fails iff one of the ->can_attach callbacks fails and
  2158. * guarantees that either all or none of the tasks in @tset are migrated.
  2159. * @tset is consumed regardless of success.
  2160. */
  2161. static int cgroup_taskset_migrate(struct cgroup_taskset *tset,
  2162. struct cgroup_root *root)
  2163. {
  2164. struct cgroup_subsys *ss;
  2165. struct task_struct *task, *tmp_task;
  2166. struct css_set *cset, *tmp_cset;
  2167. int ssid, failed_ssid, ret;
  2168. /* methods shouldn't be called if no task is actually migrating */
  2169. if (list_empty(&tset->src_csets))
  2170. return 0;
  2171. /* check that we can legitimately attach to the cgroup */
  2172. do_each_subsys_mask(ss, ssid, root->subsys_mask) {
  2173. if (ss->can_attach) {
  2174. tset->ssid = ssid;
  2175. ret = ss->can_attach(tset);
  2176. if (ret) {
  2177. failed_ssid = ssid;
  2178. goto out_cancel_attach;
  2179. }
  2180. }
  2181. } while_each_subsys_mask();
  2182. /*
  2183. * Now that we're guaranteed success, proceed to move all tasks to
  2184. * the new cgroup. There are no failure cases after here, so this
  2185. * is the commit point.
  2186. */
  2187. spin_lock_bh(&css_set_lock);
  2188. list_for_each_entry(cset, &tset->src_csets, mg_node) {
  2189. list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
  2190. struct css_set *from_cset = task_css_set(task);
  2191. struct css_set *to_cset = cset->mg_dst_cset;
  2192. get_css_set(to_cset);
  2193. css_set_move_task(task, from_cset, to_cset, true);
  2194. put_css_set_locked(from_cset);
  2195. }
  2196. }
  2197. spin_unlock_bh(&css_set_lock);
  2198. /*
  2199. * Migration is committed, all target tasks are now on dst_csets.
  2200. * Nothing is sensitive to fork() after this point. Notify
  2201. * controllers that migration is complete.
  2202. */
  2203. tset->csets = &tset->dst_csets;
  2204. do_each_subsys_mask(ss, ssid, root->subsys_mask) {
  2205. if (ss->attach) {
  2206. tset->ssid = ssid;
  2207. ss->attach(tset);
  2208. }
  2209. } while_each_subsys_mask();
  2210. ret = 0;
  2211. goto out_release_tset;
  2212. out_cancel_attach:
  2213. do_each_subsys_mask(ss, ssid, root->subsys_mask) {
  2214. if (ssid == failed_ssid)
  2215. break;
  2216. if (ss->cancel_attach) {
  2217. tset->ssid = ssid;
  2218. ss->cancel_attach(tset);
  2219. }
  2220. } while_each_subsys_mask();
  2221. out_release_tset:
  2222. spin_lock_bh(&css_set_lock);
  2223. list_splice_init(&tset->dst_csets, &tset->src_csets);
  2224. list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
  2225. list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
  2226. list_del_init(&cset->mg_node);
  2227. }
  2228. spin_unlock_bh(&css_set_lock);
  2229. return ret;
  2230. }
  2231. /**
  2232. * cgroup_may_migrate_to - verify whether a cgroup can be migration destination
  2233. * @dst_cgrp: destination cgroup to test
  2234. *
  2235. * On the default hierarchy, except for the root, subtree_control must be
  2236. * zero for migration destination cgroups with tasks so that child cgroups
  2237. * don't compete against tasks.
  2238. */
  2239. static bool cgroup_may_migrate_to(struct cgroup *dst_cgrp)
  2240. {
  2241. return !cgroup_on_dfl(dst_cgrp) || !cgroup_parent(dst_cgrp) ||
  2242. !dst_cgrp->subtree_control;
  2243. }
  2244. /**
  2245. * cgroup_migrate_finish - cleanup after attach
  2246. * @preloaded_csets: list of preloaded css_sets
  2247. *
  2248. * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
  2249. * those functions for details.
  2250. */
  2251. static void cgroup_migrate_finish(struct list_head *preloaded_csets)
  2252. {
  2253. struct css_set *cset, *tmp_cset;
  2254. lockdep_assert_held(&cgroup_mutex);
  2255. spin_lock_bh(&css_set_lock);
  2256. list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
  2257. cset->mg_src_cgrp = NULL;
  2258. cset->mg_dst_cgrp = NULL;
  2259. cset->mg_dst_cset = NULL;
  2260. list_del_init(&cset->mg_preload_node);
  2261. put_css_set_locked(cset);
  2262. }
  2263. spin_unlock_bh(&css_set_lock);
  2264. }
  2265. /**
  2266. * cgroup_migrate_add_src - add a migration source css_set
  2267. * @src_cset: the source css_set to add
  2268. * @dst_cgrp: the destination cgroup
  2269. * @preloaded_csets: list of preloaded css_sets
  2270. *
  2271. * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
  2272. * @src_cset and add it to @preloaded_csets, which should later be cleaned
  2273. * up by cgroup_migrate_finish().
  2274. *
  2275. * This function may be called without holding cgroup_threadgroup_rwsem
  2276. * even if the target is a process. Threads may be created and destroyed
  2277. * but as long as cgroup_mutex is not dropped, no new css_set can be put
  2278. * into play and the preloaded css_sets are guaranteed to cover all
  2279. * migrations.
  2280. */
  2281. static void cgroup_migrate_add_src(struct css_set *src_cset,
  2282. struct cgroup *dst_cgrp,
  2283. struct list_head *preloaded_csets)
  2284. {
  2285. struct cgroup *src_cgrp;
  2286. lockdep_assert_held(&cgroup_mutex);
  2287. lockdep_assert_held(&css_set_lock);
  2288. /*
  2289. * If ->dead, @src_set is associated with one or more dead cgroups
  2290. * and doesn't contain any migratable tasks. Ignore it early so
  2291. * that the rest of migration path doesn't get confused by it.
  2292. */
  2293. if (src_cset->dead)
  2294. return;
  2295. src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
  2296. if (!list_empty(&src_cset->mg_preload_node))
  2297. return;
  2298. WARN_ON(src_cset->mg_src_cgrp);
  2299. WARN_ON(src_cset->mg_dst_cgrp);
  2300. WARN_ON(!list_empty(&src_cset->mg_tasks));
  2301. WARN_ON(!list_empty(&src_cset->mg_node));
  2302. src_cset->mg_src_cgrp = src_cgrp;
  2303. src_cset->mg_dst_cgrp = dst_cgrp;
  2304. get_css_set(src_cset);
  2305. list_add(&src_cset->mg_preload_node, preloaded_csets);
  2306. }
  2307. /**
  2308. * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
  2309. * @preloaded_csets: list of preloaded source css_sets
  2310. *
  2311. * Tasks are about to be moved and all the source css_sets have been
  2312. * preloaded to @preloaded_csets. This function looks up and pins all
  2313. * destination css_sets, links each to its source, and append them to
  2314. * @preloaded_csets.
  2315. *
  2316. * This function must be called after cgroup_migrate_add_src() has been
  2317. * called on each migration source css_set. After migration is performed
  2318. * using cgroup_migrate(), cgroup_migrate_finish() must be called on
  2319. * @preloaded_csets.
  2320. */
  2321. static int cgroup_migrate_prepare_dst(struct list_head *preloaded_csets)
  2322. {
  2323. LIST_HEAD(csets);
  2324. struct css_set *src_cset, *tmp_cset;
  2325. lockdep_assert_held(&cgroup_mutex);
  2326. /* look up the dst cset for each src cset and link it to src */
  2327. list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
  2328. struct css_set *dst_cset;
  2329. dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
  2330. if (!dst_cset)
  2331. goto err;
  2332. WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
  2333. /*
  2334. * If src cset equals dst, it's noop. Drop the src.
  2335. * cgroup_migrate() will skip the cset too. Note that we
  2336. * can't handle src == dst as some nodes are used by both.
  2337. */
  2338. if (src_cset == dst_cset) {
  2339. src_cset->mg_src_cgrp = NULL;
  2340. src_cset->mg_dst_cgrp = NULL;
  2341. list_del_init(&src_cset->mg_preload_node);
  2342. put_css_set(src_cset);
  2343. put_css_set(dst_cset);
  2344. continue;
  2345. }
  2346. src_cset->mg_dst_cset = dst_cset;
  2347. if (list_empty(&dst_cset->mg_preload_node))
  2348. list_add(&dst_cset->mg_preload_node, &csets);
  2349. else
  2350. put_css_set(dst_cset);
  2351. }
  2352. list_splice_tail(&csets, preloaded_csets);
  2353. return 0;
  2354. err:
  2355. cgroup_migrate_finish(&csets);
  2356. return -ENOMEM;
  2357. }
  2358. /**
  2359. * cgroup_migrate - migrate a process or task to a cgroup
  2360. * @leader: the leader of the process or the task to migrate
  2361. * @threadgroup: whether @leader points to the whole process or a single task
  2362. * @root: cgroup root migration is taking place on
  2363. *
  2364. * Migrate a process or task denoted by @leader. If migrating a process,
  2365. * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
  2366. * responsible for invoking cgroup_migrate_add_src() and
  2367. * cgroup_migrate_prepare_dst() on the targets before invoking this
  2368. * function and following up with cgroup_migrate_finish().
  2369. *
  2370. * As long as a controller's ->can_attach() doesn't fail, this function is
  2371. * guaranteed to succeed. This means that, excluding ->can_attach()
  2372. * failure, when migrating multiple targets, the success or failure can be
  2373. * decided for all targets by invoking group_migrate_prepare_dst() before
  2374. * actually starting migrating.
  2375. */
  2376. static int cgroup_migrate(struct task_struct *leader, bool threadgroup,
  2377. struct cgroup_root *root)
  2378. {
  2379. struct cgroup_taskset tset = CGROUP_TASKSET_INIT(tset);
  2380. struct task_struct *task;
  2381. /*
  2382. * Prevent freeing of tasks while we take a snapshot. Tasks that are
  2383. * already PF_EXITING could be freed from underneath us unless we
  2384. * take an rcu_read_lock.
  2385. */
  2386. spin_lock_bh(&css_set_lock);
  2387. rcu_read_lock();
  2388. task = leader;
  2389. do {
  2390. cgroup_taskset_add(task, &tset);
  2391. if (!threadgroup)
  2392. break;
  2393. } while_each_thread(leader, task);
  2394. rcu_read_unlock();
  2395. spin_unlock_bh(&css_set_lock);
  2396. return cgroup_taskset_migrate(&tset, root);
  2397. }
  2398. /**
  2399. * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
  2400. * @dst_cgrp: the cgroup to attach to
  2401. * @leader: the task or the leader of the threadgroup to be attached
  2402. * @threadgroup: attach the whole threadgroup?
  2403. *
  2404. * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
  2405. */
  2406. static int cgroup_attach_task(struct cgroup *dst_cgrp,
  2407. struct task_struct *leader, bool threadgroup)
  2408. {
  2409. LIST_HEAD(preloaded_csets);
  2410. struct task_struct *task;
  2411. int ret;
  2412. if (!cgroup_may_migrate_to(dst_cgrp))
  2413. return -EBUSY;
  2414. /* look up all src csets */
  2415. spin_lock_bh(&css_set_lock);
  2416. rcu_read_lock();
  2417. task = leader;
  2418. do {
  2419. cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
  2420. &preloaded_csets);
  2421. if (!threadgroup)
  2422. break;
  2423. } while_each_thread(leader, task);
  2424. rcu_read_unlock();
  2425. spin_unlock_bh(&css_set_lock);
  2426. /* prepare dst csets and commit */
  2427. ret = cgroup_migrate_prepare_dst(&preloaded_csets);
  2428. if (!ret)
  2429. ret = cgroup_migrate(leader, threadgroup, dst_cgrp->root);
  2430. cgroup_migrate_finish(&preloaded_csets);
  2431. return ret;
  2432. }
  2433. static int cgroup_procs_write_permission(struct task_struct *task,
  2434. struct cgroup *dst_cgrp,
  2435. struct kernfs_open_file *of)
  2436. {
  2437. const struct cred *cred = current_cred();
  2438. const struct cred *tcred = get_task_cred(task);
  2439. int ret = 0;
  2440. /*
  2441. * even if we're attaching all tasks in the thread group, we only
  2442. * need to check permissions on one of them.
  2443. */
  2444. if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
  2445. !uid_eq(cred->euid, tcred->uid) &&
  2446. !uid_eq(cred->euid, tcred->suid))
  2447. ret = -EACCES;
  2448. if (!ret && cgroup_on_dfl(dst_cgrp)) {
  2449. struct super_block *sb = of->file->f_path.dentry->d_sb;
  2450. struct cgroup *cgrp;
  2451. struct inode *inode;
  2452. spin_lock_bh(&css_set_lock);
  2453. cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
  2454. spin_unlock_bh(&css_set_lock);
  2455. while (!cgroup_is_descendant(dst_cgrp, cgrp))
  2456. cgrp = cgroup_parent(cgrp);
  2457. ret = -ENOMEM;
  2458. inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
  2459. if (inode) {
  2460. ret = inode_permission(inode, MAY_WRITE);
  2461. iput(inode);
  2462. }
  2463. }
  2464. put_cred(tcred);
  2465. return ret;
  2466. }
  2467. /*
  2468. * Find the task_struct of the task to attach by vpid and pass it along to the
  2469. * function to attach either it or all tasks in its threadgroup. Will lock
  2470. * cgroup_mutex and threadgroup.
  2471. */
  2472. static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
  2473. size_t nbytes, loff_t off, bool threadgroup)
  2474. {
  2475. struct task_struct *tsk;
  2476. struct cgroup_subsys *ss;
  2477. struct cgroup *cgrp;
  2478. pid_t pid;
  2479. int ssid, ret;
  2480. if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
  2481. return -EINVAL;
  2482. cgrp = cgroup_kn_lock_live(of->kn, false);
  2483. if (!cgrp)
  2484. return -ENODEV;
  2485. percpu_down_write(&cgroup_threadgroup_rwsem);
  2486. rcu_read_lock();
  2487. if (pid) {
  2488. tsk = find_task_by_vpid(pid);
  2489. if (!tsk) {
  2490. ret = -ESRCH;
  2491. goto out_unlock_rcu;
  2492. }
  2493. } else {
  2494. tsk = current;
  2495. }
  2496. if (threadgroup)
  2497. tsk = tsk->group_leader;
  2498. /*
  2499. * Workqueue threads may acquire PF_NO_SETAFFINITY and become
  2500. * trapped in a cpuset, or RT worker may be born in a cgroup
  2501. * with no rt_runtime allocated. Just say no.
  2502. */
  2503. if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
  2504. ret = -EINVAL;
  2505. goto out_unlock_rcu;
  2506. }
  2507. get_task_struct(tsk);
  2508. rcu_read_unlock();
  2509. ret = cgroup_procs_write_permission(tsk, cgrp, of);
  2510. if (!ret)
  2511. ret = cgroup_attach_task(cgrp, tsk, threadgroup);
  2512. put_task_struct(tsk);
  2513. goto out_unlock_threadgroup;
  2514. out_unlock_rcu:
  2515. rcu_read_unlock();
  2516. out_unlock_threadgroup:
  2517. percpu_up_write(&cgroup_threadgroup_rwsem);
  2518. for_each_subsys(ss, ssid)
  2519. if (ss->post_attach)
  2520. ss->post_attach();
  2521. cgroup_kn_unlock(of->kn);
  2522. return ret ?: nbytes;
  2523. }
  2524. /**
  2525. * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
  2526. * @from: attach to all cgroups of a given task
  2527. * @tsk: the task to be attached
  2528. */
  2529. int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
  2530. {
  2531. struct cgroup_root *root;
  2532. int retval = 0;
  2533. mutex_lock(&cgroup_mutex);
  2534. for_each_root(root) {
  2535. struct cgroup *from_cgrp;
  2536. if (root == &cgrp_dfl_root)
  2537. continue;
  2538. spin_lock_bh(&css_set_lock);
  2539. from_cgrp = task_cgroup_from_root(from, root);
  2540. spin_unlock_bh(&css_set_lock);
  2541. retval = cgroup_attach_task(from_cgrp, tsk, false);
  2542. if (retval)
  2543. break;
  2544. }
  2545. mutex_unlock(&cgroup_mutex);
  2546. return retval;
  2547. }
  2548. EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
  2549. static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
  2550. char *buf, size_t nbytes, loff_t off)
  2551. {
  2552. return __cgroup_procs_write(of, buf, nbytes, off, false);
  2553. }
  2554. static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
  2555. char *buf, size_t nbytes, loff_t off)
  2556. {
  2557. return __cgroup_procs_write(of, buf, nbytes, off, true);
  2558. }
  2559. static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
  2560. char *buf, size_t nbytes, loff_t off)
  2561. {
  2562. struct cgroup *cgrp;
  2563. BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
  2564. cgrp = cgroup_kn_lock_live(of->kn, false);
  2565. if (!cgrp)
  2566. return -ENODEV;
  2567. spin_lock(&release_agent_path_lock);
  2568. strlcpy(cgrp->root->release_agent_path, strstrip(buf),
  2569. sizeof(cgrp->root->release_agent_path));
  2570. spin_unlock(&release_agent_path_lock);
  2571. cgroup_kn_unlock(of->kn);
  2572. return nbytes;
  2573. }
  2574. static int cgroup_release_agent_show(struct seq_file *seq, void *v)
  2575. {
  2576. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2577. spin_lock(&release_agent_path_lock);
  2578. seq_puts(seq, cgrp->root->release_agent_path);
  2579. spin_unlock(&release_agent_path_lock);
  2580. seq_putc(seq, '\n');
  2581. return 0;
  2582. }
  2583. static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
  2584. {
  2585. seq_puts(seq, "0\n");
  2586. return 0;
  2587. }
  2588. static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
  2589. {
  2590. struct cgroup_subsys *ss;
  2591. bool printed = false;
  2592. int ssid;
  2593. do_each_subsys_mask(ss, ssid, ss_mask) {
  2594. if (printed)
  2595. seq_putc(seq, ' ');
  2596. seq_printf(seq, "%s", ss->name);
  2597. printed = true;
  2598. } while_each_subsys_mask();
  2599. if (printed)
  2600. seq_putc(seq, '\n');
  2601. }
  2602. /* show controllers which are enabled from the parent */
  2603. static int cgroup_controllers_show(struct seq_file *seq, void *v)
  2604. {
  2605. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2606. cgroup_print_ss_mask(seq, cgroup_control(cgrp));
  2607. return 0;
  2608. }
  2609. /* show controllers which are enabled for a given cgroup's children */
  2610. static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
  2611. {
  2612. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2613. cgroup_print_ss_mask(seq, cgrp->subtree_control);
  2614. return 0;
  2615. }
  2616. /**
  2617. * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
  2618. * @cgrp: root of the subtree to update csses for
  2619. *
  2620. * @cgrp's control masks have changed and its subtree's css associations
  2621. * need to be updated accordingly. This function looks up all css_sets
  2622. * which are attached to the subtree, creates the matching updated css_sets
  2623. * and migrates the tasks to the new ones.
  2624. */
  2625. static int cgroup_update_dfl_csses(struct cgroup *cgrp)
  2626. {
  2627. LIST_HEAD(preloaded_csets);
  2628. struct cgroup_taskset tset = CGROUP_TASKSET_INIT(tset);
  2629. struct cgroup_subsys_state *d_css;
  2630. struct cgroup *dsct;
  2631. struct css_set *src_cset;
  2632. int ret;
  2633. lockdep_assert_held(&cgroup_mutex);
  2634. percpu_down_write(&cgroup_threadgroup_rwsem);
  2635. /* look up all csses currently attached to @cgrp's subtree */
  2636. spin_lock_bh(&css_set_lock);
  2637. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2638. struct cgrp_cset_link *link;
  2639. list_for_each_entry(link, &dsct->cset_links, cset_link)
  2640. cgroup_migrate_add_src(link->cset, dsct,
  2641. &preloaded_csets);
  2642. }
  2643. spin_unlock_bh(&css_set_lock);
  2644. /* NULL dst indicates self on default hierarchy */
  2645. ret = cgroup_migrate_prepare_dst(&preloaded_csets);
  2646. if (ret)
  2647. goto out_finish;
  2648. spin_lock_bh(&css_set_lock);
  2649. list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
  2650. struct task_struct *task, *ntask;
  2651. /* src_csets precede dst_csets, break on the first dst_cset */
  2652. if (!src_cset->mg_src_cgrp)
  2653. break;
  2654. /* all tasks in src_csets need to be migrated */
  2655. list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
  2656. cgroup_taskset_add(task, &tset);
  2657. }
  2658. spin_unlock_bh(&css_set_lock);
  2659. ret = cgroup_taskset_migrate(&tset, cgrp->root);
  2660. out_finish:
  2661. cgroup_migrate_finish(&preloaded_csets);
  2662. percpu_up_write(&cgroup_threadgroup_rwsem);
  2663. return ret;
  2664. }
  2665. /**
  2666. * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
  2667. * @cgrp: root of the target subtree
  2668. *
  2669. * Because css offlining is asynchronous, userland may try to re-enable a
  2670. * controller while the previous css is still around. This function grabs
  2671. * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
  2672. */
  2673. static void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
  2674. __acquires(&cgroup_mutex)
  2675. {
  2676. struct cgroup *dsct;
  2677. struct cgroup_subsys_state *d_css;
  2678. struct cgroup_subsys *ss;
  2679. int ssid;
  2680. restart:
  2681. mutex_lock(&cgroup_mutex);
  2682. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2683. for_each_subsys(ss, ssid) {
  2684. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2685. DEFINE_WAIT(wait);
  2686. if (!css || !percpu_ref_is_dying(&css->refcnt))
  2687. continue;
  2688. cgroup_get(dsct);
  2689. prepare_to_wait(&dsct->offline_waitq, &wait,
  2690. TASK_UNINTERRUPTIBLE);
  2691. mutex_unlock(&cgroup_mutex);
  2692. schedule();
  2693. finish_wait(&dsct->offline_waitq, &wait);
  2694. cgroup_put(dsct);
  2695. goto restart;
  2696. }
  2697. }
  2698. }
  2699. /**
  2700. * cgroup_save_control - save control masks of a subtree
  2701. * @cgrp: root of the target subtree
  2702. *
  2703. * Save ->subtree_control and ->subtree_ss_mask to the respective old_
  2704. * prefixed fields for @cgrp's subtree including @cgrp itself.
  2705. */
  2706. static void cgroup_save_control(struct cgroup *cgrp)
  2707. {
  2708. struct cgroup *dsct;
  2709. struct cgroup_subsys_state *d_css;
  2710. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2711. dsct->old_subtree_control = dsct->subtree_control;
  2712. dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
  2713. }
  2714. }
  2715. /**
  2716. * cgroup_propagate_control - refresh control masks of a subtree
  2717. * @cgrp: root of the target subtree
  2718. *
  2719. * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
  2720. * ->subtree_control and propagate controller availability through the
  2721. * subtree so that descendants don't have unavailable controllers enabled.
  2722. */
  2723. static void cgroup_propagate_control(struct cgroup *cgrp)
  2724. {
  2725. struct cgroup *dsct;
  2726. struct cgroup_subsys_state *d_css;
  2727. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2728. dsct->subtree_control &= cgroup_control(dsct);
  2729. dsct->subtree_ss_mask =
  2730. cgroup_calc_subtree_ss_mask(dsct->subtree_control,
  2731. cgroup_ss_mask(dsct));
  2732. }
  2733. }
  2734. /**
  2735. * cgroup_restore_control - restore control masks of a subtree
  2736. * @cgrp: root of the target subtree
  2737. *
  2738. * Restore ->subtree_control and ->subtree_ss_mask from the respective old_
  2739. * prefixed fields for @cgrp's subtree including @cgrp itself.
  2740. */
  2741. static void cgroup_restore_control(struct cgroup *cgrp)
  2742. {
  2743. struct cgroup *dsct;
  2744. struct cgroup_subsys_state *d_css;
  2745. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2746. dsct->subtree_control = dsct->old_subtree_control;
  2747. dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
  2748. }
  2749. }
  2750. static bool css_visible(struct cgroup_subsys_state *css)
  2751. {
  2752. struct cgroup_subsys *ss = css->ss;
  2753. struct cgroup *cgrp = css->cgroup;
  2754. if (cgroup_control(cgrp) & (1 << ss->id))
  2755. return true;
  2756. if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
  2757. return false;
  2758. return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
  2759. }
  2760. /**
  2761. * cgroup_apply_control_enable - enable or show csses according to control
  2762. * @cgrp: root of the target subtree
  2763. *
  2764. * Walk @cgrp's subtree and create new csses or make the existing ones
  2765. * visible. A css is created invisible if it's being implicitly enabled
  2766. * through dependency. An invisible css is made visible when the userland
  2767. * explicitly enables it.
  2768. *
  2769. * Returns 0 on success, -errno on failure. On failure, csses which have
  2770. * been processed already aren't cleaned up. The caller is responsible for
  2771. * cleaning up with cgroup_apply_control_disble().
  2772. */
  2773. static int cgroup_apply_control_enable(struct cgroup *cgrp)
  2774. {
  2775. struct cgroup *dsct;
  2776. struct cgroup_subsys_state *d_css;
  2777. struct cgroup_subsys *ss;
  2778. int ssid, ret;
  2779. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2780. for_each_subsys(ss, ssid) {
  2781. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2782. WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
  2783. if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
  2784. continue;
  2785. if (!css) {
  2786. css = css_create(dsct, ss);
  2787. if (IS_ERR(css))
  2788. return PTR_ERR(css);
  2789. }
  2790. if (css_visible(css)) {
  2791. ret = css_populate_dir(css);
  2792. if (ret)
  2793. return ret;
  2794. }
  2795. }
  2796. }
  2797. return 0;
  2798. }
  2799. /**
  2800. * cgroup_apply_control_disable - kill or hide csses according to control
  2801. * @cgrp: root of the target subtree
  2802. *
  2803. * Walk @cgrp's subtree and kill and hide csses so that they match
  2804. * cgroup_ss_mask() and cgroup_visible_mask().
  2805. *
  2806. * A css is hidden when the userland requests it to be disabled while other
  2807. * subsystems are still depending on it. The css must not actively control
  2808. * resources and be in the vanilla state if it's made visible again later.
  2809. * Controllers which may be depended upon should provide ->css_reset() for
  2810. * this purpose.
  2811. */
  2812. static void cgroup_apply_control_disable(struct cgroup *cgrp)
  2813. {
  2814. struct cgroup *dsct;
  2815. struct cgroup_subsys_state *d_css;
  2816. struct cgroup_subsys *ss;
  2817. int ssid;
  2818. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2819. for_each_subsys(ss, ssid) {
  2820. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2821. WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
  2822. if (!css)
  2823. continue;
  2824. if (css->parent &&
  2825. !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
  2826. kill_css(css);
  2827. } else if (!css_visible(css)) {
  2828. css_clear_dir(css);
  2829. if (ss->css_reset)
  2830. ss->css_reset(css);
  2831. }
  2832. }
  2833. }
  2834. }
  2835. /**
  2836. * cgroup_apply_control - apply control mask updates to the subtree
  2837. * @cgrp: root of the target subtree
  2838. *
  2839. * subsystems can be enabled and disabled in a subtree using the following
  2840. * steps.
  2841. *
  2842. * 1. Call cgroup_save_control() to stash the current state.
  2843. * 2. Update ->subtree_control masks in the subtree as desired.
  2844. * 3. Call cgroup_apply_control() to apply the changes.
  2845. * 4. Optionally perform other related operations.
  2846. * 5. Call cgroup_finalize_control() to finish up.
  2847. *
  2848. * This function implements step 3 and propagates the mask changes
  2849. * throughout @cgrp's subtree, updates csses accordingly and perform
  2850. * process migrations.
  2851. */
  2852. static int cgroup_apply_control(struct cgroup *cgrp)
  2853. {
  2854. int ret;
  2855. cgroup_propagate_control(cgrp);
  2856. ret = cgroup_apply_control_enable(cgrp);
  2857. if (ret)
  2858. return ret;
  2859. /*
  2860. * At this point, cgroup_e_css() results reflect the new csses
  2861. * making the following cgroup_update_dfl_csses() properly update
  2862. * css associations of all tasks in the subtree.
  2863. */
  2864. ret = cgroup_update_dfl_csses(cgrp);
  2865. if (ret)
  2866. return ret;
  2867. return 0;
  2868. }
  2869. /**
  2870. * cgroup_finalize_control - finalize control mask update
  2871. * @cgrp: root of the target subtree
  2872. * @ret: the result of the update
  2873. *
  2874. * Finalize control mask update. See cgroup_apply_control() for more info.
  2875. */
  2876. static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
  2877. {
  2878. if (ret) {
  2879. cgroup_restore_control(cgrp);
  2880. cgroup_propagate_control(cgrp);
  2881. }
  2882. cgroup_apply_control_disable(cgrp);
  2883. }
  2884. /* change the enabled child controllers for a cgroup in the default hierarchy */
  2885. static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
  2886. char *buf, size_t nbytes,
  2887. loff_t off)
  2888. {
  2889. u16 enable = 0, disable = 0;
  2890. struct cgroup *cgrp, *child;
  2891. struct cgroup_subsys *ss;
  2892. char *tok;
  2893. int ssid, ret;
  2894. /*
  2895. * Parse input - space separated list of subsystem names prefixed
  2896. * with either + or -.
  2897. */
  2898. buf = strstrip(buf);
  2899. while ((tok = strsep(&buf, " "))) {
  2900. if (tok[0] == '\0')
  2901. continue;
  2902. do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
  2903. if (!cgroup_ssid_enabled(ssid) ||
  2904. strcmp(tok + 1, ss->name))
  2905. continue;
  2906. if (*tok == '+') {
  2907. enable |= 1 << ssid;
  2908. disable &= ~(1 << ssid);
  2909. } else if (*tok == '-') {
  2910. disable |= 1 << ssid;
  2911. enable &= ~(1 << ssid);
  2912. } else {
  2913. return -EINVAL;
  2914. }
  2915. break;
  2916. } while_each_subsys_mask();
  2917. if (ssid == CGROUP_SUBSYS_COUNT)
  2918. return -EINVAL;
  2919. }
  2920. cgrp = cgroup_kn_lock_live(of->kn, true);
  2921. if (!cgrp)
  2922. return -ENODEV;
  2923. for_each_subsys(ss, ssid) {
  2924. if (enable & (1 << ssid)) {
  2925. if (cgrp->subtree_control & (1 << ssid)) {
  2926. enable &= ~(1 << ssid);
  2927. continue;
  2928. }
  2929. if (!(cgroup_control(cgrp) & (1 << ssid))) {
  2930. ret = -ENOENT;
  2931. goto out_unlock;
  2932. }
  2933. } else if (disable & (1 << ssid)) {
  2934. if (!(cgrp->subtree_control & (1 << ssid))) {
  2935. disable &= ~(1 << ssid);
  2936. continue;
  2937. }
  2938. /* a child has it enabled? */
  2939. cgroup_for_each_live_child(child, cgrp) {
  2940. if (child->subtree_control & (1 << ssid)) {
  2941. ret = -EBUSY;
  2942. goto out_unlock;
  2943. }
  2944. }
  2945. }
  2946. }
  2947. if (!enable && !disable) {
  2948. ret = 0;
  2949. goto out_unlock;
  2950. }
  2951. /*
  2952. * Except for the root, subtree_control must be zero for a cgroup
  2953. * with tasks so that child cgroups don't compete against tasks.
  2954. */
  2955. if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
  2956. ret = -EBUSY;
  2957. goto out_unlock;
  2958. }
  2959. /* save and update control masks and prepare csses */
  2960. cgroup_save_control(cgrp);
  2961. cgrp->subtree_control |= enable;
  2962. cgrp->subtree_control &= ~disable;
  2963. ret = cgroup_apply_control(cgrp);
  2964. cgroup_finalize_control(cgrp, ret);
  2965. kernfs_activate(cgrp->kn);
  2966. ret = 0;
  2967. out_unlock:
  2968. cgroup_kn_unlock(of->kn);
  2969. return ret ?: nbytes;
  2970. }
  2971. static int cgroup_events_show(struct seq_file *seq, void *v)
  2972. {
  2973. seq_printf(seq, "populated %d\n",
  2974. cgroup_is_populated(seq_css(seq)->cgroup));
  2975. return 0;
  2976. }
  2977. static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
  2978. size_t nbytes, loff_t off)
  2979. {
  2980. struct cgroup *cgrp = of->kn->parent->priv;
  2981. struct cftype *cft = of->kn->priv;
  2982. struct cgroup_subsys_state *css;
  2983. int ret;
  2984. if (cft->write)
  2985. return cft->write(of, buf, nbytes, off);
  2986. /*
  2987. * kernfs guarantees that a file isn't deleted with operations in
  2988. * flight, which means that the matching css is and stays alive and
  2989. * doesn't need to be pinned. The RCU locking is not necessary
  2990. * either. It's just for the convenience of using cgroup_css().
  2991. */
  2992. rcu_read_lock();
  2993. css = cgroup_css(cgrp, cft->ss);
  2994. rcu_read_unlock();
  2995. if (cft->write_u64) {
  2996. unsigned long long v;
  2997. ret = kstrtoull(buf, 0, &v);
  2998. if (!ret)
  2999. ret = cft->write_u64(css, cft, v);
  3000. } else if (cft->write_s64) {
  3001. long long v;
  3002. ret = kstrtoll(buf, 0, &v);
  3003. if (!ret)
  3004. ret = cft->write_s64(css, cft, v);
  3005. } else {
  3006. ret = -EINVAL;
  3007. }
  3008. return ret ?: nbytes;
  3009. }
  3010. static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
  3011. {
  3012. return seq_cft(seq)->seq_start(seq, ppos);
  3013. }
  3014. static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
  3015. {
  3016. return seq_cft(seq)->seq_next(seq, v, ppos);
  3017. }
  3018. static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
  3019. {
  3020. seq_cft(seq)->seq_stop(seq, v);
  3021. }
  3022. static int cgroup_seqfile_show(struct seq_file *m, void *arg)
  3023. {
  3024. struct cftype *cft = seq_cft(m);
  3025. struct cgroup_subsys_state *css = seq_css(m);
  3026. if (cft->seq_show)
  3027. return cft->seq_show(m, arg);
  3028. if (cft->read_u64)
  3029. seq_printf(m, "%llu\n", cft->read_u64(css, cft));
  3030. else if (cft->read_s64)
  3031. seq_printf(m, "%lld\n", cft->read_s64(css, cft));
  3032. else
  3033. return -EINVAL;
  3034. return 0;
  3035. }
  3036. static struct kernfs_ops cgroup_kf_single_ops = {
  3037. .atomic_write_len = PAGE_SIZE,
  3038. .write = cgroup_file_write,
  3039. .seq_show = cgroup_seqfile_show,
  3040. };
  3041. static struct kernfs_ops cgroup_kf_ops = {
  3042. .atomic_write_len = PAGE_SIZE,
  3043. .write = cgroup_file_write,
  3044. .seq_start = cgroup_seqfile_start,
  3045. .seq_next = cgroup_seqfile_next,
  3046. .seq_stop = cgroup_seqfile_stop,
  3047. .seq_show = cgroup_seqfile_show,
  3048. };
  3049. /*
  3050. * cgroup_rename - Only allow simple rename of directories in place.
  3051. */
  3052. static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
  3053. const char *new_name_str)
  3054. {
  3055. struct cgroup *cgrp = kn->priv;
  3056. int ret;
  3057. if (kernfs_type(kn) != KERNFS_DIR)
  3058. return -ENOTDIR;
  3059. if (kn->parent != new_parent)
  3060. return -EIO;
  3061. /*
  3062. * This isn't a proper migration and its usefulness is very
  3063. * limited. Disallow on the default hierarchy.
  3064. */
  3065. if (cgroup_on_dfl(cgrp))
  3066. return -EPERM;
  3067. /*
  3068. * We're gonna grab cgroup_mutex which nests outside kernfs
  3069. * active_ref. kernfs_rename() doesn't require active_ref
  3070. * protection. Break them before grabbing cgroup_mutex.
  3071. */
  3072. kernfs_break_active_protection(new_parent);
  3073. kernfs_break_active_protection(kn);
  3074. mutex_lock(&cgroup_mutex);
  3075. ret = kernfs_rename(kn, new_parent, new_name_str);
  3076. mutex_unlock(&cgroup_mutex);
  3077. kernfs_unbreak_active_protection(kn);
  3078. kernfs_unbreak_active_protection(new_parent);
  3079. return ret;
  3080. }
  3081. /* set uid and gid of cgroup dirs and files to that of the creator */
  3082. static int cgroup_kn_set_ugid(struct kernfs_node *kn)
  3083. {
  3084. struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
  3085. .ia_uid = current_fsuid(),
  3086. .ia_gid = current_fsgid(), };
  3087. if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
  3088. gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
  3089. return 0;
  3090. return kernfs_setattr(kn, &iattr);
  3091. }
  3092. static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
  3093. struct cftype *cft)
  3094. {
  3095. char name[CGROUP_FILE_NAME_MAX];
  3096. struct kernfs_node *kn;
  3097. struct lock_class_key *key = NULL;
  3098. int ret;
  3099. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  3100. key = &cft->lockdep_key;
  3101. #endif
  3102. kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
  3103. cgroup_file_mode(cft), 0, cft->kf_ops, cft,
  3104. NULL, key);
  3105. if (IS_ERR(kn))
  3106. return PTR_ERR(kn);
  3107. ret = cgroup_kn_set_ugid(kn);
  3108. if (ret) {
  3109. kernfs_remove(kn);
  3110. return ret;
  3111. }
  3112. if (cft->file_offset) {
  3113. struct cgroup_file *cfile = (void *)css + cft->file_offset;
  3114. spin_lock_irq(&cgroup_file_kn_lock);
  3115. cfile->kn = kn;
  3116. spin_unlock_irq(&cgroup_file_kn_lock);
  3117. }
  3118. return 0;
  3119. }
  3120. /**
  3121. * cgroup_addrm_files - add or remove files to a cgroup directory
  3122. * @css: the target css
  3123. * @cgrp: the target cgroup (usually css->cgroup)
  3124. * @cfts: array of cftypes to be added
  3125. * @is_add: whether to add or remove
  3126. *
  3127. * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
  3128. * For removals, this function never fails.
  3129. */
  3130. static int cgroup_addrm_files(struct cgroup_subsys_state *css,
  3131. struct cgroup *cgrp, struct cftype cfts[],
  3132. bool is_add)
  3133. {
  3134. struct cftype *cft, *cft_end = NULL;
  3135. int ret = 0;
  3136. lockdep_assert_held(&cgroup_mutex);
  3137. restart:
  3138. for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
  3139. /* does cft->flags tell us to skip this file on @cgrp? */
  3140. if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
  3141. continue;
  3142. if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
  3143. continue;
  3144. if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
  3145. continue;
  3146. if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
  3147. continue;
  3148. if (is_add) {
  3149. ret = cgroup_add_file(css, cgrp, cft);
  3150. if (ret) {
  3151. pr_warn("%s: failed to add %s, err=%d\n",
  3152. __func__, cft->name, ret);
  3153. cft_end = cft;
  3154. is_add = false;
  3155. goto restart;
  3156. }
  3157. } else {
  3158. cgroup_rm_file(cgrp, cft);
  3159. }
  3160. }
  3161. return ret;
  3162. }
  3163. static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
  3164. {
  3165. LIST_HEAD(pending);
  3166. struct cgroup_subsys *ss = cfts[0].ss;
  3167. struct cgroup *root = &ss->root->cgrp;
  3168. struct cgroup_subsys_state *css;
  3169. int ret = 0;
  3170. lockdep_assert_held(&cgroup_mutex);
  3171. /* add/rm files for all cgroups created before */
  3172. css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
  3173. struct cgroup *cgrp = css->cgroup;
  3174. if (!(css->flags & CSS_VISIBLE))
  3175. continue;
  3176. ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
  3177. if (ret)
  3178. break;
  3179. }
  3180. if (is_add && !ret)
  3181. kernfs_activate(root->kn);
  3182. return ret;
  3183. }
  3184. static void cgroup_exit_cftypes(struct cftype *cfts)
  3185. {
  3186. struct cftype *cft;
  3187. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  3188. /* free copy for custom atomic_write_len, see init_cftypes() */
  3189. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
  3190. kfree(cft->kf_ops);
  3191. cft->kf_ops = NULL;
  3192. cft->ss = NULL;
  3193. /* revert flags set by cgroup core while adding @cfts */
  3194. cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
  3195. }
  3196. }
  3197. static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3198. {
  3199. struct cftype *cft;
  3200. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  3201. struct kernfs_ops *kf_ops;
  3202. WARN_ON(cft->ss || cft->kf_ops);
  3203. if (cft->seq_start)
  3204. kf_ops = &cgroup_kf_ops;
  3205. else
  3206. kf_ops = &cgroup_kf_single_ops;
  3207. /*
  3208. * Ugh... if @cft wants a custom max_write_len, we need to
  3209. * make a copy of kf_ops to set its atomic_write_len.
  3210. */
  3211. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
  3212. kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
  3213. if (!kf_ops) {
  3214. cgroup_exit_cftypes(cfts);
  3215. return -ENOMEM;
  3216. }
  3217. kf_ops->atomic_write_len = cft->max_write_len;
  3218. }
  3219. cft->kf_ops = kf_ops;
  3220. cft->ss = ss;
  3221. }
  3222. return 0;
  3223. }
  3224. static int cgroup_rm_cftypes_locked(struct cftype *cfts)
  3225. {
  3226. lockdep_assert_held(&cgroup_mutex);
  3227. if (!cfts || !cfts[0].ss)
  3228. return -ENOENT;
  3229. list_del(&cfts->node);
  3230. cgroup_apply_cftypes(cfts, false);
  3231. cgroup_exit_cftypes(cfts);
  3232. return 0;
  3233. }
  3234. /**
  3235. * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
  3236. * @cfts: zero-length name terminated array of cftypes
  3237. *
  3238. * Unregister @cfts. Files described by @cfts are removed from all
  3239. * existing cgroups and all future cgroups won't have them either. This
  3240. * function can be called anytime whether @cfts' subsys is attached or not.
  3241. *
  3242. * Returns 0 on successful unregistration, -ENOENT if @cfts is not
  3243. * registered.
  3244. */
  3245. int cgroup_rm_cftypes(struct cftype *cfts)
  3246. {
  3247. int ret;
  3248. mutex_lock(&cgroup_mutex);
  3249. ret = cgroup_rm_cftypes_locked(cfts);
  3250. mutex_unlock(&cgroup_mutex);
  3251. return ret;
  3252. }
  3253. /**
  3254. * cgroup_add_cftypes - add an array of cftypes to a subsystem
  3255. * @ss: target cgroup subsystem
  3256. * @cfts: zero-length name terminated array of cftypes
  3257. *
  3258. * Register @cfts to @ss. Files described by @cfts are created for all
  3259. * existing cgroups to which @ss is attached and all future cgroups will
  3260. * have them too. This function can be called anytime whether @ss is
  3261. * attached or not.
  3262. *
  3263. * Returns 0 on successful registration, -errno on failure. Note that this
  3264. * function currently returns 0 as long as @cfts registration is successful
  3265. * even if some file creation attempts on existing cgroups fail.
  3266. */
  3267. static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3268. {
  3269. int ret;
  3270. if (!cgroup_ssid_enabled(ss->id))
  3271. return 0;
  3272. if (!cfts || cfts[0].name[0] == '\0')
  3273. return 0;
  3274. ret = cgroup_init_cftypes(ss, cfts);
  3275. if (ret)
  3276. return ret;
  3277. mutex_lock(&cgroup_mutex);
  3278. list_add_tail(&cfts->node, &ss->cfts);
  3279. ret = cgroup_apply_cftypes(cfts, true);
  3280. if (ret)
  3281. cgroup_rm_cftypes_locked(cfts);
  3282. mutex_unlock(&cgroup_mutex);
  3283. return ret;
  3284. }
  3285. /**
  3286. * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
  3287. * @ss: target cgroup subsystem
  3288. * @cfts: zero-length name terminated array of cftypes
  3289. *
  3290. * Similar to cgroup_add_cftypes() but the added files are only used for
  3291. * the default hierarchy.
  3292. */
  3293. int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3294. {
  3295. struct cftype *cft;
  3296. for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
  3297. cft->flags |= __CFTYPE_ONLY_ON_DFL;
  3298. return cgroup_add_cftypes(ss, cfts);
  3299. }
  3300. /**
  3301. * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
  3302. * @ss: target cgroup subsystem
  3303. * @cfts: zero-length name terminated array of cftypes
  3304. *
  3305. * Similar to cgroup_add_cftypes() but the added files are only used for
  3306. * the legacy hierarchies.
  3307. */
  3308. int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3309. {
  3310. struct cftype *cft;
  3311. for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
  3312. cft->flags |= __CFTYPE_NOT_ON_DFL;
  3313. return cgroup_add_cftypes(ss, cfts);
  3314. }
  3315. /**
  3316. * cgroup_file_notify - generate a file modified event for a cgroup_file
  3317. * @cfile: target cgroup_file
  3318. *
  3319. * @cfile must have been obtained by setting cftype->file_offset.
  3320. */
  3321. void cgroup_file_notify(struct cgroup_file *cfile)
  3322. {
  3323. unsigned long flags;
  3324. spin_lock_irqsave(&cgroup_file_kn_lock, flags);
  3325. if (cfile->kn)
  3326. kernfs_notify(cfile->kn);
  3327. spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
  3328. }
  3329. /**
  3330. * cgroup_task_count - count the number of tasks in a cgroup.
  3331. * @cgrp: the cgroup in question
  3332. *
  3333. * Return the number of tasks in the cgroup.
  3334. */
  3335. static int cgroup_task_count(const struct cgroup *cgrp)
  3336. {
  3337. int count = 0;
  3338. struct cgrp_cset_link *link;
  3339. spin_lock_bh(&css_set_lock);
  3340. list_for_each_entry(link, &cgrp->cset_links, cset_link)
  3341. count += atomic_read(&link->cset->refcount);
  3342. spin_unlock_bh(&css_set_lock);
  3343. return count;
  3344. }
  3345. /**
  3346. * css_next_child - find the next child of a given css
  3347. * @pos: the current position (%NULL to initiate traversal)
  3348. * @parent: css whose children to walk
  3349. *
  3350. * This function returns the next child of @parent and should be called
  3351. * under either cgroup_mutex or RCU read lock. The only requirement is
  3352. * that @parent and @pos are accessible. The next sibling is guaranteed to
  3353. * be returned regardless of their states.
  3354. *
  3355. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3356. * css which finished ->css_online() is guaranteed to be visible in the
  3357. * future iterations and will stay visible until the last reference is put.
  3358. * A css which hasn't finished ->css_online() or already finished
  3359. * ->css_offline() may show up during traversal. It's each subsystem's
  3360. * responsibility to synchronize against on/offlining.
  3361. */
  3362. struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
  3363. struct cgroup_subsys_state *parent)
  3364. {
  3365. struct cgroup_subsys_state *next;
  3366. cgroup_assert_mutex_or_rcu_locked();
  3367. /*
  3368. * @pos could already have been unlinked from the sibling list.
  3369. * Once a cgroup is removed, its ->sibling.next is no longer
  3370. * updated when its next sibling changes. CSS_RELEASED is set when
  3371. * @pos is taken off list, at which time its next pointer is valid,
  3372. * and, as releases are serialized, the one pointed to by the next
  3373. * pointer is guaranteed to not have started release yet. This
  3374. * implies that if we observe !CSS_RELEASED on @pos in this RCU
  3375. * critical section, the one pointed to by its next pointer is
  3376. * guaranteed to not have finished its RCU grace period even if we
  3377. * have dropped rcu_read_lock() inbetween iterations.
  3378. *
  3379. * If @pos has CSS_RELEASED set, its next pointer can't be
  3380. * dereferenced; however, as each css is given a monotonically
  3381. * increasing unique serial number and always appended to the
  3382. * sibling list, the next one can be found by walking the parent's
  3383. * children until the first css with higher serial number than
  3384. * @pos's. While this path can be slower, it happens iff iteration
  3385. * races against release and the race window is very small.
  3386. */
  3387. if (!pos) {
  3388. next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
  3389. } else if (likely(!(pos->flags & CSS_RELEASED))) {
  3390. next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
  3391. } else {
  3392. list_for_each_entry_rcu(next, &parent->children, sibling)
  3393. if (next->serial_nr > pos->serial_nr)
  3394. break;
  3395. }
  3396. /*
  3397. * @next, if not pointing to the head, can be dereferenced and is
  3398. * the next sibling.
  3399. */
  3400. if (&next->sibling != &parent->children)
  3401. return next;
  3402. return NULL;
  3403. }
  3404. /**
  3405. * css_next_descendant_pre - find the next descendant for pre-order walk
  3406. * @pos: the current position (%NULL to initiate traversal)
  3407. * @root: css whose descendants to walk
  3408. *
  3409. * To be used by css_for_each_descendant_pre(). Find the next descendant
  3410. * to visit for pre-order traversal of @root's descendants. @root is
  3411. * included in the iteration and the first node to be visited.
  3412. *
  3413. * While this function requires cgroup_mutex or RCU read locking, it
  3414. * doesn't require the whole traversal to be contained in a single critical
  3415. * section. This function will return the correct next descendant as long
  3416. * as both @pos and @root are accessible and @pos is a descendant of @root.
  3417. *
  3418. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3419. * css which finished ->css_online() is guaranteed to be visible in the
  3420. * future iterations and will stay visible until the last reference is put.
  3421. * A css which hasn't finished ->css_online() or already finished
  3422. * ->css_offline() may show up during traversal. It's each subsystem's
  3423. * responsibility to synchronize against on/offlining.
  3424. */
  3425. struct cgroup_subsys_state *
  3426. css_next_descendant_pre(struct cgroup_subsys_state *pos,
  3427. struct cgroup_subsys_state *root)
  3428. {
  3429. struct cgroup_subsys_state *next;
  3430. cgroup_assert_mutex_or_rcu_locked();
  3431. /* if first iteration, visit @root */
  3432. if (!pos)
  3433. return root;
  3434. /* visit the first child if exists */
  3435. next = css_next_child(NULL, pos);
  3436. if (next)
  3437. return next;
  3438. /* no child, visit my or the closest ancestor's next sibling */
  3439. while (pos != root) {
  3440. next = css_next_child(pos, pos->parent);
  3441. if (next)
  3442. return next;
  3443. pos = pos->parent;
  3444. }
  3445. return NULL;
  3446. }
  3447. /**
  3448. * css_rightmost_descendant - return the rightmost descendant of a css
  3449. * @pos: css of interest
  3450. *
  3451. * Return the rightmost descendant of @pos. If there's no descendant, @pos
  3452. * is returned. This can be used during pre-order traversal to skip
  3453. * subtree of @pos.
  3454. *
  3455. * While this function requires cgroup_mutex or RCU read locking, it
  3456. * doesn't require the whole traversal to be contained in a single critical
  3457. * section. This function will return the correct rightmost descendant as
  3458. * long as @pos is accessible.
  3459. */
  3460. struct cgroup_subsys_state *
  3461. css_rightmost_descendant(struct cgroup_subsys_state *pos)
  3462. {
  3463. struct cgroup_subsys_state *last, *tmp;
  3464. cgroup_assert_mutex_or_rcu_locked();
  3465. do {
  3466. last = pos;
  3467. /* ->prev isn't RCU safe, walk ->next till the end */
  3468. pos = NULL;
  3469. css_for_each_child(tmp, last)
  3470. pos = tmp;
  3471. } while (pos);
  3472. return last;
  3473. }
  3474. static struct cgroup_subsys_state *
  3475. css_leftmost_descendant(struct cgroup_subsys_state *pos)
  3476. {
  3477. struct cgroup_subsys_state *last;
  3478. do {
  3479. last = pos;
  3480. pos = css_next_child(NULL, pos);
  3481. } while (pos);
  3482. return last;
  3483. }
  3484. /**
  3485. * css_next_descendant_post - find the next descendant for post-order walk
  3486. * @pos: the current position (%NULL to initiate traversal)
  3487. * @root: css whose descendants to walk
  3488. *
  3489. * To be used by css_for_each_descendant_post(). Find the next descendant
  3490. * to visit for post-order traversal of @root's descendants. @root is
  3491. * included in the iteration and the last node to be visited.
  3492. *
  3493. * While this function requires cgroup_mutex or RCU read locking, it
  3494. * doesn't require the whole traversal to be contained in a single critical
  3495. * section. This function will return the correct next descendant as long
  3496. * as both @pos and @cgroup are accessible and @pos is a descendant of
  3497. * @cgroup.
  3498. *
  3499. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3500. * css which finished ->css_online() is guaranteed to be visible in the
  3501. * future iterations and will stay visible until the last reference is put.
  3502. * A css which hasn't finished ->css_online() or already finished
  3503. * ->css_offline() may show up during traversal. It's each subsystem's
  3504. * responsibility to synchronize against on/offlining.
  3505. */
  3506. struct cgroup_subsys_state *
  3507. css_next_descendant_post(struct cgroup_subsys_state *pos,
  3508. struct cgroup_subsys_state *root)
  3509. {
  3510. struct cgroup_subsys_state *next;
  3511. cgroup_assert_mutex_or_rcu_locked();
  3512. /* if first iteration, visit leftmost descendant which may be @root */
  3513. if (!pos)
  3514. return css_leftmost_descendant(root);
  3515. /* if we visited @root, we're done */
  3516. if (pos == root)
  3517. return NULL;
  3518. /* if there's an unvisited sibling, visit its leftmost descendant */
  3519. next = css_next_child(pos, pos->parent);
  3520. if (next)
  3521. return css_leftmost_descendant(next);
  3522. /* no sibling left, visit parent */
  3523. return pos->parent;
  3524. }
  3525. /**
  3526. * css_has_online_children - does a css have online children
  3527. * @css: the target css
  3528. *
  3529. * Returns %true if @css has any online children; otherwise, %false. This
  3530. * function can be called from any context but the caller is responsible
  3531. * for synchronizing against on/offlining as necessary.
  3532. */
  3533. bool css_has_online_children(struct cgroup_subsys_state *css)
  3534. {
  3535. struct cgroup_subsys_state *child;
  3536. bool ret = false;
  3537. rcu_read_lock();
  3538. css_for_each_child(child, css) {
  3539. if (child->flags & CSS_ONLINE) {
  3540. ret = true;
  3541. break;
  3542. }
  3543. }
  3544. rcu_read_unlock();
  3545. return ret;
  3546. }
  3547. /**
  3548. * css_task_iter_advance_css_set - advance a task itererator to the next css_set
  3549. * @it: the iterator to advance
  3550. *
  3551. * Advance @it to the next css_set to walk.
  3552. */
  3553. static void css_task_iter_advance_css_set(struct css_task_iter *it)
  3554. {
  3555. struct list_head *l = it->cset_pos;
  3556. struct cgrp_cset_link *link;
  3557. struct css_set *cset;
  3558. lockdep_assert_held(&css_set_lock);
  3559. /* Advance to the next non-empty css_set */
  3560. do {
  3561. l = l->next;
  3562. if (l == it->cset_head) {
  3563. it->cset_pos = NULL;
  3564. it->task_pos = NULL;
  3565. return;
  3566. }
  3567. if (it->ss) {
  3568. cset = container_of(l, struct css_set,
  3569. e_cset_node[it->ss->id]);
  3570. } else {
  3571. link = list_entry(l, struct cgrp_cset_link, cset_link);
  3572. cset = link->cset;
  3573. }
  3574. } while (!css_set_populated(cset));
  3575. it->cset_pos = l;
  3576. if (!list_empty(&cset->tasks))
  3577. it->task_pos = cset->tasks.next;
  3578. else
  3579. it->task_pos = cset->mg_tasks.next;
  3580. it->tasks_head = &cset->tasks;
  3581. it->mg_tasks_head = &cset->mg_tasks;
  3582. /*
  3583. * We don't keep css_sets locked across iteration steps and thus
  3584. * need to take steps to ensure that iteration can be resumed after
  3585. * the lock is re-acquired. Iteration is performed at two levels -
  3586. * css_sets and tasks in them.
  3587. *
  3588. * Once created, a css_set never leaves its cgroup lists, so a
  3589. * pinned css_set is guaranteed to stay put and we can resume
  3590. * iteration afterwards.
  3591. *
  3592. * Tasks may leave @cset across iteration steps. This is resolved
  3593. * by registering each iterator with the css_set currently being
  3594. * walked and making css_set_move_task() advance iterators whose
  3595. * next task is leaving.
  3596. */
  3597. if (it->cur_cset) {
  3598. list_del(&it->iters_node);
  3599. put_css_set_locked(it->cur_cset);
  3600. }
  3601. get_css_set(cset);
  3602. it->cur_cset = cset;
  3603. list_add(&it->iters_node, &cset->task_iters);
  3604. }
  3605. static void css_task_iter_advance(struct css_task_iter *it)
  3606. {
  3607. struct list_head *l = it->task_pos;
  3608. lockdep_assert_held(&css_set_lock);
  3609. WARN_ON_ONCE(!l);
  3610. /*
  3611. * Advance iterator to find next entry. cset->tasks is consumed
  3612. * first and then ->mg_tasks. After ->mg_tasks, we move onto the
  3613. * next cset.
  3614. */
  3615. l = l->next;
  3616. if (l == it->tasks_head)
  3617. l = it->mg_tasks_head->next;
  3618. if (l == it->mg_tasks_head)
  3619. css_task_iter_advance_css_set(it);
  3620. else
  3621. it->task_pos = l;
  3622. }
  3623. /**
  3624. * css_task_iter_start - initiate task iteration
  3625. * @css: the css to walk tasks of
  3626. * @it: the task iterator to use
  3627. *
  3628. * Initiate iteration through the tasks of @css. The caller can call
  3629. * css_task_iter_next() to walk through the tasks until the function
  3630. * returns NULL. On completion of iteration, css_task_iter_end() must be
  3631. * called.
  3632. */
  3633. void css_task_iter_start(struct cgroup_subsys_state *css,
  3634. struct css_task_iter *it)
  3635. {
  3636. /* no one should try to iterate before mounting cgroups */
  3637. WARN_ON_ONCE(!use_task_css_set_links);
  3638. memset(it, 0, sizeof(*it));
  3639. spin_lock_bh(&css_set_lock);
  3640. it->ss = css->ss;
  3641. if (it->ss)
  3642. it->cset_pos = &css->cgroup->e_csets[css->ss->id];
  3643. else
  3644. it->cset_pos = &css->cgroup->cset_links;
  3645. it->cset_head = it->cset_pos;
  3646. css_task_iter_advance_css_set(it);
  3647. spin_unlock_bh(&css_set_lock);
  3648. }
  3649. /**
  3650. * css_task_iter_next - return the next task for the iterator
  3651. * @it: the task iterator being iterated
  3652. *
  3653. * The "next" function for task iteration. @it should have been
  3654. * initialized via css_task_iter_start(). Returns NULL when the iteration
  3655. * reaches the end.
  3656. */
  3657. struct task_struct *css_task_iter_next(struct css_task_iter *it)
  3658. {
  3659. if (it->cur_task) {
  3660. put_task_struct(it->cur_task);
  3661. it->cur_task = NULL;
  3662. }
  3663. spin_lock_bh(&css_set_lock);
  3664. if (it->task_pos) {
  3665. it->cur_task = list_entry(it->task_pos, struct task_struct,
  3666. cg_list);
  3667. get_task_struct(it->cur_task);
  3668. css_task_iter_advance(it);
  3669. }
  3670. spin_unlock_bh(&css_set_lock);
  3671. return it->cur_task;
  3672. }
  3673. /**
  3674. * css_task_iter_end - finish task iteration
  3675. * @it: the task iterator to finish
  3676. *
  3677. * Finish task iteration started by css_task_iter_start().
  3678. */
  3679. void css_task_iter_end(struct css_task_iter *it)
  3680. {
  3681. if (it->cur_cset) {
  3682. spin_lock_bh(&css_set_lock);
  3683. list_del(&it->iters_node);
  3684. put_css_set_locked(it->cur_cset);
  3685. spin_unlock_bh(&css_set_lock);
  3686. }
  3687. if (it->cur_task)
  3688. put_task_struct(it->cur_task);
  3689. }
  3690. /**
  3691. * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
  3692. * @to: cgroup to which the tasks will be moved
  3693. * @from: cgroup in which the tasks currently reside
  3694. *
  3695. * Locking rules between cgroup_post_fork() and the migration path
  3696. * guarantee that, if a task is forking while being migrated, the new child
  3697. * is guaranteed to be either visible in the source cgroup after the
  3698. * parent's migration is complete or put into the target cgroup. No task
  3699. * can slip out of migration through forking.
  3700. */
  3701. int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
  3702. {
  3703. LIST_HEAD(preloaded_csets);
  3704. struct cgrp_cset_link *link;
  3705. struct css_task_iter it;
  3706. struct task_struct *task;
  3707. int ret;
  3708. if (!cgroup_may_migrate_to(to))
  3709. return -EBUSY;
  3710. mutex_lock(&cgroup_mutex);
  3711. /* all tasks in @from are being moved, all csets are source */
  3712. spin_lock_bh(&css_set_lock);
  3713. list_for_each_entry(link, &from->cset_links, cset_link)
  3714. cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
  3715. spin_unlock_bh(&css_set_lock);
  3716. ret = cgroup_migrate_prepare_dst(&preloaded_csets);
  3717. if (ret)
  3718. goto out_err;
  3719. /*
  3720. * Migrate tasks one-by-one until @from is empty. This fails iff
  3721. * ->can_attach() fails.
  3722. */
  3723. do {
  3724. css_task_iter_start(&from->self, &it);
  3725. task = css_task_iter_next(&it);
  3726. if (task)
  3727. get_task_struct(task);
  3728. css_task_iter_end(&it);
  3729. if (task) {
  3730. ret = cgroup_migrate(task, false, to->root);
  3731. put_task_struct(task);
  3732. }
  3733. } while (task && !ret);
  3734. out_err:
  3735. cgroup_migrate_finish(&preloaded_csets);
  3736. mutex_unlock(&cgroup_mutex);
  3737. return ret;
  3738. }
  3739. /*
  3740. * Stuff for reading the 'tasks'/'procs' files.
  3741. *
  3742. * Reading this file can return large amounts of data if a cgroup has
  3743. * *lots* of attached tasks. So it may need several calls to read(),
  3744. * but we cannot guarantee that the information we produce is correct
  3745. * unless we produce it entirely atomically.
  3746. *
  3747. */
  3748. /* which pidlist file are we talking about? */
  3749. enum cgroup_filetype {
  3750. CGROUP_FILE_PROCS,
  3751. CGROUP_FILE_TASKS,
  3752. };
  3753. /*
  3754. * A pidlist is a list of pids that virtually represents the contents of one
  3755. * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
  3756. * a pair (one each for procs, tasks) for each pid namespace that's relevant
  3757. * to the cgroup.
  3758. */
  3759. struct cgroup_pidlist {
  3760. /*
  3761. * used to find which pidlist is wanted. doesn't change as long as
  3762. * this particular list stays in the list.
  3763. */
  3764. struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
  3765. /* array of xids */
  3766. pid_t *list;
  3767. /* how many elements the above list has */
  3768. int length;
  3769. /* each of these stored in a list by its cgroup */
  3770. struct list_head links;
  3771. /* pointer to the cgroup we belong to, for list removal purposes */
  3772. struct cgroup *owner;
  3773. /* for delayed destruction */
  3774. struct delayed_work destroy_dwork;
  3775. };
  3776. /*
  3777. * The following two functions "fix" the issue where there are more pids
  3778. * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
  3779. * TODO: replace with a kernel-wide solution to this problem
  3780. */
  3781. #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
  3782. static void *pidlist_allocate(int count)
  3783. {
  3784. if (PIDLIST_TOO_LARGE(count))
  3785. return vmalloc(count * sizeof(pid_t));
  3786. else
  3787. return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
  3788. }
  3789. static void pidlist_free(void *p)
  3790. {
  3791. kvfree(p);
  3792. }
  3793. /*
  3794. * Used to destroy all pidlists lingering waiting for destroy timer. None
  3795. * should be left afterwards.
  3796. */
  3797. static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
  3798. {
  3799. struct cgroup_pidlist *l, *tmp_l;
  3800. mutex_lock(&cgrp->pidlist_mutex);
  3801. list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
  3802. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
  3803. mutex_unlock(&cgrp->pidlist_mutex);
  3804. flush_workqueue(cgroup_pidlist_destroy_wq);
  3805. BUG_ON(!list_empty(&cgrp->pidlists));
  3806. }
  3807. static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
  3808. {
  3809. struct delayed_work *dwork = to_delayed_work(work);
  3810. struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
  3811. destroy_dwork);
  3812. struct cgroup_pidlist *tofree = NULL;
  3813. mutex_lock(&l->owner->pidlist_mutex);
  3814. /*
  3815. * Destroy iff we didn't get queued again. The state won't change
  3816. * as destroy_dwork can only be queued while locked.
  3817. */
  3818. if (!delayed_work_pending(dwork)) {
  3819. list_del(&l->links);
  3820. pidlist_free(l->list);
  3821. put_pid_ns(l->key.ns);
  3822. tofree = l;
  3823. }
  3824. mutex_unlock(&l->owner->pidlist_mutex);
  3825. kfree(tofree);
  3826. }
  3827. /*
  3828. * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
  3829. * Returns the number of unique elements.
  3830. */
  3831. static int pidlist_uniq(pid_t *list, int length)
  3832. {
  3833. int src, dest = 1;
  3834. /*
  3835. * we presume the 0th element is unique, so i starts at 1. trivial
  3836. * edge cases first; no work needs to be done for either
  3837. */
  3838. if (length == 0 || length == 1)
  3839. return length;
  3840. /* src and dest walk down the list; dest counts unique elements */
  3841. for (src = 1; src < length; src++) {
  3842. /* find next unique element */
  3843. while (list[src] == list[src-1]) {
  3844. src++;
  3845. if (src == length)
  3846. goto after;
  3847. }
  3848. /* dest always points to where the next unique element goes */
  3849. list[dest] = list[src];
  3850. dest++;
  3851. }
  3852. after:
  3853. return dest;
  3854. }
  3855. /*
  3856. * The two pid files - task and cgroup.procs - guaranteed that the result
  3857. * is sorted, which forced this whole pidlist fiasco. As pid order is
  3858. * different per namespace, each namespace needs differently sorted list,
  3859. * making it impossible to use, for example, single rbtree of member tasks
  3860. * sorted by task pointer. As pidlists can be fairly large, allocating one
  3861. * per open file is dangerous, so cgroup had to implement shared pool of
  3862. * pidlists keyed by cgroup and namespace.
  3863. *
  3864. * All this extra complexity was caused by the original implementation
  3865. * committing to an entirely unnecessary property. In the long term, we
  3866. * want to do away with it. Explicitly scramble sort order if on the
  3867. * default hierarchy so that no such expectation exists in the new
  3868. * interface.
  3869. *
  3870. * Scrambling is done by swapping every two consecutive bits, which is
  3871. * non-identity one-to-one mapping which disturbs sort order sufficiently.
  3872. */
  3873. static pid_t pid_fry(pid_t pid)
  3874. {
  3875. unsigned a = pid & 0x55555555;
  3876. unsigned b = pid & 0xAAAAAAAA;
  3877. return (a << 1) | (b >> 1);
  3878. }
  3879. static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
  3880. {
  3881. if (cgroup_on_dfl(cgrp))
  3882. return pid_fry(pid);
  3883. else
  3884. return pid;
  3885. }
  3886. static int cmppid(const void *a, const void *b)
  3887. {
  3888. return *(pid_t *)a - *(pid_t *)b;
  3889. }
  3890. static int fried_cmppid(const void *a, const void *b)
  3891. {
  3892. return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
  3893. }
  3894. static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
  3895. enum cgroup_filetype type)
  3896. {
  3897. struct cgroup_pidlist *l;
  3898. /* don't need task_nsproxy() if we're looking at ourself */
  3899. struct pid_namespace *ns = task_active_pid_ns(current);
  3900. lockdep_assert_held(&cgrp->pidlist_mutex);
  3901. list_for_each_entry(l, &cgrp->pidlists, links)
  3902. if (l->key.type == type && l->key.ns == ns)
  3903. return l;
  3904. return NULL;
  3905. }
  3906. /*
  3907. * find the appropriate pidlist for our purpose (given procs vs tasks)
  3908. * returns with the lock on that pidlist already held, and takes care
  3909. * of the use count, or returns NULL with no locks held if we're out of
  3910. * memory.
  3911. */
  3912. static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
  3913. enum cgroup_filetype type)
  3914. {
  3915. struct cgroup_pidlist *l;
  3916. lockdep_assert_held(&cgrp->pidlist_mutex);
  3917. l = cgroup_pidlist_find(cgrp, type);
  3918. if (l)
  3919. return l;
  3920. /* entry not found; create a new one */
  3921. l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
  3922. if (!l)
  3923. return l;
  3924. INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
  3925. l->key.type = type;
  3926. /* don't need task_nsproxy() if we're looking at ourself */
  3927. l->key.ns = get_pid_ns(task_active_pid_ns(current));
  3928. l->owner = cgrp;
  3929. list_add(&l->links, &cgrp->pidlists);
  3930. return l;
  3931. }
  3932. /*
  3933. * Load a cgroup's pidarray with either procs' tgids or tasks' pids
  3934. */
  3935. static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
  3936. struct cgroup_pidlist **lp)
  3937. {
  3938. pid_t *array;
  3939. int length;
  3940. int pid, n = 0; /* used for populating the array */
  3941. struct css_task_iter it;
  3942. struct task_struct *tsk;
  3943. struct cgroup_pidlist *l;
  3944. lockdep_assert_held(&cgrp->pidlist_mutex);
  3945. /*
  3946. * If cgroup gets more users after we read count, we won't have
  3947. * enough space - tough. This race is indistinguishable to the
  3948. * caller from the case that the additional cgroup users didn't
  3949. * show up until sometime later on.
  3950. */
  3951. length = cgroup_task_count(cgrp);
  3952. array = pidlist_allocate(length);
  3953. if (!array)
  3954. return -ENOMEM;
  3955. /* now, populate the array */
  3956. css_task_iter_start(&cgrp->self, &it);
  3957. while ((tsk = css_task_iter_next(&it))) {
  3958. if (unlikely(n == length))
  3959. break;
  3960. /* get tgid or pid for procs or tasks file respectively */
  3961. if (type == CGROUP_FILE_PROCS)
  3962. pid = task_tgid_vnr(tsk);
  3963. else
  3964. pid = task_pid_vnr(tsk);
  3965. if (pid > 0) /* make sure to only use valid results */
  3966. array[n++] = pid;
  3967. }
  3968. css_task_iter_end(&it);
  3969. length = n;
  3970. /* now sort & (if procs) strip out duplicates */
  3971. if (cgroup_on_dfl(cgrp))
  3972. sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
  3973. else
  3974. sort(array, length, sizeof(pid_t), cmppid, NULL);
  3975. if (type == CGROUP_FILE_PROCS)
  3976. length = pidlist_uniq(array, length);
  3977. l = cgroup_pidlist_find_create(cgrp, type);
  3978. if (!l) {
  3979. pidlist_free(array);
  3980. return -ENOMEM;
  3981. }
  3982. /* store array, freeing old if necessary */
  3983. pidlist_free(l->list);
  3984. l->list = array;
  3985. l->length = length;
  3986. *lp = l;
  3987. return 0;
  3988. }
  3989. /**
  3990. * cgroupstats_build - build and fill cgroupstats
  3991. * @stats: cgroupstats to fill information into
  3992. * @dentry: A dentry entry belonging to the cgroup for which stats have
  3993. * been requested.
  3994. *
  3995. * Build and fill cgroupstats so that taskstats can export it to user
  3996. * space.
  3997. */
  3998. int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
  3999. {
  4000. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  4001. struct cgroup *cgrp;
  4002. struct css_task_iter it;
  4003. struct task_struct *tsk;
  4004. /* it should be kernfs_node belonging to cgroupfs and is a directory */
  4005. if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
  4006. kernfs_type(kn) != KERNFS_DIR)
  4007. return -EINVAL;
  4008. mutex_lock(&cgroup_mutex);
  4009. /*
  4010. * We aren't being called from kernfs and there's no guarantee on
  4011. * @kn->priv's validity. For this and css_tryget_online_from_dir(),
  4012. * @kn->priv is RCU safe. Let's do the RCU dancing.
  4013. */
  4014. rcu_read_lock();
  4015. cgrp = rcu_dereference(kn->priv);
  4016. if (!cgrp || cgroup_is_dead(cgrp)) {
  4017. rcu_read_unlock();
  4018. mutex_unlock(&cgroup_mutex);
  4019. return -ENOENT;
  4020. }
  4021. rcu_read_unlock();
  4022. css_task_iter_start(&cgrp->self, &it);
  4023. while ((tsk = css_task_iter_next(&it))) {
  4024. switch (tsk->state) {
  4025. case TASK_RUNNING:
  4026. stats->nr_running++;
  4027. break;
  4028. case TASK_INTERRUPTIBLE:
  4029. stats->nr_sleeping++;
  4030. break;
  4031. case TASK_UNINTERRUPTIBLE:
  4032. stats->nr_uninterruptible++;
  4033. break;
  4034. case TASK_STOPPED:
  4035. stats->nr_stopped++;
  4036. break;
  4037. default:
  4038. if (delayacct_is_task_waiting_on_io(tsk))
  4039. stats->nr_io_wait++;
  4040. break;
  4041. }
  4042. }
  4043. css_task_iter_end(&it);
  4044. mutex_unlock(&cgroup_mutex);
  4045. return 0;
  4046. }
  4047. /*
  4048. * seq_file methods for the tasks/procs files. The seq_file position is the
  4049. * next pid to display; the seq_file iterator is a pointer to the pid
  4050. * in the cgroup->l->list array.
  4051. */
  4052. static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
  4053. {
  4054. /*
  4055. * Initially we receive a position value that corresponds to
  4056. * one more than the last pid shown (or 0 on the first call or
  4057. * after a seek to the start). Use a binary-search to find the
  4058. * next pid to display, if any
  4059. */
  4060. struct kernfs_open_file *of = s->private;
  4061. struct cgroup *cgrp = seq_css(s)->cgroup;
  4062. struct cgroup_pidlist *l;
  4063. enum cgroup_filetype type = seq_cft(s)->private;
  4064. int index = 0, pid = *pos;
  4065. int *iter, ret;
  4066. mutex_lock(&cgrp->pidlist_mutex);
  4067. /*
  4068. * !NULL @of->priv indicates that this isn't the first start()
  4069. * after open. If the matching pidlist is around, we can use that.
  4070. * Look for it. Note that @of->priv can't be used directly. It
  4071. * could already have been destroyed.
  4072. */
  4073. if (of->priv)
  4074. of->priv = cgroup_pidlist_find(cgrp, type);
  4075. /*
  4076. * Either this is the first start() after open or the matching
  4077. * pidlist has been destroyed inbetween. Create a new one.
  4078. */
  4079. if (!of->priv) {
  4080. ret = pidlist_array_load(cgrp, type,
  4081. (struct cgroup_pidlist **)&of->priv);
  4082. if (ret)
  4083. return ERR_PTR(ret);
  4084. }
  4085. l = of->priv;
  4086. if (pid) {
  4087. int end = l->length;
  4088. while (index < end) {
  4089. int mid = (index + end) / 2;
  4090. if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
  4091. index = mid;
  4092. break;
  4093. } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
  4094. index = mid + 1;
  4095. else
  4096. end = mid;
  4097. }
  4098. }
  4099. /* If we're off the end of the array, we're done */
  4100. if (index >= l->length)
  4101. return NULL;
  4102. /* Update the abstract position to be the actual pid that we found */
  4103. iter = l->list + index;
  4104. *pos = cgroup_pid_fry(cgrp, *iter);
  4105. return iter;
  4106. }
  4107. static void cgroup_pidlist_stop(struct seq_file *s, void *v)
  4108. {
  4109. struct kernfs_open_file *of = s->private;
  4110. struct cgroup_pidlist *l = of->priv;
  4111. if (l)
  4112. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
  4113. CGROUP_PIDLIST_DESTROY_DELAY);
  4114. mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
  4115. }
  4116. static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
  4117. {
  4118. struct kernfs_open_file *of = s->private;
  4119. struct cgroup_pidlist *l = of->priv;
  4120. pid_t *p = v;
  4121. pid_t *end = l->list + l->length;
  4122. /*
  4123. * Advance to the next pid in the array. If this goes off the
  4124. * end, we're done
  4125. */
  4126. p++;
  4127. if (p >= end) {
  4128. return NULL;
  4129. } else {
  4130. *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
  4131. return p;
  4132. }
  4133. }
  4134. static int cgroup_pidlist_show(struct seq_file *s, void *v)
  4135. {
  4136. seq_printf(s, "%d\n", *(int *)v);
  4137. return 0;
  4138. }
  4139. static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
  4140. struct cftype *cft)
  4141. {
  4142. return notify_on_release(css->cgroup);
  4143. }
  4144. static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
  4145. struct cftype *cft, u64 val)
  4146. {
  4147. if (val)
  4148. set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  4149. else
  4150. clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  4151. return 0;
  4152. }
  4153. static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
  4154. struct cftype *cft)
  4155. {
  4156. return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4157. }
  4158. static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
  4159. struct cftype *cft, u64 val)
  4160. {
  4161. if (val)
  4162. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4163. else
  4164. clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4165. return 0;
  4166. }
  4167. /* cgroup core interface files for the default hierarchy */
  4168. static struct cftype cgroup_dfl_base_files[] = {
  4169. {
  4170. .name = "cgroup.procs",
  4171. .file_offset = offsetof(struct cgroup, procs_file),
  4172. .seq_start = cgroup_pidlist_start,
  4173. .seq_next = cgroup_pidlist_next,
  4174. .seq_stop = cgroup_pidlist_stop,
  4175. .seq_show = cgroup_pidlist_show,
  4176. .private = CGROUP_FILE_PROCS,
  4177. .write = cgroup_procs_write,
  4178. },
  4179. {
  4180. .name = "cgroup.controllers",
  4181. .seq_show = cgroup_controllers_show,
  4182. },
  4183. {
  4184. .name = "cgroup.subtree_control",
  4185. .seq_show = cgroup_subtree_control_show,
  4186. .write = cgroup_subtree_control_write,
  4187. },
  4188. {
  4189. .name = "cgroup.events",
  4190. .flags = CFTYPE_NOT_ON_ROOT,
  4191. .file_offset = offsetof(struct cgroup, events_file),
  4192. .seq_show = cgroup_events_show,
  4193. },
  4194. { } /* terminate */
  4195. };
  4196. /* cgroup core interface files for the legacy hierarchies */
  4197. static struct cftype cgroup_legacy_base_files[] = {
  4198. {
  4199. .name = "cgroup.procs",
  4200. .seq_start = cgroup_pidlist_start,
  4201. .seq_next = cgroup_pidlist_next,
  4202. .seq_stop = cgroup_pidlist_stop,
  4203. .seq_show = cgroup_pidlist_show,
  4204. .private = CGROUP_FILE_PROCS,
  4205. .write = cgroup_procs_write,
  4206. },
  4207. {
  4208. .name = "cgroup.clone_children",
  4209. .read_u64 = cgroup_clone_children_read,
  4210. .write_u64 = cgroup_clone_children_write,
  4211. },
  4212. {
  4213. .name = "cgroup.sane_behavior",
  4214. .flags = CFTYPE_ONLY_ON_ROOT,
  4215. .seq_show = cgroup_sane_behavior_show,
  4216. },
  4217. {
  4218. .name = "tasks",
  4219. .seq_start = cgroup_pidlist_start,
  4220. .seq_next = cgroup_pidlist_next,
  4221. .seq_stop = cgroup_pidlist_stop,
  4222. .seq_show = cgroup_pidlist_show,
  4223. .private = CGROUP_FILE_TASKS,
  4224. .write = cgroup_tasks_write,
  4225. },
  4226. {
  4227. .name = "notify_on_release",
  4228. .read_u64 = cgroup_read_notify_on_release,
  4229. .write_u64 = cgroup_write_notify_on_release,
  4230. },
  4231. {
  4232. .name = "release_agent",
  4233. .flags = CFTYPE_ONLY_ON_ROOT,
  4234. .seq_show = cgroup_release_agent_show,
  4235. .write = cgroup_release_agent_write,
  4236. .max_write_len = PATH_MAX - 1,
  4237. },
  4238. { } /* terminate */
  4239. };
  4240. /*
  4241. * css destruction is four-stage process.
  4242. *
  4243. * 1. Destruction starts. Killing of the percpu_ref is initiated.
  4244. * Implemented in kill_css().
  4245. *
  4246. * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
  4247. * and thus css_tryget_online() is guaranteed to fail, the css can be
  4248. * offlined by invoking offline_css(). After offlining, the base ref is
  4249. * put. Implemented in css_killed_work_fn().
  4250. *
  4251. * 3. When the percpu_ref reaches zero, the only possible remaining
  4252. * accessors are inside RCU read sections. css_release() schedules the
  4253. * RCU callback.
  4254. *
  4255. * 4. After the grace period, the css can be freed. Implemented in
  4256. * css_free_work_fn().
  4257. *
  4258. * It is actually hairier because both step 2 and 4 require process context
  4259. * and thus involve punting to css->destroy_work adding two additional
  4260. * steps to the already complex sequence.
  4261. */
  4262. static void css_free_work_fn(struct work_struct *work)
  4263. {
  4264. struct cgroup_subsys_state *css =
  4265. container_of(work, struct cgroup_subsys_state, destroy_work);
  4266. struct cgroup_subsys *ss = css->ss;
  4267. struct cgroup *cgrp = css->cgroup;
  4268. percpu_ref_exit(&css->refcnt);
  4269. if (ss) {
  4270. /* css free path */
  4271. struct cgroup_subsys_state *parent = css->parent;
  4272. int id = css->id;
  4273. ss->css_free(css);
  4274. cgroup_idr_remove(&ss->css_idr, id);
  4275. cgroup_put(cgrp);
  4276. if (parent)
  4277. css_put(parent);
  4278. } else {
  4279. /* cgroup free path */
  4280. atomic_dec(&cgrp->root->nr_cgrps);
  4281. cgroup_pidlist_destroy_all(cgrp);
  4282. cancel_work_sync(&cgrp->release_agent_work);
  4283. if (cgroup_parent(cgrp)) {
  4284. /*
  4285. * We get a ref to the parent, and put the ref when
  4286. * this cgroup is being freed, so it's guaranteed
  4287. * that the parent won't be destroyed before its
  4288. * children.
  4289. */
  4290. cgroup_put(cgroup_parent(cgrp));
  4291. kernfs_put(cgrp->kn);
  4292. kfree(cgrp);
  4293. } else {
  4294. /*
  4295. * This is root cgroup's refcnt reaching zero,
  4296. * which indicates that the root should be
  4297. * released.
  4298. */
  4299. cgroup_destroy_root(cgrp->root);
  4300. }
  4301. }
  4302. }
  4303. static void css_free_rcu_fn(struct rcu_head *rcu_head)
  4304. {
  4305. struct cgroup_subsys_state *css =
  4306. container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
  4307. INIT_WORK(&css->destroy_work, css_free_work_fn);
  4308. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4309. }
  4310. static void css_release_work_fn(struct work_struct *work)
  4311. {
  4312. struct cgroup_subsys_state *css =
  4313. container_of(work, struct cgroup_subsys_state, destroy_work);
  4314. struct cgroup_subsys *ss = css->ss;
  4315. struct cgroup *cgrp = css->cgroup;
  4316. mutex_lock(&cgroup_mutex);
  4317. css->flags |= CSS_RELEASED;
  4318. list_del_rcu(&css->sibling);
  4319. if (ss) {
  4320. /* css release path */
  4321. cgroup_idr_replace(&ss->css_idr, NULL, css->id);
  4322. if (ss->css_released)
  4323. ss->css_released(css);
  4324. } else {
  4325. /* cgroup release path */
  4326. cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
  4327. cgrp->id = -1;
  4328. /*
  4329. * There are two control paths which try to determine
  4330. * cgroup from dentry without going through kernfs -
  4331. * cgroupstats_build() and css_tryget_online_from_dir().
  4332. * Those are supported by RCU protecting clearing of
  4333. * cgrp->kn->priv backpointer.
  4334. */
  4335. if (cgrp->kn)
  4336. RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
  4337. NULL);
  4338. }
  4339. mutex_unlock(&cgroup_mutex);
  4340. call_rcu(&css->rcu_head, css_free_rcu_fn);
  4341. }
  4342. static void css_release(struct percpu_ref *ref)
  4343. {
  4344. struct cgroup_subsys_state *css =
  4345. container_of(ref, struct cgroup_subsys_state, refcnt);
  4346. INIT_WORK(&css->destroy_work, css_release_work_fn);
  4347. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4348. }
  4349. static void init_and_link_css(struct cgroup_subsys_state *css,
  4350. struct cgroup_subsys *ss, struct cgroup *cgrp)
  4351. {
  4352. lockdep_assert_held(&cgroup_mutex);
  4353. cgroup_get(cgrp);
  4354. memset(css, 0, sizeof(*css));
  4355. css->cgroup = cgrp;
  4356. css->ss = ss;
  4357. INIT_LIST_HEAD(&css->sibling);
  4358. INIT_LIST_HEAD(&css->children);
  4359. css->serial_nr = css_serial_nr_next++;
  4360. atomic_set(&css->online_cnt, 0);
  4361. if (cgroup_parent(cgrp)) {
  4362. css->parent = cgroup_css(cgroup_parent(cgrp), ss);
  4363. css_get(css->parent);
  4364. }
  4365. BUG_ON(cgroup_css(cgrp, ss));
  4366. }
  4367. /* invoke ->css_online() on a new CSS and mark it online if successful */
  4368. static int online_css(struct cgroup_subsys_state *css)
  4369. {
  4370. struct cgroup_subsys *ss = css->ss;
  4371. int ret = 0;
  4372. lockdep_assert_held(&cgroup_mutex);
  4373. if (ss->css_online)
  4374. ret = ss->css_online(css);
  4375. if (!ret) {
  4376. css->flags |= CSS_ONLINE;
  4377. rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
  4378. atomic_inc(&css->online_cnt);
  4379. if (css->parent)
  4380. atomic_inc(&css->parent->online_cnt);
  4381. }
  4382. return ret;
  4383. }
  4384. /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
  4385. static void offline_css(struct cgroup_subsys_state *css)
  4386. {
  4387. struct cgroup_subsys *ss = css->ss;
  4388. lockdep_assert_held(&cgroup_mutex);
  4389. if (!(css->flags & CSS_ONLINE))
  4390. return;
  4391. if (ss->css_reset)
  4392. ss->css_reset(css);
  4393. if (ss->css_offline)
  4394. ss->css_offline(css);
  4395. css->flags &= ~CSS_ONLINE;
  4396. RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
  4397. wake_up_all(&css->cgroup->offline_waitq);
  4398. }
  4399. /**
  4400. * css_create - create a cgroup_subsys_state
  4401. * @cgrp: the cgroup new css will be associated with
  4402. * @ss: the subsys of new css
  4403. *
  4404. * Create a new css associated with @cgrp - @ss pair. On success, the new
  4405. * css is online and installed in @cgrp. This function doesn't create the
  4406. * interface files. Returns 0 on success, -errno on failure.
  4407. */
  4408. static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
  4409. struct cgroup_subsys *ss)
  4410. {
  4411. struct cgroup *parent = cgroup_parent(cgrp);
  4412. struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
  4413. struct cgroup_subsys_state *css;
  4414. int err;
  4415. lockdep_assert_held(&cgroup_mutex);
  4416. css = ss->css_alloc(parent_css);
  4417. if (IS_ERR(css))
  4418. return css;
  4419. init_and_link_css(css, ss, cgrp);
  4420. err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
  4421. if (err)
  4422. goto err_free_css;
  4423. err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
  4424. if (err < 0)
  4425. goto err_free_percpu_ref;
  4426. css->id = err;
  4427. /* @css is ready to be brought online now, make it visible */
  4428. list_add_tail_rcu(&css->sibling, &parent_css->children);
  4429. cgroup_idr_replace(&ss->css_idr, css, css->id);
  4430. err = online_css(css);
  4431. if (err)
  4432. goto err_list_del;
  4433. if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
  4434. cgroup_parent(parent)) {
  4435. pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
  4436. current->comm, current->pid, ss->name);
  4437. if (!strcmp(ss->name, "memory"))
  4438. pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
  4439. ss->warned_broken_hierarchy = true;
  4440. }
  4441. return css;
  4442. err_list_del:
  4443. list_del_rcu(&css->sibling);
  4444. cgroup_idr_remove(&ss->css_idr, css->id);
  4445. err_free_percpu_ref:
  4446. percpu_ref_exit(&css->refcnt);
  4447. err_free_css:
  4448. call_rcu(&css->rcu_head, css_free_rcu_fn);
  4449. return ERR_PTR(err);
  4450. }
  4451. static struct cgroup *cgroup_create(struct cgroup *parent)
  4452. {
  4453. struct cgroup_root *root = parent->root;
  4454. struct cgroup *cgrp, *tcgrp;
  4455. int level = parent->level + 1;
  4456. int ret;
  4457. /* allocate the cgroup and its ID, 0 is reserved for the root */
  4458. cgrp = kzalloc(sizeof(*cgrp) +
  4459. sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
  4460. if (!cgrp)
  4461. return ERR_PTR(-ENOMEM);
  4462. ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
  4463. if (ret)
  4464. goto out_free_cgrp;
  4465. /*
  4466. * Temporarily set the pointer to NULL, so idr_find() won't return
  4467. * a half-baked cgroup.
  4468. */
  4469. cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
  4470. if (cgrp->id < 0) {
  4471. ret = -ENOMEM;
  4472. goto out_cancel_ref;
  4473. }
  4474. init_cgroup_housekeeping(cgrp);
  4475. cgrp->self.parent = &parent->self;
  4476. cgrp->root = root;
  4477. cgrp->level = level;
  4478. for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp))
  4479. cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
  4480. if (notify_on_release(parent))
  4481. set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
  4482. if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
  4483. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
  4484. cgrp->self.serial_nr = css_serial_nr_next++;
  4485. /* allocation complete, commit to creation */
  4486. list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
  4487. atomic_inc(&root->nr_cgrps);
  4488. cgroup_get(parent);
  4489. /*
  4490. * @cgrp is now fully operational. If something fails after this
  4491. * point, it'll be released via the normal destruction path.
  4492. */
  4493. cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
  4494. /*
  4495. * On the default hierarchy, a child doesn't automatically inherit
  4496. * subtree_control from the parent. Each is configured manually.
  4497. */
  4498. if (!cgroup_on_dfl(cgrp))
  4499. cgrp->subtree_control = cgroup_control(cgrp);
  4500. cgroup_propagate_control(cgrp);
  4501. /* @cgrp doesn't have dir yet so the following will only create csses */
  4502. ret = cgroup_apply_control_enable(cgrp);
  4503. if (ret)
  4504. goto out_destroy;
  4505. return cgrp;
  4506. out_cancel_ref:
  4507. percpu_ref_exit(&cgrp->self.refcnt);
  4508. out_free_cgrp:
  4509. kfree(cgrp);
  4510. return ERR_PTR(ret);
  4511. out_destroy:
  4512. cgroup_destroy_locked(cgrp);
  4513. return ERR_PTR(ret);
  4514. }
  4515. static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
  4516. umode_t mode)
  4517. {
  4518. struct cgroup *parent, *cgrp;
  4519. struct kernfs_node *kn;
  4520. int ret;
  4521. /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
  4522. if (strchr(name, '\n'))
  4523. return -EINVAL;
  4524. parent = cgroup_kn_lock_live(parent_kn, false);
  4525. if (!parent)
  4526. return -ENODEV;
  4527. cgrp = cgroup_create(parent);
  4528. if (IS_ERR(cgrp)) {
  4529. ret = PTR_ERR(cgrp);
  4530. goto out_unlock;
  4531. }
  4532. /* create the directory */
  4533. kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
  4534. if (IS_ERR(kn)) {
  4535. ret = PTR_ERR(kn);
  4536. goto out_destroy;
  4537. }
  4538. cgrp->kn = kn;
  4539. /*
  4540. * This extra ref will be put in cgroup_free_fn() and guarantees
  4541. * that @cgrp->kn is always accessible.
  4542. */
  4543. kernfs_get(kn);
  4544. ret = cgroup_kn_set_ugid(kn);
  4545. if (ret)
  4546. goto out_destroy;
  4547. ret = css_populate_dir(&cgrp->self);
  4548. if (ret)
  4549. goto out_destroy;
  4550. ret = cgroup_apply_control_enable(cgrp);
  4551. if (ret)
  4552. goto out_destroy;
  4553. /* let's create and online css's */
  4554. kernfs_activate(kn);
  4555. ret = 0;
  4556. goto out_unlock;
  4557. out_destroy:
  4558. cgroup_destroy_locked(cgrp);
  4559. out_unlock:
  4560. cgroup_kn_unlock(parent_kn);
  4561. return ret;
  4562. }
  4563. /*
  4564. * This is called when the refcnt of a css is confirmed to be killed.
  4565. * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
  4566. * initate destruction and put the css ref from kill_css().
  4567. */
  4568. static void css_killed_work_fn(struct work_struct *work)
  4569. {
  4570. struct cgroup_subsys_state *css =
  4571. container_of(work, struct cgroup_subsys_state, destroy_work);
  4572. mutex_lock(&cgroup_mutex);
  4573. do {
  4574. offline_css(css);
  4575. css_put(css);
  4576. /* @css can't go away while we're holding cgroup_mutex */
  4577. css = css->parent;
  4578. } while (css && atomic_dec_and_test(&css->online_cnt));
  4579. mutex_unlock(&cgroup_mutex);
  4580. }
  4581. /* css kill confirmation processing requires process context, bounce */
  4582. static void css_killed_ref_fn(struct percpu_ref *ref)
  4583. {
  4584. struct cgroup_subsys_state *css =
  4585. container_of(ref, struct cgroup_subsys_state, refcnt);
  4586. if (atomic_dec_and_test(&css->online_cnt)) {
  4587. INIT_WORK(&css->destroy_work, css_killed_work_fn);
  4588. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4589. }
  4590. }
  4591. /**
  4592. * kill_css - destroy a css
  4593. * @css: css to destroy
  4594. *
  4595. * This function initiates destruction of @css by removing cgroup interface
  4596. * files and putting its base reference. ->css_offline() will be invoked
  4597. * asynchronously once css_tryget_online() is guaranteed to fail and when
  4598. * the reference count reaches zero, @css will be released.
  4599. */
  4600. static void kill_css(struct cgroup_subsys_state *css)
  4601. {
  4602. lockdep_assert_held(&cgroup_mutex);
  4603. /*
  4604. * This must happen before css is disassociated with its cgroup.
  4605. * See seq_css() for details.
  4606. */
  4607. css_clear_dir(css);
  4608. /*
  4609. * Killing would put the base ref, but we need to keep it alive
  4610. * until after ->css_offline().
  4611. */
  4612. css_get(css);
  4613. /*
  4614. * cgroup core guarantees that, by the time ->css_offline() is
  4615. * invoked, no new css reference will be given out via
  4616. * css_tryget_online(). We can't simply call percpu_ref_kill() and
  4617. * proceed to offlining css's because percpu_ref_kill() doesn't
  4618. * guarantee that the ref is seen as killed on all CPUs on return.
  4619. *
  4620. * Use percpu_ref_kill_and_confirm() to get notifications as each
  4621. * css is confirmed to be seen as killed on all CPUs.
  4622. */
  4623. percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
  4624. }
  4625. /**
  4626. * cgroup_destroy_locked - the first stage of cgroup destruction
  4627. * @cgrp: cgroup to be destroyed
  4628. *
  4629. * css's make use of percpu refcnts whose killing latency shouldn't be
  4630. * exposed to userland and are RCU protected. Also, cgroup core needs to
  4631. * guarantee that css_tryget_online() won't succeed by the time
  4632. * ->css_offline() is invoked. To satisfy all the requirements,
  4633. * destruction is implemented in the following two steps.
  4634. *
  4635. * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
  4636. * userland visible parts and start killing the percpu refcnts of
  4637. * css's. Set up so that the next stage will be kicked off once all
  4638. * the percpu refcnts are confirmed to be killed.
  4639. *
  4640. * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
  4641. * rest of destruction. Once all cgroup references are gone, the
  4642. * cgroup is RCU-freed.
  4643. *
  4644. * This function implements s1. After this step, @cgrp is gone as far as
  4645. * the userland is concerned and a new cgroup with the same name may be
  4646. * created. As cgroup doesn't care about the names internally, this
  4647. * doesn't cause any problem.
  4648. */
  4649. static int cgroup_destroy_locked(struct cgroup *cgrp)
  4650. __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
  4651. {
  4652. struct cgroup_subsys_state *css;
  4653. struct cgrp_cset_link *link;
  4654. int ssid;
  4655. lockdep_assert_held(&cgroup_mutex);
  4656. /*
  4657. * Only migration can raise populated from zero and we're already
  4658. * holding cgroup_mutex.
  4659. */
  4660. if (cgroup_is_populated(cgrp))
  4661. return -EBUSY;
  4662. /*
  4663. * Make sure there's no live children. We can't test emptiness of
  4664. * ->self.children as dead children linger on it while being
  4665. * drained; otherwise, "rmdir parent/child parent" may fail.
  4666. */
  4667. if (css_has_online_children(&cgrp->self))
  4668. return -EBUSY;
  4669. /*
  4670. * Mark @cgrp and the associated csets dead. The former prevents
  4671. * further task migration and child creation by disabling
  4672. * cgroup_lock_live_group(). The latter makes the csets ignored by
  4673. * the migration path.
  4674. */
  4675. cgrp->self.flags &= ~CSS_ONLINE;
  4676. spin_lock_bh(&css_set_lock);
  4677. list_for_each_entry(link, &cgrp->cset_links, cset_link)
  4678. link->cset->dead = true;
  4679. spin_unlock_bh(&css_set_lock);
  4680. /* initiate massacre of all css's */
  4681. for_each_css(css, ssid, cgrp)
  4682. kill_css(css);
  4683. /*
  4684. * Remove @cgrp directory along with the base files. @cgrp has an
  4685. * extra ref on its kn.
  4686. */
  4687. kernfs_remove(cgrp->kn);
  4688. check_for_release(cgroup_parent(cgrp));
  4689. /* put the base reference */
  4690. percpu_ref_kill(&cgrp->self.refcnt);
  4691. return 0;
  4692. };
  4693. static int cgroup_rmdir(struct kernfs_node *kn)
  4694. {
  4695. struct cgroup *cgrp;
  4696. int ret = 0;
  4697. cgrp = cgroup_kn_lock_live(kn, false);
  4698. if (!cgrp)
  4699. return 0;
  4700. ret = cgroup_destroy_locked(cgrp);
  4701. cgroup_kn_unlock(kn);
  4702. return ret;
  4703. }
  4704. static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
  4705. .remount_fs = cgroup_remount,
  4706. .show_options = cgroup_show_options,
  4707. .mkdir = cgroup_mkdir,
  4708. .rmdir = cgroup_rmdir,
  4709. .rename = cgroup_rename,
  4710. .show_path = cgroup_show_path,
  4711. };
  4712. static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
  4713. {
  4714. struct cgroup_subsys_state *css;
  4715. pr_debug("Initializing cgroup subsys %s\n", ss->name);
  4716. mutex_lock(&cgroup_mutex);
  4717. idr_init(&ss->css_idr);
  4718. INIT_LIST_HEAD(&ss->cfts);
  4719. /* Create the root cgroup state for this subsystem */
  4720. ss->root = &cgrp_dfl_root;
  4721. css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
  4722. /* We don't handle early failures gracefully */
  4723. BUG_ON(IS_ERR(css));
  4724. init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
  4725. /*
  4726. * Root csses are never destroyed and we can't initialize
  4727. * percpu_ref during early init. Disable refcnting.
  4728. */
  4729. css->flags |= CSS_NO_REF;
  4730. if (early) {
  4731. /* allocation can't be done safely during early init */
  4732. css->id = 1;
  4733. } else {
  4734. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
  4735. BUG_ON(css->id < 0);
  4736. }
  4737. /* Update the init_css_set to contain a subsys
  4738. * pointer to this state - since the subsystem is
  4739. * newly registered, all tasks and hence the
  4740. * init_css_set is in the subsystem's root cgroup. */
  4741. init_css_set.subsys[ss->id] = css;
  4742. have_fork_callback |= (bool)ss->fork << ss->id;
  4743. have_exit_callback |= (bool)ss->exit << ss->id;
  4744. have_free_callback |= (bool)ss->free << ss->id;
  4745. have_canfork_callback |= (bool)ss->can_fork << ss->id;
  4746. /* At system boot, before all subsystems have been
  4747. * registered, no tasks have been forked, so we don't
  4748. * need to invoke fork callbacks here. */
  4749. BUG_ON(!list_empty(&init_task.tasks));
  4750. BUG_ON(online_css(css));
  4751. mutex_unlock(&cgroup_mutex);
  4752. }
  4753. /**
  4754. * cgroup_init_early - cgroup initialization at system boot
  4755. *
  4756. * Initialize cgroups at system boot, and initialize any
  4757. * subsystems that request early init.
  4758. */
  4759. int __init cgroup_init_early(void)
  4760. {
  4761. static struct cgroup_sb_opts __initdata opts;
  4762. struct cgroup_subsys *ss;
  4763. int i;
  4764. init_cgroup_root(&cgrp_dfl_root, &opts);
  4765. cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
  4766. RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
  4767. for_each_subsys(ss, i) {
  4768. WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
  4769. "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
  4770. i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
  4771. ss->id, ss->name);
  4772. WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
  4773. "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
  4774. ss->id = i;
  4775. ss->name = cgroup_subsys_name[i];
  4776. if (!ss->legacy_name)
  4777. ss->legacy_name = cgroup_subsys_name[i];
  4778. if (ss->early_init)
  4779. cgroup_init_subsys(ss, true);
  4780. }
  4781. return 0;
  4782. }
  4783. static u16 cgroup_disable_mask __initdata;
  4784. /**
  4785. * cgroup_init - cgroup initialization
  4786. *
  4787. * Register cgroup filesystem and /proc file, and initialize
  4788. * any subsystems that didn't request early init.
  4789. */
  4790. int __init cgroup_init(void)
  4791. {
  4792. struct cgroup_subsys *ss;
  4793. int ssid;
  4794. BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
  4795. BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
  4796. BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
  4797. BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
  4798. get_user_ns(init_cgroup_ns.user_ns);
  4799. mutex_lock(&cgroup_mutex);
  4800. /*
  4801. * Add init_css_set to the hash table so that dfl_root can link to
  4802. * it during init.
  4803. */
  4804. hash_add(css_set_table, &init_css_set.hlist,
  4805. css_set_hash(init_css_set.subsys));
  4806. BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
  4807. mutex_unlock(&cgroup_mutex);
  4808. for_each_subsys(ss, ssid) {
  4809. if (ss->early_init) {
  4810. struct cgroup_subsys_state *css =
  4811. init_css_set.subsys[ss->id];
  4812. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
  4813. GFP_KERNEL);
  4814. BUG_ON(css->id < 0);
  4815. } else {
  4816. cgroup_init_subsys(ss, false);
  4817. }
  4818. list_add_tail(&init_css_set.e_cset_node[ssid],
  4819. &cgrp_dfl_root.cgrp.e_csets[ssid]);
  4820. /*
  4821. * Setting dfl_root subsys_mask needs to consider the
  4822. * disabled flag and cftype registration needs kmalloc,
  4823. * both of which aren't available during early_init.
  4824. */
  4825. if (cgroup_disable_mask & (1 << ssid)) {
  4826. static_branch_disable(cgroup_subsys_enabled_key[ssid]);
  4827. printk(KERN_INFO "Disabling %s control group subsystem\n",
  4828. ss->name);
  4829. continue;
  4830. }
  4831. if (cgroup_ssid_no_v1(ssid))
  4832. printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
  4833. ss->name);
  4834. cgrp_dfl_root.subsys_mask |= 1 << ss->id;
  4835. if (ss->implicit_on_dfl)
  4836. cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
  4837. else if (!ss->dfl_cftypes)
  4838. cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
  4839. if (ss->dfl_cftypes == ss->legacy_cftypes) {
  4840. WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
  4841. } else {
  4842. WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
  4843. WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
  4844. }
  4845. if (ss->bind)
  4846. ss->bind(init_css_set.subsys[ssid]);
  4847. }
  4848. /* init_css_set.subsys[] has been updated, re-hash */
  4849. hash_del(&init_css_set.hlist);
  4850. hash_add(css_set_table, &init_css_set.hlist,
  4851. css_set_hash(init_css_set.subsys));
  4852. WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
  4853. WARN_ON(register_filesystem(&cgroup_fs_type));
  4854. WARN_ON(register_filesystem(&cgroup2_fs_type));
  4855. WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
  4856. return 0;
  4857. }
  4858. static int __init cgroup_wq_init(void)
  4859. {
  4860. /*
  4861. * There isn't much point in executing destruction path in
  4862. * parallel. Good chunk is serialized with cgroup_mutex anyway.
  4863. * Use 1 for @max_active.
  4864. *
  4865. * We would prefer to do this in cgroup_init() above, but that
  4866. * is called before init_workqueues(): so leave this until after.
  4867. */
  4868. cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
  4869. BUG_ON(!cgroup_destroy_wq);
  4870. /*
  4871. * Used to destroy pidlists and separate to serve as flush domain.
  4872. * Cap @max_active to 1 too.
  4873. */
  4874. cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
  4875. 0, 1);
  4876. BUG_ON(!cgroup_pidlist_destroy_wq);
  4877. return 0;
  4878. }
  4879. core_initcall(cgroup_wq_init);
  4880. /*
  4881. * proc_cgroup_show()
  4882. * - Print task's cgroup paths into seq_file, one line for each hierarchy
  4883. * - Used for /proc/<pid>/cgroup.
  4884. */
  4885. int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
  4886. struct pid *pid, struct task_struct *tsk)
  4887. {
  4888. char *buf, *path;
  4889. int retval;
  4890. struct cgroup_root *root;
  4891. retval = -ENOMEM;
  4892. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  4893. if (!buf)
  4894. goto out;
  4895. mutex_lock(&cgroup_mutex);
  4896. spin_lock_bh(&css_set_lock);
  4897. for_each_root(root) {
  4898. struct cgroup_subsys *ss;
  4899. struct cgroup *cgrp;
  4900. int ssid, count = 0;
  4901. if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
  4902. continue;
  4903. seq_printf(m, "%d:", root->hierarchy_id);
  4904. if (root != &cgrp_dfl_root)
  4905. for_each_subsys(ss, ssid)
  4906. if (root->subsys_mask & (1 << ssid))
  4907. seq_printf(m, "%s%s", count++ ? "," : "",
  4908. ss->legacy_name);
  4909. if (strlen(root->name))
  4910. seq_printf(m, "%sname=%s", count ? "," : "",
  4911. root->name);
  4912. seq_putc(m, ':');
  4913. cgrp = task_cgroup_from_root(tsk, root);
  4914. /*
  4915. * On traditional hierarchies, all zombie tasks show up as
  4916. * belonging to the root cgroup. On the default hierarchy,
  4917. * while a zombie doesn't show up in "cgroup.procs" and
  4918. * thus can't be migrated, its /proc/PID/cgroup keeps
  4919. * reporting the cgroup it belonged to before exiting. If
  4920. * the cgroup is removed before the zombie is reaped,
  4921. * " (deleted)" is appended to the cgroup path.
  4922. */
  4923. if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
  4924. path = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
  4925. current->nsproxy->cgroup_ns);
  4926. if (!path) {
  4927. retval = -ENAMETOOLONG;
  4928. goto out_unlock;
  4929. }
  4930. } else {
  4931. path = "/";
  4932. }
  4933. seq_puts(m, path);
  4934. if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
  4935. seq_puts(m, " (deleted)\n");
  4936. else
  4937. seq_putc(m, '\n');
  4938. }
  4939. retval = 0;
  4940. out_unlock:
  4941. spin_unlock_bh(&css_set_lock);
  4942. mutex_unlock(&cgroup_mutex);
  4943. kfree(buf);
  4944. out:
  4945. return retval;
  4946. }
  4947. /* Display information about each subsystem and each hierarchy */
  4948. static int proc_cgroupstats_show(struct seq_file *m, void *v)
  4949. {
  4950. struct cgroup_subsys *ss;
  4951. int i;
  4952. seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
  4953. /*
  4954. * ideally we don't want subsystems moving around while we do this.
  4955. * cgroup_mutex is also necessary to guarantee an atomic snapshot of
  4956. * subsys/hierarchy state.
  4957. */
  4958. mutex_lock(&cgroup_mutex);
  4959. for_each_subsys(ss, i)
  4960. seq_printf(m, "%s\t%d\t%d\t%d\n",
  4961. ss->legacy_name, ss->root->hierarchy_id,
  4962. atomic_read(&ss->root->nr_cgrps),
  4963. cgroup_ssid_enabled(i));
  4964. mutex_unlock(&cgroup_mutex);
  4965. return 0;
  4966. }
  4967. static int cgroupstats_open(struct inode *inode, struct file *file)
  4968. {
  4969. return single_open(file, proc_cgroupstats_show, NULL);
  4970. }
  4971. static const struct file_operations proc_cgroupstats_operations = {
  4972. .open = cgroupstats_open,
  4973. .read = seq_read,
  4974. .llseek = seq_lseek,
  4975. .release = single_release,
  4976. };
  4977. /**
  4978. * cgroup_fork - initialize cgroup related fields during copy_process()
  4979. * @child: pointer to task_struct of forking parent process.
  4980. *
  4981. * A task is associated with the init_css_set until cgroup_post_fork()
  4982. * attaches it to the parent's css_set. Empty cg_list indicates that
  4983. * @child isn't holding reference to its css_set.
  4984. */
  4985. void cgroup_fork(struct task_struct *child)
  4986. {
  4987. RCU_INIT_POINTER(child->cgroups, &init_css_set);
  4988. INIT_LIST_HEAD(&child->cg_list);
  4989. }
  4990. /**
  4991. * cgroup_can_fork - called on a new task before the process is exposed
  4992. * @child: the task in question.
  4993. *
  4994. * This calls the subsystem can_fork() callbacks. If the can_fork() callback
  4995. * returns an error, the fork aborts with that error code. This allows for
  4996. * a cgroup subsystem to conditionally allow or deny new forks.
  4997. */
  4998. int cgroup_can_fork(struct task_struct *child)
  4999. {
  5000. struct cgroup_subsys *ss;
  5001. int i, j, ret;
  5002. do_each_subsys_mask(ss, i, have_canfork_callback) {
  5003. ret = ss->can_fork(child);
  5004. if (ret)
  5005. goto out_revert;
  5006. } while_each_subsys_mask();
  5007. return 0;
  5008. out_revert:
  5009. for_each_subsys(ss, j) {
  5010. if (j >= i)
  5011. break;
  5012. if (ss->cancel_fork)
  5013. ss->cancel_fork(child);
  5014. }
  5015. return ret;
  5016. }
  5017. /**
  5018. * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
  5019. * @child: the task in question
  5020. *
  5021. * This calls the cancel_fork() callbacks if a fork failed *after*
  5022. * cgroup_can_fork() succeded.
  5023. */
  5024. void cgroup_cancel_fork(struct task_struct *child)
  5025. {
  5026. struct cgroup_subsys *ss;
  5027. int i;
  5028. for_each_subsys(ss, i)
  5029. if (ss->cancel_fork)
  5030. ss->cancel_fork(child);
  5031. }
  5032. /**
  5033. * cgroup_post_fork - called on a new task after adding it to the task list
  5034. * @child: the task in question
  5035. *
  5036. * Adds the task to the list running through its css_set if necessary and
  5037. * call the subsystem fork() callbacks. Has to be after the task is
  5038. * visible on the task list in case we race with the first call to
  5039. * cgroup_task_iter_start() - to guarantee that the new task ends up on its
  5040. * list.
  5041. */
  5042. void cgroup_post_fork(struct task_struct *child)
  5043. {
  5044. struct cgroup_subsys *ss;
  5045. int i;
  5046. /*
  5047. * This may race against cgroup_enable_task_cg_lists(). As that
  5048. * function sets use_task_css_set_links before grabbing
  5049. * tasklist_lock and we just went through tasklist_lock to add
  5050. * @child, it's guaranteed that either we see the set
  5051. * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
  5052. * @child during its iteration.
  5053. *
  5054. * If we won the race, @child is associated with %current's
  5055. * css_set. Grabbing css_set_lock guarantees both that the
  5056. * association is stable, and, on completion of the parent's
  5057. * migration, @child is visible in the source of migration or
  5058. * already in the destination cgroup. This guarantee is necessary
  5059. * when implementing operations which need to migrate all tasks of
  5060. * a cgroup to another.
  5061. *
  5062. * Note that if we lose to cgroup_enable_task_cg_lists(), @child
  5063. * will remain in init_css_set. This is safe because all tasks are
  5064. * in the init_css_set before cg_links is enabled and there's no
  5065. * operation which transfers all tasks out of init_css_set.
  5066. */
  5067. if (use_task_css_set_links) {
  5068. struct css_set *cset;
  5069. spin_lock_bh(&css_set_lock);
  5070. cset = task_css_set(current);
  5071. if (list_empty(&child->cg_list)) {
  5072. get_css_set(cset);
  5073. css_set_move_task(child, NULL, cset, false);
  5074. }
  5075. spin_unlock_bh(&css_set_lock);
  5076. }
  5077. /*
  5078. * Call ss->fork(). This must happen after @child is linked on
  5079. * css_set; otherwise, @child might change state between ->fork()
  5080. * and addition to css_set.
  5081. */
  5082. do_each_subsys_mask(ss, i, have_fork_callback) {
  5083. ss->fork(child);
  5084. } while_each_subsys_mask();
  5085. }
  5086. /**
  5087. * cgroup_exit - detach cgroup from exiting task
  5088. * @tsk: pointer to task_struct of exiting process
  5089. *
  5090. * Description: Detach cgroup from @tsk and release it.
  5091. *
  5092. * Note that cgroups marked notify_on_release force every task in
  5093. * them to take the global cgroup_mutex mutex when exiting.
  5094. * This could impact scaling on very large systems. Be reluctant to
  5095. * use notify_on_release cgroups where very high task exit scaling
  5096. * is required on large systems.
  5097. *
  5098. * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
  5099. * call cgroup_exit() while the task is still competent to handle
  5100. * notify_on_release(), then leave the task attached to the root cgroup in
  5101. * each hierarchy for the remainder of its exit. No need to bother with
  5102. * init_css_set refcnting. init_css_set never goes away and we can't race
  5103. * with migration path - PF_EXITING is visible to migration path.
  5104. */
  5105. void cgroup_exit(struct task_struct *tsk)
  5106. {
  5107. struct cgroup_subsys *ss;
  5108. struct css_set *cset;
  5109. int i;
  5110. /*
  5111. * Unlink from @tsk from its css_set. As migration path can't race
  5112. * with us, we can check css_set and cg_list without synchronization.
  5113. */
  5114. cset = task_css_set(tsk);
  5115. if (!list_empty(&tsk->cg_list)) {
  5116. spin_lock_bh(&css_set_lock);
  5117. css_set_move_task(tsk, cset, NULL, false);
  5118. spin_unlock_bh(&css_set_lock);
  5119. } else {
  5120. get_css_set(cset);
  5121. }
  5122. /* see cgroup_post_fork() for details */
  5123. do_each_subsys_mask(ss, i, have_exit_callback) {
  5124. ss->exit(tsk);
  5125. } while_each_subsys_mask();
  5126. }
  5127. void cgroup_free(struct task_struct *task)
  5128. {
  5129. struct css_set *cset = task_css_set(task);
  5130. struct cgroup_subsys *ss;
  5131. int ssid;
  5132. do_each_subsys_mask(ss, ssid, have_free_callback) {
  5133. ss->free(task);
  5134. } while_each_subsys_mask();
  5135. put_css_set(cset);
  5136. }
  5137. static void check_for_release(struct cgroup *cgrp)
  5138. {
  5139. if (notify_on_release(cgrp) && !cgroup_is_populated(cgrp) &&
  5140. !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
  5141. schedule_work(&cgrp->release_agent_work);
  5142. }
  5143. /*
  5144. * Notify userspace when a cgroup is released, by running the
  5145. * configured release agent with the name of the cgroup (path
  5146. * relative to the root of cgroup file system) as the argument.
  5147. *
  5148. * Most likely, this user command will try to rmdir this cgroup.
  5149. *
  5150. * This races with the possibility that some other task will be
  5151. * attached to this cgroup before it is removed, or that some other
  5152. * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
  5153. * The presumed 'rmdir' will fail quietly if this cgroup is no longer
  5154. * unused, and this cgroup will be reprieved from its death sentence,
  5155. * to continue to serve a useful existence. Next time it's released,
  5156. * we will get notified again, if it still has 'notify_on_release' set.
  5157. *
  5158. * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
  5159. * means only wait until the task is successfully execve()'d. The
  5160. * separate release agent task is forked by call_usermodehelper(),
  5161. * then control in this thread returns here, without waiting for the
  5162. * release agent task. We don't bother to wait because the caller of
  5163. * this routine has no use for the exit status of the release agent
  5164. * task, so no sense holding our caller up for that.
  5165. */
  5166. static void cgroup_release_agent(struct work_struct *work)
  5167. {
  5168. struct cgroup *cgrp =
  5169. container_of(work, struct cgroup, release_agent_work);
  5170. char *pathbuf = NULL, *agentbuf = NULL, *path;
  5171. char *argv[3], *envp[3];
  5172. mutex_lock(&cgroup_mutex);
  5173. pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
  5174. agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
  5175. if (!pathbuf || !agentbuf)
  5176. goto out;
  5177. spin_lock_bh(&css_set_lock);
  5178. path = cgroup_path_ns_locked(cgrp, pathbuf, PATH_MAX, &init_cgroup_ns);
  5179. spin_unlock_bh(&css_set_lock);
  5180. if (!path)
  5181. goto out;
  5182. argv[0] = agentbuf;
  5183. argv[1] = path;
  5184. argv[2] = NULL;
  5185. /* minimal command environment */
  5186. envp[0] = "HOME=/";
  5187. envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
  5188. envp[2] = NULL;
  5189. mutex_unlock(&cgroup_mutex);
  5190. call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
  5191. goto out_free;
  5192. out:
  5193. mutex_unlock(&cgroup_mutex);
  5194. out_free:
  5195. kfree(agentbuf);
  5196. kfree(pathbuf);
  5197. }
  5198. static int __init cgroup_disable(char *str)
  5199. {
  5200. struct cgroup_subsys *ss;
  5201. char *token;
  5202. int i;
  5203. while ((token = strsep(&str, ",")) != NULL) {
  5204. if (!*token)
  5205. continue;
  5206. for_each_subsys(ss, i) {
  5207. if (strcmp(token, ss->name) &&
  5208. strcmp(token, ss->legacy_name))
  5209. continue;
  5210. cgroup_disable_mask |= 1 << i;
  5211. }
  5212. }
  5213. return 1;
  5214. }
  5215. __setup("cgroup_disable=", cgroup_disable);
  5216. static int __init cgroup_no_v1(char *str)
  5217. {
  5218. struct cgroup_subsys *ss;
  5219. char *token;
  5220. int i;
  5221. while ((token = strsep(&str, ",")) != NULL) {
  5222. if (!*token)
  5223. continue;
  5224. if (!strcmp(token, "all")) {
  5225. cgroup_no_v1_mask = U16_MAX;
  5226. break;
  5227. }
  5228. for_each_subsys(ss, i) {
  5229. if (strcmp(token, ss->name) &&
  5230. strcmp(token, ss->legacy_name))
  5231. continue;
  5232. cgroup_no_v1_mask |= 1 << i;
  5233. }
  5234. }
  5235. return 1;
  5236. }
  5237. __setup("cgroup_no_v1=", cgroup_no_v1);
  5238. /**
  5239. * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
  5240. * @dentry: directory dentry of interest
  5241. * @ss: subsystem of interest
  5242. *
  5243. * If @dentry is a directory for a cgroup which has @ss enabled on it, try
  5244. * to get the corresponding css and return it. If such css doesn't exist
  5245. * or can't be pinned, an ERR_PTR value is returned.
  5246. */
  5247. struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
  5248. struct cgroup_subsys *ss)
  5249. {
  5250. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  5251. struct file_system_type *s_type = dentry->d_sb->s_type;
  5252. struct cgroup_subsys_state *css = NULL;
  5253. struct cgroup *cgrp;
  5254. /* is @dentry a cgroup dir? */
  5255. if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
  5256. !kn || kernfs_type(kn) != KERNFS_DIR)
  5257. return ERR_PTR(-EBADF);
  5258. rcu_read_lock();
  5259. /*
  5260. * This path doesn't originate from kernfs and @kn could already
  5261. * have been or be removed at any point. @kn->priv is RCU
  5262. * protected for this access. See css_release_work_fn() for details.
  5263. */
  5264. cgrp = rcu_dereference(kn->priv);
  5265. if (cgrp)
  5266. css = cgroup_css(cgrp, ss);
  5267. if (!css || !css_tryget_online(css))
  5268. css = ERR_PTR(-ENOENT);
  5269. rcu_read_unlock();
  5270. return css;
  5271. }
  5272. /**
  5273. * css_from_id - lookup css by id
  5274. * @id: the cgroup id
  5275. * @ss: cgroup subsys to be looked into
  5276. *
  5277. * Returns the css if there's valid one with @id, otherwise returns NULL.
  5278. * Should be called under rcu_read_lock().
  5279. */
  5280. struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
  5281. {
  5282. WARN_ON_ONCE(!rcu_read_lock_held());
  5283. return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
  5284. }
  5285. /**
  5286. * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
  5287. * @path: path on the default hierarchy
  5288. *
  5289. * Find the cgroup at @path on the default hierarchy, increment its
  5290. * reference count and return it. Returns pointer to the found cgroup on
  5291. * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
  5292. * if @path points to a non-directory.
  5293. */
  5294. struct cgroup *cgroup_get_from_path(const char *path)
  5295. {
  5296. struct kernfs_node *kn;
  5297. struct cgroup *cgrp;
  5298. mutex_lock(&cgroup_mutex);
  5299. kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
  5300. if (kn) {
  5301. if (kernfs_type(kn) == KERNFS_DIR) {
  5302. cgrp = kn->priv;
  5303. cgroup_get(cgrp);
  5304. } else {
  5305. cgrp = ERR_PTR(-ENOTDIR);
  5306. }
  5307. kernfs_put(kn);
  5308. } else {
  5309. cgrp = ERR_PTR(-ENOENT);
  5310. }
  5311. mutex_unlock(&cgroup_mutex);
  5312. return cgrp;
  5313. }
  5314. EXPORT_SYMBOL_GPL(cgroup_get_from_path);
  5315. /*
  5316. * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
  5317. * definition in cgroup-defs.h.
  5318. */
  5319. #ifdef CONFIG_SOCK_CGROUP_DATA
  5320. #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
  5321. DEFINE_SPINLOCK(cgroup_sk_update_lock);
  5322. static bool cgroup_sk_alloc_disabled __read_mostly;
  5323. void cgroup_sk_alloc_disable(void)
  5324. {
  5325. if (cgroup_sk_alloc_disabled)
  5326. return;
  5327. pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
  5328. cgroup_sk_alloc_disabled = true;
  5329. }
  5330. #else
  5331. #define cgroup_sk_alloc_disabled false
  5332. #endif
  5333. void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
  5334. {
  5335. if (cgroup_sk_alloc_disabled)
  5336. return;
  5337. rcu_read_lock();
  5338. while (true) {
  5339. struct css_set *cset;
  5340. cset = task_css_set(current);
  5341. if (likely(cgroup_tryget(cset->dfl_cgrp))) {
  5342. skcd->val = (unsigned long)cset->dfl_cgrp;
  5343. break;
  5344. }
  5345. cpu_relax();
  5346. }
  5347. rcu_read_unlock();
  5348. }
  5349. void cgroup_sk_free(struct sock_cgroup_data *skcd)
  5350. {
  5351. cgroup_put(sock_cgroup_ptr(skcd));
  5352. }
  5353. #endif /* CONFIG_SOCK_CGROUP_DATA */
  5354. /* cgroup namespaces */
  5355. static struct cgroup_namespace *alloc_cgroup_ns(void)
  5356. {
  5357. struct cgroup_namespace *new_ns;
  5358. int ret;
  5359. new_ns = kzalloc(sizeof(struct cgroup_namespace), GFP_KERNEL);
  5360. if (!new_ns)
  5361. return ERR_PTR(-ENOMEM);
  5362. ret = ns_alloc_inum(&new_ns->ns);
  5363. if (ret) {
  5364. kfree(new_ns);
  5365. return ERR_PTR(ret);
  5366. }
  5367. atomic_set(&new_ns->count, 1);
  5368. new_ns->ns.ops = &cgroupns_operations;
  5369. return new_ns;
  5370. }
  5371. void free_cgroup_ns(struct cgroup_namespace *ns)
  5372. {
  5373. put_css_set(ns->root_cset);
  5374. put_user_ns(ns->user_ns);
  5375. ns_free_inum(&ns->ns);
  5376. kfree(ns);
  5377. }
  5378. EXPORT_SYMBOL(free_cgroup_ns);
  5379. struct cgroup_namespace *copy_cgroup_ns(unsigned long flags,
  5380. struct user_namespace *user_ns,
  5381. struct cgroup_namespace *old_ns)
  5382. {
  5383. struct cgroup_namespace *new_ns;
  5384. struct css_set *cset;
  5385. BUG_ON(!old_ns);
  5386. if (!(flags & CLONE_NEWCGROUP)) {
  5387. get_cgroup_ns(old_ns);
  5388. return old_ns;
  5389. }
  5390. /* Allow only sysadmin to create cgroup namespace. */
  5391. if (!ns_capable(user_ns, CAP_SYS_ADMIN))
  5392. return ERR_PTR(-EPERM);
  5393. mutex_lock(&cgroup_mutex);
  5394. spin_lock_bh(&css_set_lock);
  5395. cset = task_css_set(current);
  5396. get_css_set(cset);
  5397. spin_unlock_bh(&css_set_lock);
  5398. mutex_unlock(&cgroup_mutex);
  5399. new_ns = alloc_cgroup_ns();
  5400. if (IS_ERR(new_ns)) {
  5401. put_css_set(cset);
  5402. return new_ns;
  5403. }
  5404. new_ns->user_ns = get_user_ns(user_ns);
  5405. new_ns->root_cset = cset;
  5406. return new_ns;
  5407. }
  5408. static inline struct cgroup_namespace *to_cg_ns(struct ns_common *ns)
  5409. {
  5410. return container_of(ns, struct cgroup_namespace, ns);
  5411. }
  5412. static int cgroupns_install(struct nsproxy *nsproxy, struct ns_common *ns)
  5413. {
  5414. struct cgroup_namespace *cgroup_ns = to_cg_ns(ns);
  5415. if (!ns_capable(current_user_ns(), CAP_SYS_ADMIN) ||
  5416. !ns_capable(cgroup_ns->user_ns, CAP_SYS_ADMIN))
  5417. return -EPERM;
  5418. /* Don't need to do anything if we are attaching to our own cgroupns. */
  5419. if (cgroup_ns == nsproxy->cgroup_ns)
  5420. return 0;
  5421. get_cgroup_ns(cgroup_ns);
  5422. put_cgroup_ns(nsproxy->cgroup_ns);
  5423. nsproxy->cgroup_ns = cgroup_ns;
  5424. return 0;
  5425. }
  5426. static struct ns_common *cgroupns_get(struct task_struct *task)
  5427. {
  5428. struct cgroup_namespace *ns = NULL;
  5429. struct nsproxy *nsproxy;
  5430. task_lock(task);
  5431. nsproxy = task->nsproxy;
  5432. if (nsproxy) {
  5433. ns = nsproxy->cgroup_ns;
  5434. get_cgroup_ns(ns);
  5435. }
  5436. task_unlock(task);
  5437. return ns ? &ns->ns : NULL;
  5438. }
  5439. static void cgroupns_put(struct ns_common *ns)
  5440. {
  5441. put_cgroup_ns(to_cg_ns(ns));
  5442. }
  5443. const struct proc_ns_operations cgroupns_operations = {
  5444. .name = "cgroup",
  5445. .type = CLONE_NEWCGROUP,
  5446. .get = cgroupns_get,
  5447. .put = cgroupns_put,
  5448. .install = cgroupns_install,
  5449. };
  5450. static __init int cgroup_namespaces_init(void)
  5451. {
  5452. return 0;
  5453. }
  5454. subsys_initcall(cgroup_namespaces_init);
  5455. #ifdef CONFIG_CGROUP_DEBUG
  5456. static struct cgroup_subsys_state *
  5457. debug_css_alloc(struct cgroup_subsys_state *parent_css)
  5458. {
  5459. struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
  5460. if (!css)
  5461. return ERR_PTR(-ENOMEM);
  5462. return css;
  5463. }
  5464. static void debug_css_free(struct cgroup_subsys_state *css)
  5465. {
  5466. kfree(css);
  5467. }
  5468. static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
  5469. struct cftype *cft)
  5470. {
  5471. return cgroup_task_count(css->cgroup);
  5472. }
  5473. static u64 current_css_set_read(struct cgroup_subsys_state *css,
  5474. struct cftype *cft)
  5475. {
  5476. return (u64)(unsigned long)current->cgroups;
  5477. }
  5478. static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
  5479. struct cftype *cft)
  5480. {
  5481. u64 count;
  5482. rcu_read_lock();
  5483. count = atomic_read(&task_css_set(current)->refcount);
  5484. rcu_read_unlock();
  5485. return count;
  5486. }
  5487. static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
  5488. {
  5489. struct cgrp_cset_link *link;
  5490. struct css_set *cset;
  5491. char *name_buf;
  5492. name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
  5493. if (!name_buf)
  5494. return -ENOMEM;
  5495. spin_lock_bh(&css_set_lock);
  5496. rcu_read_lock();
  5497. cset = rcu_dereference(current->cgroups);
  5498. list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
  5499. struct cgroup *c = link->cgrp;
  5500. cgroup_name(c, name_buf, NAME_MAX + 1);
  5501. seq_printf(seq, "Root %d group %s\n",
  5502. c->root->hierarchy_id, name_buf);
  5503. }
  5504. rcu_read_unlock();
  5505. spin_unlock_bh(&css_set_lock);
  5506. kfree(name_buf);
  5507. return 0;
  5508. }
  5509. #define MAX_TASKS_SHOWN_PER_CSS 25
  5510. static int cgroup_css_links_read(struct seq_file *seq, void *v)
  5511. {
  5512. struct cgroup_subsys_state *css = seq_css(seq);
  5513. struct cgrp_cset_link *link;
  5514. spin_lock_bh(&css_set_lock);
  5515. list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
  5516. struct css_set *cset = link->cset;
  5517. struct task_struct *task;
  5518. int count = 0;
  5519. seq_printf(seq, "css_set %p\n", cset);
  5520. list_for_each_entry(task, &cset->tasks, cg_list) {
  5521. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  5522. goto overflow;
  5523. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  5524. }
  5525. list_for_each_entry(task, &cset->mg_tasks, cg_list) {
  5526. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  5527. goto overflow;
  5528. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  5529. }
  5530. continue;
  5531. overflow:
  5532. seq_puts(seq, " ...\n");
  5533. }
  5534. spin_unlock_bh(&css_set_lock);
  5535. return 0;
  5536. }
  5537. static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
  5538. {
  5539. return (!cgroup_is_populated(css->cgroup) &&
  5540. !css_has_online_children(&css->cgroup->self));
  5541. }
  5542. static struct cftype debug_files[] = {
  5543. {
  5544. .name = "taskcount",
  5545. .read_u64 = debug_taskcount_read,
  5546. },
  5547. {
  5548. .name = "current_css_set",
  5549. .read_u64 = current_css_set_read,
  5550. },
  5551. {
  5552. .name = "current_css_set_refcount",
  5553. .read_u64 = current_css_set_refcount_read,
  5554. },
  5555. {
  5556. .name = "current_css_set_cg_links",
  5557. .seq_show = current_css_set_cg_links_read,
  5558. },
  5559. {
  5560. .name = "cgroup_css_links",
  5561. .seq_show = cgroup_css_links_read,
  5562. },
  5563. {
  5564. .name = "releasable",
  5565. .read_u64 = releasable_read,
  5566. },
  5567. { } /* terminate */
  5568. };
  5569. struct cgroup_subsys debug_cgrp_subsys = {
  5570. .css_alloc = debug_css_alloc,
  5571. .css_free = debug_css_free,
  5572. .legacy_cftypes = debug_files,
  5573. };
  5574. #endif /* CONFIG_CGROUP_DEBUG */