cgroup.c 141 KB

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