cgroup.c 172 KB

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