cgroup.c 144 KB

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