cgroup.c 155 KB

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