cgroup.c 145 KB

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