cgroup.c 175 KB

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