cgroup.c 139 KB

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