cgroup.c 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466
  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 *cgrp;
  2426. pid_t pid;
  2427. int ret;
  2428. if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
  2429. return -EINVAL;
  2430. cgrp = cgroup_kn_lock_live(of->kn, false);
  2431. if (!cgrp)
  2432. return -ENODEV;
  2433. percpu_down_write(&cgroup_threadgroup_rwsem);
  2434. rcu_read_lock();
  2435. if (pid) {
  2436. tsk = find_task_by_vpid(pid);
  2437. if (!tsk) {
  2438. ret = -ESRCH;
  2439. goto out_unlock_rcu;
  2440. }
  2441. } else {
  2442. tsk = current;
  2443. }
  2444. if (threadgroup)
  2445. tsk = tsk->group_leader;
  2446. /*
  2447. * Workqueue threads may acquire PF_NO_SETAFFINITY and become
  2448. * trapped in a cpuset, or RT worker may be born in a cgroup
  2449. * with no rt_runtime allocated. Just say no.
  2450. */
  2451. if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
  2452. ret = -EINVAL;
  2453. goto out_unlock_rcu;
  2454. }
  2455. get_task_struct(tsk);
  2456. rcu_read_unlock();
  2457. ret = cgroup_procs_write_permission(tsk, cgrp, of);
  2458. if (!ret)
  2459. ret = cgroup_attach_task(cgrp, tsk, threadgroup);
  2460. put_task_struct(tsk);
  2461. goto out_unlock_threadgroup;
  2462. out_unlock_rcu:
  2463. rcu_read_unlock();
  2464. out_unlock_threadgroup:
  2465. percpu_up_write(&cgroup_threadgroup_rwsem);
  2466. cgroup_kn_unlock(of->kn);
  2467. cpuset_post_attach_flush();
  2468. return ret ?: nbytes;
  2469. }
  2470. /**
  2471. * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
  2472. * @from: attach to all cgroups of a given task
  2473. * @tsk: the task to be attached
  2474. */
  2475. int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
  2476. {
  2477. struct cgroup_root *root;
  2478. int retval = 0;
  2479. mutex_lock(&cgroup_mutex);
  2480. for_each_root(root) {
  2481. struct cgroup *from_cgrp;
  2482. if (root == &cgrp_dfl_root)
  2483. continue;
  2484. spin_lock_bh(&css_set_lock);
  2485. from_cgrp = task_cgroup_from_root(from, root);
  2486. spin_unlock_bh(&css_set_lock);
  2487. retval = cgroup_attach_task(from_cgrp, tsk, false);
  2488. if (retval)
  2489. break;
  2490. }
  2491. mutex_unlock(&cgroup_mutex);
  2492. return retval;
  2493. }
  2494. EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
  2495. static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
  2496. char *buf, size_t nbytes, loff_t off)
  2497. {
  2498. return __cgroup_procs_write(of, buf, nbytes, off, false);
  2499. }
  2500. static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
  2501. char *buf, size_t nbytes, loff_t off)
  2502. {
  2503. return __cgroup_procs_write(of, buf, nbytes, off, true);
  2504. }
  2505. static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
  2506. char *buf, size_t nbytes, loff_t off)
  2507. {
  2508. struct cgroup *cgrp;
  2509. BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
  2510. cgrp = cgroup_kn_lock_live(of->kn, false);
  2511. if (!cgrp)
  2512. return -ENODEV;
  2513. spin_lock(&release_agent_path_lock);
  2514. strlcpy(cgrp->root->release_agent_path, strstrip(buf),
  2515. sizeof(cgrp->root->release_agent_path));
  2516. spin_unlock(&release_agent_path_lock);
  2517. cgroup_kn_unlock(of->kn);
  2518. return nbytes;
  2519. }
  2520. static int cgroup_release_agent_show(struct seq_file *seq, void *v)
  2521. {
  2522. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2523. spin_lock(&release_agent_path_lock);
  2524. seq_puts(seq, cgrp->root->release_agent_path);
  2525. spin_unlock(&release_agent_path_lock);
  2526. seq_putc(seq, '\n');
  2527. return 0;
  2528. }
  2529. static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
  2530. {
  2531. seq_puts(seq, "0\n");
  2532. return 0;
  2533. }
  2534. static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
  2535. {
  2536. struct cgroup_subsys *ss;
  2537. bool printed = false;
  2538. int ssid;
  2539. do_each_subsys_mask(ss, ssid, ss_mask) {
  2540. if (printed)
  2541. seq_putc(seq, ' ');
  2542. seq_printf(seq, "%s", ss->name);
  2543. printed = true;
  2544. } while_each_subsys_mask();
  2545. if (printed)
  2546. seq_putc(seq, '\n');
  2547. }
  2548. /* show controllers which are enabled from the parent */
  2549. static int cgroup_controllers_show(struct seq_file *seq, void *v)
  2550. {
  2551. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2552. cgroup_print_ss_mask(seq, cgroup_control(cgrp));
  2553. return 0;
  2554. }
  2555. /* show controllers which are enabled for a given cgroup's children */
  2556. static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
  2557. {
  2558. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2559. cgroup_print_ss_mask(seq, cgrp->subtree_control);
  2560. return 0;
  2561. }
  2562. /**
  2563. * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
  2564. * @cgrp: root of the subtree to update csses for
  2565. *
  2566. * @cgrp's control masks have changed and its subtree's css associations
  2567. * need to be updated accordingly. This function looks up all css_sets
  2568. * which are attached to the subtree, creates the matching updated css_sets
  2569. * and migrates the tasks to the new ones.
  2570. */
  2571. static int cgroup_update_dfl_csses(struct cgroup *cgrp)
  2572. {
  2573. LIST_HEAD(preloaded_csets);
  2574. struct cgroup_taskset tset = CGROUP_TASKSET_INIT(tset);
  2575. struct cgroup_subsys_state *d_css;
  2576. struct cgroup *dsct;
  2577. struct css_set *src_cset;
  2578. int ret;
  2579. lockdep_assert_held(&cgroup_mutex);
  2580. percpu_down_write(&cgroup_threadgroup_rwsem);
  2581. /* look up all csses currently attached to @cgrp's subtree */
  2582. spin_lock_bh(&css_set_lock);
  2583. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2584. struct cgrp_cset_link *link;
  2585. list_for_each_entry(link, &dsct->cset_links, cset_link)
  2586. cgroup_migrate_add_src(link->cset, dsct,
  2587. &preloaded_csets);
  2588. }
  2589. spin_unlock_bh(&css_set_lock);
  2590. /* NULL dst indicates self on default hierarchy */
  2591. ret = cgroup_migrate_prepare_dst(&preloaded_csets);
  2592. if (ret)
  2593. goto out_finish;
  2594. spin_lock_bh(&css_set_lock);
  2595. list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
  2596. struct task_struct *task, *ntask;
  2597. /* src_csets precede dst_csets, break on the first dst_cset */
  2598. if (!src_cset->mg_src_cgrp)
  2599. break;
  2600. /* all tasks in src_csets need to be migrated */
  2601. list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
  2602. cgroup_taskset_add(task, &tset);
  2603. }
  2604. spin_unlock_bh(&css_set_lock);
  2605. ret = cgroup_taskset_migrate(&tset, cgrp->root);
  2606. out_finish:
  2607. cgroup_migrate_finish(&preloaded_csets);
  2608. percpu_up_write(&cgroup_threadgroup_rwsem);
  2609. return ret;
  2610. }
  2611. /**
  2612. * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
  2613. * @cgrp: root of the target subtree
  2614. *
  2615. * Because css offlining is asynchronous, userland may try to re-enable a
  2616. * controller while the previous css is still around. This function grabs
  2617. * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
  2618. */
  2619. static void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
  2620. __acquires(&cgroup_mutex)
  2621. {
  2622. struct cgroup *dsct;
  2623. struct cgroup_subsys_state *d_css;
  2624. struct cgroup_subsys *ss;
  2625. int ssid;
  2626. restart:
  2627. mutex_lock(&cgroup_mutex);
  2628. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2629. for_each_subsys(ss, ssid) {
  2630. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2631. DEFINE_WAIT(wait);
  2632. if (!css || !percpu_ref_is_dying(&css->refcnt))
  2633. continue;
  2634. cgroup_get(dsct);
  2635. prepare_to_wait(&dsct->offline_waitq, &wait,
  2636. TASK_UNINTERRUPTIBLE);
  2637. mutex_unlock(&cgroup_mutex);
  2638. schedule();
  2639. finish_wait(&dsct->offline_waitq, &wait);
  2640. cgroup_put(dsct);
  2641. goto restart;
  2642. }
  2643. }
  2644. }
  2645. /**
  2646. * cgroup_save_control - save control masks of a subtree
  2647. * @cgrp: root of the target subtree
  2648. *
  2649. * Save ->subtree_control and ->subtree_ss_mask to the respective old_
  2650. * prefixed fields for @cgrp's subtree including @cgrp itself.
  2651. */
  2652. static void cgroup_save_control(struct cgroup *cgrp)
  2653. {
  2654. struct cgroup *dsct;
  2655. struct cgroup_subsys_state *d_css;
  2656. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2657. dsct->old_subtree_control = dsct->subtree_control;
  2658. dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
  2659. }
  2660. }
  2661. /**
  2662. * cgroup_propagate_control - refresh control masks of a subtree
  2663. * @cgrp: root of the target subtree
  2664. *
  2665. * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
  2666. * ->subtree_control and propagate controller availability through the
  2667. * subtree so that descendants don't have unavailable controllers enabled.
  2668. */
  2669. static void cgroup_propagate_control(struct cgroup *cgrp)
  2670. {
  2671. struct cgroup *dsct;
  2672. struct cgroup_subsys_state *d_css;
  2673. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2674. dsct->subtree_control &= cgroup_control(dsct);
  2675. dsct->subtree_ss_mask =
  2676. cgroup_calc_subtree_ss_mask(dsct->subtree_control,
  2677. cgroup_ss_mask(dsct));
  2678. }
  2679. }
  2680. /**
  2681. * cgroup_restore_control - restore control masks of a subtree
  2682. * @cgrp: root of the target subtree
  2683. *
  2684. * Restore ->subtree_control and ->subtree_ss_mask from the respective old_
  2685. * prefixed fields for @cgrp's subtree including @cgrp itself.
  2686. */
  2687. static void cgroup_restore_control(struct cgroup *cgrp)
  2688. {
  2689. struct cgroup *dsct;
  2690. struct cgroup_subsys_state *d_css;
  2691. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2692. dsct->subtree_control = dsct->old_subtree_control;
  2693. dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
  2694. }
  2695. }
  2696. static bool css_visible(struct cgroup_subsys_state *css)
  2697. {
  2698. struct cgroup_subsys *ss = css->ss;
  2699. struct cgroup *cgrp = css->cgroup;
  2700. if (cgroup_control(cgrp) & (1 << ss->id))
  2701. return true;
  2702. if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
  2703. return false;
  2704. return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
  2705. }
  2706. /**
  2707. * cgroup_apply_control_enable - enable or show csses according to control
  2708. * @cgrp: root of the target subtree
  2709. *
  2710. * Walk @cgrp's subtree and create new csses or make the existing ones
  2711. * visible. A css is created invisible if it's being implicitly enabled
  2712. * through dependency. An invisible css is made visible when the userland
  2713. * explicitly enables it.
  2714. *
  2715. * Returns 0 on success, -errno on failure. On failure, csses which have
  2716. * been processed already aren't cleaned up. The caller is responsible for
  2717. * cleaning up with cgroup_apply_control_disble().
  2718. */
  2719. static int cgroup_apply_control_enable(struct cgroup *cgrp)
  2720. {
  2721. struct cgroup *dsct;
  2722. struct cgroup_subsys_state *d_css;
  2723. struct cgroup_subsys *ss;
  2724. int ssid, ret;
  2725. cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
  2726. for_each_subsys(ss, ssid) {
  2727. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2728. WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
  2729. if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
  2730. continue;
  2731. if (!css) {
  2732. css = css_create(dsct, ss);
  2733. if (IS_ERR(css))
  2734. return PTR_ERR(css);
  2735. }
  2736. if (css_visible(css)) {
  2737. ret = css_populate_dir(css);
  2738. if (ret)
  2739. return ret;
  2740. }
  2741. }
  2742. }
  2743. return 0;
  2744. }
  2745. /**
  2746. * cgroup_apply_control_disable - kill or hide csses according to control
  2747. * @cgrp: root of the target subtree
  2748. *
  2749. * Walk @cgrp's subtree and kill and hide csses so that they match
  2750. * cgroup_ss_mask() and cgroup_visible_mask().
  2751. *
  2752. * A css is hidden when the userland requests it to be disabled while other
  2753. * subsystems are still depending on it. The css must not actively control
  2754. * resources and be in the vanilla state if it's made visible again later.
  2755. * Controllers which may be depended upon should provide ->css_reset() for
  2756. * this purpose.
  2757. */
  2758. static void cgroup_apply_control_disable(struct cgroup *cgrp)
  2759. {
  2760. struct cgroup *dsct;
  2761. struct cgroup_subsys_state *d_css;
  2762. struct cgroup_subsys *ss;
  2763. int ssid;
  2764. cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
  2765. for_each_subsys(ss, ssid) {
  2766. struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
  2767. WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
  2768. if (!css)
  2769. continue;
  2770. if (css->parent &&
  2771. !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
  2772. kill_css(css);
  2773. } else if (!css_visible(css)) {
  2774. css_clear_dir(css);
  2775. if (ss->css_reset)
  2776. ss->css_reset(css);
  2777. }
  2778. }
  2779. }
  2780. }
  2781. /**
  2782. * cgroup_apply_control - apply control mask updates to the subtree
  2783. * @cgrp: root of the target subtree
  2784. *
  2785. * subsystems can be enabled and disabled in a subtree using the following
  2786. * steps.
  2787. *
  2788. * 1. Call cgroup_save_control() to stash the current state.
  2789. * 2. Update ->subtree_control masks in the subtree as desired.
  2790. * 3. Call cgroup_apply_control() to apply the changes.
  2791. * 4. Optionally perform other related operations.
  2792. * 5. Call cgroup_finalize_control() to finish up.
  2793. *
  2794. * This function implements step 3 and propagates the mask changes
  2795. * throughout @cgrp's subtree, updates csses accordingly and perform
  2796. * process migrations.
  2797. */
  2798. static int cgroup_apply_control(struct cgroup *cgrp)
  2799. {
  2800. int ret;
  2801. cgroup_propagate_control(cgrp);
  2802. ret = cgroup_apply_control_enable(cgrp);
  2803. if (ret)
  2804. return ret;
  2805. /*
  2806. * At this point, cgroup_e_css() results reflect the new csses
  2807. * making the following cgroup_update_dfl_csses() properly update
  2808. * css associations of all tasks in the subtree.
  2809. */
  2810. ret = cgroup_update_dfl_csses(cgrp);
  2811. if (ret)
  2812. return ret;
  2813. return 0;
  2814. }
  2815. /**
  2816. * cgroup_finalize_control - finalize control mask update
  2817. * @cgrp: root of the target subtree
  2818. * @ret: the result of the update
  2819. *
  2820. * Finalize control mask update. See cgroup_apply_control() for more info.
  2821. */
  2822. static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
  2823. {
  2824. if (ret) {
  2825. cgroup_restore_control(cgrp);
  2826. cgroup_propagate_control(cgrp);
  2827. }
  2828. cgroup_apply_control_disable(cgrp);
  2829. }
  2830. /* change the enabled child controllers for a cgroup in the default hierarchy */
  2831. static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
  2832. char *buf, size_t nbytes,
  2833. loff_t off)
  2834. {
  2835. u16 enable = 0, disable = 0;
  2836. struct cgroup *cgrp, *child;
  2837. struct cgroup_subsys *ss;
  2838. char *tok;
  2839. int ssid, ret;
  2840. /*
  2841. * Parse input - space separated list of subsystem names prefixed
  2842. * with either + or -.
  2843. */
  2844. buf = strstrip(buf);
  2845. while ((tok = strsep(&buf, " "))) {
  2846. if (tok[0] == '\0')
  2847. continue;
  2848. do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
  2849. if (!cgroup_ssid_enabled(ssid) ||
  2850. strcmp(tok + 1, ss->name))
  2851. continue;
  2852. if (*tok == '+') {
  2853. enable |= 1 << ssid;
  2854. disable &= ~(1 << ssid);
  2855. } else if (*tok == '-') {
  2856. disable |= 1 << ssid;
  2857. enable &= ~(1 << ssid);
  2858. } else {
  2859. return -EINVAL;
  2860. }
  2861. break;
  2862. } while_each_subsys_mask();
  2863. if (ssid == CGROUP_SUBSYS_COUNT)
  2864. return -EINVAL;
  2865. }
  2866. cgrp = cgroup_kn_lock_live(of->kn, true);
  2867. if (!cgrp)
  2868. return -ENODEV;
  2869. for_each_subsys(ss, ssid) {
  2870. if (enable & (1 << ssid)) {
  2871. if (cgrp->subtree_control & (1 << ssid)) {
  2872. enable &= ~(1 << ssid);
  2873. continue;
  2874. }
  2875. if (!(cgroup_control(cgrp) & (1 << ssid))) {
  2876. ret = -ENOENT;
  2877. goto out_unlock;
  2878. }
  2879. } else if (disable & (1 << ssid)) {
  2880. if (!(cgrp->subtree_control & (1 << ssid))) {
  2881. disable &= ~(1 << ssid);
  2882. continue;
  2883. }
  2884. /* a child has it enabled? */
  2885. cgroup_for_each_live_child(child, cgrp) {
  2886. if (child->subtree_control & (1 << ssid)) {
  2887. ret = -EBUSY;
  2888. goto out_unlock;
  2889. }
  2890. }
  2891. }
  2892. }
  2893. if (!enable && !disable) {
  2894. ret = 0;
  2895. goto out_unlock;
  2896. }
  2897. /*
  2898. * Except for the root, subtree_control must be zero for a cgroup
  2899. * with tasks so that child cgroups don't compete against tasks.
  2900. */
  2901. if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
  2902. ret = -EBUSY;
  2903. goto out_unlock;
  2904. }
  2905. /* save and update control masks and prepare csses */
  2906. cgroup_save_control(cgrp);
  2907. cgrp->subtree_control |= enable;
  2908. cgrp->subtree_control &= ~disable;
  2909. ret = cgroup_apply_control(cgrp);
  2910. cgroup_finalize_control(cgrp, ret);
  2911. kernfs_activate(cgrp->kn);
  2912. ret = 0;
  2913. out_unlock:
  2914. cgroup_kn_unlock(of->kn);
  2915. return ret ?: nbytes;
  2916. }
  2917. static int cgroup_events_show(struct seq_file *seq, void *v)
  2918. {
  2919. seq_printf(seq, "populated %d\n",
  2920. cgroup_is_populated(seq_css(seq)->cgroup));
  2921. return 0;
  2922. }
  2923. static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
  2924. size_t nbytes, loff_t off)
  2925. {
  2926. struct cgroup *cgrp = of->kn->parent->priv;
  2927. struct cftype *cft = of->kn->priv;
  2928. struct cgroup_subsys_state *css;
  2929. int ret;
  2930. if (cft->write)
  2931. return cft->write(of, buf, nbytes, off);
  2932. /*
  2933. * kernfs guarantees that a file isn't deleted with operations in
  2934. * flight, which means that the matching css is and stays alive and
  2935. * doesn't need to be pinned. The RCU locking is not necessary
  2936. * either. It's just for the convenience of using cgroup_css().
  2937. */
  2938. rcu_read_lock();
  2939. css = cgroup_css(cgrp, cft->ss);
  2940. rcu_read_unlock();
  2941. if (cft->write_u64) {
  2942. unsigned long long v;
  2943. ret = kstrtoull(buf, 0, &v);
  2944. if (!ret)
  2945. ret = cft->write_u64(css, cft, v);
  2946. } else if (cft->write_s64) {
  2947. long long v;
  2948. ret = kstrtoll(buf, 0, &v);
  2949. if (!ret)
  2950. ret = cft->write_s64(css, cft, v);
  2951. } else {
  2952. ret = -EINVAL;
  2953. }
  2954. return ret ?: nbytes;
  2955. }
  2956. static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
  2957. {
  2958. return seq_cft(seq)->seq_start(seq, ppos);
  2959. }
  2960. static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
  2961. {
  2962. return seq_cft(seq)->seq_next(seq, v, ppos);
  2963. }
  2964. static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
  2965. {
  2966. seq_cft(seq)->seq_stop(seq, v);
  2967. }
  2968. static int cgroup_seqfile_show(struct seq_file *m, void *arg)
  2969. {
  2970. struct cftype *cft = seq_cft(m);
  2971. struct cgroup_subsys_state *css = seq_css(m);
  2972. if (cft->seq_show)
  2973. return cft->seq_show(m, arg);
  2974. if (cft->read_u64)
  2975. seq_printf(m, "%llu\n", cft->read_u64(css, cft));
  2976. else if (cft->read_s64)
  2977. seq_printf(m, "%lld\n", cft->read_s64(css, cft));
  2978. else
  2979. return -EINVAL;
  2980. return 0;
  2981. }
  2982. static struct kernfs_ops cgroup_kf_single_ops = {
  2983. .atomic_write_len = PAGE_SIZE,
  2984. .write = cgroup_file_write,
  2985. .seq_show = cgroup_seqfile_show,
  2986. };
  2987. static struct kernfs_ops cgroup_kf_ops = {
  2988. .atomic_write_len = PAGE_SIZE,
  2989. .write = cgroup_file_write,
  2990. .seq_start = cgroup_seqfile_start,
  2991. .seq_next = cgroup_seqfile_next,
  2992. .seq_stop = cgroup_seqfile_stop,
  2993. .seq_show = cgroup_seqfile_show,
  2994. };
  2995. /*
  2996. * cgroup_rename - Only allow simple rename of directories in place.
  2997. */
  2998. static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
  2999. const char *new_name_str)
  3000. {
  3001. struct cgroup *cgrp = kn->priv;
  3002. int ret;
  3003. if (kernfs_type(kn) != KERNFS_DIR)
  3004. return -ENOTDIR;
  3005. if (kn->parent != new_parent)
  3006. return -EIO;
  3007. /*
  3008. * This isn't a proper migration and its usefulness is very
  3009. * limited. Disallow on the default hierarchy.
  3010. */
  3011. if (cgroup_on_dfl(cgrp))
  3012. return -EPERM;
  3013. /*
  3014. * We're gonna grab cgroup_mutex which nests outside kernfs
  3015. * active_ref. kernfs_rename() doesn't require active_ref
  3016. * protection. Break them before grabbing cgroup_mutex.
  3017. */
  3018. kernfs_break_active_protection(new_parent);
  3019. kernfs_break_active_protection(kn);
  3020. mutex_lock(&cgroup_mutex);
  3021. ret = kernfs_rename(kn, new_parent, new_name_str);
  3022. mutex_unlock(&cgroup_mutex);
  3023. kernfs_unbreak_active_protection(kn);
  3024. kernfs_unbreak_active_protection(new_parent);
  3025. return ret;
  3026. }
  3027. /* set uid and gid of cgroup dirs and files to that of the creator */
  3028. static int cgroup_kn_set_ugid(struct kernfs_node *kn)
  3029. {
  3030. struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
  3031. .ia_uid = current_fsuid(),
  3032. .ia_gid = current_fsgid(), };
  3033. if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
  3034. gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
  3035. return 0;
  3036. return kernfs_setattr(kn, &iattr);
  3037. }
  3038. static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
  3039. struct cftype *cft)
  3040. {
  3041. char name[CGROUP_FILE_NAME_MAX];
  3042. struct kernfs_node *kn;
  3043. struct lock_class_key *key = NULL;
  3044. int ret;
  3045. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  3046. key = &cft->lockdep_key;
  3047. #endif
  3048. kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
  3049. cgroup_file_mode(cft), 0, cft->kf_ops, cft,
  3050. NULL, key);
  3051. if (IS_ERR(kn))
  3052. return PTR_ERR(kn);
  3053. ret = cgroup_kn_set_ugid(kn);
  3054. if (ret) {
  3055. kernfs_remove(kn);
  3056. return ret;
  3057. }
  3058. if (cft->file_offset) {
  3059. struct cgroup_file *cfile = (void *)css + cft->file_offset;
  3060. spin_lock_irq(&cgroup_file_kn_lock);
  3061. cfile->kn = kn;
  3062. spin_unlock_irq(&cgroup_file_kn_lock);
  3063. }
  3064. return 0;
  3065. }
  3066. /**
  3067. * cgroup_addrm_files - add or remove files to a cgroup directory
  3068. * @css: the target css
  3069. * @cgrp: the target cgroup (usually css->cgroup)
  3070. * @cfts: array of cftypes to be added
  3071. * @is_add: whether to add or remove
  3072. *
  3073. * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
  3074. * For removals, this function never fails.
  3075. */
  3076. static int cgroup_addrm_files(struct cgroup_subsys_state *css,
  3077. struct cgroup *cgrp, struct cftype cfts[],
  3078. bool is_add)
  3079. {
  3080. struct cftype *cft, *cft_end = NULL;
  3081. int ret = 0;
  3082. lockdep_assert_held(&cgroup_mutex);
  3083. restart:
  3084. for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
  3085. /* does cft->flags tell us to skip this file on @cgrp? */
  3086. if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
  3087. continue;
  3088. if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
  3089. continue;
  3090. if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
  3091. continue;
  3092. if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
  3093. continue;
  3094. if (is_add) {
  3095. ret = cgroup_add_file(css, cgrp, cft);
  3096. if (ret) {
  3097. pr_warn("%s: failed to add %s, err=%d\n",
  3098. __func__, cft->name, ret);
  3099. cft_end = cft;
  3100. is_add = false;
  3101. goto restart;
  3102. }
  3103. } else {
  3104. cgroup_rm_file(cgrp, cft);
  3105. }
  3106. }
  3107. return ret;
  3108. }
  3109. static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
  3110. {
  3111. LIST_HEAD(pending);
  3112. struct cgroup_subsys *ss = cfts[0].ss;
  3113. struct cgroup *root = &ss->root->cgrp;
  3114. struct cgroup_subsys_state *css;
  3115. int ret = 0;
  3116. lockdep_assert_held(&cgroup_mutex);
  3117. /* add/rm files for all cgroups created before */
  3118. css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
  3119. struct cgroup *cgrp = css->cgroup;
  3120. if (!(css->flags & CSS_VISIBLE))
  3121. continue;
  3122. ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
  3123. if (ret)
  3124. break;
  3125. }
  3126. if (is_add && !ret)
  3127. kernfs_activate(root->kn);
  3128. return ret;
  3129. }
  3130. static void cgroup_exit_cftypes(struct cftype *cfts)
  3131. {
  3132. struct cftype *cft;
  3133. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  3134. /* free copy for custom atomic_write_len, see init_cftypes() */
  3135. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
  3136. kfree(cft->kf_ops);
  3137. cft->kf_ops = NULL;
  3138. cft->ss = NULL;
  3139. /* revert flags set by cgroup core while adding @cfts */
  3140. cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
  3141. }
  3142. }
  3143. static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3144. {
  3145. struct cftype *cft;
  3146. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  3147. struct kernfs_ops *kf_ops;
  3148. WARN_ON(cft->ss || cft->kf_ops);
  3149. if (cft->seq_start)
  3150. kf_ops = &cgroup_kf_ops;
  3151. else
  3152. kf_ops = &cgroup_kf_single_ops;
  3153. /*
  3154. * Ugh... if @cft wants a custom max_write_len, we need to
  3155. * make a copy of kf_ops to set its atomic_write_len.
  3156. */
  3157. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
  3158. kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
  3159. if (!kf_ops) {
  3160. cgroup_exit_cftypes(cfts);
  3161. return -ENOMEM;
  3162. }
  3163. kf_ops->atomic_write_len = cft->max_write_len;
  3164. }
  3165. cft->kf_ops = kf_ops;
  3166. cft->ss = ss;
  3167. }
  3168. return 0;
  3169. }
  3170. static int cgroup_rm_cftypes_locked(struct cftype *cfts)
  3171. {
  3172. lockdep_assert_held(&cgroup_mutex);
  3173. if (!cfts || !cfts[0].ss)
  3174. return -ENOENT;
  3175. list_del(&cfts->node);
  3176. cgroup_apply_cftypes(cfts, false);
  3177. cgroup_exit_cftypes(cfts);
  3178. return 0;
  3179. }
  3180. /**
  3181. * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
  3182. * @cfts: zero-length name terminated array of cftypes
  3183. *
  3184. * Unregister @cfts. Files described by @cfts are removed from all
  3185. * existing cgroups and all future cgroups won't have them either. This
  3186. * function can be called anytime whether @cfts' subsys is attached or not.
  3187. *
  3188. * Returns 0 on successful unregistration, -ENOENT if @cfts is not
  3189. * registered.
  3190. */
  3191. int cgroup_rm_cftypes(struct cftype *cfts)
  3192. {
  3193. int ret;
  3194. mutex_lock(&cgroup_mutex);
  3195. ret = cgroup_rm_cftypes_locked(cfts);
  3196. mutex_unlock(&cgroup_mutex);
  3197. return ret;
  3198. }
  3199. /**
  3200. * cgroup_add_cftypes - add an array of cftypes to a subsystem
  3201. * @ss: target cgroup subsystem
  3202. * @cfts: zero-length name terminated array of cftypes
  3203. *
  3204. * Register @cfts to @ss. Files described by @cfts are created for all
  3205. * existing cgroups to which @ss is attached and all future cgroups will
  3206. * have them too. This function can be called anytime whether @ss is
  3207. * attached or not.
  3208. *
  3209. * Returns 0 on successful registration, -errno on failure. Note that this
  3210. * function currently returns 0 as long as @cfts registration is successful
  3211. * even if some file creation attempts on existing cgroups fail.
  3212. */
  3213. static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3214. {
  3215. int ret;
  3216. if (!cgroup_ssid_enabled(ss->id))
  3217. return 0;
  3218. if (!cfts || cfts[0].name[0] == '\0')
  3219. return 0;
  3220. ret = cgroup_init_cftypes(ss, cfts);
  3221. if (ret)
  3222. return ret;
  3223. mutex_lock(&cgroup_mutex);
  3224. list_add_tail(&cfts->node, &ss->cfts);
  3225. ret = cgroup_apply_cftypes(cfts, true);
  3226. if (ret)
  3227. cgroup_rm_cftypes_locked(cfts);
  3228. mutex_unlock(&cgroup_mutex);
  3229. return ret;
  3230. }
  3231. /**
  3232. * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
  3233. * @ss: target cgroup subsystem
  3234. * @cfts: zero-length name terminated array of cftypes
  3235. *
  3236. * Similar to cgroup_add_cftypes() but the added files are only used for
  3237. * the default hierarchy.
  3238. */
  3239. int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3240. {
  3241. struct cftype *cft;
  3242. for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
  3243. cft->flags |= __CFTYPE_ONLY_ON_DFL;
  3244. return cgroup_add_cftypes(ss, cfts);
  3245. }
  3246. /**
  3247. * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
  3248. * @ss: target cgroup subsystem
  3249. * @cfts: zero-length name terminated array of cftypes
  3250. *
  3251. * Similar to cgroup_add_cftypes() but the added files are only used for
  3252. * the legacy hierarchies.
  3253. */
  3254. int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  3255. {
  3256. struct cftype *cft;
  3257. for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
  3258. cft->flags |= __CFTYPE_NOT_ON_DFL;
  3259. return cgroup_add_cftypes(ss, cfts);
  3260. }
  3261. /**
  3262. * cgroup_file_notify - generate a file modified event for a cgroup_file
  3263. * @cfile: target cgroup_file
  3264. *
  3265. * @cfile must have been obtained by setting cftype->file_offset.
  3266. */
  3267. void cgroup_file_notify(struct cgroup_file *cfile)
  3268. {
  3269. unsigned long flags;
  3270. spin_lock_irqsave(&cgroup_file_kn_lock, flags);
  3271. if (cfile->kn)
  3272. kernfs_notify(cfile->kn);
  3273. spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
  3274. }
  3275. /**
  3276. * cgroup_task_count - count the number of tasks in a cgroup.
  3277. * @cgrp: the cgroup in question
  3278. *
  3279. * Return the number of tasks in the cgroup.
  3280. */
  3281. static int cgroup_task_count(const struct cgroup *cgrp)
  3282. {
  3283. int count = 0;
  3284. struct cgrp_cset_link *link;
  3285. spin_lock_bh(&css_set_lock);
  3286. list_for_each_entry(link, &cgrp->cset_links, cset_link)
  3287. count += atomic_read(&link->cset->refcount);
  3288. spin_unlock_bh(&css_set_lock);
  3289. return count;
  3290. }
  3291. /**
  3292. * css_next_child - find the next child of a given css
  3293. * @pos: the current position (%NULL to initiate traversal)
  3294. * @parent: css whose children to walk
  3295. *
  3296. * This function returns the next child of @parent and should be called
  3297. * under either cgroup_mutex or RCU read lock. The only requirement is
  3298. * that @parent and @pos are accessible. The next sibling is guaranteed to
  3299. * be returned regardless of their states.
  3300. *
  3301. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3302. * css which finished ->css_online() is guaranteed to be visible in the
  3303. * future iterations and will stay visible until the last reference is put.
  3304. * A css which hasn't finished ->css_online() or already finished
  3305. * ->css_offline() may show up during traversal. It's each subsystem's
  3306. * responsibility to synchronize against on/offlining.
  3307. */
  3308. struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
  3309. struct cgroup_subsys_state *parent)
  3310. {
  3311. struct cgroup_subsys_state *next;
  3312. cgroup_assert_mutex_or_rcu_locked();
  3313. /*
  3314. * @pos could already have been unlinked from the sibling list.
  3315. * Once a cgroup is removed, its ->sibling.next is no longer
  3316. * updated when its next sibling changes. CSS_RELEASED is set when
  3317. * @pos is taken off list, at which time its next pointer is valid,
  3318. * and, as releases are serialized, the one pointed to by the next
  3319. * pointer is guaranteed to not have started release yet. This
  3320. * implies that if we observe !CSS_RELEASED on @pos in this RCU
  3321. * critical section, the one pointed to by its next pointer is
  3322. * guaranteed to not have finished its RCU grace period even if we
  3323. * have dropped rcu_read_lock() inbetween iterations.
  3324. *
  3325. * If @pos has CSS_RELEASED set, its next pointer can't be
  3326. * dereferenced; however, as each css is given a monotonically
  3327. * increasing unique serial number and always appended to the
  3328. * sibling list, the next one can be found by walking the parent's
  3329. * children until the first css with higher serial number than
  3330. * @pos's. While this path can be slower, it happens iff iteration
  3331. * races against release and the race window is very small.
  3332. */
  3333. if (!pos) {
  3334. next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
  3335. } else if (likely(!(pos->flags & CSS_RELEASED))) {
  3336. next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
  3337. } else {
  3338. list_for_each_entry_rcu(next, &parent->children, sibling)
  3339. if (next->serial_nr > pos->serial_nr)
  3340. break;
  3341. }
  3342. /*
  3343. * @next, if not pointing to the head, can be dereferenced and is
  3344. * the next sibling.
  3345. */
  3346. if (&next->sibling != &parent->children)
  3347. return next;
  3348. return NULL;
  3349. }
  3350. /**
  3351. * css_next_descendant_pre - find the next descendant for pre-order walk
  3352. * @pos: the current position (%NULL to initiate traversal)
  3353. * @root: css whose descendants to walk
  3354. *
  3355. * To be used by css_for_each_descendant_pre(). Find the next descendant
  3356. * to visit for pre-order traversal of @root's descendants. @root is
  3357. * included in the iteration and the first node to be visited.
  3358. *
  3359. * While this function requires cgroup_mutex or RCU read locking, it
  3360. * doesn't require the whole traversal to be contained in a single critical
  3361. * section. This function will return the correct next descendant as long
  3362. * as both @pos and @root are accessible and @pos is a descendant of @root.
  3363. *
  3364. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3365. * css which finished ->css_online() is guaranteed to be visible in the
  3366. * future iterations and will stay visible until the last reference is put.
  3367. * A css which hasn't finished ->css_online() or already finished
  3368. * ->css_offline() may show up during traversal. It's each subsystem's
  3369. * responsibility to synchronize against on/offlining.
  3370. */
  3371. struct cgroup_subsys_state *
  3372. css_next_descendant_pre(struct cgroup_subsys_state *pos,
  3373. struct cgroup_subsys_state *root)
  3374. {
  3375. struct cgroup_subsys_state *next;
  3376. cgroup_assert_mutex_or_rcu_locked();
  3377. /* if first iteration, visit @root */
  3378. if (!pos)
  3379. return root;
  3380. /* visit the first child if exists */
  3381. next = css_next_child(NULL, pos);
  3382. if (next)
  3383. return next;
  3384. /* no child, visit my or the closest ancestor's next sibling */
  3385. while (pos != root) {
  3386. next = css_next_child(pos, pos->parent);
  3387. if (next)
  3388. return next;
  3389. pos = pos->parent;
  3390. }
  3391. return NULL;
  3392. }
  3393. /**
  3394. * css_rightmost_descendant - return the rightmost descendant of a css
  3395. * @pos: css of interest
  3396. *
  3397. * Return the rightmost descendant of @pos. If there's no descendant, @pos
  3398. * is returned. This can be used during pre-order traversal to skip
  3399. * subtree of @pos.
  3400. *
  3401. * While this function requires cgroup_mutex or RCU read locking, it
  3402. * doesn't require the whole traversal to be contained in a single critical
  3403. * section. This function will return the correct rightmost descendant as
  3404. * long as @pos is accessible.
  3405. */
  3406. struct cgroup_subsys_state *
  3407. css_rightmost_descendant(struct cgroup_subsys_state *pos)
  3408. {
  3409. struct cgroup_subsys_state *last, *tmp;
  3410. cgroup_assert_mutex_or_rcu_locked();
  3411. do {
  3412. last = pos;
  3413. /* ->prev isn't RCU safe, walk ->next till the end */
  3414. pos = NULL;
  3415. css_for_each_child(tmp, last)
  3416. pos = tmp;
  3417. } while (pos);
  3418. return last;
  3419. }
  3420. static struct cgroup_subsys_state *
  3421. css_leftmost_descendant(struct cgroup_subsys_state *pos)
  3422. {
  3423. struct cgroup_subsys_state *last;
  3424. do {
  3425. last = pos;
  3426. pos = css_next_child(NULL, pos);
  3427. } while (pos);
  3428. return last;
  3429. }
  3430. /**
  3431. * css_next_descendant_post - find the next descendant for post-order walk
  3432. * @pos: the current position (%NULL to initiate traversal)
  3433. * @root: css whose descendants to walk
  3434. *
  3435. * To be used by css_for_each_descendant_post(). Find the next descendant
  3436. * to visit for post-order traversal of @root's descendants. @root is
  3437. * included in the iteration and the last node to be visited.
  3438. *
  3439. * While this function requires cgroup_mutex or RCU read locking, it
  3440. * doesn't require the whole traversal to be contained in a single critical
  3441. * section. This function will return the correct next descendant as long
  3442. * as both @pos and @cgroup are accessible and @pos is a descendant of
  3443. * @cgroup.
  3444. *
  3445. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  3446. * css which finished ->css_online() is guaranteed to be visible in the
  3447. * future iterations and will stay visible until the last reference is put.
  3448. * A css which hasn't finished ->css_online() or already finished
  3449. * ->css_offline() may show up during traversal. It's each subsystem's
  3450. * responsibility to synchronize against on/offlining.
  3451. */
  3452. struct cgroup_subsys_state *
  3453. css_next_descendant_post(struct cgroup_subsys_state *pos,
  3454. struct cgroup_subsys_state *root)
  3455. {
  3456. struct cgroup_subsys_state *next;
  3457. cgroup_assert_mutex_or_rcu_locked();
  3458. /* if first iteration, visit leftmost descendant which may be @root */
  3459. if (!pos)
  3460. return css_leftmost_descendant(root);
  3461. /* if we visited @root, we're done */
  3462. if (pos == root)
  3463. return NULL;
  3464. /* if there's an unvisited sibling, visit its leftmost descendant */
  3465. next = css_next_child(pos, pos->parent);
  3466. if (next)
  3467. return css_leftmost_descendant(next);
  3468. /* no sibling left, visit parent */
  3469. return pos->parent;
  3470. }
  3471. /**
  3472. * css_has_online_children - does a css have online children
  3473. * @css: the target css
  3474. *
  3475. * Returns %true if @css has any online children; otherwise, %false. This
  3476. * function can be called from any context but the caller is responsible
  3477. * for synchronizing against on/offlining as necessary.
  3478. */
  3479. bool css_has_online_children(struct cgroup_subsys_state *css)
  3480. {
  3481. struct cgroup_subsys_state *child;
  3482. bool ret = false;
  3483. rcu_read_lock();
  3484. css_for_each_child(child, css) {
  3485. if (child->flags & CSS_ONLINE) {
  3486. ret = true;
  3487. break;
  3488. }
  3489. }
  3490. rcu_read_unlock();
  3491. return ret;
  3492. }
  3493. /**
  3494. * css_task_iter_advance_css_set - advance a task itererator to the next css_set
  3495. * @it: the iterator to advance
  3496. *
  3497. * Advance @it to the next css_set to walk.
  3498. */
  3499. static void css_task_iter_advance_css_set(struct css_task_iter *it)
  3500. {
  3501. struct list_head *l = it->cset_pos;
  3502. struct cgrp_cset_link *link;
  3503. struct css_set *cset;
  3504. lockdep_assert_held(&css_set_lock);
  3505. /* Advance to the next non-empty css_set */
  3506. do {
  3507. l = l->next;
  3508. if (l == it->cset_head) {
  3509. it->cset_pos = NULL;
  3510. it->task_pos = NULL;
  3511. return;
  3512. }
  3513. if (it->ss) {
  3514. cset = container_of(l, struct css_set,
  3515. e_cset_node[it->ss->id]);
  3516. } else {
  3517. link = list_entry(l, struct cgrp_cset_link, cset_link);
  3518. cset = link->cset;
  3519. }
  3520. } while (!css_set_populated(cset));
  3521. it->cset_pos = l;
  3522. if (!list_empty(&cset->tasks))
  3523. it->task_pos = cset->tasks.next;
  3524. else
  3525. it->task_pos = cset->mg_tasks.next;
  3526. it->tasks_head = &cset->tasks;
  3527. it->mg_tasks_head = &cset->mg_tasks;
  3528. /*
  3529. * We don't keep css_sets locked across iteration steps and thus
  3530. * need to take steps to ensure that iteration can be resumed after
  3531. * the lock is re-acquired. Iteration is performed at two levels -
  3532. * css_sets and tasks in them.
  3533. *
  3534. * Once created, a css_set never leaves its cgroup lists, so a
  3535. * pinned css_set is guaranteed to stay put and we can resume
  3536. * iteration afterwards.
  3537. *
  3538. * Tasks may leave @cset across iteration steps. This is resolved
  3539. * by registering each iterator with the css_set currently being
  3540. * walked and making css_set_move_task() advance iterators whose
  3541. * next task is leaving.
  3542. */
  3543. if (it->cur_cset) {
  3544. list_del(&it->iters_node);
  3545. put_css_set_locked(it->cur_cset);
  3546. }
  3547. get_css_set(cset);
  3548. it->cur_cset = cset;
  3549. list_add(&it->iters_node, &cset->task_iters);
  3550. }
  3551. static void css_task_iter_advance(struct css_task_iter *it)
  3552. {
  3553. struct list_head *l = it->task_pos;
  3554. lockdep_assert_held(&css_set_lock);
  3555. WARN_ON_ONCE(!l);
  3556. /*
  3557. * Advance iterator to find next entry. cset->tasks is consumed
  3558. * first and then ->mg_tasks. After ->mg_tasks, we move onto the
  3559. * next cset.
  3560. */
  3561. l = l->next;
  3562. if (l == it->tasks_head)
  3563. l = it->mg_tasks_head->next;
  3564. if (l == it->mg_tasks_head)
  3565. css_task_iter_advance_css_set(it);
  3566. else
  3567. it->task_pos = l;
  3568. }
  3569. /**
  3570. * css_task_iter_start - initiate task iteration
  3571. * @css: the css to walk tasks of
  3572. * @it: the task iterator to use
  3573. *
  3574. * Initiate iteration through the tasks of @css. The caller can call
  3575. * css_task_iter_next() to walk through the tasks until the function
  3576. * returns NULL. On completion of iteration, css_task_iter_end() must be
  3577. * called.
  3578. */
  3579. void css_task_iter_start(struct cgroup_subsys_state *css,
  3580. struct css_task_iter *it)
  3581. {
  3582. /* no one should try to iterate before mounting cgroups */
  3583. WARN_ON_ONCE(!use_task_css_set_links);
  3584. memset(it, 0, sizeof(*it));
  3585. spin_lock_bh(&css_set_lock);
  3586. it->ss = css->ss;
  3587. if (it->ss)
  3588. it->cset_pos = &css->cgroup->e_csets[css->ss->id];
  3589. else
  3590. it->cset_pos = &css->cgroup->cset_links;
  3591. it->cset_head = it->cset_pos;
  3592. css_task_iter_advance_css_set(it);
  3593. spin_unlock_bh(&css_set_lock);
  3594. }
  3595. /**
  3596. * css_task_iter_next - return the next task for the iterator
  3597. * @it: the task iterator being iterated
  3598. *
  3599. * The "next" function for task iteration. @it should have been
  3600. * initialized via css_task_iter_start(). Returns NULL when the iteration
  3601. * reaches the end.
  3602. */
  3603. struct task_struct *css_task_iter_next(struct css_task_iter *it)
  3604. {
  3605. if (it->cur_task) {
  3606. put_task_struct(it->cur_task);
  3607. it->cur_task = NULL;
  3608. }
  3609. spin_lock_bh(&css_set_lock);
  3610. if (it->task_pos) {
  3611. it->cur_task = list_entry(it->task_pos, struct task_struct,
  3612. cg_list);
  3613. get_task_struct(it->cur_task);
  3614. css_task_iter_advance(it);
  3615. }
  3616. spin_unlock_bh(&css_set_lock);
  3617. return it->cur_task;
  3618. }
  3619. /**
  3620. * css_task_iter_end - finish task iteration
  3621. * @it: the task iterator to finish
  3622. *
  3623. * Finish task iteration started by css_task_iter_start().
  3624. */
  3625. void css_task_iter_end(struct css_task_iter *it)
  3626. {
  3627. if (it->cur_cset) {
  3628. spin_lock_bh(&css_set_lock);
  3629. list_del(&it->iters_node);
  3630. put_css_set_locked(it->cur_cset);
  3631. spin_unlock_bh(&css_set_lock);
  3632. }
  3633. if (it->cur_task)
  3634. put_task_struct(it->cur_task);
  3635. }
  3636. /**
  3637. * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
  3638. * @to: cgroup to which the tasks will be moved
  3639. * @from: cgroup in which the tasks currently reside
  3640. *
  3641. * Locking rules between cgroup_post_fork() and the migration path
  3642. * guarantee that, if a task is forking while being migrated, the new child
  3643. * is guaranteed to be either visible in the source cgroup after the
  3644. * parent's migration is complete or put into the target cgroup. No task
  3645. * can slip out of migration through forking.
  3646. */
  3647. int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
  3648. {
  3649. LIST_HEAD(preloaded_csets);
  3650. struct cgrp_cset_link *link;
  3651. struct css_task_iter it;
  3652. struct task_struct *task;
  3653. int ret;
  3654. if (!cgroup_may_migrate_to(to))
  3655. return -EBUSY;
  3656. mutex_lock(&cgroup_mutex);
  3657. /* all tasks in @from are being moved, all csets are source */
  3658. spin_lock_bh(&css_set_lock);
  3659. list_for_each_entry(link, &from->cset_links, cset_link)
  3660. cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
  3661. spin_unlock_bh(&css_set_lock);
  3662. ret = cgroup_migrate_prepare_dst(&preloaded_csets);
  3663. if (ret)
  3664. goto out_err;
  3665. /*
  3666. * Migrate tasks one-by-one until @from is empty. This fails iff
  3667. * ->can_attach() fails.
  3668. */
  3669. do {
  3670. css_task_iter_start(&from->self, &it);
  3671. task = css_task_iter_next(&it);
  3672. if (task)
  3673. get_task_struct(task);
  3674. css_task_iter_end(&it);
  3675. if (task) {
  3676. ret = cgroup_migrate(task, false, to->root);
  3677. put_task_struct(task);
  3678. }
  3679. } while (task && !ret);
  3680. out_err:
  3681. cgroup_migrate_finish(&preloaded_csets);
  3682. mutex_unlock(&cgroup_mutex);
  3683. return ret;
  3684. }
  3685. /*
  3686. * Stuff for reading the 'tasks'/'procs' files.
  3687. *
  3688. * Reading this file can return large amounts of data if a cgroup has
  3689. * *lots* of attached tasks. So it may need several calls to read(),
  3690. * but we cannot guarantee that the information we produce is correct
  3691. * unless we produce it entirely atomically.
  3692. *
  3693. */
  3694. /* which pidlist file are we talking about? */
  3695. enum cgroup_filetype {
  3696. CGROUP_FILE_PROCS,
  3697. CGROUP_FILE_TASKS,
  3698. };
  3699. /*
  3700. * A pidlist is a list of pids that virtually represents the contents of one
  3701. * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
  3702. * a pair (one each for procs, tasks) for each pid namespace that's relevant
  3703. * to the cgroup.
  3704. */
  3705. struct cgroup_pidlist {
  3706. /*
  3707. * used to find which pidlist is wanted. doesn't change as long as
  3708. * this particular list stays in the list.
  3709. */
  3710. struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
  3711. /* array of xids */
  3712. pid_t *list;
  3713. /* how many elements the above list has */
  3714. int length;
  3715. /* each of these stored in a list by its cgroup */
  3716. struct list_head links;
  3717. /* pointer to the cgroup we belong to, for list removal purposes */
  3718. struct cgroup *owner;
  3719. /* for delayed destruction */
  3720. struct delayed_work destroy_dwork;
  3721. };
  3722. /*
  3723. * The following two functions "fix" the issue where there are more pids
  3724. * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
  3725. * TODO: replace with a kernel-wide solution to this problem
  3726. */
  3727. #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
  3728. static void *pidlist_allocate(int count)
  3729. {
  3730. if (PIDLIST_TOO_LARGE(count))
  3731. return vmalloc(count * sizeof(pid_t));
  3732. else
  3733. return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
  3734. }
  3735. static void pidlist_free(void *p)
  3736. {
  3737. kvfree(p);
  3738. }
  3739. /*
  3740. * Used to destroy all pidlists lingering waiting for destroy timer. None
  3741. * should be left afterwards.
  3742. */
  3743. static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
  3744. {
  3745. struct cgroup_pidlist *l, *tmp_l;
  3746. mutex_lock(&cgrp->pidlist_mutex);
  3747. list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
  3748. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
  3749. mutex_unlock(&cgrp->pidlist_mutex);
  3750. flush_workqueue(cgroup_pidlist_destroy_wq);
  3751. BUG_ON(!list_empty(&cgrp->pidlists));
  3752. }
  3753. static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
  3754. {
  3755. struct delayed_work *dwork = to_delayed_work(work);
  3756. struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
  3757. destroy_dwork);
  3758. struct cgroup_pidlist *tofree = NULL;
  3759. mutex_lock(&l->owner->pidlist_mutex);
  3760. /*
  3761. * Destroy iff we didn't get queued again. The state won't change
  3762. * as destroy_dwork can only be queued while locked.
  3763. */
  3764. if (!delayed_work_pending(dwork)) {
  3765. list_del(&l->links);
  3766. pidlist_free(l->list);
  3767. put_pid_ns(l->key.ns);
  3768. tofree = l;
  3769. }
  3770. mutex_unlock(&l->owner->pidlist_mutex);
  3771. kfree(tofree);
  3772. }
  3773. /*
  3774. * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
  3775. * Returns the number of unique elements.
  3776. */
  3777. static int pidlist_uniq(pid_t *list, int length)
  3778. {
  3779. int src, dest = 1;
  3780. /*
  3781. * we presume the 0th element is unique, so i starts at 1. trivial
  3782. * edge cases first; no work needs to be done for either
  3783. */
  3784. if (length == 0 || length == 1)
  3785. return length;
  3786. /* src and dest walk down the list; dest counts unique elements */
  3787. for (src = 1; src < length; src++) {
  3788. /* find next unique element */
  3789. while (list[src] == list[src-1]) {
  3790. src++;
  3791. if (src == length)
  3792. goto after;
  3793. }
  3794. /* dest always points to where the next unique element goes */
  3795. list[dest] = list[src];
  3796. dest++;
  3797. }
  3798. after:
  3799. return dest;
  3800. }
  3801. /*
  3802. * The two pid files - task and cgroup.procs - guaranteed that the result
  3803. * is sorted, which forced this whole pidlist fiasco. As pid order is
  3804. * different per namespace, each namespace needs differently sorted list,
  3805. * making it impossible to use, for example, single rbtree of member tasks
  3806. * sorted by task pointer. As pidlists can be fairly large, allocating one
  3807. * per open file is dangerous, so cgroup had to implement shared pool of
  3808. * pidlists keyed by cgroup and namespace.
  3809. *
  3810. * All this extra complexity was caused by the original implementation
  3811. * committing to an entirely unnecessary property. In the long term, we
  3812. * want to do away with it. Explicitly scramble sort order if on the
  3813. * default hierarchy so that no such expectation exists in the new
  3814. * interface.
  3815. *
  3816. * Scrambling is done by swapping every two consecutive bits, which is
  3817. * non-identity one-to-one mapping which disturbs sort order sufficiently.
  3818. */
  3819. static pid_t pid_fry(pid_t pid)
  3820. {
  3821. unsigned a = pid & 0x55555555;
  3822. unsigned b = pid & 0xAAAAAAAA;
  3823. return (a << 1) | (b >> 1);
  3824. }
  3825. static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
  3826. {
  3827. if (cgroup_on_dfl(cgrp))
  3828. return pid_fry(pid);
  3829. else
  3830. return pid;
  3831. }
  3832. static int cmppid(const void *a, const void *b)
  3833. {
  3834. return *(pid_t *)a - *(pid_t *)b;
  3835. }
  3836. static int fried_cmppid(const void *a, const void *b)
  3837. {
  3838. return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
  3839. }
  3840. static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
  3841. enum cgroup_filetype type)
  3842. {
  3843. struct cgroup_pidlist *l;
  3844. /* don't need task_nsproxy() if we're looking at ourself */
  3845. struct pid_namespace *ns = task_active_pid_ns(current);
  3846. lockdep_assert_held(&cgrp->pidlist_mutex);
  3847. list_for_each_entry(l, &cgrp->pidlists, links)
  3848. if (l->key.type == type && l->key.ns == ns)
  3849. return l;
  3850. return NULL;
  3851. }
  3852. /*
  3853. * find the appropriate pidlist for our purpose (given procs vs tasks)
  3854. * returns with the lock on that pidlist already held, and takes care
  3855. * of the use count, or returns NULL with no locks held if we're out of
  3856. * memory.
  3857. */
  3858. static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
  3859. enum cgroup_filetype type)
  3860. {
  3861. struct cgroup_pidlist *l;
  3862. lockdep_assert_held(&cgrp->pidlist_mutex);
  3863. l = cgroup_pidlist_find(cgrp, type);
  3864. if (l)
  3865. return l;
  3866. /* entry not found; create a new one */
  3867. l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
  3868. if (!l)
  3869. return l;
  3870. INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
  3871. l->key.type = type;
  3872. /* don't need task_nsproxy() if we're looking at ourself */
  3873. l->key.ns = get_pid_ns(task_active_pid_ns(current));
  3874. l->owner = cgrp;
  3875. list_add(&l->links, &cgrp->pidlists);
  3876. return l;
  3877. }
  3878. /*
  3879. * Load a cgroup's pidarray with either procs' tgids or tasks' pids
  3880. */
  3881. static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
  3882. struct cgroup_pidlist **lp)
  3883. {
  3884. pid_t *array;
  3885. int length;
  3886. int pid, n = 0; /* used for populating the array */
  3887. struct css_task_iter it;
  3888. struct task_struct *tsk;
  3889. struct cgroup_pidlist *l;
  3890. lockdep_assert_held(&cgrp->pidlist_mutex);
  3891. /*
  3892. * If cgroup gets more users after we read count, we won't have
  3893. * enough space - tough. This race is indistinguishable to the
  3894. * caller from the case that the additional cgroup users didn't
  3895. * show up until sometime later on.
  3896. */
  3897. length = cgroup_task_count(cgrp);
  3898. array = pidlist_allocate(length);
  3899. if (!array)
  3900. return -ENOMEM;
  3901. /* now, populate the array */
  3902. css_task_iter_start(&cgrp->self, &it);
  3903. while ((tsk = css_task_iter_next(&it))) {
  3904. if (unlikely(n == length))
  3905. break;
  3906. /* get tgid or pid for procs or tasks file respectively */
  3907. if (type == CGROUP_FILE_PROCS)
  3908. pid = task_tgid_vnr(tsk);
  3909. else
  3910. pid = task_pid_vnr(tsk);
  3911. if (pid > 0) /* make sure to only use valid results */
  3912. array[n++] = pid;
  3913. }
  3914. css_task_iter_end(&it);
  3915. length = n;
  3916. /* now sort & (if procs) strip out duplicates */
  3917. if (cgroup_on_dfl(cgrp))
  3918. sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
  3919. else
  3920. sort(array, length, sizeof(pid_t), cmppid, NULL);
  3921. if (type == CGROUP_FILE_PROCS)
  3922. length = pidlist_uniq(array, length);
  3923. l = cgroup_pidlist_find_create(cgrp, type);
  3924. if (!l) {
  3925. pidlist_free(array);
  3926. return -ENOMEM;
  3927. }
  3928. /* store array, freeing old if necessary */
  3929. pidlist_free(l->list);
  3930. l->list = array;
  3931. l->length = length;
  3932. *lp = l;
  3933. return 0;
  3934. }
  3935. /**
  3936. * cgroupstats_build - build and fill cgroupstats
  3937. * @stats: cgroupstats to fill information into
  3938. * @dentry: A dentry entry belonging to the cgroup for which stats have
  3939. * been requested.
  3940. *
  3941. * Build and fill cgroupstats so that taskstats can export it to user
  3942. * space.
  3943. */
  3944. int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
  3945. {
  3946. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  3947. struct cgroup *cgrp;
  3948. struct css_task_iter it;
  3949. struct task_struct *tsk;
  3950. /* it should be kernfs_node belonging to cgroupfs and is a directory */
  3951. if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
  3952. kernfs_type(kn) != KERNFS_DIR)
  3953. return -EINVAL;
  3954. mutex_lock(&cgroup_mutex);
  3955. /*
  3956. * We aren't being called from kernfs and there's no guarantee on
  3957. * @kn->priv's validity. For this and css_tryget_online_from_dir(),
  3958. * @kn->priv is RCU safe. Let's do the RCU dancing.
  3959. */
  3960. rcu_read_lock();
  3961. cgrp = rcu_dereference(kn->priv);
  3962. if (!cgrp || cgroup_is_dead(cgrp)) {
  3963. rcu_read_unlock();
  3964. mutex_unlock(&cgroup_mutex);
  3965. return -ENOENT;
  3966. }
  3967. rcu_read_unlock();
  3968. css_task_iter_start(&cgrp->self, &it);
  3969. while ((tsk = css_task_iter_next(&it))) {
  3970. switch (tsk->state) {
  3971. case TASK_RUNNING:
  3972. stats->nr_running++;
  3973. break;
  3974. case TASK_INTERRUPTIBLE:
  3975. stats->nr_sleeping++;
  3976. break;
  3977. case TASK_UNINTERRUPTIBLE:
  3978. stats->nr_uninterruptible++;
  3979. break;
  3980. case TASK_STOPPED:
  3981. stats->nr_stopped++;
  3982. break;
  3983. default:
  3984. if (delayacct_is_task_waiting_on_io(tsk))
  3985. stats->nr_io_wait++;
  3986. break;
  3987. }
  3988. }
  3989. css_task_iter_end(&it);
  3990. mutex_unlock(&cgroup_mutex);
  3991. return 0;
  3992. }
  3993. /*
  3994. * seq_file methods for the tasks/procs files. The seq_file position is the
  3995. * next pid to display; the seq_file iterator is a pointer to the pid
  3996. * in the cgroup->l->list array.
  3997. */
  3998. static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
  3999. {
  4000. /*
  4001. * Initially we receive a position value that corresponds to
  4002. * one more than the last pid shown (or 0 on the first call or
  4003. * after a seek to the start). Use a binary-search to find the
  4004. * next pid to display, if any
  4005. */
  4006. struct kernfs_open_file *of = s->private;
  4007. struct cgroup *cgrp = seq_css(s)->cgroup;
  4008. struct cgroup_pidlist *l;
  4009. enum cgroup_filetype type = seq_cft(s)->private;
  4010. int index = 0, pid = *pos;
  4011. int *iter, ret;
  4012. mutex_lock(&cgrp->pidlist_mutex);
  4013. /*
  4014. * !NULL @of->priv indicates that this isn't the first start()
  4015. * after open. If the matching pidlist is around, we can use that.
  4016. * Look for it. Note that @of->priv can't be used directly. It
  4017. * could already have been destroyed.
  4018. */
  4019. if (of->priv)
  4020. of->priv = cgroup_pidlist_find(cgrp, type);
  4021. /*
  4022. * Either this is the first start() after open or the matching
  4023. * pidlist has been destroyed inbetween. Create a new one.
  4024. */
  4025. if (!of->priv) {
  4026. ret = pidlist_array_load(cgrp, type,
  4027. (struct cgroup_pidlist **)&of->priv);
  4028. if (ret)
  4029. return ERR_PTR(ret);
  4030. }
  4031. l = of->priv;
  4032. if (pid) {
  4033. int end = l->length;
  4034. while (index < end) {
  4035. int mid = (index + end) / 2;
  4036. if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
  4037. index = mid;
  4038. break;
  4039. } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
  4040. index = mid + 1;
  4041. else
  4042. end = mid;
  4043. }
  4044. }
  4045. /* If we're off the end of the array, we're done */
  4046. if (index >= l->length)
  4047. return NULL;
  4048. /* Update the abstract position to be the actual pid that we found */
  4049. iter = l->list + index;
  4050. *pos = cgroup_pid_fry(cgrp, *iter);
  4051. return iter;
  4052. }
  4053. static void cgroup_pidlist_stop(struct seq_file *s, void *v)
  4054. {
  4055. struct kernfs_open_file *of = s->private;
  4056. struct cgroup_pidlist *l = of->priv;
  4057. if (l)
  4058. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
  4059. CGROUP_PIDLIST_DESTROY_DELAY);
  4060. mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
  4061. }
  4062. static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
  4063. {
  4064. struct kernfs_open_file *of = s->private;
  4065. struct cgroup_pidlist *l = of->priv;
  4066. pid_t *p = v;
  4067. pid_t *end = l->list + l->length;
  4068. /*
  4069. * Advance to the next pid in the array. If this goes off the
  4070. * end, we're done
  4071. */
  4072. p++;
  4073. if (p >= end) {
  4074. return NULL;
  4075. } else {
  4076. *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
  4077. return p;
  4078. }
  4079. }
  4080. static int cgroup_pidlist_show(struct seq_file *s, void *v)
  4081. {
  4082. seq_printf(s, "%d\n", *(int *)v);
  4083. return 0;
  4084. }
  4085. static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
  4086. struct cftype *cft)
  4087. {
  4088. return notify_on_release(css->cgroup);
  4089. }
  4090. static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
  4091. struct cftype *cft, u64 val)
  4092. {
  4093. if (val)
  4094. set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  4095. else
  4096. clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  4097. return 0;
  4098. }
  4099. static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
  4100. struct cftype *cft)
  4101. {
  4102. return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4103. }
  4104. static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
  4105. struct cftype *cft, u64 val)
  4106. {
  4107. if (val)
  4108. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4109. else
  4110. clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  4111. return 0;
  4112. }
  4113. /* cgroup core interface files for the default hierarchy */
  4114. static struct cftype cgroup_dfl_base_files[] = {
  4115. {
  4116. .name = "cgroup.procs",
  4117. .file_offset = offsetof(struct cgroup, procs_file),
  4118. .seq_start = cgroup_pidlist_start,
  4119. .seq_next = cgroup_pidlist_next,
  4120. .seq_stop = cgroup_pidlist_stop,
  4121. .seq_show = cgroup_pidlist_show,
  4122. .private = CGROUP_FILE_PROCS,
  4123. .write = cgroup_procs_write,
  4124. },
  4125. {
  4126. .name = "cgroup.controllers",
  4127. .seq_show = cgroup_controllers_show,
  4128. },
  4129. {
  4130. .name = "cgroup.subtree_control",
  4131. .seq_show = cgroup_subtree_control_show,
  4132. .write = cgroup_subtree_control_write,
  4133. },
  4134. {
  4135. .name = "cgroup.events",
  4136. .flags = CFTYPE_NOT_ON_ROOT,
  4137. .file_offset = offsetof(struct cgroup, events_file),
  4138. .seq_show = cgroup_events_show,
  4139. },
  4140. { } /* terminate */
  4141. };
  4142. /* cgroup core interface files for the legacy hierarchies */
  4143. static struct cftype cgroup_legacy_base_files[] = {
  4144. {
  4145. .name = "cgroup.procs",
  4146. .seq_start = cgroup_pidlist_start,
  4147. .seq_next = cgroup_pidlist_next,
  4148. .seq_stop = cgroup_pidlist_stop,
  4149. .seq_show = cgroup_pidlist_show,
  4150. .private = CGROUP_FILE_PROCS,
  4151. .write = cgroup_procs_write,
  4152. },
  4153. {
  4154. .name = "cgroup.clone_children",
  4155. .read_u64 = cgroup_clone_children_read,
  4156. .write_u64 = cgroup_clone_children_write,
  4157. },
  4158. {
  4159. .name = "cgroup.sane_behavior",
  4160. .flags = CFTYPE_ONLY_ON_ROOT,
  4161. .seq_show = cgroup_sane_behavior_show,
  4162. },
  4163. {
  4164. .name = "tasks",
  4165. .seq_start = cgroup_pidlist_start,
  4166. .seq_next = cgroup_pidlist_next,
  4167. .seq_stop = cgroup_pidlist_stop,
  4168. .seq_show = cgroup_pidlist_show,
  4169. .private = CGROUP_FILE_TASKS,
  4170. .write = cgroup_tasks_write,
  4171. },
  4172. {
  4173. .name = "notify_on_release",
  4174. .read_u64 = cgroup_read_notify_on_release,
  4175. .write_u64 = cgroup_write_notify_on_release,
  4176. },
  4177. {
  4178. .name = "release_agent",
  4179. .flags = CFTYPE_ONLY_ON_ROOT,
  4180. .seq_show = cgroup_release_agent_show,
  4181. .write = cgroup_release_agent_write,
  4182. .max_write_len = PATH_MAX - 1,
  4183. },
  4184. { } /* terminate */
  4185. };
  4186. /*
  4187. * css destruction is four-stage process.
  4188. *
  4189. * 1. Destruction starts. Killing of the percpu_ref is initiated.
  4190. * Implemented in kill_css().
  4191. *
  4192. * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
  4193. * and thus css_tryget_online() is guaranteed to fail, the css can be
  4194. * offlined by invoking offline_css(). After offlining, the base ref is
  4195. * put. Implemented in css_killed_work_fn().
  4196. *
  4197. * 3. When the percpu_ref reaches zero, the only possible remaining
  4198. * accessors are inside RCU read sections. css_release() schedules the
  4199. * RCU callback.
  4200. *
  4201. * 4. After the grace period, the css can be freed. Implemented in
  4202. * css_free_work_fn().
  4203. *
  4204. * It is actually hairier because both step 2 and 4 require process context
  4205. * and thus involve punting to css->destroy_work adding two additional
  4206. * steps to the already complex sequence.
  4207. */
  4208. static void css_free_work_fn(struct work_struct *work)
  4209. {
  4210. struct cgroup_subsys_state *css =
  4211. container_of(work, struct cgroup_subsys_state, destroy_work);
  4212. struct cgroup_subsys *ss = css->ss;
  4213. struct cgroup *cgrp = css->cgroup;
  4214. percpu_ref_exit(&css->refcnt);
  4215. if (ss) {
  4216. /* css free path */
  4217. struct cgroup_subsys_state *parent = css->parent;
  4218. int id = css->id;
  4219. ss->css_free(css);
  4220. cgroup_idr_remove(&ss->css_idr, id);
  4221. cgroup_put(cgrp);
  4222. if (parent)
  4223. css_put(parent);
  4224. } else {
  4225. /* cgroup free path */
  4226. atomic_dec(&cgrp->root->nr_cgrps);
  4227. cgroup_pidlist_destroy_all(cgrp);
  4228. cancel_work_sync(&cgrp->release_agent_work);
  4229. if (cgroup_parent(cgrp)) {
  4230. /*
  4231. * We get a ref to the parent, and put the ref when
  4232. * this cgroup is being freed, so it's guaranteed
  4233. * that the parent won't be destroyed before its
  4234. * children.
  4235. */
  4236. cgroup_put(cgroup_parent(cgrp));
  4237. kernfs_put(cgrp->kn);
  4238. kfree(cgrp);
  4239. } else {
  4240. /*
  4241. * This is root cgroup's refcnt reaching zero,
  4242. * which indicates that the root should be
  4243. * released.
  4244. */
  4245. cgroup_destroy_root(cgrp->root);
  4246. }
  4247. }
  4248. }
  4249. static void css_free_rcu_fn(struct rcu_head *rcu_head)
  4250. {
  4251. struct cgroup_subsys_state *css =
  4252. container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
  4253. INIT_WORK(&css->destroy_work, css_free_work_fn);
  4254. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4255. }
  4256. static void css_release_work_fn(struct work_struct *work)
  4257. {
  4258. struct cgroup_subsys_state *css =
  4259. container_of(work, struct cgroup_subsys_state, destroy_work);
  4260. struct cgroup_subsys *ss = css->ss;
  4261. struct cgroup *cgrp = css->cgroup;
  4262. mutex_lock(&cgroup_mutex);
  4263. css->flags |= CSS_RELEASED;
  4264. list_del_rcu(&css->sibling);
  4265. if (ss) {
  4266. /* css release path */
  4267. cgroup_idr_replace(&ss->css_idr, NULL, css->id);
  4268. if (ss->css_released)
  4269. ss->css_released(css);
  4270. } else {
  4271. /* cgroup release path */
  4272. cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
  4273. cgrp->id = -1;
  4274. /*
  4275. * There are two control paths which try to determine
  4276. * cgroup from dentry without going through kernfs -
  4277. * cgroupstats_build() and css_tryget_online_from_dir().
  4278. * Those are supported by RCU protecting clearing of
  4279. * cgrp->kn->priv backpointer.
  4280. */
  4281. if (cgrp->kn)
  4282. RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
  4283. NULL);
  4284. }
  4285. mutex_unlock(&cgroup_mutex);
  4286. call_rcu(&css->rcu_head, css_free_rcu_fn);
  4287. }
  4288. static void css_release(struct percpu_ref *ref)
  4289. {
  4290. struct cgroup_subsys_state *css =
  4291. container_of(ref, struct cgroup_subsys_state, refcnt);
  4292. INIT_WORK(&css->destroy_work, css_release_work_fn);
  4293. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4294. }
  4295. static void init_and_link_css(struct cgroup_subsys_state *css,
  4296. struct cgroup_subsys *ss, struct cgroup *cgrp)
  4297. {
  4298. lockdep_assert_held(&cgroup_mutex);
  4299. cgroup_get(cgrp);
  4300. memset(css, 0, sizeof(*css));
  4301. css->cgroup = cgrp;
  4302. css->ss = ss;
  4303. INIT_LIST_HEAD(&css->sibling);
  4304. INIT_LIST_HEAD(&css->children);
  4305. css->serial_nr = css_serial_nr_next++;
  4306. atomic_set(&css->online_cnt, 0);
  4307. if (cgroup_parent(cgrp)) {
  4308. css->parent = cgroup_css(cgroup_parent(cgrp), ss);
  4309. css_get(css->parent);
  4310. }
  4311. BUG_ON(cgroup_css(cgrp, ss));
  4312. }
  4313. /* invoke ->css_online() on a new CSS and mark it online if successful */
  4314. static int online_css(struct cgroup_subsys_state *css)
  4315. {
  4316. struct cgroup_subsys *ss = css->ss;
  4317. int ret = 0;
  4318. lockdep_assert_held(&cgroup_mutex);
  4319. if (ss->css_online)
  4320. ret = ss->css_online(css);
  4321. if (!ret) {
  4322. css->flags |= CSS_ONLINE;
  4323. rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
  4324. atomic_inc(&css->online_cnt);
  4325. if (css->parent)
  4326. atomic_inc(&css->parent->online_cnt);
  4327. }
  4328. return ret;
  4329. }
  4330. /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
  4331. static void offline_css(struct cgroup_subsys_state *css)
  4332. {
  4333. struct cgroup_subsys *ss = css->ss;
  4334. lockdep_assert_held(&cgroup_mutex);
  4335. if (!(css->flags & CSS_ONLINE))
  4336. return;
  4337. if (ss->css_reset)
  4338. ss->css_reset(css);
  4339. if (ss->css_offline)
  4340. ss->css_offline(css);
  4341. css->flags &= ~CSS_ONLINE;
  4342. RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
  4343. wake_up_all(&css->cgroup->offline_waitq);
  4344. }
  4345. /**
  4346. * css_create - create a cgroup_subsys_state
  4347. * @cgrp: the cgroup new css will be associated with
  4348. * @ss: the subsys of new css
  4349. *
  4350. * Create a new css associated with @cgrp - @ss pair. On success, the new
  4351. * css is online and installed in @cgrp. This function doesn't create the
  4352. * interface files. Returns 0 on success, -errno on failure.
  4353. */
  4354. static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
  4355. struct cgroup_subsys *ss)
  4356. {
  4357. struct cgroup *parent = cgroup_parent(cgrp);
  4358. struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
  4359. struct cgroup_subsys_state *css;
  4360. int err;
  4361. lockdep_assert_held(&cgroup_mutex);
  4362. css = ss->css_alloc(parent_css);
  4363. if (IS_ERR(css))
  4364. return css;
  4365. init_and_link_css(css, ss, cgrp);
  4366. err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
  4367. if (err)
  4368. goto err_free_css;
  4369. err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
  4370. if (err < 0)
  4371. goto err_free_percpu_ref;
  4372. css->id = err;
  4373. /* @css is ready to be brought online now, make it visible */
  4374. list_add_tail_rcu(&css->sibling, &parent_css->children);
  4375. cgroup_idr_replace(&ss->css_idr, css, css->id);
  4376. err = online_css(css);
  4377. if (err)
  4378. goto err_list_del;
  4379. if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
  4380. cgroup_parent(parent)) {
  4381. pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
  4382. current->comm, current->pid, ss->name);
  4383. if (!strcmp(ss->name, "memory"))
  4384. pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
  4385. ss->warned_broken_hierarchy = true;
  4386. }
  4387. return css;
  4388. err_list_del:
  4389. list_del_rcu(&css->sibling);
  4390. cgroup_idr_remove(&ss->css_idr, css->id);
  4391. err_free_percpu_ref:
  4392. percpu_ref_exit(&css->refcnt);
  4393. err_free_css:
  4394. call_rcu(&css->rcu_head, css_free_rcu_fn);
  4395. return ERR_PTR(err);
  4396. }
  4397. static struct cgroup *cgroup_create(struct cgroup *parent)
  4398. {
  4399. struct cgroup_root *root = parent->root;
  4400. struct cgroup *cgrp, *tcgrp;
  4401. int level = parent->level + 1;
  4402. int ret;
  4403. /* allocate the cgroup and its ID, 0 is reserved for the root */
  4404. cgrp = kzalloc(sizeof(*cgrp) +
  4405. sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
  4406. if (!cgrp)
  4407. return ERR_PTR(-ENOMEM);
  4408. ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
  4409. if (ret)
  4410. goto out_free_cgrp;
  4411. /*
  4412. * Temporarily set the pointer to NULL, so idr_find() won't return
  4413. * a half-baked cgroup.
  4414. */
  4415. cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
  4416. if (cgrp->id < 0) {
  4417. ret = -ENOMEM;
  4418. goto out_cancel_ref;
  4419. }
  4420. init_cgroup_housekeeping(cgrp);
  4421. cgrp->self.parent = &parent->self;
  4422. cgrp->root = root;
  4423. cgrp->level = level;
  4424. for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp))
  4425. cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
  4426. if (notify_on_release(parent))
  4427. set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
  4428. if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
  4429. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
  4430. cgrp->self.serial_nr = css_serial_nr_next++;
  4431. /* allocation complete, commit to creation */
  4432. list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
  4433. atomic_inc(&root->nr_cgrps);
  4434. cgroup_get(parent);
  4435. /*
  4436. * @cgrp is now fully operational. If something fails after this
  4437. * point, it'll be released via the normal destruction path.
  4438. */
  4439. cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
  4440. /*
  4441. * On the default hierarchy, a child doesn't automatically inherit
  4442. * subtree_control from the parent. Each is configured manually.
  4443. */
  4444. if (!cgroup_on_dfl(cgrp))
  4445. cgrp->subtree_control = cgroup_control(cgrp);
  4446. cgroup_propagate_control(cgrp);
  4447. /* @cgrp doesn't have dir yet so the following will only create csses */
  4448. ret = cgroup_apply_control_enable(cgrp);
  4449. if (ret)
  4450. goto out_destroy;
  4451. return cgrp;
  4452. out_cancel_ref:
  4453. percpu_ref_exit(&cgrp->self.refcnt);
  4454. out_free_cgrp:
  4455. kfree(cgrp);
  4456. return ERR_PTR(ret);
  4457. out_destroy:
  4458. cgroup_destroy_locked(cgrp);
  4459. return ERR_PTR(ret);
  4460. }
  4461. static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
  4462. umode_t mode)
  4463. {
  4464. struct cgroup *parent, *cgrp;
  4465. struct kernfs_node *kn;
  4466. int ret;
  4467. /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
  4468. if (strchr(name, '\n'))
  4469. return -EINVAL;
  4470. parent = cgroup_kn_lock_live(parent_kn, false);
  4471. if (!parent)
  4472. return -ENODEV;
  4473. cgrp = cgroup_create(parent);
  4474. if (IS_ERR(cgrp)) {
  4475. ret = PTR_ERR(cgrp);
  4476. goto out_unlock;
  4477. }
  4478. /* create the directory */
  4479. kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
  4480. if (IS_ERR(kn)) {
  4481. ret = PTR_ERR(kn);
  4482. goto out_destroy;
  4483. }
  4484. cgrp->kn = kn;
  4485. /*
  4486. * This extra ref will be put in cgroup_free_fn() and guarantees
  4487. * that @cgrp->kn is always accessible.
  4488. */
  4489. kernfs_get(kn);
  4490. ret = cgroup_kn_set_ugid(kn);
  4491. if (ret)
  4492. goto out_destroy;
  4493. ret = css_populate_dir(&cgrp->self);
  4494. if (ret)
  4495. goto out_destroy;
  4496. ret = cgroup_apply_control_enable(cgrp);
  4497. if (ret)
  4498. goto out_destroy;
  4499. /* let's create and online css's */
  4500. kernfs_activate(kn);
  4501. ret = 0;
  4502. goto out_unlock;
  4503. out_destroy:
  4504. cgroup_destroy_locked(cgrp);
  4505. out_unlock:
  4506. cgroup_kn_unlock(parent_kn);
  4507. return ret;
  4508. }
  4509. /*
  4510. * This is called when the refcnt of a css is confirmed to be killed.
  4511. * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
  4512. * initate destruction and put the css ref from kill_css().
  4513. */
  4514. static void css_killed_work_fn(struct work_struct *work)
  4515. {
  4516. struct cgroup_subsys_state *css =
  4517. container_of(work, struct cgroup_subsys_state, destroy_work);
  4518. mutex_lock(&cgroup_mutex);
  4519. do {
  4520. offline_css(css);
  4521. css_put(css);
  4522. /* @css can't go away while we're holding cgroup_mutex */
  4523. css = css->parent;
  4524. } while (css && atomic_dec_and_test(&css->online_cnt));
  4525. mutex_unlock(&cgroup_mutex);
  4526. }
  4527. /* css kill confirmation processing requires process context, bounce */
  4528. static void css_killed_ref_fn(struct percpu_ref *ref)
  4529. {
  4530. struct cgroup_subsys_state *css =
  4531. container_of(ref, struct cgroup_subsys_state, refcnt);
  4532. if (atomic_dec_and_test(&css->online_cnt)) {
  4533. INIT_WORK(&css->destroy_work, css_killed_work_fn);
  4534. queue_work(cgroup_destroy_wq, &css->destroy_work);
  4535. }
  4536. }
  4537. /**
  4538. * kill_css - destroy a css
  4539. * @css: css to destroy
  4540. *
  4541. * This function initiates destruction of @css by removing cgroup interface
  4542. * files and putting its base reference. ->css_offline() will be invoked
  4543. * asynchronously once css_tryget_online() is guaranteed to fail and when
  4544. * the reference count reaches zero, @css will be released.
  4545. */
  4546. static void kill_css(struct cgroup_subsys_state *css)
  4547. {
  4548. lockdep_assert_held(&cgroup_mutex);
  4549. /*
  4550. * This must happen before css is disassociated with its cgroup.
  4551. * See seq_css() for details.
  4552. */
  4553. css_clear_dir(css);
  4554. /*
  4555. * Killing would put the base ref, but we need to keep it alive
  4556. * until after ->css_offline().
  4557. */
  4558. css_get(css);
  4559. /*
  4560. * cgroup core guarantees that, by the time ->css_offline() is
  4561. * invoked, no new css reference will be given out via
  4562. * css_tryget_online(). We can't simply call percpu_ref_kill() and
  4563. * proceed to offlining css's because percpu_ref_kill() doesn't
  4564. * guarantee that the ref is seen as killed on all CPUs on return.
  4565. *
  4566. * Use percpu_ref_kill_and_confirm() to get notifications as each
  4567. * css is confirmed to be seen as killed on all CPUs.
  4568. */
  4569. percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
  4570. }
  4571. /**
  4572. * cgroup_destroy_locked - the first stage of cgroup destruction
  4573. * @cgrp: cgroup to be destroyed
  4574. *
  4575. * css's make use of percpu refcnts whose killing latency shouldn't be
  4576. * exposed to userland and are RCU protected. Also, cgroup core needs to
  4577. * guarantee that css_tryget_online() won't succeed by the time
  4578. * ->css_offline() is invoked. To satisfy all the requirements,
  4579. * destruction is implemented in the following two steps.
  4580. *
  4581. * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
  4582. * userland visible parts and start killing the percpu refcnts of
  4583. * css's. Set up so that the next stage will be kicked off once all
  4584. * the percpu refcnts are confirmed to be killed.
  4585. *
  4586. * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
  4587. * rest of destruction. Once all cgroup references are gone, the
  4588. * cgroup is RCU-freed.
  4589. *
  4590. * This function implements s1. After this step, @cgrp is gone as far as
  4591. * the userland is concerned and a new cgroup with the same name may be
  4592. * created. As cgroup doesn't care about the names internally, this
  4593. * doesn't cause any problem.
  4594. */
  4595. static int cgroup_destroy_locked(struct cgroup *cgrp)
  4596. __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
  4597. {
  4598. struct cgroup_subsys_state *css;
  4599. struct cgrp_cset_link *link;
  4600. int ssid;
  4601. lockdep_assert_held(&cgroup_mutex);
  4602. /*
  4603. * Only migration can raise populated from zero and we're already
  4604. * holding cgroup_mutex.
  4605. */
  4606. if (cgroup_is_populated(cgrp))
  4607. return -EBUSY;
  4608. /*
  4609. * Make sure there's no live children. We can't test emptiness of
  4610. * ->self.children as dead children linger on it while being
  4611. * drained; otherwise, "rmdir parent/child parent" may fail.
  4612. */
  4613. if (css_has_online_children(&cgrp->self))
  4614. return -EBUSY;
  4615. /*
  4616. * Mark @cgrp and the associated csets dead. The former prevents
  4617. * further task migration and child creation by disabling
  4618. * cgroup_lock_live_group(). The latter makes the csets ignored by
  4619. * the migration path.
  4620. */
  4621. cgrp->self.flags &= ~CSS_ONLINE;
  4622. spin_lock_bh(&css_set_lock);
  4623. list_for_each_entry(link, &cgrp->cset_links, cset_link)
  4624. link->cset->dead = true;
  4625. spin_unlock_bh(&css_set_lock);
  4626. /* initiate massacre of all css's */
  4627. for_each_css(css, ssid, cgrp)
  4628. kill_css(css);
  4629. /*
  4630. * Remove @cgrp directory along with the base files. @cgrp has an
  4631. * extra ref on its kn.
  4632. */
  4633. kernfs_remove(cgrp->kn);
  4634. check_for_release(cgroup_parent(cgrp));
  4635. /* put the base reference */
  4636. percpu_ref_kill(&cgrp->self.refcnt);
  4637. return 0;
  4638. };
  4639. static int cgroup_rmdir(struct kernfs_node *kn)
  4640. {
  4641. struct cgroup *cgrp;
  4642. int ret = 0;
  4643. cgrp = cgroup_kn_lock_live(kn, false);
  4644. if (!cgrp)
  4645. return 0;
  4646. ret = cgroup_destroy_locked(cgrp);
  4647. cgroup_kn_unlock(kn);
  4648. return ret;
  4649. }
  4650. static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
  4651. .remount_fs = cgroup_remount,
  4652. .show_options = cgroup_show_options,
  4653. .mkdir = cgroup_mkdir,
  4654. .rmdir = cgroup_rmdir,
  4655. .rename = cgroup_rename,
  4656. };
  4657. static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
  4658. {
  4659. struct cgroup_subsys_state *css;
  4660. pr_debug("Initializing cgroup subsys %s\n", ss->name);
  4661. mutex_lock(&cgroup_mutex);
  4662. idr_init(&ss->css_idr);
  4663. INIT_LIST_HEAD(&ss->cfts);
  4664. /* Create the root cgroup state for this subsystem */
  4665. ss->root = &cgrp_dfl_root;
  4666. css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
  4667. /* We don't handle early failures gracefully */
  4668. BUG_ON(IS_ERR(css));
  4669. init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
  4670. /*
  4671. * Root csses are never destroyed and we can't initialize
  4672. * percpu_ref during early init. Disable refcnting.
  4673. */
  4674. css->flags |= CSS_NO_REF;
  4675. if (early) {
  4676. /* allocation can't be done safely during early init */
  4677. css->id = 1;
  4678. } else {
  4679. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
  4680. BUG_ON(css->id < 0);
  4681. }
  4682. /* Update the init_css_set to contain a subsys
  4683. * pointer to this state - since the subsystem is
  4684. * newly registered, all tasks and hence the
  4685. * init_css_set is in the subsystem's root cgroup. */
  4686. init_css_set.subsys[ss->id] = css;
  4687. have_fork_callback |= (bool)ss->fork << ss->id;
  4688. have_exit_callback |= (bool)ss->exit << ss->id;
  4689. have_free_callback |= (bool)ss->free << ss->id;
  4690. have_canfork_callback |= (bool)ss->can_fork << ss->id;
  4691. /* At system boot, before all subsystems have been
  4692. * registered, no tasks have been forked, so we don't
  4693. * need to invoke fork callbacks here. */
  4694. BUG_ON(!list_empty(&init_task.tasks));
  4695. BUG_ON(online_css(css));
  4696. mutex_unlock(&cgroup_mutex);
  4697. }
  4698. /**
  4699. * cgroup_init_early - cgroup initialization at system boot
  4700. *
  4701. * Initialize cgroups at system boot, and initialize any
  4702. * subsystems that request early init.
  4703. */
  4704. int __init cgroup_init_early(void)
  4705. {
  4706. static struct cgroup_sb_opts __initdata opts;
  4707. struct cgroup_subsys *ss;
  4708. int i;
  4709. init_cgroup_root(&cgrp_dfl_root, &opts);
  4710. cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
  4711. RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
  4712. for_each_subsys(ss, i) {
  4713. WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
  4714. "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
  4715. i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
  4716. ss->id, ss->name);
  4717. WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
  4718. "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
  4719. ss->id = i;
  4720. ss->name = cgroup_subsys_name[i];
  4721. if (!ss->legacy_name)
  4722. ss->legacy_name = cgroup_subsys_name[i];
  4723. if (ss->early_init)
  4724. cgroup_init_subsys(ss, true);
  4725. }
  4726. return 0;
  4727. }
  4728. static u16 cgroup_disable_mask __initdata;
  4729. /**
  4730. * cgroup_init - cgroup initialization
  4731. *
  4732. * Register cgroup filesystem and /proc file, and initialize
  4733. * any subsystems that didn't request early init.
  4734. */
  4735. int __init cgroup_init(void)
  4736. {
  4737. struct cgroup_subsys *ss;
  4738. int ssid;
  4739. BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
  4740. BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
  4741. BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
  4742. BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
  4743. get_user_ns(init_cgroup_ns.user_ns);
  4744. mutex_lock(&cgroup_mutex);
  4745. /*
  4746. * Add init_css_set to the hash table so that dfl_root can link to
  4747. * it during init.
  4748. */
  4749. hash_add(css_set_table, &init_css_set.hlist,
  4750. css_set_hash(init_css_set.subsys));
  4751. BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
  4752. mutex_unlock(&cgroup_mutex);
  4753. for_each_subsys(ss, ssid) {
  4754. if (ss->early_init) {
  4755. struct cgroup_subsys_state *css =
  4756. init_css_set.subsys[ss->id];
  4757. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
  4758. GFP_KERNEL);
  4759. BUG_ON(css->id < 0);
  4760. } else {
  4761. cgroup_init_subsys(ss, false);
  4762. }
  4763. list_add_tail(&init_css_set.e_cset_node[ssid],
  4764. &cgrp_dfl_root.cgrp.e_csets[ssid]);
  4765. /*
  4766. * Setting dfl_root subsys_mask needs to consider the
  4767. * disabled flag and cftype registration needs kmalloc,
  4768. * both of which aren't available during early_init.
  4769. */
  4770. if (cgroup_disable_mask & (1 << ssid)) {
  4771. static_branch_disable(cgroup_subsys_enabled_key[ssid]);
  4772. printk(KERN_INFO "Disabling %s control group subsystem\n",
  4773. ss->name);
  4774. continue;
  4775. }
  4776. if (cgroup_ssid_no_v1(ssid))
  4777. printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
  4778. ss->name);
  4779. cgrp_dfl_root.subsys_mask |= 1 << ss->id;
  4780. if (ss->implicit_on_dfl)
  4781. cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
  4782. else if (!ss->dfl_cftypes)
  4783. cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
  4784. if (ss->dfl_cftypes == ss->legacy_cftypes) {
  4785. WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
  4786. } else {
  4787. WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
  4788. WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
  4789. }
  4790. if (ss->bind)
  4791. ss->bind(init_css_set.subsys[ssid]);
  4792. }
  4793. /* init_css_set.subsys[] has been updated, re-hash */
  4794. hash_del(&init_css_set.hlist);
  4795. hash_add(css_set_table, &init_css_set.hlist,
  4796. css_set_hash(init_css_set.subsys));
  4797. WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
  4798. WARN_ON(register_filesystem(&cgroup_fs_type));
  4799. WARN_ON(register_filesystem(&cgroup2_fs_type));
  4800. WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
  4801. return 0;
  4802. }
  4803. static int __init cgroup_wq_init(void)
  4804. {
  4805. /*
  4806. * There isn't much point in executing destruction path in
  4807. * parallel. Good chunk is serialized with cgroup_mutex anyway.
  4808. * Use 1 for @max_active.
  4809. *
  4810. * We would prefer to do this in cgroup_init() above, but that
  4811. * is called before init_workqueues(): so leave this until after.
  4812. */
  4813. cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
  4814. BUG_ON(!cgroup_destroy_wq);
  4815. /*
  4816. * Used to destroy pidlists and separate to serve as flush domain.
  4817. * Cap @max_active to 1 too.
  4818. */
  4819. cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
  4820. 0, 1);
  4821. BUG_ON(!cgroup_pidlist_destroy_wq);
  4822. return 0;
  4823. }
  4824. core_initcall(cgroup_wq_init);
  4825. /*
  4826. * proc_cgroup_show()
  4827. * - Print task's cgroup paths into seq_file, one line for each hierarchy
  4828. * - Used for /proc/<pid>/cgroup.
  4829. */
  4830. int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
  4831. struct pid *pid, struct task_struct *tsk)
  4832. {
  4833. char *buf, *path;
  4834. int retval;
  4835. struct cgroup_root *root;
  4836. retval = -ENOMEM;
  4837. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  4838. if (!buf)
  4839. goto out;
  4840. mutex_lock(&cgroup_mutex);
  4841. spin_lock_bh(&css_set_lock);
  4842. for_each_root(root) {
  4843. struct cgroup_subsys *ss;
  4844. struct cgroup *cgrp;
  4845. int ssid, count = 0;
  4846. if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
  4847. continue;
  4848. seq_printf(m, "%d:", root->hierarchy_id);
  4849. if (root != &cgrp_dfl_root)
  4850. for_each_subsys(ss, ssid)
  4851. if (root->subsys_mask & (1 << ssid))
  4852. seq_printf(m, "%s%s", count++ ? "," : "",
  4853. ss->legacy_name);
  4854. if (strlen(root->name))
  4855. seq_printf(m, "%sname=%s", count ? "," : "",
  4856. root->name);
  4857. seq_putc(m, ':');
  4858. cgrp = task_cgroup_from_root(tsk, root);
  4859. /*
  4860. * On traditional hierarchies, all zombie tasks show up as
  4861. * belonging to the root cgroup. On the default hierarchy,
  4862. * while a zombie doesn't show up in "cgroup.procs" and
  4863. * thus can't be migrated, its /proc/PID/cgroup keeps
  4864. * reporting the cgroup it belonged to before exiting. If
  4865. * the cgroup is removed before the zombie is reaped,
  4866. * " (deleted)" is appended to the cgroup path.
  4867. */
  4868. if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
  4869. path = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
  4870. current->nsproxy->cgroup_ns);
  4871. if (!path) {
  4872. retval = -ENAMETOOLONG;
  4873. goto out_unlock;
  4874. }
  4875. } else {
  4876. path = "/";
  4877. }
  4878. seq_puts(m, path);
  4879. if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
  4880. seq_puts(m, " (deleted)\n");
  4881. else
  4882. seq_putc(m, '\n');
  4883. }
  4884. retval = 0;
  4885. out_unlock:
  4886. spin_unlock_bh(&css_set_lock);
  4887. mutex_unlock(&cgroup_mutex);
  4888. kfree(buf);
  4889. out:
  4890. return retval;
  4891. }
  4892. /* Display information about each subsystem and each hierarchy */
  4893. static int proc_cgroupstats_show(struct seq_file *m, void *v)
  4894. {
  4895. struct cgroup_subsys *ss;
  4896. int i;
  4897. seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
  4898. /*
  4899. * ideally we don't want subsystems moving around while we do this.
  4900. * cgroup_mutex is also necessary to guarantee an atomic snapshot of
  4901. * subsys/hierarchy state.
  4902. */
  4903. mutex_lock(&cgroup_mutex);
  4904. for_each_subsys(ss, i)
  4905. seq_printf(m, "%s\t%d\t%d\t%d\n",
  4906. ss->legacy_name, ss->root->hierarchy_id,
  4907. atomic_read(&ss->root->nr_cgrps),
  4908. cgroup_ssid_enabled(i));
  4909. mutex_unlock(&cgroup_mutex);
  4910. return 0;
  4911. }
  4912. static int cgroupstats_open(struct inode *inode, struct file *file)
  4913. {
  4914. return single_open(file, proc_cgroupstats_show, NULL);
  4915. }
  4916. static const struct file_operations proc_cgroupstats_operations = {
  4917. .open = cgroupstats_open,
  4918. .read = seq_read,
  4919. .llseek = seq_lseek,
  4920. .release = single_release,
  4921. };
  4922. /**
  4923. * cgroup_fork - initialize cgroup related fields during copy_process()
  4924. * @child: pointer to task_struct of forking parent process.
  4925. *
  4926. * A task is associated with the init_css_set until cgroup_post_fork()
  4927. * attaches it to the parent's css_set. Empty cg_list indicates that
  4928. * @child isn't holding reference to its css_set.
  4929. */
  4930. void cgroup_fork(struct task_struct *child)
  4931. {
  4932. RCU_INIT_POINTER(child->cgroups, &init_css_set);
  4933. INIT_LIST_HEAD(&child->cg_list);
  4934. }
  4935. /**
  4936. * cgroup_can_fork - called on a new task before the process is exposed
  4937. * @child: the task in question.
  4938. *
  4939. * This calls the subsystem can_fork() callbacks. If the can_fork() callback
  4940. * returns an error, the fork aborts with that error code. This allows for
  4941. * a cgroup subsystem to conditionally allow or deny new forks.
  4942. */
  4943. int cgroup_can_fork(struct task_struct *child)
  4944. {
  4945. struct cgroup_subsys *ss;
  4946. int i, j, ret;
  4947. do_each_subsys_mask(ss, i, have_canfork_callback) {
  4948. ret = ss->can_fork(child);
  4949. if (ret)
  4950. goto out_revert;
  4951. } while_each_subsys_mask();
  4952. return 0;
  4953. out_revert:
  4954. for_each_subsys(ss, j) {
  4955. if (j >= i)
  4956. break;
  4957. if (ss->cancel_fork)
  4958. ss->cancel_fork(child);
  4959. }
  4960. return ret;
  4961. }
  4962. /**
  4963. * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
  4964. * @child: the task in question
  4965. *
  4966. * This calls the cancel_fork() callbacks if a fork failed *after*
  4967. * cgroup_can_fork() succeded.
  4968. */
  4969. void cgroup_cancel_fork(struct task_struct *child)
  4970. {
  4971. struct cgroup_subsys *ss;
  4972. int i;
  4973. for_each_subsys(ss, i)
  4974. if (ss->cancel_fork)
  4975. ss->cancel_fork(child);
  4976. }
  4977. /**
  4978. * cgroup_post_fork - called on a new task after adding it to the task list
  4979. * @child: the task in question
  4980. *
  4981. * Adds the task to the list running through its css_set if necessary and
  4982. * call the subsystem fork() callbacks. Has to be after the task is
  4983. * visible on the task list in case we race with the first call to
  4984. * cgroup_task_iter_start() - to guarantee that the new task ends up on its
  4985. * list.
  4986. */
  4987. void cgroup_post_fork(struct task_struct *child)
  4988. {
  4989. struct cgroup_subsys *ss;
  4990. int i;
  4991. /*
  4992. * This may race against cgroup_enable_task_cg_lists(). As that
  4993. * function sets use_task_css_set_links before grabbing
  4994. * tasklist_lock and we just went through tasklist_lock to add
  4995. * @child, it's guaranteed that either we see the set
  4996. * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
  4997. * @child during its iteration.
  4998. *
  4999. * If we won the race, @child is associated with %current's
  5000. * css_set. Grabbing css_set_lock guarantees both that the
  5001. * association is stable, and, on completion of the parent's
  5002. * migration, @child is visible in the source of migration or
  5003. * already in the destination cgroup. This guarantee is necessary
  5004. * when implementing operations which need to migrate all tasks of
  5005. * a cgroup to another.
  5006. *
  5007. * Note that if we lose to cgroup_enable_task_cg_lists(), @child
  5008. * will remain in init_css_set. This is safe because all tasks are
  5009. * in the init_css_set before cg_links is enabled and there's no
  5010. * operation which transfers all tasks out of init_css_set.
  5011. */
  5012. if (use_task_css_set_links) {
  5013. struct css_set *cset;
  5014. spin_lock_bh(&css_set_lock);
  5015. cset = task_css_set(current);
  5016. if (list_empty(&child->cg_list)) {
  5017. get_css_set(cset);
  5018. css_set_move_task(child, NULL, cset, false);
  5019. }
  5020. spin_unlock_bh(&css_set_lock);
  5021. }
  5022. /*
  5023. * Call ss->fork(). This must happen after @child is linked on
  5024. * css_set; otherwise, @child might change state between ->fork()
  5025. * and addition to css_set.
  5026. */
  5027. do_each_subsys_mask(ss, i, have_fork_callback) {
  5028. ss->fork(child);
  5029. } while_each_subsys_mask();
  5030. }
  5031. /**
  5032. * cgroup_exit - detach cgroup from exiting task
  5033. * @tsk: pointer to task_struct of exiting process
  5034. *
  5035. * Description: Detach cgroup from @tsk and release it.
  5036. *
  5037. * Note that cgroups marked notify_on_release force every task in
  5038. * them to take the global cgroup_mutex mutex when exiting.
  5039. * This could impact scaling on very large systems. Be reluctant to
  5040. * use notify_on_release cgroups where very high task exit scaling
  5041. * is required on large systems.
  5042. *
  5043. * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
  5044. * call cgroup_exit() while the task is still competent to handle
  5045. * notify_on_release(), then leave the task attached to the root cgroup in
  5046. * each hierarchy for the remainder of its exit. No need to bother with
  5047. * init_css_set refcnting. init_css_set never goes away and we can't race
  5048. * with migration path - PF_EXITING is visible to migration path.
  5049. */
  5050. void cgroup_exit(struct task_struct *tsk)
  5051. {
  5052. struct cgroup_subsys *ss;
  5053. struct css_set *cset;
  5054. int i;
  5055. /*
  5056. * Unlink from @tsk from its css_set. As migration path can't race
  5057. * with us, we can check css_set and cg_list without synchronization.
  5058. */
  5059. cset = task_css_set(tsk);
  5060. if (!list_empty(&tsk->cg_list)) {
  5061. spin_lock_bh(&css_set_lock);
  5062. css_set_move_task(tsk, cset, NULL, false);
  5063. spin_unlock_bh(&css_set_lock);
  5064. } else {
  5065. get_css_set(cset);
  5066. }
  5067. /* see cgroup_post_fork() for details */
  5068. do_each_subsys_mask(ss, i, have_exit_callback) {
  5069. ss->exit(tsk);
  5070. } while_each_subsys_mask();
  5071. }
  5072. void cgroup_free(struct task_struct *task)
  5073. {
  5074. struct css_set *cset = task_css_set(task);
  5075. struct cgroup_subsys *ss;
  5076. int ssid;
  5077. do_each_subsys_mask(ss, ssid, have_free_callback) {
  5078. ss->free(task);
  5079. } while_each_subsys_mask();
  5080. put_css_set(cset);
  5081. }
  5082. static void check_for_release(struct cgroup *cgrp)
  5083. {
  5084. if (notify_on_release(cgrp) && !cgroup_is_populated(cgrp) &&
  5085. !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
  5086. schedule_work(&cgrp->release_agent_work);
  5087. }
  5088. /*
  5089. * Notify userspace when a cgroup is released, by running the
  5090. * configured release agent with the name of the cgroup (path
  5091. * relative to the root of cgroup file system) as the argument.
  5092. *
  5093. * Most likely, this user command will try to rmdir this cgroup.
  5094. *
  5095. * This races with the possibility that some other task will be
  5096. * attached to this cgroup before it is removed, or that some other
  5097. * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
  5098. * The presumed 'rmdir' will fail quietly if this cgroup is no longer
  5099. * unused, and this cgroup will be reprieved from its death sentence,
  5100. * to continue to serve a useful existence. Next time it's released,
  5101. * we will get notified again, if it still has 'notify_on_release' set.
  5102. *
  5103. * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
  5104. * means only wait until the task is successfully execve()'d. The
  5105. * separate release agent task is forked by call_usermodehelper(),
  5106. * then control in this thread returns here, without waiting for the
  5107. * release agent task. We don't bother to wait because the caller of
  5108. * this routine has no use for the exit status of the release agent
  5109. * task, so no sense holding our caller up for that.
  5110. */
  5111. static void cgroup_release_agent(struct work_struct *work)
  5112. {
  5113. struct cgroup *cgrp =
  5114. container_of(work, struct cgroup, release_agent_work);
  5115. char *pathbuf = NULL, *agentbuf = NULL, *path;
  5116. char *argv[3], *envp[3];
  5117. mutex_lock(&cgroup_mutex);
  5118. pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
  5119. agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
  5120. if (!pathbuf || !agentbuf)
  5121. goto out;
  5122. spin_lock_bh(&css_set_lock);
  5123. path = cgroup_path_ns_locked(cgrp, pathbuf, PATH_MAX, &init_cgroup_ns);
  5124. spin_unlock_bh(&css_set_lock);
  5125. if (!path)
  5126. goto out;
  5127. argv[0] = agentbuf;
  5128. argv[1] = path;
  5129. argv[2] = NULL;
  5130. /* minimal command environment */
  5131. envp[0] = "HOME=/";
  5132. envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
  5133. envp[2] = NULL;
  5134. mutex_unlock(&cgroup_mutex);
  5135. call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
  5136. goto out_free;
  5137. out:
  5138. mutex_unlock(&cgroup_mutex);
  5139. out_free:
  5140. kfree(agentbuf);
  5141. kfree(pathbuf);
  5142. }
  5143. static int __init cgroup_disable(char *str)
  5144. {
  5145. struct cgroup_subsys *ss;
  5146. char *token;
  5147. int i;
  5148. while ((token = strsep(&str, ",")) != NULL) {
  5149. if (!*token)
  5150. continue;
  5151. for_each_subsys(ss, i) {
  5152. if (strcmp(token, ss->name) &&
  5153. strcmp(token, ss->legacy_name))
  5154. continue;
  5155. cgroup_disable_mask |= 1 << i;
  5156. }
  5157. }
  5158. return 1;
  5159. }
  5160. __setup("cgroup_disable=", cgroup_disable);
  5161. static int __init cgroup_no_v1(char *str)
  5162. {
  5163. struct cgroup_subsys *ss;
  5164. char *token;
  5165. int i;
  5166. while ((token = strsep(&str, ",")) != NULL) {
  5167. if (!*token)
  5168. continue;
  5169. if (!strcmp(token, "all")) {
  5170. cgroup_no_v1_mask = U16_MAX;
  5171. break;
  5172. }
  5173. for_each_subsys(ss, i) {
  5174. if (strcmp(token, ss->name) &&
  5175. strcmp(token, ss->legacy_name))
  5176. continue;
  5177. cgroup_no_v1_mask |= 1 << i;
  5178. }
  5179. }
  5180. return 1;
  5181. }
  5182. __setup("cgroup_no_v1=", cgroup_no_v1);
  5183. /**
  5184. * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
  5185. * @dentry: directory dentry of interest
  5186. * @ss: subsystem of interest
  5187. *
  5188. * If @dentry is a directory for a cgroup which has @ss enabled on it, try
  5189. * to get the corresponding css and return it. If such css doesn't exist
  5190. * or can't be pinned, an ERR_PTR value is returned.
  5191. */
  5192. struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
  5193. struct cgroup_subsys *ss)
  5194. {
  5195. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  5196. struct file_system_type *s_type = dentry->d_sb->s_type;
  5197. struct cgroup_subsys_state *css = NULL;
  5198. struct cgroup *cgrp;
  5199. /* is @dentry a cgroup dir? */
  5200. if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
  5201. !kn || kernfs_type(kn) != KERNFS_DIR)
  5202. return ERR_PTR(-EBADF);
  5203. rcu_read_lock();
  5204. /*
  5205. * This path doesn't originate from kernfs and @kn could already
  5206. * have been or be removed at any point. @kn->priv is RCU
  5207. * protected for this access. See css_release_work_fn() for details.
  5208. */
  5209. cgrp = rcu_dereference(kn->priv);
  5210. if (cgrp)
  5211. css = cgroup_css(cgrp, ss);
  5212. if (!css || !css_tryget_online(css))
  5213. css = ERR_PTR(-ENOENT);
  5214. rcu_read_unlock();
  5215. return css;
  5216. }
  5217. /**
  5218. * css_from_id - lookup css by id
  5219. * @id: the cgroup id
  5220. * @ss: cgroup subsys to be looked into
  5221. *
  5222. * Returns the css if there's valid one with @id, otherwise returns NULL.
  5223. * Should be called under rcu_read_lock().
  5224. */
  5225. struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
  5226. {
  5227. WARN_ON_ONCE(!rcu_read_lock_held());
  5228. return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
  5229. }
  5230. /**
  5231. * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
  5232. * @path: path on the default hierarchy
  5233. *
  5234. * Find the cgroup at @path on the default hierarchy, increment its
  5235. * reference count and return it. Returns pointer to the found cgroup on
  5236. * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
  5237. * if @path points to a non-directory.
  5238. */
  5239. struct cgroup *cgroup_get_from_path(const char *path)
  5240. {
  5241. struct kernfs_node *kn;
  5242. struct cgroup *cgrp;
  5243. mutex_lock(&cgroup_mutex);
  5244. kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
  5245. if (kn) {
  5246. if (kernfs_type(kn) == KERNFS_DIR) {
  5247. cgrp = kn->priv;
  5248. cgroup_get(cgrp);
  5249. } else {
  5250. cgrp = ERR_PTR(-ENOTDIR);
  5251. }
  5252. kernfs_put(kn);
  5253. } else {
  5254. cgrp = ERR_PTR(-ENOENT);
  5255. }
  5256. mutex_unlock(&cgroup_mutex);
  5257. return cgrp;
  5258. }
  5259. EXPORT_SYMBOL_GPL(cgroup_get_from_path);
  5260. /*
  5261. * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
  5262. * definition in cgroup-defs.h.
  5263. */
  5264. #ifdef CONFIG_SOCK_CGROUP_DATA
  5265. #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
  5266. DEFINE_SPINLOCK(cgroup_sk_update_lock);
  5267. static bool cgroup_sk_alloc_disabled __read_mostly;
  5268. void cgroup_sk_alloc_disable(void)
  5269. {
  5270. if (cgroup_sk_alloc_disabled)
  5271. return;
  5272. pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
  5273. cgroup_sk_alloc_disabled = true;
  5274. }
  5275. #else
  5276. #define cgroup_sk_alloc_disabled false
  5277. #endif
  5278. void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
  5279. {
  5280. if (cgroup_sk_alloc_disabled)
  5281. return;
  5282. rcu_read_lock();
  5283. while (true) {
  5284. struct css_set *cset;
  5285. cset = task_css_set(current);
  5286. if (likely(cgroup_tryget(cset->dfl_cgrp))) {
  5287. skcd->val = (unsigned long)cset->dfl_cgrp;
  5288. break;
  5289. }
  5290. cpu_relax();
  5291. }
  5292. rcu_read_unlock();
  5293. }
  5294. void cgroup_sk_free(struct sock_cgroup_data *skcd)
  5295. {
  5296. cgroup_put(sock_cgroup_ptr(skcd));
  5297. }
  5298. #endif /* CONFIG_SOCK_CGROUP_DATA */
  5299. /* cgroup namespaces */
  5300. static struct cgroup_namespace *alloc_cgroup_ns(void)
  5301. {
  5302. struct cgroup_namespace *new_ns;
  5303. int ret;
  5304. new_ns = kzalloc(sizeof(struct cgroup_namespace), GFP_KERNEL);
  5305. if (!new_ns)
  5306. return ERR_PTR(-ENOMEM);
  5307. ret = ns_alloc_inum(&new_ns->ns);
  5308. if (ret) {
  5309. kfree(new_ns);
  5310. return ERR_PTR(ret);
  5311. }
  5312. atomic_set(&new_ns->count, 1);
  5313. new_ns->ns.ops = &cgroupns_operations;
  5314. return new_ns;
  5315. }
  5316. void free_cgroup_ns(struct cgroup_namespace *ns)
  5317. {
  5318. put_css_set(ns->root_cset);
  5319. put_user_ns(ns->user_ns);
  5320. ns_free_inum(&ns->ns);
  5321. kfree(ns);
  5322. }
  5323. EXPORT_SYMBOL(free_cgroup_ns);
  5324. struct cgroup_namespace *copy_cgroup_ns(unsigned long flags,
  5325. struct user_namespace *user_ns,
  5326. struct cgroup_namespace *old_ns)
  5327. {
  5328. struct cgroup_namespace *new_ns;
  5329. struct css_set *cset;
  5330. BUG_ON(!old_ns);
  5331. if (!(flags & CLONE_NEWCGROUP)) {
  5332. get_cgroup_ns(old_ns);
  5333. return old_ns;
  5334. }
  5335. /* Allow only sysadmin to create cgroup namespace. */
  5336. if (!ns_capable(user_ns, CAP_SYS_ADMIN))
  5337. return ERR_PTR(-EPERM);
  5338. mutex_lock(&cgroup_mutex);
  5339. spin_lock_bh(&css_set_lock);
  5340. cset = task_css_set(current);
  5341. get_css_set(cset);
  5342. spin_unlock_bh(&css_set_lock);
  5343. mutex_unlock(&cgroup_mutex);
  5344. new_ns = alloc_cgroup_ns();
  5345. if (IS_ERR(new_ns)) {
  5346. put_css_set(cset);
  5347. return new_ns;
  5348. }
  5349. new_ns->user_ns = get_user_ns(user_ns);
  5350. new_ns->root_cset = cset;
  5351. return new_ns;
  5352. }
  5353. static inline struct cgroup_namespace *to_cg_ns(struct ns_common *ns)
  5354. {
  5355. return container_of(ns, struct cgroup_namespace, ns);
  5356. }
  5357. static int cgroupns_install(struct nsproxy *nsproxy, struct ns_common *ns)
  5358. {
  5359. struct cgroup_namespace *cgroup_ns = to_cg_ns(ns);
  5360. if (!ns_capable(current_user_ns(), CAP_SYS_ADMIN) ||
  5361. !ns_capable(cgroup_ns->user_ns, CAP_SYS_ADMIN))
  5362. return -EPERM;
  5363. /* Don't need to do anything if we are attaching to our own cgroupns. */
  5364. if (cgroup_ns == nsproxy->cgroup_ns)
  5365. return 0;
  5366. get_cgroup_ns(cgroup_ns);
  5367. put_cgroup_ns(nsproxy->cgroup_ns);
  5368. nsproxy->cgroup_ns = cgroup_ns;
  5369. return 0;
  5370. }
  5371. static struct ns_common *cgroupns_get(struct task_struct *task)
  5372. {
  5373. struct cgroup_namespace *ns = NULL;
  5374. struct nsproxy *nsproxy;
  5375. task_lock(task);
  5376. nsproxy = task->nsproxy;
  5377. if (nsproxy) {
  5378. ns = nsproxy->cgroup_ns;
  5379. get_cgroup_ns(ns);
  5380. }
  5381. task_unlock(task);
  5382. return ns ? &ns->ns : NULL;
  5383. }
  5384. static void cgroupns_put(struct ns_common *ns)
  5385. {
  5386. put_cgroup_ns(to_cg_ns(ns));
  5387. }
  5388. const struct proc_ns_operations cgroupns_operations = {
  5389. .name = "cgroup",
  5390. .type = CLONE_NEWCGROUP,
  5391. .get = cgroupns_get,
  5392. .put = cgroupns_put,
  5393. .install = cgroupns_install,
  5394. };
  5395. static __init int cgroup_namespaces_init(void)
  5396. {
  5397. return 0;
  5398. }
  5399. subsys_initcall(cgroup_namespaces_init);
  5400. #ifdef CONFIG_CGROUP_DEBUG
  5401. static struct cgroup_subsys_state *
  5402. debug_css_alloc(struct cgroup_subsys_state *parent_css)
  5403. {
  5404. struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
  5405. if (!css)
  5406. return ERR_PTR(-ENOMEM);
  5407. return css;
  5408. }
  5409. static void debug_css_free(struct cgroup_subsys_state *css)
  5410. {
  5411. kfree(css);
  5412. }
  5413. static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
  5414. struct cftype *cft)
  5415. {
  5416. return cgroup_task_count(css->cgroup);
  5417. }
  5418. static u64 current_css_set_read(struct cgroup_subsys_state *css,
  5419. struct cftype *cft)
  5420. {
  5421. return (u64)(unsigned long)current->cgroups;
  5422. }
  5423. static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
  5424. struct cftype *cft)
  5425. {
  5426. u64 count;
  5427. rcu_read_lock();
  5428. count = atomic_read(&task_css_set(current)->refcount);
  5429. rcu_read_unlock();
  5430. return count;
  5431. }
  5432. static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
  5433. {
  5434. struct cgrp_cset_link *link;
  5435. struct css_set *cset;
  5436. char *name_buf;
  5437. name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
  5438. if (!name_buf)
  5439. return -ENOMEM;
  5440. spin_lock_bh(&css_set_lock);
  5441. rcu_read_lock();
  5442. cset = rcu_dereference(current->cgroups);
  5443. list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
  5444. struct cgroup *c = link->cgrp;
  5445. cgroup_name(c, name_buf, NAME_MAX + 1);
  5446. seq_printf(seq, "Root %d group %s\n",
  5447. c->root->hierarchy_id, name_buf);
  5448. }
  5449. rcu_read_unlock();
  5450. spin_unlock_bh(&css_set_lock);
  5451. kfree(name_buf);
  5452. return 0;
  5453. }
  5454. #define MAX_TASKS_SHOWN_PER_CSS 25
  5455. static int cgroup_css_links_read(struct seq_file *seq, void *v)
  5456. {
  5457. struct cgroup_subsys_state *css = seq_css(seq);
  5458. struct cgrp_cset_link *link;
  5459. spin_lock_bh(&css_set_lock);
  5460. list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
  5461. struct css_set *cset = link->cset;
  5462. struct task_struct *task;
  5463. int count = 0;
  5464. seq_printf(seq, "css_set %p\n", cset);
  5465. list_for_each_entry(task, &cset->tasks, cg_list) {
  5466. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  5467. goto overflow;
  5468. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  5469. }
  5470. list_for_each_entry(task, &cset->mg_tasks, cg_list) {
  5471. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  5472. goto overflow;
  5473. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  5474. }
  5475. continue;
  5476. overflow:
  5477. seq_puts(seq, " ...\n");
  5478. }
  5479. spin_unlock_bh(&css_set_lock);
  5480. return 0;
  5481. }
  5482. static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
  5483. {
  5484. return (!cgroup_is_populated(css->cgroup) &&
  5485. !css_has_online_children(&css->cgroup->self));
  5486. }
  5487. static struct cftype debug_files[] = {
  5488. {
  5489. .name = "taskcount",
  5490. .read_u64 = debug_taskcount_read,
  5491. },
  5492. {
  5493. .name = "current_css_set",
  5494. .read_u64 = current_css_set_read,
  5495. },
  5496. {
  5497. .name = "current_css_set_refcount",
  5498. .read_u64 = current_css_set_refcount_read,
  5499. },
  5500. {
  5501. .name = "current_css_set_cg_links",
  5502. .seq_show = current_css_set_cg_links_read,
  5503. },
  5504. {
  5505. .name = "cgroup_css_links",
  5506. .seq_show = cgroup_css_links_read,
  5507. },
  5508. {
  5509. .name = "releasable",
  5510. .read_u64 = releasable_read,
  5511. },
  5512. { } /* terminate */
  5513. };
  5514. struct cgroup_subsys debug_cgrp_subsys = {
  5515. .css_alloc = debug_css_alloc,
  5516. .css_free = debug_css_free,
  5517. .legacy_cftypes = debug_files,
  5518. };
  5519. #endif /* CONFIG_CGROUP_DEBUG */