cgroup.c 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404
  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 super_block *pinned_sb = NULL;
  1408. struct cgroup_subsys *ss;
  1409. struct cgroup_root *root;
  1410. struct cgroup_sb_opts opts;
  1411. struct dentry *dentry;
  1412. int ret;
  1413. int i;
  1414. bool new_sb;
  1415. /*
  1416. * The first time anyone tries to mount a cgroup, enable the list
  1417. * linking each css_set to its tasks and fix up all existing tasks.
  1418. */
  1419. if (!use_task_css_set_links)
  1420. cgroup_enable_task_cg_lists();
  1421. mutex_lock(&cgroup_mutex);
  1422. /* First find the desired set of subsystems */
  1423. ret = parse_cgroupfs_options(data, &opts);
  1424. if (ret)
  1425. goto out_unlock;
  1426. /* look for a matching existing root */
  1427. if (!opts.subsys_mask && !opts.none && !opts.name) {
  1428. cgrp_dfl_root_visible = true;
  1429. root = &cgrp_dfl_root;
  1430. cgroup_get(&root->cgrp);
  1431. ret = 0;
  1432. goto out_unlock;
  1433. }
  1434. /*
  1435. * Destruction of cgroup root is asynchronous, so subsystems may
  1436. * still be dying after the previous unmount. Let's drain the
  1437. * dying subsystems. We just need to ensure that the ones
  1438. * unmounted previously finish dying and don't care about new ones
  1439. * starting. Testing ref liveliness is good enough.
  1440. */
  1441. for_each_subsys(ss, i) {
  1442. if (!(opts.subsys_mask & (1 << i)) ||
  1443. ss->root == &cgrp_dfl_root)
  1444. continue;
  1445. if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
  1446. mutex_unlock(&cgroup_mutex);
  1447. msleep(10);
  1448. ret = restart_syscall();
  1449. goto out_free;
  1450. }
  1451. cgroup_put(&ss->root->cgrp);
  1452. }
  1453. for_each_root(root) {
  1454. bool name_match = false;
  1455. if (root == &cgrp_dfl_root)
  1456. continue;
  1457. /*
  1458. * If we asked for a name then it must match. Also, if
  1459. * name matches but sybsys_mask doesn't, we should fail.
  1460. * Remember whether name matched.
  1461. */
  1462. if (opts.name) {
  1463. if (strcmp(opts.name, root->name))
  1464. continue;
  1465. name_match = true;
  1466. }
  1467. /*
  1468. * If we asked for subsystems (or explicitly for no
  1469. * subsystems) then they must match.
  1470. */
  1471. if ((opts.subsys_mask || opts.none) &&
  1472. (opts.subsys_mask != root->subsys_mask)) {
  1473. if (!name_match)
  1474. continue;
  1475. ret = -EBUSY;
  1476. goto out_unlock;
  1477. }
  1478. if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
  1479. if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
  1480. pr_err("sane_behavior: new mount options should match the existing superblock\n");
  1481. ret = -EINVAL;
  1482. goto out_unlock;
  1483. } else {
  1484. pr_warn("new mount options do not match the existing superblock, will be ignored\n");
  1485. }
  1486. }
  1487. /*
  1488. * We want to reuse @root whose lifetime is governed by its
  1489. * ->cgrp. Let's check whether @root is alive and keep it
  1490. * that way. As cgroup_kill_sb() can happen anytime, we
  1491. * want to block it by pinning the sb so that @root doesn't
  1492. * get killed before mount is complete.
  1493. *
  1494. * With the sb pinned, tryget_live can reliably indicate
  1495. * whether @root can be reused. If it's being killed,
  1496. * drain it. We can use wait_queue for the wait but this
  1497. * path is super cold. Let's just sleep a bit and retry.
  1498. */
  1499. pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
  1500. if (IS_ERR(pinned_sb) ||
  1501. !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
  1502. mutex_unlock(&cgroup_mutex);
  1503. if (!IS_ERR_OR_NULL(pinned_sb))
  1504. deactivate_super(pinned_sb);
  1505. msleep(10);
  1506. ret = restart_syscall();
  1507. goto out_free;
  1508. }
  1509. ret = 0;
  1510. goto out_unlock;
  1511. }
  1512. /*
  1513. * No such thing, create a new one. name= matching without subsys
  1514. * specification is allowed for already existing hierarchies but we
  1515. * can't create new one without subsys specification.
  1516. */
  1517. if (!opts.subsys_mask && !opts.none) {
  1518. ret = -EINVAL;
  1519. goto out_unlock;
  1520. }
  1521. root = kzalloc(sizeof(*root), GFP_KERNEL);
  1522. if (!root) {
  1523. ret = -ENOMEM;
  1524. goto out_unlock;
  1525. }
  1526. init_cgroup_root(root, &opts);
  1527. ret = cgroup_setup_root(root, opts.subsys_mask);
  1528. if (ret)
  1529. cgroup_free_root(root);
  1530. out_unlock:
  1531. mutex_unlock(&cgroup_mutex);
  1532. out_free:
  1533. kfree(opts.release_agent);
  1534. kfree(opts.name);
  1535. if (ret)
  1536. return ERR_PTR(ret);
  1537. dentry = kernfs_mount(fs_type, flags, root->kf_root,
  1538. CGROUP_SUPER_MAGIC, &new_sb);
  1539. if (IS_ERR(dentry) || !new_sb)
  1540. cgroup_put(&root->cgrp);
  1541. /*
  1542. * If @pinned_sb, we're reusing an existing root and holding an
  1543. * extra ref on its sb. Mount is complete. Put the extra ref.
  1544. */
  1545. if (pinned_sb) {
  1546. WARN_ON(new_sb);
  1547. deactivate_super(pinned_sb);
  1548. }
  1549. return dentry;
  1550. }
  1551. static void cgroup_kill_sb(struct super_block *sb)
  1552. {
  1553. struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
  1554. struct cgroup_root *root = cgroup_root_from_kf(kf_root);
  1555. /*
  1556. * If @root doesn't have any mounts or children, start killing it.
  1557. * This prevents new mounts by disabling percpu_ref_tryget_live().
  1558. * cgroup_mount() may wait for @root's release.
  1559. *
  1560. * And don't kill the default root.
  1561. */
  1562. if (css_has_online_children(&root->cgrp.self) ||
  1563. root == &cgrp_dfl_root)
  1564. cgroup_put(&root->cgrp);
  1565. else
  1566. percpu_ref_kill(&root->cgrp.self.refcnt);
  1567. kernfs_kill_sb(sb);
  1568. }
  1569. static struct file_system_type cgroup_fs_type = {
  1570. .name = "cgroup",
  1571. .mount = cgroup_mount,
  1572. .kill_sb = cgroup_kill_sb,
  1573. };
  1574. static struct kobject *cgroup_kobj;
  1575. /**
  1576. * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
  1577. * @task: target task
  1578. * @buf: the buffer to write the path into
  1579. * @buflen: the length of the buffer
  1580. *
  1581. * Determine @task's cgroup on the first (the one with the lowest non-zero
  1582. * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
  1583. * function grabs cgroup_mutex and shouldn't be used inside locks used by
  1584. * cgroup controller callbacks.
  1585. *
  1586. * Return value is the same as kernfs_path().
  1587. */
  1588. char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
  1589. {
  1590. struct cgroup_root *root;
  1591. struct cgroup *cgrp;
  1592. int hierarchy_id = 1;
  1593. char *path = NULL;
  1594. mutex_lock(&cgroup_mutex);
  1595. down_read(&css_set_rwsem);
  1596. root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
  1597. if (root) {
  1598. cgrp = task_cgroup_from_root(task, root);
  1599. path = cgroup_path(cgrp, buf, buflen);
  1600. } else {
  1601. /* if no hierarchy exists, everyone is in "/" */
  1602. if (strlcpy(buf, "/", buflen) < buflen)
  1603. path = buf;
  1604. }
  1605. up_read(&css_set_rwsem);
  1606. mutex_unlock(&cgroup_mutex);
  1607. return path;
  1608. }
  1609. EXPORT_SYMBOL_GPL(task_cgroup_path);
  1610. /* used to track tasks and other necessary states during migration */
  1611. struct cgroup_taskset {
  1612. /* the src and dst cset list running through cset->mg_node */
  1613. struct list_head src_csets;
  1614. struct list_head dst_csets;
  1615. /*
  1616. * Fields for cgroup_taskset_*() iteration.
  1617. *
  1618. * Before migration is committed, the target migration tasks are on
  1619. * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
  1620. * the csets on ->dst_csets. ->csets point to either ->src_csets
  1621. * or ->dst_csets depending on whether migration is committed.
  1622. *
  1623. * ->cur_csets and ->cur_task point to the current task position
  1624. * during iteration.
  1625. */
  1626. struct list_head *csets;
  1627. struct css_set *cur_cset;
  1628. struct task_struct *cur_task;
  1629. };
  1630. /**
  1631. * cgroup_taskset_first - reset taskset and return the first task
  1632. * @tset: taskset of interest
  1633. *
  1634. * @tset iteration is initialized and the first task is returned.
  1635. */
  1636. struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
  1637. {
  1638. tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
  1639. tset->cur_task = NULL;
  1640. return cgroup_taskset_next(tset);
  1641. }
  1642. /**
  1643. * cgroup_taskset_next - iterate to the next task in taskset
  1644. * @tset: taskset of interest
  1645. *
  1646. * Return the next task in @tset. Iteration must have been initialized
  1647. * with cgroup_taskset_first().
  1648. */
  1649. struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
  1650. {
  1651. struct css_set *cset = tset->cur_cset;
  1652. struct task_struct *task = tset->cur_task;
  1653. while (&cset->mg_node != tset->csets) {
  1654. if (!task)
  1655. task = list_first_entry(&cset->mg_tasks,
  1656. struct task_struct, cg_list);
  1657. else
  1658. task = list_next_entry(task, cg_list);
  1659. if (&task->cg_list != &cset->mg_tasks) {
  1660. tset->cur_cset = cset;
  1661. tset->cur_task = task;
  1662. return task;
  1663. }
  1664. cset = list_next_entry(cset, mg_node);
  1665. task = NULL;
  1666. }
  1667. return NULL;
  1668. }
  1669. /**
  1670. * cgroup_task_migrate - move a task from one cgroup to another.
  1671. * @old_cgrp: the cgroup @tsk is being migrated from
  1672. * @tsk: the task being migrated
  1673. * @new_cset: the new css_set @tsk is being attached to
  1674. *
  1675. * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
  1676. */
  1677. static void cgroup_task_migrate(struct cgroup *old_cgrp,
  1678. struct task_struct *tsk,
  1679. struct css_set *new_cset)
  1680. {
  1681. struct css_set *old_cset;
  1682. lockdep_assert_held(&cgroup_mutex);
  1683. lockdep_assert_held(&css_set_rwsem);
  1684. /*
  1685. * We are synchronized through threadgroup_lock() against PF_EXITING
  1686. * setting such that we can't race against cgroup_exit() changing the
  1687. * css_set to init_css_set and dropping the old one.
  1688. */
  1689. WARN_ON_ONCE(tsk->flags & PF_EXITING);
  1690. old_cset = task_css_set(tsk);
  1691. get_css_set(new_cset);
  1692. rcu_assign_pointer(tsk->cgroups, new_cset);
  1693. /*
  1694. * Use move_tail so that cgroup_taskset_first() still returns the
  1695. * leader after migration. This works because cgroup_migrate()
  1696. * ensures that the dst_cset of the leader is the first on the
  1697. * tset's dst_csets list.
  1698. */
  1699. list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
  1700. /*
  1701. * We just gained a reference on old_cset by taking it from the
  1702. * task. As trading it for new_cset is protected by cgroup_mutex,
  1703. * we're safe to drop it here; it will be freed under RCU.
  1704. */
  1705. set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
  1706. put_css_set_locked(old_cset, false);
  1707. }
  1708. /**
  1709. * cgroup_migrate_finish - cleanup after attach
  1710. * @preloaded_csets: list of preloaded css_sets
  1711. *
  1712. * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
  1713. * those functions for details.
  1714. */
  1715. static void cgroup_migrate_finish(struct list_head *preloaded_csets)
  1716. {
  1717. struct css_set *cset, *tmp_cset;
  1718. lockdep_assert_held(&cgroup_mutex);
  1719. down_write(&css_set_rwsem);
  1720. list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
  1721. cset->mg_src_cgrp = NULL;
  1722. cset->mg_dst_cset = NULL;
  1723. list_del_init(&cset->mg_preload_node);
  1724. put_css_set_locked(cset, false);
  1725. }
  1726. up_write(&css_set_rwsem);
  1727. }
  1728. /**
  1729. * cgroup_migrate_add_src - add a migration source css_set
  1730. * @src_cset: the source css_set to add
  1731. * @dst_cgrp: the destination cgroup
  1732. * @preloaded_csets: list of preloaded css_sets
  1733. *
  1734. * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
  1735. * @src_cset and add it to @preloaded_csets, which should later be cleaned
  1736. * up by cgroup_migrate_finish().
  1737. *
  1738. * This function may be called without holding threadgroup_lock even if the
  1739. * target is a process. Threads may be created and destroyed but as long
  1740. * as cgroup_mutex is not dropped, no new css_set can be put into play and
  1741. * the preloaded css_sets are guaranteed to cover all migrations.
  1742. */
  1743. static void cgroup_migrate_add_src(struct css_set *src_cset,
  1744. struct cgroup *dst_cgrp,
  1745. struct list_head *preloaded_csets)
  1746. {
  1747. struct cgroup *src_cgrp;
  1748. lockdep_assert_held(&cgroup_mutex);
  1749. lockdep_assert_held(&css_set_rwsem);
  1750. src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
  1751. if (!list_empty(&src_cset->mg_preload_node))
  1752. return;
  1753. WARN_ON(src_cset->mg_src_cgrp);
  1754. WARN_ON(!list_empty(&src_cset->mg_tasks));
  1755. WARN_ON(!list_empty(&src_cset->mg_node));
  1756. src_cset->mg_src_cgrp = src_cgrp;
  1757. get_css_set(src_cset);
  1758. list_add(&src_cset->mg_preload_node, preloaded_csets);
  1759. }
  1760. /**
  1761. * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
  1762. * @dst_cgrp: the destination cgroup (may be %NULL)
  1763. * @preloaded_csets: list of preloaded source css_sets
  1764. *
  1765. * Tasks are about to be moved to @dst_cgrp and all the source css_sets
  1766. * have been preloaded to @preloaded_csets. This function looks up and
  1767. * pins all destination css_sets, links each to its source, and append them
  1768. * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
  1769. * source css_set is assumed to be its cgroup on the default hierarchy.
  1770. *
  1771. * This function must be called after cgroup_migrate_add_src() has been
  1772. * called on each migration source css_set. After migration is performed
  1773. * using cgroup_migrate(), cgroup_migrate_finish() must be called on
  1774. * @preloaded_csets.
  1775. */
  1776. static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
  1777. struct list_head *preloaded_csets)
  1778. {
  1779. LIST_HEAD(csets);
  1780. struct css_set *src_cset, *tmp_cset;
  1781. lockdep_assert_held(&cgroup_mutex);
  1782. /*
  1783. * Except for the root, child_subsys_mask must be zero for a cgroup
  1784. * with tasks so that child cgroups don't compete against tasks.
  1785. */
  1786. if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
  1787. dst_cgrp->child_subsys_mask)
  1788. return -EBUSY;
  1789. /* look up the dst cset for each src cset and link it to src */
  1790. list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
  1791. struct css_set *dst_cset;
  1792. dst_cset = find_css_set(src_cset,
  1793. dst_cgrp ?: src_cset->dfl_cgrp);
  1794. if (!dst_cset)
  1795. goto err;
  1796. WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
  1797. /*
  1798. * If src cset equals dst, it's noop. Drop the src.
  1799. * cgroup_migrate() will skip the cset too. Note that we
  1800. * can't handle src == dst as some nodes are used by both.
  1801. */
  1802. if (src_cset == dst_cset) {
  1803. src_cset->mg_src_cgrp = NULL;
  1804. list_del_init(&src_cset->mg_preload_node);
  1805. put_css_set(src_cset, false);
  1806. put_css_set(dst_cset, false);
  1807. continue;
  1808. }
  1809. src_cset->mg_dst_cset = dst_cset;
  1810. if (list_empty(&dst_cset->mg_preload_node))
  1811. list_add(&dst_cset->mg_preload_node, &csets);
  1812. else
  1813. put_css_set(dst_cset, false);
  1814. }
  1815. list_splice_tail(&csets, preloaded_csets);
  1816. return 0;
  1817. err:
  1818. cgroup_migrate_finish(&csets);
  1819. return -ENOMEM;
  1820. }
  1821. /**
  1822. * cgroup_migrate - migrate a process or task to a cgroup
  1823. * @cgrp: the destination cgroup
  1824. * @leader: the leader of the process or the task to migrate
  1825. * @threadgroup: whether @leader points to the whole process or a single task
  1826. *
  1827. * Migrate a process or task denoted by @leader to @cgrp. If migrating a
  1828. * process, the caller must be holding threadgroup_lock of @leader. The
  1829. * caller is also responsible for invoking cgroup_migrate_add_src() and
  1830. * cgroup_migrate_prepare_dst() on the targets before invoking this
  1831. * function and following up with cgroup_migrate_finish().
  1832. *
  1833. * As long as a controller's ->can_attach() doesn't fail, this function is
  1834. * guaranteed to succeed. This means that, excluding ->can_attach()
  1835. * failure, when migrating multiple targets, the success or failure can be
  1836. * decided for all targets by invoking group_migrate_prepare_dst() before
  1837. * actually starting migrating.
  1838. */
  1839. static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
  1840. bool threadgroup)
  1841. {
  1842. struct cgroup_taskset tset = {
  1843. .src_csets = LIST_HEAD_INIT(tset.src_csets),
  1844. .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
  1845. .csets = &tset.src_csets,
  1846. };
  1847. struct cgroup_subsys_state *css, *failed_css = NULL;
  1848. struct css_set *cset, *tmp_cset;
  1849. struct task_struct *task, *tmp_task;
  1850. int i, ret;
  1851. /*
  1852. * Prevent freeing of tasks while we take a snapshot. Tasks that are
  1853. * already PF_EXITING could be freed from underneath us unless we
  1854. * take an rcu_read_lock.
  1855. */
  1856. down_write(&css_set_rwsem);
  1857. rcu_read_lock();
  1858. task = leader;
  1859. do {
  1860. /* @task either already exited or can't exit until the end */
  1861. if (task->flags & PF_EXITING)
  1862. goto next;
  1863. /* leave @task alone if post_fork() hasn't linked it yet */
  1864. if (list_empty(&task->cg_list))
  1865. goto next;
  1866. cset = task_css_set(task);
  1867. if (!cset->mg_src_cgrp)
  1868. goto next;
  1869. /*
  1870. * cgroup_taskset_first() must always return the leader.
  1871. * Take care to avoid disturbing the ordering.
  1872. */
  1873. list_move_tail(&task->cg_list, &cset->mg_tasks);
  1874. if (list_empty(&cset->mg_node))
  1875. list_add_tail(&cset->mg_node, &tset.src_csets);
  1876. if (list_empty(&cset->mg_dst_cset->mg_node))
  1877. list_move_tail(&cset->mg_dst_cset->mg_node,
  1878. &tset.dst_csets);
  1879. next:
  1880. if (!threadgroup)
  1881. break;
  1882. } while_each_thread(leader, task);
  1883. rcu_read_unlock();
  1884. up_write(&css_set_rwsem);
  1885. /* methods shouldn't be called if no task is actually migrating */
  1886. if (list_empty(&tset.src_csets))
  1887. return 0;
  1888. /* check that we can legitimately attach to the cgroup */
  1889. for_each_e_css(css, i, cgrp) {
  1890. if (css->ss->can_attach) {
  1891. ret = css->ss->can_attach(css, &tset);
  1892. if (ret) {
  1893. failed_css = css;
  1894. goto out_cancel_attach;
  1895. }
  1896. }
  1897. }
  1898. /*
  1899. * Now that we're guaranteed success, proceed to move all tasks to
  1900. * the new cgroup. There are no failure cases after here, so this
  1901. * is the commit point.
  1902. */
  1903. down_write(&css_set_rwsem);
  1904. list_for_each_entry(cset, &tset.src_csets, mg_node) {
  1905. list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
  1906. cgroup_task_migrate(cset->mg_src_cgrp, task,
  1907. cset->mg_dst_cset);
  1908. }
  1909. up_write(&css_set_rwsem);
  1910. /*
  1911. * Migration is committed, all target tasks are now on dst_csets.
  1912. * Nothing is sensitive to fork() after this point. Notify
  1913. * controllers that migration is complete.
  1914. */
  1915. tset.csets = &tset.dst_csets;
  1916. for_each_e_css(css, i, cgrp)
  1917. if (css->ss->attach)
  1918. css->ss->attach(css, &tset);
  1919. ret = 0;
  1920. goto out_release_tset;
  1921. out_cancel_attach:
  1922. for_each_e_css(css, i, cgrp) {
  1923. if (css == failed_css)
  1924. break;
  1925. if (css->ss->cancel_attach)
  1926. css->ss->cancel_attach(css, &tset);
  1927. }
  1928. out_release_tset:
  1929. down_write(&css_set_rwsem);
  1930. list_splice_init(&tset.dst_csets, &tset.src_csets);
  1931. list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
  1932. list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
  1933. list_del_init(&cset->mg_node);
  1934. }
  1935. up_write(&css_set_rwsem);
  1936. return ret;
  1937. }
  1938. /**
  1939. * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
  1940. * @dst_cgrp: the cgroup to attach to
  1941. * @leader: the task or the leader of the threadgroup to be attached
  1942. * @threadgroup: attach the whole threadgroup?
  1943. *
  1944. * Call holding cgroup_mutex and threadgroup_lock of @leader.
  1945. */
  1946. static int cgroup_attach_task(struct cgroup *dst_cgrp,
  1947. struct task_struct *leader, bool threadgroup)
  1948. {
  1949. LIST_HEAD(preloaded_csets);
  1950. struct task_struct *task;
  1951. int ret;
  1952. /* look up all src csets */
  1953. down_read(&css_set_rwsem);
  1954. rcu_read_lock();
  1955. task = leader;
  1956. do {
  1957. cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
  1958. &preloaded_csets);
  1959. if (!threadgroup)
  1960. break;
  1961. } while_each_thread(leader, task);
  1962. rcu_read_unlock();
  1963. up_read(&css_set_rwsem);
  1964. /* prepare dst csets and commit */
  1965. ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
  1966. if (!ret)
  1967. ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
  1968. cgroup_migrate_finish(&preloaded_csets);
  1969. return ret;
  1970. }
  1971. /*
  1972. * Find the task_struct of the task to attach by vpid and pass it along to the
  1973. * function to attach either it or all tasks in its threadgroup. Will lock
  1974. * cgroup_mutex and threadgroup.
  1975. */
  1976. static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
  1977. size_t nbytes, loff_t off, bool threadgroup)
  1978. {
  1979. struct task_struct *tsk;
  1980. const struct cred *cred = current_cred(), *tcred;
  1981. struct cgroup *cgrp;
  1982. pid_t pid;
  1983. int ret;
  1984. if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
  1985. return -EINVAL;
  1986. cgrp = cgroup_kn_lock_live(of->kn);
  1987. if (!cgrp)
  1988. return -ENODEV;
  1989. retry_find_task:
  1990. rcu_read_lock();
  1991. if (pid) {
  1992. tsk = find_task_by_vpid(pid);
  1993. if (!tsk) {
  1994. rcu_read_unlock();
  1995. ret = -ESRCH;
  1996. goto out_unlock_cgroup;
  1997. }
  1998. /*
  1999. * even if we're attaching all tasks in the thread group, we
  2000. * only need to check permissions on one of them.
  2001. */
  2002. tcred = __task_cred(tsk);
  2003. if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
  2004. !uid_eq(cred->euid, tcred->uid) &&
  2005. !uid_eq(cred->euid, tcred->suid)) {
  2006. rcu_read_unlock();
  2007. ret = -EACCES;
  2008. goto out_unlock_cgroup;
  2009. }
  2010. } else
  2011. tsk = current;
  2012. if (threadgroup)
  2013. tsk = tsk->group_leader;
  2014. /*
  2015. * Workqueue threads may acquire PF_NO_SETAFFINITY and become
  2016. * trapped in a cpuset, or RT worker may be born in a cgroup
  2017. * with no rt_runtime allocated. Just say no.
  2018. */
  2019. if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
  2020. ret = -EINVAL;
  2021. rcu_read_unlock();
  2022. goto out_unlock_cgroup;
  2023. }
  2024. get_task_struct(tsk);
  2025. rcu_read_unlock();
  2026. threadgroup_lock(tsk);
  2027. if (threadgroup) {
  2028. if (!thread_group_leader(tsk)) {
  2029. /*
  2030. * a race with de_thread from another thread's exec()
  2031. * may strip us of our leadership, if this happens,
  2032. * there is no choice but to throw this task away and
  2033. * try again; this is
  2034. * "double-double-toil-and-trouble-check locking".
  2035. */
  2036. threadgroup_unlock(tsk);
  2037. put_task_struct(tsk);
  2038. goto retry_find_task;
  2039. }
  2040. }
  2041. ret = cgroup_attach_task(cgrp, tsk, threadgroup);
  2042. threadgroup_unlock(tsk);
  2043. put_task_struct(tsk);
  2044. out_unlock_cgroup:
  2045. cgroup_kn_unlock(of->kn);
  2046. return ret ?: nbytes;
  2047. }
  2048. /**
  2049. * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
  2050. * @from: attach to all cgroups of a given task
  2051. * @tsk: the task to be attached
  2052. */
  2053. int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
  2054. {
  2055. struct cgroup_root *root;
  2056. int retval = 0;
  2057. mutex_lock(&cgroup_mutex);
  2058. for_each_root(root) {
  2059. struct cgroup *from_cgrp;
  2060. if (root == &cgrp_dfl_root)
  2061. continue;
  2062. down_read(&css_set_rwsem);
  2063. from_cgrp = task_cgroup_from_root(from, root);
  2064. up_read(&css_set_rwsem);
  2065. retval = cgroup_attach_task(from_cgrp, tsk, false);
  2066. if (retval)
  2067. break;
  2068. }
  2069. mutex_unlock(&cgroup_mutex);
  2070. return retval;
  2071. }
  2072. EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
  2073. static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
  2074. char *buf, size_t nbytes, loff_t off)
  2075. {
  2076. return __cgroup_procs_write(of, buf, nbytes, off, false);
  2077. }
  2078. static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
  2079. char *buf, size_t nbytes, loff_t off)
  2080. {
  2081. return __cgroup_procs_write(of, buf, nbytes, off, true);
  2082. }
  2083. static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
  2084. char *buf, size_t nbytes, loff_t off)
  2085. {
  2086. struct cgroup *cgrp;
  2087. BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
  2088. cgrp = cgroup_kn_lock_live(of->kn);
  2089. if (!cgrp)
  2090. return -ENODEV;
  2091. spin_lock(&release_agent_path_lock);
  2092. strlcpy(cgrp->root->release_agent_path, strstrip(buf),
  2093. sizeof(cgrp->root->release_agent_path));
  2094. spin_unlock(&release_agent_path_lock);
  2095. cgroup_kn_unlock(of->kn);
  2096. return nbytes;
  2097. }
  2098. static int cgroup_release_agent_show(struct seq_file *seq, void *v)
  2099. {
  2100. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2101. spin_lock(&release_agent_path_lock);
  2102. seq_puts(seq, cgrp->root->release_agent_path);
  2103. spin_unlock(&release_agent_path_lock);
  2104. seq_putc(seq, '\n');
  2105. return 0;
  2106. }
  2107. static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
  2108. {
  2109. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2110. seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
  2111. return 0;
  2112. }
  2113. static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
  2114. {
  2115. struct cgroup_subsys *ss;
  2116. bool printed = false;
  2117. int ssid;
  2118. for_each_subsys(ss, ssid) {
  2119. if (ss_mask & (1 << ssid)) {
  2120. if (printed)
  2121. seq_putc(seq, ' ');
  2122. seq_printf(seq, "%s", ss->name);
  2123. printed = true;
  2124. }
  2125. }
  2126. if (printed)
  2127. seq_putc(seq, '\n');
  2128. }
  2129. /* show controllers which are currently attached to the default hierarchy */
  2130. static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
  2131. {
  2132. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2133. cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
  2134. ~cgrp_dfl_root_inhibit_ss_mask);
  2135. return 0;
  2136. }
  2137. /* show controllers which are enabled from the parent */
  2138. static int cgroup_controllers_show(struct seq_file *seq, void *v)
  2139. {
  2140. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2141. cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->child_subsys_mask);
  2142. return 0;
  2143. }
  2144. /* show controllers which are enabled for a given cgroup's children */
  2145. static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
  2146. {
  2147. struct cgroup *cgrp = seq_css(seq)->cgroup;
  2148. cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
  2149. return 0;
  2150. }
  2151. /**
  2152. * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
  2153. * @cgrp: root of the subtree to update csses for
  2154. *
  2155. * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
  2156. * css associations need to be updated accordingly. This function looks up
  2157. * all css_sets which are attached to the subtree, creates the matching
  2158. * updated css_sets and migrates the tasks to the new ones.
  2159. */
  2160. static int cgroup_update_dfl_csses(struct cgroup *cgrp)
  2161. {
  2162. LIST_HEAD(preloaded_csets);
  2163. struct cgroup_subsys_state *css;
  2164. struct css_set *src_cset;
  2165. int ret;
  2166. lockdep_assert_held(&cgroup_mutex);
  2167. /* look up all csses currently attached to @cgrp's subtree */
  2168. down_read(&css_set_rwsem);
  2169. css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
  2170. struct cgrp_cset_link *link;
  2171. /* self is not affected by child_subsys_mask change */
  2172. if (css->cgroup == cgrp)
  2173. continue;
  2174. list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
  2175. cgroup_migrate_add_src(link->cset, cgrp,
  2176. &preloaded_csets);
  2177. }
  2178. up_read(&css_set_rwsem);
  2179. /* NULL dst indicates self on default hierarchy */
  2180. ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
  2181. if (ret)
  2182. goto out_finish;
  2183. list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
  2184. struct task_struct *last_task = NULL, *task;
  2185. /* src_csets precede dst_csets, break on the first dst_cset */
  2186. if (!src_cset->mg_src_cgrp)
  2187. break;
  2188. /*
  2189. * All tasks in src_cset need to be migrated to the
  2190. * matching dst_cset. Empty it process by process. We
  2191. * walk tasks but migrate processes. The leader might even
  2192. * belong to a different cset but such src_cset would also
  2193. * be among the target src_csets because the default
  2194. * hierarchy enforces per-process membership.
  2195. */
  2196. while (true) {
  2197. down_read(&css_set_rwsem);
  2198. task = list_first_entry_or_null(&src_cset->tasks,
  2199. struct task_struct, cg_list);
  2200. if (task) {
  2201. task = task->group_leader;
  2202. WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
  2203. get_task_struct(task);
  2204. }
  2205. up_read(&css_set_rwsem);
  2206. if (!task)
  2207. break;
  2208. /* guard against possible infinite loop */
  2209. if (WARN(last_task == task,
  2210. "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
  2211. goto out_finish;
  2212. last_task = task;
  2213. threadgroup_lock(task);
  2214. /* raced against de_thread() from another thread? */
  2215. if (!thread_group_leader(task)) {
  2216. threadgroup_unlock(task);
  2217. put_task_struct(task);
  2218. continue;
  2219. }
  2220. ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
  2221. threadgroup_unlock(task);
  2222. put_task_struct(task);
  2223. if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
  2224. goto out_finish;
  2225. }
  2226. }
  2227. out_finish:
  2228. cgroup_migrate_finish(&preloaded_csets);
  2229. return ret;
  2230. }
  2231. /* change the enabled child controllers for a cgroup in the default hierarchy */
  2232. static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
  2233. char *buf, size_t nbytes,
  2234. loff_t off)
  2235. {
  2236. unsigned int enable = 0, disable = 0;
  2237. struct cgroup *cgrp, *child;
  2238. struct cgroup_subsys *ss;
  2239. char *tok;
  2240. int ssid, ret;
  2241. /*
  2242. * Parse input - space separated list of subsystem names prefixed
  2243. * with either + or -.
  2244. */
  2245. buf = strstrip(buf);
  2246. while ((tok = strsep(&buf, " "))) {
  2247. if (tok[0] == '\0')
  2248. continue;
  2249. for_each_subsys(ss, ssid) {
  2250. if (ss->disabled || strcmp(tok + 1, ss->name) ||
  2251. ((1 << ss->id) & cgrp_dfl_root_inhibit_ss_mask))
  2252. continue;
  2253. if (*tok == '+') {
  2254. enable |= 1 << ssid;
  2255. disable &= ~(1 << ssid);
  2256. } else if (*tok == '-') {
  2257. disable |= 1 << ssid;
  2258. enable &= ~(1 << ssid);
  2259. } else {
  2260. return -EINVAL;
  2261. }
  2262. break;
  2263. }
  2264. if (ssid == CGROUP_SUBSYS_COUNT)
  2265. return -EINVAL;
  2266. }
  2267. cgrp = cgroup_kn_lock_live(of->kn);
  2268. if (!cgrp)
  2269. return -ENODEV;
  2270. for_each_subsys(ss, ssid) {
  2271. if (enable & (1 << ssid)) {
  2272. if (cgrp->child_subsys_mask & (1 << ssid)) {
  2273. enable &= ~(1 << ssid);
  2274. continue;
  2275. }
  2276. /*
  2277. * Because css offlining is asynchronous, userland
  2278. * might try to re-enable the same controller while
  2279. * the previous instance is still around. In such
  2280. * cases, wait till it's gone using offline_waitq.
  2281. */
  2282. cgroup_for_each_live_child(child, cgrp) {
  2283. DEFINE_WAIT(wait);
  2284. if (!cgroup_css(child, ss))
  2285. continue;
  2286. cgroup_get(child);
  2287. prepare_to_wait(&child->offline_waitq, &wait,
  2288. TASK_UNINTERRUPTIBLE);
  2289. cgroup_kn_unlock(of->kn);
  2290. schedule();
  2291. finish_wait(&child->offline_waitq, &wait);
  2292. cgroup_put(child);
  2293. return restart_syscall();
  2294. }
  2295. /* unavailable or not enabled on the parent? */
  2296. if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
  2297. (cgroup_parent(cgrp) &&
  2298. !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ssid)))) {
  2299. ret = -ENOENT;
  2300. goto out_unlock;
  2301. }
  2302. } else if (disable & (1 << ssid)) {
  2303. if (!(cgrp->child_subsys_mask & (1 << ssid))) {
  2304. disable &= ~(1 << ssid);
  2305. continue;
  2306. }
  2307. /* a child has it enabled? */
  2308. cgroup_for_each_live_child(child, cgrp) {
  2309. if (child->child_subsys_mask & (1 << ssid)) {
  2310. ret = -EBUSY;
  2311. goto out_unlock;
  2312. }
  2313. }
  2314. }
  2315. }
  2316. if (!enable && !disable) {
  2317. ret = 0;
  2318. goto out_unlock;
  2319. }
  2320. /*
  2321. * Except for the root, child_subsys_mask must be zero for a cgroup
  2322. * with tasks so that child cgroups don't compete against tasks.
  2323. */
  2324. if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
  2325. ret = -EBUSY;
  2326. goto out_unlock;
  2327. }
  2328. /*
  2329. * Create csses for enables and update child_subsys_mask. This
  2330. * changes cgroup_e_css() results which in turn makes the
  2331. * subsequent cgroup_update_dfl_csses() associate all tasks in the
  2332. * subtree to the updated csses.
  2333. */
  2334. for_each_subsys(ss, ssid) {
  2335. if (!(enable & (1 << ssid)))
  2336. continue;
  2337. cgroup_for_each_live_child(child, cgrp) {
  2338. ret = create_css(child, ss);
  2339. if (ret)
  2340. goto err_undo_css;
  2341. }
  2342. }
  2343. cgrp->child_subsys_mask |= enable;
  2344. cgrp->child_subsys_mask &= ~disable;
  2345. ret = cgroup_update_dfl_csses(cgrp);
  2346. if (ret)
  2347. goto err_undo_css;
  2348. /* all tasks are now migrated away from the old csses, kill them */
  2349. for_each_subsys(ss, ssid) {
  2350. if (!(disable & (1 << ssid)))
  2351. continue;
  2352. cgroup_for_each_live_child(child, cgrp)
  2353. kill_css(cgroup_css(child, ss));
  2354. }
  2355. kernfs_activate(cgrp->kn);
  2356. ret = 0;
  2357. out_unlock:
  2358. cgroup_kn_unlock(of->kn);
  2359. return ret ?: nbytes;
  2360. err_undo_css:
  2361. cgrp->child_subsys_mask &= ~enable;
  2362. cgrp->child_subsys_mask |= disable;
  2363. for_each_subsys(ss, ssid) {
  2364. if (!(enable & (1 << ssid)))
  2365. continue;
  2366. cgroup_for_each_live_child(child, cgrp) {
  2367. struct cgroup_subsys_state *css = cgroup_css(child, ss);
  2368. if (css)
  2369. kill_css(css);
  2370. }
  2371. }
  2372. goto out_unlock;
  2373. }
  2374. static int cgroup_populated_show(struct seq_file *seq, void *v)
  2375. {
  2376. seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
  2377. return 0;
  2378. }
  2379. static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
  2380. size_t nbytes, loff_t off)
  2381. {
  2382. struct cgroup *cgrp = of->kn->parent->priv;
  2383. struct cftype *cft = of->kn->priv;
  2384. struct cgroup_subsys_state *css;
  2385. int ret;
  2386. if (cft->write)
  2387. return cft->write(of, buf, nbytes, off);
  2388. /*
  2389. * kernfs guarantees that a file isn't deleted with operations in
  2390. * flight, which means that the matching css is and stays alive and
  2391. * doesn't need to be pinned. The RCU locking is not necessary
  2392. * either. It's just for the convenience of using cgroup_css().
  2393. */
  2394. rcu_read_lock();
  2395. css = cgroup_css(cgrp, cft->ss);
  2396. rcu_read_unlock();
  2397. if (cft->write_u64) {
  2398. unsigned long long v;
  2399. ret = kstrtoull(buf, 0, &v);
  2400. if (!ret)
  2401. ret = cft->write_u64(css, cft, v);
  2402. } else if (cft->write_s64) {
  2403. long long v;
  2404. ret = kstrtoll(buf, 0, &v);
  2405. if (!ret)
  2406. ret = cft->write_s64(css, cft, v);
  2407. } else {
  2408. ret = -EINVAL;
  2409. }
  2410. return ret ?: nbytes;
  2411. }
  2412. static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
  2413. {
  2414. return seq_cft(seq)->seq_start(seq, ppos);
  2415. }
  2416. static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
  2417. {
  2418. return seq_cft(seq)->seq_next(seq, v, ppos);
  2419. }
  2420. static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
  2421. {
  2422. seq_cft(seq)->seq_stop(seq, v);
  2423. }
  2424. static int cgroup_seqfile_show(struct seq_file *m, void *arg)
  2425. {
  2426. struct cftype *cft = seq_cft(m);
  2427. struct cgroup_subsys_state *css = seq_css(m);
  2428. if (cft->seq_show)
  2429. return cft->seq_show(m, arg);
  2430. if (cft->read_u64)
  2431. seq_printf(m, "%llu\n", cft->read_u64(css, cft));
  2432. else if (cft->read_s64)
  2433. seq_printf(m, "%lld\n", cft->read_s64(css, cft));
  2434. else
  2435. return -EINVAL;
  2436. return 0;
  2437. }
  2438. static struct kernfs_ops cgroup_kf_single_ops = {
  2439. .atomic_write_len = PAGE_SIZE,
  2440. .write = cgroup_file_write,
  2441. .seq_show = cgroup_seqfile_show,
  2442. };
  2443. static struct kernfs_ops cgroup_kf_ops = {
  2444. .atomic_write_len = PAGE_SIZE,
  2445. .write = cgroup_file_write,
  2446. .seq_start = cgroup_seqfile_start,
  2447. .seq_next = cgroup_seqfile_next,
  2448. .seq_stop = cgroup_seqfile_stop,
  2449. .seq_show = cgroup_seqfile_show,
  2450. };
  2451. /*
  2452. * cgroup_rename - Only allow simple rename of directories in place.
  2453. */
  2454. static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
  2455. const char *new_name_str)
  2456. {
  2457. struct cgroup *cgrp = kn->priv;
  2458. int ret;
  2459. if (kernfs_type(kn) != KERNFS_DIR)
  2460. return -ENOTDIR;
  2461. if (kn->parent != new_parent)
  2462. return -EIO;
  2463. /*
  2464. * This isn't a proper migration and its usefulness is very
  2465. * limited. Disallow if sane_behavior.
  2466. */
  2467. if (cgroup_sane_behavior(cgrp))
  2468. return -EPERM;
  2469. /*
  2470. * We're gonna grab cgroup_mutex which nests outside kernfs
  2471. * active_ref. kernfs_rename() doesn't require active_ref
  2472. * protection. Break them before grabbing cgroup_mutex.
  2473. */
  2474. kernfs_break_active_protection(new_parent);
  2475. kernfs_break_active_protection(kn);
  2476. mutex_lock(&cgroup_mutex);
  2477. ret = kernfs_rename(kn, new_parent, new_name_str);
  2478. mutex_unlock(&cgroup_mutex);
  2479. kernfs_unbreak_active_protection(kn);
  2480. kernfs_unbreak_active_protection(new_parent);
  2481. return ret;
  2482. }
  2483. /* set uid and gid of cgroup dirs and files to that of the creator */
  2484. static int cgroup_kn_set_ugid(struct kernfs_node *kn)
  2485. {
  2486. struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
  2487. .ia_uid = current_fsuid(),
  2488. .ia_gid = current_fsgid(), };
  2489. if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
  2490. gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
  2491. return 0;
  2492. return kernfs_setattr(kn, &iattr);
  2493. }
  2494. static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
  2495. {
  2496. char name[CGROUP_FILE_NAME_MAX];
  2497. struct kernfs_node *kn;
  2498. struct lock_class_key *key = NULL;
  2499. int ret;
  2500. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  2501. key = &cft->lockdep_key;
  2502. #endif
  2503. kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
  2504. cgroup_file_mode(cft), 0, cft->kf_ops, cft,
  2505. NULL, false, key);
  2506. if (IS_ERR(kn))
  2507. return PTR_ERR(kn);
  2508. ret = cgroup_kn_set_ugid(kn);
  2509. if (ret) {
  2510. kernfs_remove(kn);
  2511. return ret;
  2512. }
  2513. if (cft->seq_show == cgroup_populated_show)
  2514. cgrp->populated_kn = kn;
  2515. return 0;
  2516. }
  2517. /**
  2518. * cgroup_addrm_files - add or remove files to a cgroup directory
  2519. * @cgrp: the target cgroup
  2520. * @cfts: array of cftypes to be added
  2521. * @is_add: whether to add or remove
  2522. *
  2523. * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
  2524. * For removals, this function never fails. If addition fails, this
  2525. * function doesn't remove files already added. The caller is responsible
  2526. * for cleaning up.
  2527. */
  2528. static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
  2529. bool is_add)
  2530. {
  2531. struct cftype *cft;
  2532. int ret;
  2533. lockdep_assert_held(&cgroup_mutex);
  2534. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  2535. /* does cft->flags tell us to skip this file on @cgrp? */
  2536. if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
  2537. continue;
  2538. if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
  2539. continue;
  2540. if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
  2541. continue;
  2542. if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
  2543. continue;
  2544. if (is_add) {
  2545. ret = cgroup_add_file(cgrp, cft);
  2546. if (ret) {
  2547. pr_warn("%s: failed to add %s, err=%d\n",
  2548. __func__, cft->name, ret);
  2549. return ret;
  2550. }
  2551. } else {
  2552. cgroup_rm_file(cgrp, cft);
  2553. }
  2554. }
  2555. return 0;
  2556. }
  2557. static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
  2558. {
  2559. LIST_HEAD(pending);
  2560. struct cgroup_subsys *ss = cfts[0].ss;
  2561. struct cgroup *root = &ss->root->cgrp;
  2562. struct cgroup_subsys_state *css;
  2563. int ret = 0;
  2564. lockdep_assert_held(&cgroup_mutex);
  2565. /* add/rm files for all cgroups created before */
  2566. css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
  2567. struct cgroup *cgrp = css->cgroup;
  2568. if (cgroup_is_dead(cgrp))
  2569. continue;
  2570. ret = cgroup_addrm_files(cgrp, cfts, is_add);
  2571. if (ret)
  2572. break;
  2573. }
  2574. if (is_add && !ret)
  2575. kernfs_activate(root->kn);
  2576. return ret;
  2577. }
  2578. static void cgroup_exit_cftypes(struct cftype *cfts)
  2579. {
  2580. struct cftype *cft;
  2581. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  2582. /* free copy for custom atomic_write_len, see init_cftypes() */
  2583. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
  2584. kfree(cft->kf_ops);
  2585. cft->kf_ops = NULL;
  2586. cft->ss = NULL;
  2587. }
  2588. }
  2589. static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  2590. {
  2591. struct cftype *cft;
  2592. for (cft = cfts; cft->name[0] != '\0'; cft++) {
  2593. struct kernfs_ops *kf_ops;
  2594. WARN_ON(cft->ss || cft->kf_ops);
  2595. if (cft->seq_start)
  2596. kf_ops = &cgroup_kf_ops;
  2597. else
  2598. kf_ops = &cgroup_kf_single_ops;
  2599. /*
  2600. * Ugh... if @cft wants a custom max_write_len, we need to
  2601. * make a copy of kf_ops to set its atomic_write_len.
  2602. */
  2603. if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
  2604. kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
  2605. if (!kf_ops) {
  2606. cgroup_exit_cftypes(cfts);
  2607. return -ENOMEM;
  2608. }
  2609. kf_ops->atomic_write_len = cft->max_write_len;
  2610. }
  2611. cft->kf_ops = kf_ops;
  2612. cft->ss = ss;
  2613. }
  2614. return 0;
  2615. }
  2616. static int cgroup_rm_cftypes_locked(struct cftype *cfts)
  2617. {
  2618. lockdep_assert_held(&cgroup_mutex);
  2619. if (!cfts || !cfts[0].ss)
  2620. return -ENOENT;
  2621. list_del(&cfts->node);
  2622. cgroup_apply_cftypes(cfts, false);
  2623. cgroup_exit_cftypes(cfts);
  2624. return 0;
  2625. }
  2626. /**
  2627. * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
  2628. * @cfts: zero-length name terminated array of cftypes
  2629. *
  2630. * Unregister @cfts. Files described by @cfts are removed from all
  2631. * existing cgroups and all future cgroups won't have them either. This
  2632. * function can be called anytime whether @cfts' subsys is attached or not.
  2633. *
  2634. * Returns 0 on successful unregistration, -ENOENT if @cfts is not
  2635. * registered.
  2636. */
  2637. int cgroup_rm_cftypes(struct cftype *cfts)
  2638. {
  2639. int ret;
  2640. mutex_lock(&cgroup_mutex);
  2641. ret = cgroup_rm_cftypes_locked(cfts);
  2642. mutex_unlock(&cgroup_mutex);
  2643. return ret;
  2644. }
  2645. /**
  2646. * cgroup_add_cftypes - add an array of cftypes to a subsystem
  2647. * @ss: target cgroup subsystem
  2648. * @cfts: zero-length name terminated array of cftypes
  2649. *
  2650. * Register @cfts to @ss. Files described by @cfts are created for all
  2651. * existing cgroups to which @ss is attached and all future cgroups will
  2652. * have them too. This function can be called anytime whether @ss is
  2653. * attached or not.
  2654. *
  2655. * Returns 0 on successful registration, -errno on failure. Note that this
  2656. * function currently returns 0 as long as @cfts registration is successful
  2657. * even if some file creation attempts on existing cgroups fail.
  2658. */
  2659. int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
  2660. {
  2661. int ret;
  2662. if (ss->disabled)
  2663. return 0;
  2664. if (!cfts || cfts[0].name[0] == '\0')
  2665. return 0;
  2666. ret = cgroup_init_cftypes(ss, cfts);
  2667. if (ret)
  2668. return ret;
  2669. mutex_lock(&cgroup_mutex);
  2670. list_add_tail(&cfts->node, &ss->cfts);
  2671. ret = cgroup_apply_cftypes(cfts, true);
  2672. if (ret)
  2673. cgroup_rm_cftypes_locked(cfts);
  2674. mutex_unlock(&cgroup_mutex);
  2675. return ret;
  2676. }
  2677. /**
  2678. * cgroup_task_count - count the number of tasks in a cgroup.
  2679. * @cgrp: the cgroup in question
  2680. *
  2681. * Return the number of tasks in the cgroup.
  2682. */
  2683. static int cgroup_task_count(const struct cgroup *cgrp)
  2684. {
  2685. int count = 0;
  2686. struct cgrp_cset_link *link;
  2687. down_read(&css_set_rwsem);
  2688. list_for_each_entry(link, &cgrp->cset_links, cset_link)
  2689. count += atomic_read(&link->cset->refcount);
  2690. up_read(&css_set_rwsem);
  2691. return count;
  2692. }
  2693. /**
  2694. * css_next_child - find the next child of a given css
  2695. * @pos: the current position (%NULL to initiate traversal)
  2696. * @parent: css whose children to walk
  2697. *
  2698. * This function returns the next child of @parent and should be called
  2699. * under either cgroup_mutex or RCU read lock. The only requirement is
  2700. * that @parent and @pos are accessible. The next sibling is guaranteed to
  2701. * be returned regardless of their states.
  2702. *
  2703. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  2704. * css which finished ->css_online() is guaranteed to be visible in the
  2705. * future iterations and will stay visible until the last reference is put.
  2706. * A css which hasn't finished ->css_online() or already finished
  2707. * ->css_offline() may show up during traversal. It's each subsystem's
  2708. * responsibility to synchronize against on/offlining.
  2709. */
  2710. struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
  2711. struct cgroup_subsys_state *parent)
  2712. {
  2713. struct cgroup_subsys_state *next;
  2714. cgroup_assert_mutex_or_rcu_locked();
  2715. /*
  2716. * @pos could already have been unlinked from the sibling list.
  2717. * Once a cgroup is removed, its ->sibling.next is no longer
  2718. * updated when its next sibling changes. CSS_RELEASED is set when
  2719. * @pos is taken off list, at which time its next pointer is valid,
  2720. * and, as releases are serialized, the one pointed to by the next
  2721. * pointer is guaranteed to not have started release yet. This
  2722. * implies that if we observe !CSS_RELEASED on @pos in this RCU
  2723. * critical section, the one pointed to by its next pointer is
  2724. * guaranteed to not have finished its RCU grace period even if we
  2725. * have dropped rcu_read_lock() inbetween iterations.
  2726. *
  2727. * If @pos has CSS_RELEASED set, its next pointer can't be
  2728. * dereferenced; however, as each css is given a monotonically
  2729. * increasing unique serial number and always appended to the
  2730. * sibling list, the next one can be found by walking the parent's
  2731. * children until the first css with higher serial number than
  2732. * @pos's. While this path can be slower, it happens iff iteration
  2733. * races against release and the race window is very small.
  2734. */
  2735. if (!pos) {
  2736. next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
  2737. } else if (likely(!(pos->flags & CSS_RELEASED))) {
  2738. next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
  2739. } else {
  2740. list_for_each_entry_rcu(next, &parent->children, sibling)
  2741. if (next->serial_nr > pos->serial_nr)
  2742. break;
  2743. }
  2744. /*
  2745. * @next, if not pointing to the head, can be dereferenced and is
  2746. * the next sibling.
  2747. */
  2748. if (&next->sibling != &parent->children)
  2749. return next;
  2750. return NULL;
  2751. }
  2752. /**
  2753. * css_next_descendant_pre - find the next descendant for pre-order walk
  2754. * @pos: the current position (%NULL to initiate traversal)
  2755. * @root: css whose descendants to walk
  2756. *
  2757. * To be used by css_for_each_descendant_pre(). Find the next descendant
  2758. * to visit for pre-order traversal of @root's descendants. @root is
  2759. * included in the iteration and the first node to be visited.
  2760. *
  2761. * While this function requires cgroup_mutex or RCU read locking, it
  2762. * doesn't require the whole traversal to be contained in a single critical
  2763. * section. This function will return the correct next descendant as long
  2764. * as both @pos and @root are accessible and @pos is a descendant of @root.
  2765. *
  2766. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  2767. * css which finished ->css_online() is guaranteed to be visible in the
  2768. * future iterations and will stay visible until the last reference is put.
  2769. * A css which hasn't finished ->css_online() or already finished
  2770. * ->css_offline() may show up during traversal. It's each subsystem's
  2771. * responsibility to synchronize against on/offlining.
  2772. */
  2773. struct cgroup_subsys_state *
  2774. css_next_descendant_pre(struct cgroup_subsys_state *pos,
  2775. struct cgroup_subsys_state *root)
  2776. {
  2777. struct cgroup_subsys_state *next;
  2778. cgroup_assert_mutex_or_rcu_locked();
  2779. /* if first iteration, visit @root */
  2780. if (!pos)
  2781. return root;
  2782. /* visit the first child if exists */
  2783. next = css_next_child(NULL, pos);
  2784. if (next)
  2785. return next;
  2786. /* no child, visit my or the closest ancestor's next sibling */
  2787. while (pos != root) {
  2788. next = css_next_child(pos, pos->parent);
  2789. if (next)
  2790. return next;
  2791. pos = pos->parent;
  2792. }
  2793. return NULL;
  2794. }
  2795. /**
  2796. * css_rightmost_descendant - return the rightmost descendant of a css
  2797. * @pos: css of interest
  2798. *
  2799. * Return the rightmost descendant of @pos. If there's no descendant, @pos
  2800. * is returned. This can be used during pre-order traversal to skip
  2801. * subtree of @pos.
  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 rightmost descendant as
  2806. * long as @pos is accessible.
  2807. */
  2808. struct cgroup_subsys_state *
  2809. css_rightmost_descendant(struct cgroup_subsys_state *pos)
  2810. {
  2811. struct cgroup_subsys_state *last, *tmp;
  2812. cgroup_assert_mutex_or_rcu_locked();
  2813. do {
  2814. last = pos;
  2815. /* ->prev isn't RCU safe, walk ->next till the end */
  2816. pos = NULL;
  2817. css_for_each_child(tmp, last)
  2818. pos = tmp;
  2819. } while (pos);
  2820. return last;
  2821. }
  2822. static struct cgroup_subsys_state *
  2823. css_leftmost_descendant(struct cgroup_subsys_state *pos)
  2824. {
  2825. struct cgroup_subsys_state *last;
  2826. do {
  2827. last = pos;
  2828. pos = css_next_child(NULL, pos);
  2829. } while (pos);
  2830. return last;
  2831. }
  2832. /**
  2833. * css_next_descendant_post - find the next descendant for post-order walk
  2834. * @pos: the current position (%NULL to initiate traversal)
  2835. * @root: css whose descendants to walk
  2836. *
  2837. * To be used by css_for_each_descendant_post(). Find the next descendant
  2838. * to visit for post-order traversal of @root's descendants. @root is
  2839. * included in the iteration and the last node to be visited.
  2840. *
  2841. * While this function requires cgroup_mutex or RCU read locking, it
  2842. * doesn't require the whole traversal to be contained in a single critical
  2843. * section. This function will return the correct next descendant as long
  2844. * as both @pos and @cgroup are accessible and @pos is a descendant of
  2845. * @cgroup.
  2846. *
  2847. * If a subsystem synchronizes ->css_online() and the start of iteration, a
  2848. * css which finished ->css_online() is guaranteed to be visible in the
  2849. * future iterations and will stay visible until the last reference is put.
  2850. * A css which hasn't finished ->css_online() or already finished
  2851. * ->css_offline() may show up during traversal. It's each subsystem's
  2852. * responsibility to synchronize against on/offlining.
  2853. */
  2854. struct cgroup_subsys_state *
  2855. css_next_descendant_post(struct cgroup_subsys_state *pos,
  2856. struct cgroup_subsys_state *root)
  2857. {
  2858. struct cgroup_subsys_state *next;
  2859. cgroup_assert_mutex_or_rcu_locked();
  2860. /* if first iteration, visit leftmost descendant which may be @root */
  2861. if (!pos)
  2862. return css_leftmost_descendant(root);
  2863. /* if we visited @root, we're done */
  2864. if (pos == root)
  2865. return NULL;
  2866. /* if there's an unvisited sibling, visit its leftmost descendant */
  2867. next = css_next_child(pos, pos->parent);
  2868. if (next)
  2869. return css_leftmost_descendant(next);
  2870. /* no sibling left, visit parent */
  2871. return pos->parent;
  2872. }
  2873. /**
  2874. * css_has_online_children - does a css have online children
  2875. * @css: the target css
  2876. *
  2877. * Returns %true if @css has any online children; otherwise, %false. This
  2878. * function can be called from any context but the caller is responsible
  2879. * for synchronizing against on/offlining as necessary.
  2880. */
  2881. bool css_has_online_children(struct cgroup_subsys_state *css)
  2882. {
  2883. struct cgroup_subsys_state *child;
  2884. bool ret = false;
  2885. rcu_read_lock();
  2886. css_for_each_child(child, css) {
  2887. if (child->flags & CSS_ONLINE) {
  2888. ret = true;
  2889. break;
  2890. }
  2891. }
  2892. rcu_read_unlock();
  2893. return ret;
  2894. }
  2895. /**
  2896. * css_advance_task_iter - advance a task itererator to the next css_set
  2897. * @it: the iterator to advance
  2898. *
  2899. * Advance @it to the next css_set to walk.
  2900. */
  2901. static void css_advance_task_iter(struct css_task_iter *it)
  2902. {
  2903. struct list_head *l = it->cset_pos;
  2904. struct cgrp_cset_link *link;
  2905. struct css_set *cset;
  2906. /* Advance to the next non-empty css_set */
  2907. do {
  2908. l = l->next;
  2909. if (l == it->cset_head) {
  2910. it->cset_pos = NULL;
  2911. return;
  2912. }
  2913. if (it->ss) {
  2914. cset = container_of(l, struct css_set,
  2915. e_cset_node[it->ss->id]);
  2916. } else {
  2917. link = list_entry(l, struct cgrp_cset_link, cset_link);
  2918. cset = link->cset;
  2919. }
  2920. } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
  2921. it->cset_pos = l;
  2922. if (!list_empty(&cset->tasks))
  2923. it->task_pos = cset->tasks.next;
  2924. else
  2925. it->task_pos = cset->mg_tasks.next;
  2926. it->tasks_head = &cset->tasks;
  2927. it->mg_tasks_head = &cset->mg_tasks;
  2928. }
  2929. /**
  2930. * css_task_iter_start - initiate task iteration
  2931. * @css: the css to walk tasks of
  2932. * @it: the task iterator to use
  2933. *
  2934. * Initiate iteration through the tasks of @css. The caller can call
  2935. * css_task_iter_next() to walk through the tasks until the function
  2936. * returns NULL. On completion of iteration, css_task_iter_end() must be
  2937. * called.
  2938. *
  2939. * Note that this function acquires a lock which is released when the
  2940. * iteration finishes. The caller can't sleep while iteration is in
  2941. * progress.
  2942. */
  2943. void css_task_iter_start(struct cgroup_subsys_state *css,
  2944. struct css_task_iter *it)
  2945. __acquires(css_set_rwsem)
  2946. {
  2947. /* no one should try to iterate before mounting cgroups */
  2948. WARN_ON_ONCE(!use_task_css_set_links);
  2949. down_read(&css_set_rwsem);
  2950. it->ss = css->ss;
  2951. if (it->ss)
  2952. it->cset_pos = &css->cgroup->e_csets[css->ss->id];
  2953. else
  2954. it->cset_pos = &css->cgroup->cset_links;
  2955. it->cset_head = it->cset_pos;
  2956. css_advance_task_iter(it);
  2957. }
  2958. /**
  2959. * css_task_iter_next - return the next task for the iterator
  2960. * @it: the task iterator being iterated
  2961. *
  2962. * The "next" function for task iteration. @it should have been
  2963. * initialized via css_task_iter_start(). Returns NULL when the iteration
  2964. * reaches the end.
  2965. */
  2966. struct task_struct *css_task_iter_next(struct css_task_iter *it)
  2967. {
  2968. struct task_struct *res;
  2969. struct list_head *l = it->task_pos;
  2970. /* If the iterator cg is NULL, we have no tasks */
  2971. if (!it->cset_pos)
  2972. return NULL;
  2973. res = list_entry(l, struct task_struct, cg_list);
  2974. /*
  2975. * Advance iterator to find next entry. cset->tasks is consumed
  2976. * first and then ->mg_tasks. After ->mg_tasks, we move onto the
  2977. * next cset.
  2978. */
  2979. l = l->next;
  2980. if (l == it->tasks_head)
  2981. l = it->mg_tasks_head->next;
  2982. if (l == it->mg_tasks_head)
  2983. css_advance_task_iter(it);
  2984. else
  2985. it->task_pos = l;
  2986. return res;
  2987. }
  2988. /**
  2989. * css_task_iter_end - finish task iteration
  2990. * @it: the task iterator to finish
  2991. *
  2992. * Finish task iteration started by css_task_iter_start().
  2993. */
  2994. void css_task_iter_end(struct css_task_iter *it)
  2995. __releases(css_set_rwsem)
  2996. {
  2997. up_read(&css_set_rwsem);
  2998. }
  2999. /**
  3000. * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
  3001. * @to: cgroup to which the tasks will be moved
  3002. * @from: cgroup in which the tasks currently reside
  3003. *
  3004. * Locking rules between cgroup_post_fork() and the migration path
  3005. * guarantee that, if a task is forking while being migrated, the new child
  3006. * is guaranteed to be either visible in the source cgroup after the
  3007. * parent's migration is complete or put into the target cgroup. No task
  3008. * can slip out of migration through forking.
  3009. */
  3010. int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
  3011. {
  3012. LIST_HEAD(preloaded_csets);
  3013. struct cgrp_cset_link *link;
  3014. struct css_task_iter it;
  3015. struct task_struct *task;
  3016. int ret;
  3017. mutex_lock(&cgroup_mutex);
  3018. /* all tasks in @from are being moved, all csets are source */
  3019. down_read(&css_set_rwsem);
  3020. list_for_each_entry(link, &from->cset_links, cset_link)
  3021. cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
  3022. up_read(&css_set_rwsem);
  3023. ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
  3024. if (ret)
  3025. goto out_err;
  3026. /*
  3027. * Migrate tasks one-by-one until @form is empty. This fails iff
  3028. * ->can_attach() fails.
  3029. */
  3030. do {
  3031. css_task_iter_start(&from->self, &it);
  3032. task = css_task_iter_next(&it);
  3033. if (task)
  3034. get_task_struct(task);
  3035. css_task_iter_end(&it);
  3036. if (task) {
  3037. ret = cgroup_migrate(to, task, false);
  3038. put_task_struct(task);
  3039. }
  3040. } while (task && !ret);
  3041. out_err:
  3042. cgroup_migrate_finish(&preloaded_csets);
  3043. mutex_unlock(&cgroup_mutex);
  3044. return ret;
  3045. }
  3046. /*
  3047. * Stuff for reading the 'tasks'/'procs' files.
  3048. *
  3049. * Reading this file can return large amounts of data if a cgroup has
  3050. * *lots* of attached tasks. So it may need several calls to read(),
  3051. * but we cannot guarantee that the information we produce is correct
  3052. * unless we produce it entirely atomically.
  3053. *
  3054. */
  3055. /* which pidlist file are we talking about? */
  3056. enum cgroup_filetype {
  3057. CGROUP_FILE_PROCS,
  3058. CGROUP_FILE_TASKS,
  3059. };
  3060. /*
  3061. * A pidlist is a list of pids that virtually represents the contents of one
  3062. * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
  3063. * a pair (one each for procs, tasks) for each pid namespace that's relevant
  3064. * to the cgroup.
  3065. */
  3066. struct cgroup_pidlist {
  3067. /*
  3068. * used to find which pidlist is wanted. doesn't change as long as
  3069. * this particular list stays in the list.
  3070. */
  3071. struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
  3072. /* array of xids */
  3073. pid_t *list;
  3074. /* how many elements the above list has */
  3075. int length;
  3076. /* each of these stored in a list by its cgroup */
  3077. struct list_head links;
  3078. /* pointer to the cgroup we belong to, for list removal purposes */
  3079. struct cgroup *owner;
  3080. /* for delayed destruction */
  3081. struct delayed_work destroy_dwork;
  3082. };
  3083. /*
  3084. * The following two functions "fix" the issue where there are more pids
  3085. * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
  3086. * TODO: replace with a kernel-wide solution to this problem
  3087. */
  3088. #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
  3089. static void *pidlist_allocate(int count)
  3090. {
  3091. if (PIDLIST_TOO_LARGE(count))
  3092. return vmalloc(count * sizeof(pid_t));
  3093. else
  3094. return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
  3095. }
  3096. static void pidlist_free(void *p)
  3097. {
  3098. if (is_vmalloc_addr(p))
  3099. vfree(p);
  3100. else
  3101. kfree(p);
  3102. }
  3103. /*
  3104. * Used to destroy all pidlists lingering waiting for destroy timer. None
  3105. * should be left afterwards.
  3106. */
  3107. static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
  3108. {
  3109. struct cgroup_pidlist *l, *tmp_l;
  3110. mutex_lock(&cgrp->pidlist_mutex);
  3111. list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
  3112. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
  3113. mutex_unlock(&cgrp->pidlist_mutex);
  3114. flush_workqueue(cgroup_pidlist_destroy_wq);
  3115. BUG_ON(!list_empty(&cgrp->pidlists));
  3116. }
  3117. static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
  3118. {
  3119. struct delayed_work *dwork = to_delayed_work(work);
  3120. struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
  3121. destroy_dwork);
  3122. struct cgroup_pidlist *tofree = NULL;
  3123. mutex_lock(&l->owner->pidlist_mutex);
  3124. /*
  3125. * Destroy iff we didn't get queued again. The state won't change
  3126. * as destroy_dwork can only be queued while locked.
  3127. */
  3128. if (!delayed_work_pending(dwork)) {
  3129. list_del(&l->links);
  3130. pidlist_free(l->list);
  3131. put_pid_ns(l->key.ns);
  3132. tofree = l;
  3133. }
  3134. mutex_unlock(&l->owner->pidlist_mutex);
  3135. kfree(tofree);
  3136. }
  3137. /*
  3138. * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
  3139. * Returns the number of unique elements.
  3140. */
  3141. static int pidlist_uniq(pid_t *list, int length)
  3142. {
  3143. int src, dest = 1;
  3144. /*
  3145. * we presume the 0th element is unique, so i starts at 1. trivial
  3146. * edge cases first; no work needs to be done for either
  3147. */
  3148. if (length == 0 || length == 1)
  3149. return length;
  3150. /* src and dest walk down the list; dest counts unique elements */
  3151. for (src = 1; src < length; src++) {
  3152. /* find next unique element */
  3153. while (list[src] == list[src-1]) {
  3154. src++;
  3155. if (src == length)
  3156. goto after;
  3157. }
  3158. /* dest always points to where the next unique element goes */
  3159. list[dest] = list[src];
  3160. dest++;
  3161. }
  3162. after:
  3163. return dest;
  3164. }
  3165. /*
  3166. * The two pid files - task and cgroup.procs - guaranteed that the result
  3167. * is sorted, which forced this whole pidlist fiasco. As pid order is
  3168. * different per namespace, each namespace needs differently sorted list,
  3169. * making it impossible to use, for example, single rbtree of member tasks
  3170. * sorted by task pointer. As pidlists can be fairly large, allocating one
  3171. * per open file is dangerous, so cgroup had to implement shared pool of
  3172. * pidlists keyed by cgroup and namespace.
  3173. *
  3174. * All this extra complexity was caused by the original implementation
  3175. * committing to an entirely unnecessary property. In the long term, we
  3176. * want to do away with it. Explicitly scramble sort order if
  3177. * sane_behavior so that no such expectation exists in the new interface.
  3178. *
  3179. * Scrambling is done by swapping every two consecutive bits, which is
  3180. * non-identity one-to-one mapping which disturbs sort order sufficiently.
  3181. */
  3182. static pid_t pid_fry(pid_t pid)
  3183. {
  3184. unsigned a = pid & 0x55555555;
  3185. unsigned b = pid & 0xAAAAAAAA;
  3186. return (a << 1) | (b >> 1);
  3187. }
  3188. static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
  3189. {
  3190. if (cgroup_sane_behavior(cgrp))
  3191. return pid_fry(pid);
  3192. else
  3193. return pid;
  3194. }
  3195. static int cmppid(const void *a, const void *b)
  3196. {
  3197. return *(pid_t *)a - *(pid_t *)b;
  3198. }
  3199. static int fried_cmppid(const void *a, const void *b)
  3200. {
  3201. return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
  3202. }
  3203. static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
  3204. enum cgroup_filetype type)
  3205. {
  3206. struct cgroup_pidlist *l;
  3207. /* don't need task_nsproxy() if we're looking at ourself */
  3208. struct pid_namespace *ns = task_active_pid_ns(current);
  3209. lockdep_assert_held(&cgrp->pidlist_mutex);
  3210. list_for_each_entry(l, &cgrp->pidlists, links)
  3211. if (l->key.type == type && l->key.ns == ns)
  3212. return l;
  3213. return NULL;
  3214. }
  3215. /*
  3216. * find the appropriate pidlist for our purpose (given procs vs tasks)
  3217. * returns with the lock on that pidlist already held, and takes care
  3218. * of the use count, or returns NULL with no locks held if we're out of
  3219. * memory.
  3220. */
  3221. static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
  3222. enum cgroup_filetype type)
  3223. {
  3224. struct cgroup_pidlist *l;
  3225. lockdep_assert_held(&cgrp->pidlist_mutex);
  3226. l = cgroup_pidlist_find(cgrp, type);
  3227. if (l)
  3228. return l;
  3229. /* entry not found; create a new one */
  3230. l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
  3231. if (!l)
  3232. return l;
  3233. INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
  3234. l->key.type = type;
  3235. /* don't need task_nsproxy() if we're looking at ourself */
  3236. l->key.ns = get_pid_ns(task_active_pid_ns(current));
  3237. l->owner = cgrp;
  3238. list_add(&l->links, &cgrp->pidlists);
  3239. return l;
  3240. }
  3241. /*
  3242. * Load a cgroup's pidarray with either procs' tgids or tasks' pids
  3243. */
  3244. static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
  3245. struct cgroup_pidlist **lp)
  3246. {
  3247. pid_t *array;
  3248. int length;
  3249. int pid, n = 0; /* used for populating the array */
  3250. struct css_task_iter it;
  3251. struct task_struct *tsk;
  3252. struct cgroup_pidlist *l;
  3253. lockdep_assert_held(&cgrp->pidlist_mutex);
  3254. /*
  3255. * If cgroup gets more users after we read count, we won't have
  3256. * enough space - tough. This race is indistinguishable to the
  3257. * caller from the case that the additional cgroup users didn't
  3258. * show up until sometime later on.
  3259. */
  3260. length = cgroup_task_count(cgrp);
  3261. array = pidlist_allocate(length);
  3262. if (!array)
  3263. return -ENOMEM;
  3264. /* now, populate the array */
  3265. css_task_iter_start(&cgrp->self, &it);
  3266. while ((tsk = css_task_iter_next(&it))) {
  3267. if (unlikely(n == length))
  3268. break;
  3269. /* get tgid or pid for procs or tasks file respectively */
  3270. if (type == CGROUP_FILE_PROCS)
  3271. pid = task_tgid_vnr(tsk);
  3272. else
  3273. pid = task_pid_vnr(tsk);
  3274. if (pid > 0) /* make sure to only use valid results */
  3275. array[n++] = pid;
  3276. }
  3277. css_task_iter_end(&it);
  3278. length = n;
  3279. /* now sort & (if procs) strip out duplicates */
  3280. if (cgroup_sane_behavior(cgrp))
  3281. sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
  3282. else
  3283. sort(array, length, sizeof(pid_t), cmppid, NULL);
  3284. if (type == CGROUP_FILE_PROCS)
  3285. length = pidlist_uniq(array, length);
  3286. l = cgroup_pidlist_find_create(cgrp, type);
  3287. if (!l) {
  3288. mutex_unlock(&cgrp->pidlist_mutex);
  3289. pidlist_free(array);
  3290. return -ENOMEM;
  3291. }
  3292. /* store array, freeing old if necessary */
  3293. pidlist_free(l->list);
  3294. l->list = array;
  3295. l->length = length;
  3296. *lp = l;
  3297. return 0;
  3298. }
  3299. /**
  3300. * cgroupstats_build - build and fill cgroupstats
  3301. * @stats: cgroupstats to fill information into
  3302. * @dentry: A dentry entry belonging to the cgroup for which stats have
  3303. * been requested.
  3304. *
  3305. * Build and fill cgroupstats so that taskstats can export it to user
  3306. * space.
  3307. */
  3308. int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
  3309. {
  3310. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  3311. struct cgroup *cgrp;
  3312. struct css_task_iter it;
  3313. struct task_struct *tsk;
  3314. /* it should be kernfs_node belonging to cgroupfs and is a directory */
  3315. if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
  3316. kernfs_type(kn) != KERNFS_DIR)
  3317. return -EINVAL;
  3318. mutex_lock(&cgroup_mutex);
  3319. /*
  3320. * We aren't being called from kernfs and there's no guarantee on
  3321. * @kn->priv's validity. For this and css_tryget_online_from_dir(),
  3322. * @kn->priv is RCU safe. Let's do the RCU dancing.
  3323. */
  3324. rcu_read_lock();
  3325. cgrp = rcu_dereference(kn->priv);
  3326. if (!cgrp || cgroup_is_dead(cgrp)) {
  3327. rcu_read_unlock();
  3328. mutex_unlock(&cgroup_mutex);
  3329. return -ENOENT;
  3330. }
  3331. rcu_read_unlock();
  3332. css_task_iter_start(&cgrp->self, &it);
  3333. while ((tsk = css_task_iter_next(&it))) {
  3334. switch (tsk->state) {
  3335. case TASK_RUNNING:
  3336. stats->nr_running++;
  3337. break;
  3338. case TASK_INTERRUPTIBLE:
  3339. stats->nr_sleeping++;
  3340. break;
  3341. case TASK_UNINTERRUPTIBLE:
  3342. stats->nr_uninterruptible++;
  3343. break;
  3344. case TASK_STOPPED:
  3345. stats->nr_stopped++;
  3346. break;
  3347. default:
  3348. if (delayacct_is_task_waiting_on_io(tsk))
  3349. stats->nr_io_wait++;
  3350. break;
  3351. }
  3352. }
  3353. css_task_iter_end(&it);
  3354. mutex_unlock(&cgroup_mutex);
  3355. return 0;
  3356. }
  3357. /*
  3358. * seq_file methods for the tasks/procs files. The seq_file position is the
  3359. * next pid to display; the seq_file iterator is a pointer to the pid
  3360. * in the cgroup->l->list array.
  3361. */
  3362. static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
  3363. {
  3364. /*
  3365. * Initially we receive a position value that corresponds to
  3366. * one more than the last pid shown (or 0 on the first call or
  3367. * after a seek to the start). Use a binary-search to find the
  3368. * next pid to display, if any
  3369. */
  3370. struct kernfs_open_file *of = s->private;
  3371. struct cgroup *cgrp = seq_css(s)->cgroup;
  3372. struct cgroup_pidlist *l;
  3373. enum cgroup_filetype type = seq_cft(s)->private;
  3374. int index = 0, pid = *pos;
  3375. int *iter, ret;
  3376. mutex_lock(&cgrp->pidlist_mutex);
  3377. /*
  3378. * !NULL @of->priv indicates that this isn't the first start()
  3379. * after open. If the matching pidlist is around, we can use that.
  3380. * Look for it. Note that @of->priv can't be used directly. It
  3381. * could already have been destroyed.
  3382. */
  3383. if (of->priv)
  3384. of->priv = cgroup_pidlist_find(cgrp, type);
  3385. /*
  3386. * Either this is the first start() after open or the matching
  3387. * pidlist has been destroyed inbetween. Create a new one.
  3388. */
  3389. if (!of->priv) {
  3390. ret = pidlist_array_load(cgrp, type,
  3391. (struct cgroup_pidlist **)&of->priv);
  3392. if (ret)
  3393. return ERR_PTR(ret);
  3394. }
  3395. l = of->priv;
  3396. if (pid) {
  3397. int end = l->length;
  3398. while (index < end) {
  3399. int mid = (index + end) / 2;
  3400. if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
  3401. index = mid;
  3402. break;
  3403. } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
  3404. index = mid + 1;
  3405. else
  3406. end = mid;
  3407. }
  3408. }
  3409. /* If we're off the end of the array, we're done */
  3410. if (index >= l->length)
  3411. return NULL;
  3412. /* Update the abstract position to be the actual pid that we found */
  3413. iter = l->list + index;
  3414. *pos = cgroup_pid_fry(cgrp, *iter);
  3415. return iter;
  3416. }
  3417. static void cgroup_pidlist_stop(struct seq_file *s, void *v)
  3418. {
  3419. struct kernfs_open_file *of = s->private;
  3420. struct cgroup_pidlist *l = of->priv;
  3421. if (l)
  3422. mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
  3423. CGROUP_PIDLIST_DESTROY_DELAY);
  3424. mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
  3425. }
  3426. static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
  3427. {
  3428. struct kernfs_open_file *of = s->private;
  3429. struct cgroup_pidlist *l = of->priv;
  3430. pid_t *p = v;
  3431. pid_t *end = l->list + l->length;
  3432. /*
  3433. * Advance to the next pid in the array. If this goes off the
  3434. * end, we're done
  3435. */
  3436. p++;
  3437. if (p >= end) {
  3438. return NULL;
  3439. } else {
  3440. *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
  3441. return p;
  3442. }
  3443. }
  3444. static int cgroup_pidlist_show(struct seq_file *s, void *v)
  3445. {
  3446. return seq_printf(s, "%d\n", *(int *)v);
  3447. }
  3448. static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
  3449. struct cftype *cft)
  3450. {
  3451. return notify_on_release(css->cgroup);
  3452. }
  3453. static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
  3454. struct cftype *cft, u64 val)
  3455. {
  3456. clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
  3457. if (val)
  3458. set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  3459. else
  3460. clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
  3461. return 0;
  3462. }
  3463. static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
  3464. struct cftype *cft)
  3465. {
  3466. return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  3467. }
  3468. static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
  3469. struct cftype *cft, u64 val)
  3470. {
  3471. if (val)
  3472. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  3473. else
  3474. clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
  3475. return 0;
  3476. }
  3477. static struct cftype cgroup_base_files[] = {
  3478. {
  3479. .name = "cgroup.procs",
  3480. .seq_start = cgroup_pidlist_start,
  3481. .seq_next = cgroup_pidlist_next,
  3482. .seq_stop = cgroup_pidlist_stop,
  3483. .seq_show = cgroup_pidlist_show,
  3484. .private = CGROUP_FILE_PROCS,
  3485. .write = cgroup_procs_write,
  3486. .mode = S_IRUGO | S_IWUSR,
  3487. },
  3488. {
  3489. .name = "cgroup.clone_children",
  3490. .flags = CFTYPE_INSANE,
  3491. .read_u64 = cgroup_clone_children_read,
  3492. .write_u64 = cgroup_clone_children_write,
  3493. },
  3494. {
  3495. .name = "cgroup.sane_behavior",
  3496. .flags = CFTYPE_ONLY_ON_ROOT,
  3497. .seq_show = cgroup_sane_behavior_show,
  3498. },
  3499. {
  3500. .name = "cgroup.controllers",
  3501. .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
  3502. .seq_show = cgroup_root_controllers_show,
  3503. },
  3504. {
  3505. .name = "cgroup.controllers",
  3506. .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
  3507. .seq_show = cgroup_controllers_show,
  3508. },
  3509. {
  3510. .name = "cgroup.subtree_control",
  3511. .flags = CFTYPE_ONLY_ON_DFL,
  3512. .seq_show = cgroup_subtree_control_show,
  3513. .write = cgroup_subtree_control_write,
  3514. },
  3515. {
  3516. .name = "cgroup.populated",
  3517. .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
  3518. .seq_show = cgroup_populated_show,
  3519. },
  3520. /*
  3521. * Historical crazy stuff. These don't have "cgroup." prefix and
  3522. * don't exist if sane_behavior. If you're depending on these, be
  3523. * prepared to be burned.
  3524. */
  3525. {
  3526. .name = "tasks",
  3527. .flags = CFTYPE_INSANE, /* use "procs" instead */
  3528. .seq_start = cgroup_pidlist_start,
  3529. .seq_next = cgroup_pidlist_next,
  3530. .seq_stop = cgroup_pidlist_stop,
  3531. .seq_show = cgroup_pidlist_show,
  3532. .private = CGROUP_FILE_TASKS,
  3533. .write = cgroup_tasks_write,
  3534. .mode = S_IRUGO | S_IWUSR,
  3535. },
  3536. {
  3537. .name = "notify_on_release",
  3538. .flags = CFTYPE_INSANE,
  3539. .read_u64 = cgroup_read_notify_on_release,
  3540. .write_u64 = cgroup_write_notify_on_release,
  3541. },
  3542. {
  3543. .name = "release_agent",
  3544. .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
  3545. .seq_show = cgroup_release_agent_show,
  3546. .write = cgroup_release_agent_write,
  3547. .max_write_len = PATH_MAX - 1,
  3548. },
  3549. { } /* terminate */
  3550. };
  3551. /**
  3552. * cgroup_populate_dir - create subsys files in a cgroup directory
  3553. * @cgrp: target cgroup
  3554. * @subsys_mask: mask of the subsystem ids whose files should be added
  3555. *
  3556. * On failure, no file is added.
  3557. */
  3558. static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
  3559. {
  3560. struct cgroup_subsys *ss;
  3561. int i, ret = 0;
  3562. /* process cftsets of each subsystem */
  3563. for_each_subsys(ss, i) {
  3564. struct cftype *cfts;
  3565. if (!(subsys_mask & (1 << i)))
  3566. continue;
  3567. list_for_each_entry(cfts, &ss->cfts, node) {
  3568. ret = cgroup_addrm_files(cgrp, cfts, true);
  3569. if (ret < 0)
  3570. goto err;
  3571. }
  3572. }
  3573. return 0;
  3574. err:
  3575. cgroup_clear_dir(cgrp, subsys_mask);
  3576. return ret;
  3577. }
  3578. /*
  3579. * css destruction is four-stage process.
  3580. *
  3581. * 1. Destruction starts. Killing of the percpu_ref is initiated.
  3582. * Implemented in kill_css().
  3583. *
  3584. * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
  3585. * and thus css_tryget_online() is guaranteed to fail, the css can be
  3586. * offlined by invoking offline_css(). After offlining, the base ref is
  3587. * put. Implemented in css_killed_work_fn().
  3588. *
  3589. * 3. When the percpu_ref reaches zero, the only possible remaining
  3590. * accessors are inside RCU read sections. css_release() schedules the
  3591. * RCU callback.
  3592. *
  3593. * 4. After the grace period, the css can be freed. Implemented in
  3594. * css_free_work_fn().
  3595. *
  3596. * It is actually hairier because both step 2 and 4 require process context
  3597. * and thus involve punting to css->destroy_work adding two additional
  3598. * steps to the already complex sequence.
  3599. */
  3600. static void css_free_work_fn(struct work_struct *work)
  3601. {
  3602. struct cgroup_subsys_state *css =
  3603. container_of(work, struct cgroup_subsys_state, destroy_work);
  3604. struct cgroup *cgrp = css->cgroup;
  3605. if (css->ss) {
  3606. /* css free path */
  3607. if (css->parent)
  3608. css_put(css->parent);
  3609. css->ss->css_free(css);
  3610. cgroup_put(cgrp);
  3611. } else {
  3612. /* cgroup free path */
  3613. atomic_dec(&cgrp->root->nr_cgrps);
  3614. cgroup_pidlist_destroy_all(cgrp);
  3615. if (cgroup_parent(cgrp)) {
  3616. /*
  3617. * We get a ref to the parent, and put the ref when
  3618. * this cgroup is being freed, so it's guaranteed
  3619. * that the parent won't be destroyed before its
  3620. * children.
  3621. */
  3622. cgroup_put(cgroup_parent(cgrp));
  3623. kernfs_put(cgrp->kn);
  3624. kfree(cgrp);
  3625. } else {
  3626. /*
  3627. * This is root cgroup's refcnt reaching zero,
  3628. * which indicates that the root should be
  3629. * released.
  3630. */
  3631. cgroup_destroy_root(cgrp->root);
  3632. }
  3633. }
  3634. }
  3635. static void css_free_rcu_fn(struct rcu_head *rcu_head)
  3636. {
  3637. struct cgroup_subsys_state *css =
  3638. container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
  3639. INIT_WORK(&css->destroy_work, css_free_work_fn);
  3640. queue_work(cgroup_destroy_wq, &css->destroy_work);
  3641. }
  3642. static void css_release_work_fn(struct work_struct *work)
  3643. {
  3644. struct cgroup_subsys_state *css =
  3645. container_of(work, struct cgroup_subsys_state, destroy_work);
  3646. struct cgroup_subsys *ss = css->ss;
  3647. struct cgroup *cgrp = css->cgroup;
  3648. mutex_lock(&cgroup_mutex);
  3649. css->flags |= CSS_RELEASED;
  3650. list_del_rcu(&css->sibling);
  3651. if (ss) {
  3652. /* css release path */
  3653. cgroup_idr_remove(&ss->css_idr, css->id);
  3654. } else {
  3655. /* cgroup release path */
  3656. cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
  3657. cgrp->id = -1;
  3658. }
  3659. mutex_unlock(&cgroup_mutex);
  3660. call_rcu(&css->rcu_head, css_free_rcu_fn);
  3661. }
  3662. static void css_release(struct percpu_ref *ref)
  3663. {
  3664. struct cgroup_subsys_state *css =
  3665. container_of(ref, struct cgroup_subsys_state, refcnt);
  3666. INIT_WORK(&css->destroy_work, css_release_work_fn);
  3667. queue_work(cgroup_destroy_wq, &css->destroy_work);
  3668. }
  3669. static void init_and_link_css(struct cgroup_subsys_state *css,
  3670. struct cgroup_subsys *ss, struct cgroup *cgrp)
  3671. {
  3672. lockdep_assert_held(&cgroup_mutex);
  3673. cgroup_get(cgrp);
  3674. memset(css, 0, sizeof(*css));
  3675. css->cgroup = cgrp;
  3676. css->ss = ss;
  3677. INIT_LIST_HEAD(&css->sibling);
  3678. INIT_LIST_HEAD(&css->children);
  3679. css->serial_nr = css_serial_nr_next++;
  3680. if (cgroup_parent(cgrp)) {
  3681. css->parent = cgroup_css(cgroup_parent(cgrp), ss);
  3682. css_get(css->parent);
  3683. }
  3684. BUG_ON(cgroup_css(cgrp, ss));
  3685. }
  3686. /* invoke ->css_online() on a new CSS and mark it online if successful */
  3687. static int online_css(struct cgroup_subsys_state *css)
  3688. {
  3689. struct cgroup_subsys *ss = css->ss;
  3690. int ret = 0;
  3691. lockdep_assert_held(&cgroup_mutex);
  3692. if (ss->css_online)
  3693. ret = ss->css_online(css);
  3694. if (!ret) {
  3695. css->flags |= CSS_ONLINE;
  3696. rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
  3697. }
  3698. return ret;
  3699. }
  3700. /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
  3701. static void offline_css(struct cgroup_subsys_state *css)
  3702. {
  3703. struct cgroup_subsys *ss = css->ss;
  3704. lockdep_assert_held(&cgroup_mutex);
  3705. if (!(css->flags & CSS_ONLINE))
  3706. return;
  3707. if (ss->css_offline)
  3708. ss->css_offline(css);
  3709. css->flags &= ~CSS_ONLINE;
  3710. RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
  3711. wake_up_all(&css->cgroup->offline_waitq);
  3712. }
  3713. /**
  3714. * create_css - create a cgroup_subsys_state
  3715. * @cgrp: the cgroup new css will be associated with
  3716. * @ss: the subsys of new css
  3717. *
  3718. * Create a new css associated with @cgrp - @ss pair. On success, the new
  3719. * css is online and installed in @cgrp with all interface files created.
  3720. * Returns 0 on success, -errno on failure.
  3721. */
  3722. static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
  3723. {
  3724. struct cgroup *parent = cgroup_parent(cgrp);
  3725. struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
  3726. struct cgroup_subsys_state *css;
  3727. int err;
  3728. lockdep_assert_held(&cgroup_mutex);
  3729. css = ss->css_alloc(parent_css);
  3730. if (IS_ERR(css))
  3731. return PTR_ERR(css);
  3732. init_and_link_css(css, ss, cgrp);
  3733. err = percpu_ref_init(&css->refcnt, css_release);
  3734. if (err)
  3735. goto err_free_css;
  3736. err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
  3737. if (err < 0)
  3738. goto err_free_percpu_ref;
  3739. css->id = err;
  3740. err = cgroup_populate_dir(cgrp, 1 << ss->id);
  3741. if (err)
  3742. goto err_free_id;
  3743. /* @css is ready to be brought online now, make it visible */
  3744. list_add_tail_rcu(&css->sibling, &parent_css->children);
  3745. cgroup_idr_replace(&ss->css_idr, css, css->id);
  3746. err = online_css(css);
  3747. if (err)
  3748. goto err_list_del;
  3749. if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
  3750. cgroup_parent(parent)) {
  3751. pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
  3752. current->comm, current->pid, ss->name);
  3753. if (!strcmp(ss->name, "memory"))
  3754. pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
  3755. ss->warned_broken_hierarchy = true;
  3756. }
  3757. return 0;
  3758. err_list_del:
  3759. list_del_rcu(&css->sibling);
  3760. cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
  3761. err_free_id:
  3762. cgroup_idr_remove(&ss->css_idr, css->id);
  3763. err_free_percpu_ref:
  3764. percpu_ref_cancel_init(&css->refcnt);
  3765. err_free_css:
  3766. call_rcu(&css->rcu_head, css_free_rcu_fn);
  3767. return err;
  3768. }
  3769. static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
  3770. umode_t mode)
  3771. {
  3772. struct cgroup *parent, *cgrp;
  3773. struct cgroup_root *root;
  3774. struct cgroup_subsys *ss;
  3775. struct kernfs_node *kn;
  3776. int ssid, ret;
  3777. parent = cgroup_kn_lock_live(parent_kn);
  3778. if (!parent)
  3779. return -ENODEV;
  3780. root = parent->root;
  3781. /* allocate the cgroup and its ID, 0 is reserved for the root */
  3782. cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
  3783. if (!cgrp) {
  3784. ret = -ENOMEM;
  3785. goto out_unlock;
  3786. }
  3787. ret = percpu_ref_init(&cgrp->self.refcnt, css_release);
  3788. if (ret)
  3789. goto out_free_cgrp;
  3790. /*
  3791. * Temporarily set the pointer to NULL, so idr_find() won't return
  3792. * a half-baked cgroup.
  3793. */
  3794. cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
  3795. if (cgrp->id < 0) {
  3796. ret = -ENOMEM;
  3797. goto out_cancel_ref;
  3798. }
  3799. init_cgroup_housekeeping(cgrp);
  3800. cgrp->self.parent = &parent->self;
  3801. cgrp->root = root;
  3802. if (notify_on_release(parent))
  3803. set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
  3804. if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
  3805. set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
  3806. /* create the directory */
  3807. kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
  3808. if (IS_ERR(kn)) {
  3809. ret = PTR_ERR(kn);
  3810. goto out_free_id;
  3811. }
  3812. cgrp->kn = kn;
  3813. /*
  3814. * This extra ref will be put in cgroup_free_fn() and guarantees
  3815. * that @cgrp->kn is always accessible.
  3816. */
  3817. kernfs_get(kn);
  3818. cgrp->self.serial_nr = css_serial_nr_next++;
  3819. /* allocation complete, commit to creation */
  3820. list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
  3821. atomic_inc(&root->nr_cgrps);
  3822. cgroup_get(parent);
  3823. /*
  3824. * @cgrp is now fully operational. If something fails after this
  3825. * point, it'll be released via the normal destruction path.
  3826. */
  3827. cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
  3828. ret = cgroup_kn_set_ugid(kn);
  3829. if (ret)
  3830. goto out_destroy;
  3831. ret = cgroup_addrm_files(cgrp, cgroup_base_files, true);
  3832. if (ret)
  3833. goto out_destroy;
  3834. /* let's create and online css's */
  3835. for_each_subsys(ss, ssid) {
  3836. if (parent->child_subsys_mask & (1 << ssid)) {
  3837. ret = create_css(cgrp, ss);
  3838. if (ret)
  3839. goto out_destroy;
  3840. }
  3841. }
  3842. /*
  3843. * On the default hierarchy, a child doesn't automatically inherit
  3844. * child_subsys_mask from the parent. Each is configured manually.
  3845. */
  3846. if (!cgroup_on_dfl(cgrp))
  3847. cgrp->child_subsys_mask = parent->child_subsys_mask;
  3848. kernfs_activate(kn);
  3849. ret = 0;
  3850. goto out_unlock;
  3851. out_free_id:
  3852. cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
  3853. out_cancel_ref:
  3854. percpu_ref_cancel_init(&cgrp->self.refcnt);
  3855. out_free_cgrp:
  3856. kfree(cgrp);
  3857. out_unlock:
  3858. cgroup_kn_unlock(parent_kn);
  3859. return ret;
  3860. out_destroy:
  3861. cgroup_destroy_locked(cgrp);
  3862. goto out_unlock;
  3863. }
  3864. /*
  3865. * This is called when the refcnt of a css is confirmed to be killed.
  3866. * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
  3867. * initate destruction and put the css ref from kill_css().
  3868. */
  3869. static void css_killed_work_fn(struct work_struct *work)
  3870. {
  3871. struct cgroup_subsys_state *css =
  3872. container_of(work, struct cgroup_subsys_state, destroy_work);
  3873. mutex_lock(&cgroup_mutex);
  3874. offline_css(css);
  3875. mutex_unlock(&cgroup_mutex);
  3876. css_put(css);
  3877. }
  3878. /* css kill confirmation processing requires process context, bounce */
  3879. static void css_killed_ref_fn(struct percpu_ref *ref)
  3880. {
  3881. struct cgroup_subsys_state *css =
  3882. container_of(ref, struct cgroup_subsys_state, refcnt);
  3883. INIT_WORK(&css->destroy_work, css_killed_work_fn);
  3884. queue_work(cgroup_destroy_wq, &css->destroy_work);
  3885. }
  3886. /**
  3887. * kill_css - destroy a css
  3888. * @css: css to destroy
  3889. *
  3890. * This function initiates destruction of @css by removing cgroup interface
  3891. * files and putting its base reference. ->css_offline() will be invoked
  3892. * asynchronously once css_tryget_online() is guaranteed to fail and when
  3893. * the reference count reaches zero, @css will be released.
  3894. */
  3895. static void kill_css(struct cgroup_subsys_state *css)
  3896. {
  3897. lockdep_assert_held(&cgroup_mutex);
  3898. /*
  3899. * This must happen before css is disassociated with its cgroup.
  3900. * See seq_css() for details.
  3901. */
  3902. cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
  3903. /*
  3904. * Killing would put the base ref, but we need to keep it alive
  3905. * until after ->css_offline().
  3906. */
  3907. css_get(css);
  3908. /*
  3909. * cgroup core guarantees that, by the time ->css_offline() is
  3910. * invoked, no new css reference will be given out via
  3911. * css_tryget_online(). We can't simply call percpu_ref_kill() and
  3912. * proceed to offlining css's because percpu_ref_kill() doesn't
  3913. * guarantee that the ref is seen as killed on all CPUs on return.
  3914. *
  3915. * Use percpu_ref_kill_and_confirm() to get notifications as each
  3916. * css is confirmed to be seen as killed on all CPUs.
  3917. */
  3918. percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
  3919. }
  3920. /**
  3921. * cgroup_destroy_locked - the first stage of cgroup destruction
  3922. * @cgrp: cgroup to be destroyed
  3923. *
  3924. * css's make use of percpu refcnts whose killing latency shouldn't be
  3925. * exposed to userland and are RCU protected. Also, cgroup core needs to
  3926. * guarantee that css_tryget_online() won't succeed by the time
  3927. * ->css_offline() is invoked. To satisfy all the requirements,
  3928. * destruction is implemented in the following two steps.
  3929. *
  3930. * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
  3931. * userland visible parts and start killing the percpu refcnts of
  3932. * css's. Set up so that the next stage will be kicked off once all
  3933. * the percpu refcnts are confirmed to be killed.
  3934. *
  3935. * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
  3936. * rest of destruction. Once all cgroup references are gone, the
  3937. * cgroup is RCU-freed.
  3938. *
  3939. * This function implements s1. After this step, @cgrp is gone as far as
  3940. * the userland is concerned and a new cgroup with the same name may be
  3941. * created. As cgroup doesn't care about the names internally, this
  3942. * doesn't cause any problem.
  3943. */
  3944. static int cgroup_destroy_locked(struct cgroup *cgrp)
  3945. __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
  3946. {
  3947. struct cgroup_subsys_state *css;
  3948. bool empty;
  3949. int ssid;
  3950. lockdep_assert_held(&cgroup_mutex);
  3951. /*
  3952. * css_set_rwsem synchronizes access to ->cset_links and prevents
  3953. * @cgrp from being removed while put_css_set() is in progress.
  3954. */
  3955. down_read(&css_set_rwsem);
  3956. empty = list_empty(&cgrp->cset_links);
  3957. up_read(&css_set_rwsem);
  3958. if (!empty)
  3959. return -EBUSY;
  3960. /*
  3961. * Make sure there's no live children. We can't test emptiness of
  3962. * ->self.children as dead children linger on it while being
  3963. * drained; otherwise, "rmdir parent/child parent" may fail.
  3964. */
  3965. if (css_has_online_children(&cgrp->self))
  3966. return -EBUSY;
  3967. /*
  3968. * Mark @cgrp dead. This prevents further task migration and child
  3969. * creation by disabling cgroup_lock_live_group().
  3970. */
  3971. cgrp->self.flags &= ~CSS_ONLINE;
  3972. /* initiate massacre of all css's */
  3973. for_each_css(css, ssid, cgrp)
  3974. kill_css(css);
  3975. /* CSS_ONLINE is clear, remove from ->release_list for the last time */
  3976. raw_spin_lock(&release_list_lock);
  3977. if (!list_empty(&cgrp->release_list))
  3978. list_del_init(&cgrp->release_list);
  3979. raw_spin_unlock(&release_list_lock);
  3980. /*
  3981. * Remove @cgrp directory along with the base files. @cgrp has an
  3982. * extra ref on its kn.
  3983. */
  3984. kernfs_remove(cgrp->kn);
  3985. set_bit(CGRP_RELEASABLE, &cgroup_parent(cgrp)->flags);
  3986. check_for_release(cgroup_parent(cgrp));
  3987. /* put the base reference */
  3988. percpu_ref_kill(&cgrp->self.refcnt);
  3989. return 0;
  3990. };
  3991. static int cgroup_rmdir(struct kernfs_node *kn)
  3992. {
  3993. struct cgroup *cgrp;
  3994. int ret = 0;
  3995. cgrp = cgroup_kn_lock_live(kn);
  3996. if (!cgrp)
  3997. return 0;
  3998. cgroup_get(cgrp); /* for @kn->priv clearing */
  3999. ret = cgroup_destroy_locked(cgrp);
  4000. cgroup_kn_unlock(kn);
  4001. /*
  4002. * There are two control paths which try to determine cgroup from
  4003. * dentry without going through kernfs - cgroupstats_build() and
  4004. * css_tryget_online_from_dir(). Those are supported by RCU
  4005. * protecting clearing of cgrp->kn->priv backpointer, which should
  4006. * happen after all files under it have been removed.
  4007. */
  4008. if (!ret)
  4009. RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
  4010. cgroup_put(cgrp);
  4011. return ret;
  4012. }
  4013. static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
  4014. .remount_fs = cgroup_remount,
  4015. .show_options = cgroup_show_options,
  4016. .mkdir = cgroup_mkdir,
  4017. .rmdir = cgroup_rmdir,
  4018. .rename = cgroup_rename,
  4019. };
  4020. static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
  4021. {
  4022. struct cgroup_subsys_state *css;
  4023. printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
  4024. mutex_lock(&cgroup_mutex);
  4025. idr_init(&ss->css_idr);
  4026. INIT_LIST_HEAD(&ss->cfts);
  4027. /* Create the root cgroup state for this subsystem */
  4028. ss->root = &cgrp_dfl_root;
  4029. css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
  4030. /* We don't handle early failures gracefully */
  4031. BUG_ON(IS_ERR(css));
  4032. init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
  4033. /*
  4034. * Root csses are never destroyed and we can't initialize
  4035. * percpu_ref during early init. Disable refcnting.
  4036. */
  4037. css->flags |= CSS_NO_REF;
  4038. if (early) {
  4039. /* allocation can't be done safely during early init */
  4040. css->id = 1;
  4041. } else {
  4042. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
  4043. BUG_ON(css->id < 0);
  4044. }
  4045. /* Update the init_css_set to contain a subsys
  4046. * pointer to this state - since the subsystem is
  4047. * newly registered, all tasks and hence the
  4048. * init_css_set is in the subsystem's root cgroup. */
  4049. init_css_set.subsys[ss->id] = css;
  4050. need_forkexit_callback |= ss->fork || ss->exit;
  4051. /* At system boot, before all subsystems have been
  4052. * registered, no tasks have been forked, so we don't
  4053. * need to invoke fork callbacks here. */
  4054. BUG_ON(!list_empty(&init_task.tasks));
  4055. BUG_ON(online_css(css));
  4056. mutex_unlock(&cgroup_mutex);
  4057. }
  4058. /**
  4059. * cgroup_init_early - cgroup initialization at system boot
  4060. *
  4061. * Initialize cgroups at system boot, and initialize any
  4062. * subsystems that request early init.
  4063. */
  4064. int __init cgroup_init_early(void)
  4065. {
  4066. static struct cgroup_sb_opts __initdata opts =
  4067. { .flags = CGRP_ROOT_SANE_BEHAVIOR };
  4068. struct cgroup_subsys *ss;
  4069. int i;
  4070. init_cgroup_root(&cgrp_dfl_root, &opts);
  4071. cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
  4072. RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
  4073. for_each_subsys(ss, i) {
  4074. WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
  4075. "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
  4076. i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
  4077. ss->id, ss->name);
  4078. WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
  4079. "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
  4080. ss->id = i;
  4081. ss->name = cgroup_subsys_name[i];
  4082. if (ss->early_init)
  4083. cgroup_init_subsys(ss, true);
  4084. }
  4085. return 0;
  4086. }
  4087. /**
  4088. * cgroup_init - cgroup initialization
  4089. *
  4090. * Register cgroup filesystem and /proc file, and initialize
  4091. * any subsystems that didn't request early init.
  4092. */
  4093. int __init cgroup_init(void)
  4094. {
  4095. struct cgroup_subsys *ss;
  4096. unsigned long key;
  4097. int ssid, err;
  4098. BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
  4099. mutex_lock(&cgroup_mutex);
  4100. /* Add init_css_set to the hash table */
  4101. key = css_set_hash(init_css_set.subsys);
  4102. hash_add(css_set_table, &init_css_set.hlist, key);
  4103. BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
  4104. mutex_unlock(&cgroup_mutex);
  4105. for_each_subsys(ss, ssid) {
  4106. if (ss->early_init) {
  4107. struct cgroup_subsys_state *css =
  4108. init_css_set.subsys[ss->id];
  4109. css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
  4110. GFP_KERNEL);
  4111. BUG_ON(css->id < 0);
  4112. } else {
  4113. cgroup_init_subsys(ss, false);
  4114. }
  4115. list_add_tail(&init_css_set.e_cset_node[ssid],
  4116. &cgrp_dfl_root.cgrp.e_csets[ssid]);
  4117. /*
  4118. * Setting dfl_root subsys_mask needs to consider the
  4119. * disabled flag and cftype registration needs kmalloc,
  4120. * both of which aren't available during early_init.
  4121. */
  4122. if (!ss->disabled) {
  4123. cgrp_dfl_root.subsys_mask |= 1 << ss->id;
  4124. WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
  4125. }
  4126. }
  4127. cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
  4128. if (!cgroup_kobj)
  4129. return -ENOMEM;
  4130. err = register_filesystem(&cgroup_fs_type);
  4131. if (err < 0) {
  4132. kobject_put(cgroup_kobj);
  4133. return err;
  4134. }
  4135. proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
  4136. return 0;
  4137. }
  4138. static int __init cgroup_wq_init(void)
  4139. {
  4140. /*
  4141. * There isn't much point in executing destruction path in
  4142. * parallel. Good chunk is serialized with cgroup_mutex anyway.
  4143. * Use 1 for @max_active.
  4144. *
  4145. * We would prefer to do this in cgroup_init() above, but that
  4146. * is called before init_workqueues(): so leave this until after.
  4147. */
  4148. cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
  4149. BUG_ON(!cgroup_destroy_wq);
  4150. /*
  4151. * Used to destroy pidlists and separate to serve as flush domain.
  4152. * Cap @max_active to 1 too.
  4153. */
  4154. cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
  4155. 0, 1);
  4156. BUG_ON(!cgroup_pidlist_destroy_wq);
  4157. return 0;
  4158. }
  4159. core_initcall(cgroup_wq_init);
  4160. /*
  4161. * proc_cgroup_show()
  4162. * - Print task's cgroup paths into seq_file, one line for each hierarchy
  4163. * - Used for /proc/<pid>/cgroup.
  4164. */
  4165. /* TODO: Use a proper seq_file iterator */
  4166. int proc_cgroup_show(struct seq_file *m, void *v)
  4167. {
  4168. struct pid *pid;
  4169. struct task_struct *tsk;
  4170. char *buf, *path;
  4171. int retval;
  4172. struct cgroup_root *root;
  4173. retval = -ENOMEM;
  4174. buf = kmalloc(PATH_MAX, GFP_KERNEL);
  4175. if (!buf)
  4176. goto out;
  4177. retval = -ESRCH;
  4178. pid = m->private;
  4179. tsk = get_pid_task(pid, PIDTYPE_PID);
  4180. if (!tsk)
  4181. goto out_free;
  4182. retval = 0;
  4183. mutex_lock(&cgroup_mutex);
  4184. down_read(&css_set_rwsem);
  4185. for_each_root(root) {
  4186. struct cgroup_subsys *ss;
  4187. struct cgroup *cgrp;
  4188. int ssid, count = 0;
  4189. if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
  4190. continue;
  4191. seq_printf(m, "%d:", root->hierarchy_id);
  4192. for_each_subsys(ss, ssid)
  4193. if (root->subsys_mask & (1 << ssid))
  4194. seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
  4195. if (strlen(root->name))
  4196. seq_printf(m, "%sname=%s", count ? "," : "",
  4197. root->name);
  4198. seq_putc(m, ':');
  4199. cgrp = task_cgroup_from_root(tsk, root);
  4200. path = cgroup_path(cgrp, buf, PATH_MAX);
  4201. if (!path) {
  4202. retval = -ENAMETOOLONG;
  4203. goto out_unlock;
  4204. }
  4205. seq_puts(m, path);
  4206. seq_putc(m, '\n');
  4207. }
  4208. out_unlock:
  4209. up_read(&css_set_rwsem);
  4210. mutex_unlock(&cgroup_mutex);
  4211. put_task_struct(tsk);
  4212. out_free:
  4213. kfree(buf);
  4214. out:
  4215. return retval;
  4216. }
  4217. /* Display information about each subsystem and each hierarchy */
  4218. static int proc_cgroupstats_show(struct seq_file *m, void *v)
  4219. {
  4220. struct cgroup_subsys *ss;
  4221. int i;
  4222. seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
  4223. /*
  4224. * ideally we don't want subsystems moving around while we do this.
  4225. * cgroup_mutex is also necessary to guarantee an atomic snapshot of
  4226. * subsys/hierarchy state.
  4227. */
  4228. mutex_lock(&cgroup_mutex);
  4229. for_each_subsys(ss, i)
  4230. seq_printf(m, "%s\t%d\t%d\t%d\n",
  4231. ss->name, ss->root->hierarchy_id,
  4232. atomic_read(&ss->root->nr_cgrps), !ss->disabled);
  4233. mutex_unlock(&cgroup_mutex);
  4234. return 0;
  4235. }
  4236. static int cgroupstats_open(struct inode *inode, struct file *file)
  4237. {
  4238. return single_open(file, proc_cgroupstats_show, NULL);
  4239. }
  4240. static const struct file_operations proc_cgroupstats_operations = {
  4241. .open = cgroupstats_open,
  4242. .read = seq_read,
  4243. .llseek = seq_lseek,
  4244. .release = single_release,
  4245. };
  4246. /**
  4247. * cgroup_fork - initialize cgroup related fields during copy_process()
  4248. * @child: pointer to task_struct of forking parent process.
  4249. *
  4250. * A task is associated with the init_css_set until cgroup_post_fork()
  4251. * attaches it to the parent's css_set. Empty cg_list indicates that
  4252. * @child isn't holding reference to its css_set.
  4253. */
  4254. void cgroup_fork(struct task_struct *child)
  4255. {
  4256. RCU_INIT_POINTER(child->cgroups, &init_css_set);
  4257. INIT_LIST_HEAD(&child->cg_list);
  4258. }
  4259. /**
  4260. * cgroup_post_fork - called on a new task after adding it to the task list
  4261. * @child: the task in question
  4262. *
  4263. * Adds the task to the list running through its css_set if necessary and
  4264. * call the subsystem fork() callbacks. Has to be after the task is
  4265. * visible on the task list in case we race with the first call to
  4266. * cgroup_task_iter_start() - to guarantee that the new task ends up on its
  4267. * list.
  4268. */
  4269. void cgroup_post_fork(struct task_struct *child)
  4270. {
  4271. struct cgroup_subsys *ss;
  4272. int i;
  4273. /*
  4274. * This may race against cgroup_enable_task_cg_links(). As that
  4275. * function sets use_task_css_set_links before grabbing
  4276. * tasklist_lock and we just went through tasklist_lock to add
  4277. * @child, it's guaranteed that either we see the set
  4278. * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
  4279. * @child during its iteration.
  4280. *
  4281. * If we won the race, @child is associated with %current's
  4282. * css_set. Grabbing css_set_rwsem guarantees both that the
  4283. * association is stable, and, on completion of the parent's
  4284. * migration, @child is visible in the source of migration or
  4285. * already in the destination cgroup. This guarantee is necessary
  4286. * when implementing operations which need to migrate all tasks of
  4287. * a cgroup to another.
  4288. *
  4289. * Note that if we lose to cgroup_enable_task_cg_links(), @child
  4290. * will remain in init_css_set. This is safe because all tasks are
  4291. * in the init_css_set before cg_links is enabled and there's no
  4292. * operation which transfers all tasks out of init_css_set.
  4293. */
  4294. if (use_task_css_set_links) {
  4295. struct css_set *cset;
  4296. down_write(&css_set_rwsem);
  4297. cset = task_css_set(current);
  4298. if (list_empty(&child->cg_list)) {
  4299. rcu_assign_pointer(child->cgroups, cset);
  4300. list_add(&child->cg_list, &cset->tasks);
  4301. get_css_set(cset);
  4302. }
  4303. up_write(&css_set_rwsem);
  4304. }
  4305. /*
  4306. * Call ss->fork(). This must happen after @child is linked on
  4307. * css_set; otherwise, @child might change state between ->fork()
  4308. * and addition to css_set.
  4309. */
  4310. if (need_forkexit_callback) {
  4311. for_each_subsys(ss, i)
  4312. if (ss->fork)
  4313. ss->fork(child);
  4314. }
  4315. }
  4316. /**
  4317. * cgroup_exit - detach cgroup from exiting task
  4318. * @tsk: pointer to task_struct of exiting process
  4319. *
  4320. * Description: Detach cgroup from @tsk and release it.
  4321. *
  4322. * Note that cgroups marked notify_on_release force every task in
  4323. * them to take the global cgroup_mutex mutex when exiting.
  4324. * This could impact scaling on very large systems. Be reluctant to
  4325. * use notify_on_release cgroups where very high task exit scaling
  4326. * is required on large systems.
  4327. *
  4328. * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
  4329. * call cgroup_exit() while the task is still competent to handle
  4330. * notify_on_release(), then leave the task attached to the root cgroup in
  4331. * each hierarchy for the remainder of its exit. No need to bother with
  4332. * init_css_set refcnting. init_css_set never goes away and we can't race
  4333. * with migration path - PF_EXITING is visible to migration path.
  4334. */
  4335. void cgroup_exit(struct task_struct *tsk)
  4336. {
  4337. struct cgroup_subsys *ss;
  4338. struct css_set *cset;
  4339. bool put_cset = false;
  4340. int i;
  4341. /*
  4342. * Unlink from @tsk from its css_set. As migration path can't race
  4343. * with us, we can check cg_list without grabbing css_set_rwsem.
  4344. */
  4345. if (!list_empty(&tsk->cg_list)) {
  4346. down_write(&css_set_rwsem);
  4347. list_del_init(&tsk->cg_list);
  4348. up_write(&css_set_rwsem);
  4349. put_cset = true;
  4350. }
  4351. /* Reassign the task to the init_css_set. */
  4352. cset = task_css_set(tsk);
  4353. RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
  4354. if (need_forkexit_callback) {
  4355. /* see cgroup_post_fork() for details */
  4356. for_each_subsys(ss, i) {
  4357. if (ss->exit) {
  4358. struct cgroup_subsys_state *old_css = cset->subsys[i];
  4359. struct cgroup_subsys_state *css = task_css(tsk, i);
  4360. ss->exit(css, old_css, tsk);
  4361. }
  4362. }
  4363. }
  4364. if (put_cset)
  4365. put_css_set(cset, true);
  4366. }
  4367. static void check_for_release(struct cgroup *cgrp)
  4368. {
  4369. if (cgroup_is_releasable(cgrp) && list_empty(&cgrp->cset_links) &&
  4370. !css_has_online_children(&cgrp->self)) {
  4371. /*
  4372. * Control Group is currently removeable. If it's not
  4373. * already queued for a userspace notification, queue
  4374. * it now
  4375. */
  4376. int need_schedule_work = 0;
  4377. raw_spin_lock(&release_list_lock);
  4378. if (!cgroup_is_dead(cgrp) &&
  4379. list_empty(&cgrp->release_list)) {
  4380. list_add(&cgrp->release_list, &release_list);
  4381. need_schedule_work = 1;
  4382. }
  4383. raw_spin_unlock(&release_list_lock);
  4384. if (need_schedule_work)
  4385. schedule_work(&release_agent_work);
  4386. }
  4387. }
  4388. /*
  4389. * Notify userspace when a cgroup is released, by running the
  4390. * configured release agent with the name of the cgroup (path
  4391. * relative to the root of cgroup file system) as the argument.
  4392. *
  4393. * Most likely, this user command will try to rmdir this cgroup.
  4394. *
  4395. * This races with the possibility that some other task will be
  4396. * attached to this cgroup before it is removed, or that some other
  4397. * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
  4398. * The presumed 'rmdir' will fail quietly if this cgroup is no longer
  4399. * unused, and this cgroup will be reprieved from its death sentence,
  4400. * to continue to serve a useful existence. Next time it's released,
  4401. * we will get notified again, if it still has 'notify_on_release' set.
  4402. *
  4403. * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
  4404. * means only wait until the task is successfully execve()'d. The
  4405. * separate release agent task is forked by call_usermodehelper(),
  4406. * then control in this thread returns here, without waiting for the
  4407. * release agent task. We don't bother to wait because the caller of
  4408. * this routine has no use for the exit status of the release agent
  4409. * task, so no sense holding our caller up for that.
  4410. */
  4411. static void cgroup_release_agent(struct work_struct *work)
  4412. {
  4413. BUG_ON(work != &release_agent_work);
  4414. mutex_lock(&cgroup_mutex);
  4415. raw_spin_lock(&release_list_lock);
  4416. while (!list_empty(&release_list)) {
  4417. char *argv[3], *envp[3];
  4418. int i;
  4419. char *pathbuf = NULL, *agentbuf = NULL, *path;
  4420. struct cgroup *cgrp = list_entry(release_list.next,
  4421. struct cgroup,
  4422. release_list);
  4423. list_del_init(&cgrp->release_list);
  4424. raw_spin_unlock(&release_list_lock);
  4425. pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
  4426. if (!pathbuf)
  4427. goto continue_free;
  4428. path = cgroup_path(cgrp, pathbuf, PATH_MAX);
  4429. if (!path)
  4430. goto continue_free;
  4431. agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
  4432. if (!agentbuf)
  4433. goto continue_free;
  4434. i = 0;
  4435. argv[i++] = agentbuf;
  4436. argv[i++] = path;
  4437. argv[i] = NULL;
  4438. i = 0;
  4439. /* minimal command environment */
  4440. envp[i++] = "HOME=/";
  4441. envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
  4442. envp[i] = NULL;
  4443. /* Drop the lock while we invoke the usermode helper,
  4444. * since the exec could involve hitting disk and hence
  4445. * be a slow process */
  4446. mutex_unlock(&cgroup_mutex);
  4447. call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
  4448. mutex_lock(&cgroup_mutex);
  4449. continue_free:
  4450. kfree(pathbuf);
  4451. kfree(agentbuf);
  4452. raw_spin_lock(&release_list_lock);
  4453. }
  4454. raw_spin_unlock(&release_list_lock);
  4455. mutex_unlock(&cgroup_mutex);
  4456. }
  4457. static int __init cgroup_disable(char *str)
  4458. {
  4459. struct cgroup_subsys *ss;
  4460. char *token;
  4461. int i;
  4462. while ((token = strsep(&str, ",")) != NULL) {
  4463. if (!*token)
  4464. continue;
  4465. for_each_subsys(ss, i) {
  4466. if (!strcmp(token, ss->name)) {
  4467. ss->disabled = 1;
  4468. printk(KERN_INFO "Disabling %s control group"
  4469. " subsystem\n", ss->name);
  4470. break;
  4471. }
  4472. }
  4473. }
  4474. return 1;
  4475. }
  4476. __setup("cgroup_disable=", cgroup_disable);
  4477. /**
  4478. * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
  4479. * @dentry: directory dentry of interest
  4480. * @ss: subsystem of interest
  4481. *
  4482. * If @dentry is a directory for a cgroup which has @ss enabled on it, try
  4483. * to get the corresponding css and return it. If such css doesn't exist
  4484. * or can't be pinned, an ERR_PTR value is returned.
  4485. */
  4486. struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
  4487. struct cgroup_subsys *ss)
  4488. {
  4489. struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
  4490. struct cgroup_subsys_state *css = NULL;
  4491. struct cgroup *cgrp;
  4492. /* is @dentry a cgroup dir? */
  4493. if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
  4494. kernfs_type(kn) != KERNFS_DIR)
  4495. return ERR_PTR(-EBADF);
  4496. rcu_read_lock();
  4497. /*
  4498. * This path doesn't originate from kernfs and @kn could already
  4499. * have been or be removed at any point. @kn->priv is RCU
  4500. * protected for this access. See cgroup_rmdir() for details.
  4501. */
  4502. cgrp = rcu_dereference(kn->priv);
  4503. if (cgrp)
  4504. css = cgroup_css(cgrp, ss);
  4505. if (!css || !css_tryget_online(css))
  4506. css = ERR_PTR(-ENOENT);
  4507. rcu_read_unlock();
  4508. return css;
  4509. }
  4510. /**
  4511. * css_from_id - lookup css by id
  4512. * @id: the cgroup id
  4513. * @ss: cgroup subsys to be looked into
  4514. *
  4515. * Returns the css if there's valid one with @id, otherwise returns NULL.
  4516. * Should be called under rcu_read_lock().
  4517. */
  4518. struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
  4519. {
  4520. WARN_ON_ONCE(!rcu_read_lock_held());
  4521. return idr_find(&ss->css_idr, id);
  4522. }
  4523. #ifdef CONFIG_CGROUP_DEBUG
  4524. static struct cgroup_subsys_state *
  4525. debug_css_alloc(struct cgroup_subsys_state *parent_css)
  4526. {
  4527. struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
  4528. if (!css)
  4529. return ERR_PTR(-ENOMEM);
  4530. return css;
  4531. }
  4532. static void debug_css_free(struct cgroup_subsys_state *css)
  4533. {
  4534. kfree(css);
  4535. }
  4536. static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
  4537. struct cftype *cft)
  4538. {
  4539. return cgroup_task_count(css->cgroup);
  4540. }
  4541. static u64 current_css_set_read(struct cgroup_subsys_state *css,
  4542. struct cftype *cft)
  4543. {
  4544. return (u64)(unsigned long)current->cgroups;
  4545. }
  4546. static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
  4547. struct cftype *cft)
  4548. {
  4549. u64 count;
  4550. rcu_read_lock();
  4551. count = atomic_read(&task_css_set(current)->refcount);
  4552. rcu_read_unlock();
  4553. return count;
  4554. }
  4555. static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
  4556. {
  4557. struct cgrp_cset_link *link;
  4558. struct css_set *cset;
  4559. char *name_buf;
  4560. name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
  4561. if (!name_buf)
  4562. return -ENOMEM;
  4563. down_read(&css_set_rwsem);
  4564. rcu_read_lock();
  4565. cset = rcu_dereference(current->cgroups);
  4566. list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
  4567. struct cgroup *c = link->cgrp;
  4568. cgroup_name(c, name_buf, NAME_MAX + 1);
  4569. seq_printf(seq, "Root %d group %s\n",
  4570. c->root->hierarchy_id, name_buf);
  4571. }
  4572. rcu_read_unlock();
  4573. up_read(&css_set_rwsem);
  4574. kfree(name_buf);
  4575. return 0;
  4576. }
  4577. #define MAX_TASKS_SHOWN_PER_CSS 25
  4578. static int cgroup_css_links_read(struct seq_file *seq, void *v)
  4579. {
  4580. struct cgroup_subsys_state *css = seq_css(seq);
  4581. struct cgrp_cset_link *link;
  4582. down_read(&css_set_rwsem);
  4583. list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
  4584. struct css_set *cset = link->cset;
  4585. struct task_struct *task;
  4586. int count = 0;
  4587. seq_printf(seq, "css_set %p\n", cset);
  4588. list_for_each_entry(task, &cset->tasks, cg_list) {
  4589. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  4590. goto overflow;
  4591. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  4592. }
  4593. list_for_each_entry(task, &cset->mg_tasks, cg_list) {
  4594. if (count++ > MAX_TASKS_SHOWN_PER_CSS)
  4595. goto overflow;
  4596. seq_printf(seq, " task %d\n", task_pid_vnr(task));
  4597. }
  4598. continue;
  4599. overflow:
  4600. seq_puts(seq, " ...\n");
  4601. }
  4602. up_read(&css_set_rwsem);
  4603. return 0;
  4604. }
  4605. static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
  4606. {
  4607. return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
  4608. }
  4609. static struct cftype debug_files[] = {
  4610. {
  4611. .name = "taskcount",
  4612. .read_u64 = debug_taskcount_read,
  4613. },
  4614. {
  4615. .name = "current_css_set",
  4616. .read_u64 = current_css_set_read,
  4617. },
  4618. {
  4619. .name = "current_css_set_refcount",
  4620. .read_u64 = current_css_set_refcount_read,
  4621. },
  4622. {
  4623. .name = "current_css_set_cg_links",
  4624. .seq_show = current_css_set_cg_links_read,
  4625. },
  4626. {
  4627. .name = "cgroup_css_links",
  4628. .seq_show = cgroup_css_links_read,
  4629. },
  4630. {
  4631. .name = "releasable",
  4632. .read_u64 = releasable_read,
  4633. },
  4634. { } /* terminate */
  4635. };
  4636. struct cgroup_subsys debug_cgrp_subsys = {
  4637. .css_alloc = debug_css_alloc,
  4638. .css_free = debug_css_free,
  4639. .base_cftypes = debug_files,
  4640. };
  4641. #endif /* CONFIG_CGROUP_DEBUG */