cgroup.c 144 KB

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