cgroup.c 136 KB

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