memcontrol.c 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715
  1. /* memcontrol.c - Memory Controller
  2. *
  3. * Copyright IBM Corporation, 2007
  4. * Author Balbir Singh <balbir@linux.vnet.ibm.com>
  5. *
  6. * Copyright 2007 OpenVZ SWsoft Inc
  7. * Author: Pavel Emelianov <xemul@openvz.org>
  8. *
  9. * Memory thresholds
  10. * Copyright (C) 2009 Nokia Corporation
  11. * Author: Kirill A. Shutemov
  12. *
  13. * Kernel Memory Controller
  14. * Copyright (C) 2012 Parallels Inc. and Google Inc.
  15. * Authors: Glauber Costa and Suleiman Souhlal
  16. *
  17. * Native page reclaim
  18. * Charge lifetime sanitation
  19. * Lockless page tracking & accounting
  20. * Unified hierarchy configuration model
  21. * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 2 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. */
  33. #include <linux/page_counter.h>
  34. #include <linux/memcontrol.h>
  35. #include <linux/cgroup.h>
  36. #include <linux/mm.h>
  37. #include <linux/hugetlb.h>
  38. #include <linux/pagemap.h>
  39. #include <linux/smp.h>
  40. #include <linux/page-flags.h>
  41. #include <linux/backing-dev.h>
  42. #include <linux/bit_spinlock.h>
  43. #include <linux/rcupdate.h>
  44. #include <linux/limits.h>
  45. #include <linux/export.h>
  46. #include <linux/mutex.h>
  47. #include <linux/rbtree.h>
  48. #include <linux/slab.h>
  49. #include <linux/swap.h>
  50. #include <linux/swapops.h>
  51. #include <linux/spinlock.h>
  52. #include <linux/eventfd.h>
  53. #include <linux/poll.h>
  54. #include <linux/sort.h>
  55. #include <linux/fs.h>
  56. #include <linux/seq_file.h>
  57. #include <linux/vmpressure.h>
  58. #include <linux/mm_inline.h>
  59. #include <linux/swap_cgroup.h>
  60. #include <linux/cpu.h>
  61. #include <linux/oom.h>
  62. #include <linux/lockdep.h>
  63. #include <linux/file.h>
  64. #include <linux/tracehook.h>
  65. #include "internal.h"
  66. #include <net/sock.h>
  67. #include <net/ip.h>
  68. #include <net/tcp_memcontrol.h>
  69. #include "slab.h"
  70. #include <asm/uaccess.h>
  71. #include <trace/events/vmscan.h>
  72. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  73. EXPORT_SYMBOL(memory_cgrp_subsys);
  74. #define MEM_CGROUP_RECLAIM_RETRIES 5
  75. static struct mem_cgroup *root_mem_cgroup __read_mostly;
  76. struct cgroup_subsys_state *mem_cgroup_root_css __read_mostly;
  77. /* Whether the swap controller is active */
  78. #ifdef CONFIG_MEMCG_SWAP
  79. int do_swap_account __read_mostly;
  80. #else
  81. #define do_swap_account 0
  82. #endif
  83. static const char * const mem_cgroup_stat_names[] = {
  84. "cache",
  85. "rss",
  86. "rss_huge",
  87. "mapped_file",
  88. "dirty",
  89. "writeback",
  90. "swap",
  91. };
  92. static const char * const mem_cgroup_events_names[] = {
  93. "pgpgin",
  94. "pgpgout",
  95. "pgfault",
  96. "pgmajfault",
  97. };
  98. static const char * const mem_cgroup_lru_names[] = {
  99. "inactive_anon",
  100. "active_anon",
  101. "inactive_file",
  102. "active_file",
  103. "unevictable",
  104. };
  105. #define THRESHOLDS_EVENTS_TARGET 128
  106. #define SOFTLIMIT_EVENTS_TARGET 1024
  107. #define NUMAINFO_EVENTS_TARGET 1024
  108. /*
  109. * Cgroups above their limits are maintained in a RB-Tree, independent of
  110. * their hierarchy representation
  111. */
  112. struct mem_cgroup_tree_per_zone {
  113. struct rb_root rb_root;
  114. spinlock_t lock;
  115. };
  116. struct mem_cgroup_tree_per_node {
  117. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  118. };
  119. struct mem_cgroup_tree {
  120. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  121. };
  122. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  123. /* for OOM */
  124. struct mem_cgroup_eventfd_list {
  125. struct list_head list;
  126. struct eventfd_ctx *eventfd;
  127. };
  128. /*
  129. * cgroup_event represents events which userspace want to receive.
  130. */
  131. struct mem_cgroup_event {
  132. /*
  133. * memcg which the event belongs to.
  134. */
  135. struct mem_cgroup *memcg;
  136. /*
  137. * eventfd to signal userspace about the event.
  138. */
  139. struct eventfd_ctx *eventfd;
  140. /*
  141. * Each of these stored in a list by the cgroup.
  142. */
  143. struct list_head list;
  144. /*
  145. * register_event() callback will be used to add new userspace
  146. * waiter for changes related to this event. Use eventfd_signal()
  147. * on eventfd to send notification to userspace.
  148. */
  149. int (*register_event)(struct mem_cgroup *memcg,
  150. struct eventfd_ctx *eventfd, const char *args);
  151. /*
  152. * unregister_event() callback will be called when userspace closes
  153. * the eventfd or on cgroup removing. This callback must be set,
  154. * if you want provide notification functionality.
  155. */
  156. void (*unregister_event)(struct mem_cgroup *memcg,
  157. struct eventfd_ctx *eventfd);
  158. /*
  159. * All fields below needed to unregister event when
  160. * userspace closes eventfd.
  161. */
  162. poll_table pt;
  163. wait_queue_head_t *wqh;
  164. wait_queue_t wait;
  165. struct work_struct remove;
  166. };
  167. static void mem_cgroup_threshold(struct mem_cgroup *memcg);
  168. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
  169. /* Stuffs for move charges at task migration. */
  170. /*
  171. * Types of charges to be moved.
  172. */
  173. #define MOVE_ANON 0x1U
  174. #define MOVE_FILE 0x2U
  175. #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
  176. /* "mc" and its members are protected by cgroup_mutex */
  177. static struct move_charge_struct {
  178. spinlock_t lock; /* for from, to */
  179. struct mem_cgroup *from;
  180. struct mem_cgroup *to;
  181. unsigned long flags;
  182. unsigned long precharge;
  183. unsigned long moved_charge;
  184. unsigned long moved_swap;
  185. struct task_struct *moving_task; /* a task moving charges */
  186. wait_queue_head_t waitq; /* a waitq for other context */
  187. } mc = {
  188. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  189. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  190. };
  191. /*
  192. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  193. * limit reclaim to prevent infinite loops, if they ever occur.
  194. */
  195. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  196. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  197. enum charge_type {
  198. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  199. MEM_CGROUP_CHARGE_TYPE_ANON,
  200. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  201. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  202. NR_CHARGE_TYPE,
  203. };
  204. /* for encoding cft->private value on file */
  205. enum res_type {
  206. _MEM,
  207. _MEMSWAP,
  208. _OOM_TYPE,
  209. _KMEM,
  210. };
  211. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  212. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  213. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  214. /* Used for OOM nofiier */
  215. #define OOM_CONTROL (0)
  216. /*
  217. * The memcg_create_mutex will be held whenever a new cgroup is created.
  218. * As a consequence, any change that needs to protect against new child cgroups
  219. * appearing has to hold it as well.
  220. */
  221. static DEFINE_MUTEX(memcg_create_mutex);
  222. /* Some nice accessors for the vmpressure. */
  223. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  224. {
  225. if (!memcg)
  226. memcg = root_mem_cgroup;
  227. return &memcg->vmpressure;
  228. }
  229. struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
  230. {
  231. return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
  232. }
  233. static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  234. {
  235. return (memcg == root_mem_cgroup);
  236. }
  237. /*
  238. * We restrict the id in the range of [1, 65535], so it can fit into
  239. * an unsigned short.
  240. */
  241. #define MEM_CGROUP_ID_MAX USHRT_MAX
  242. static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
  243. {
  244. return memcg->css.id;
  245. }
  246. /*
  247. * A helper function to get mem_cgroup from ID. must be called under
  248. * rcu_read_lock(). The caller is responsible for calling
  249. * css_tryget_online() if the mem_cgroup is used for charging. (dropping
  250. * refcnt from swap can be called against removed memcg.)
  251. */
  252. static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
  253. {
  254. struct cgroup_subsys_state *css;
  255. css = css_from_id(id, &memory_cgrp_subsys);
  256. return mem_cgroup_from_css(css);
  257. }
  258. /* Writing them here to avoid exposing memcg's inner layout */
  259. #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
  260. void sock_update_memcg(struct sock *sk)
  261. {
  262. if (mem_cgroup_sockets_enabled) {
  263. struct mem_cgroup *memcg;
  264. struct cg_proto *cg_proto;
  265. BUG_ON(!sk->sk_prot->proto_cgroup);
  266. /* Socket cloning can throw us here with sk_cgrp already
  267. * filled. It won't however, necessarily happen from
  268. * process context. So the test for root memcg given
  269. * the current task's memcg won't help us in this case.
  270. *
  271. * Respecting the original socket's memcg is a better
  272. * decision in this case.
  273. */
  274. if (sk->sk_cgrp) {
  275. BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
  276. css_get(&sk->sk_cgrp->memcg->css);
  277. return;
  278. }
  279. rcu_read_lock();
  280. memcg = mem_cgroup_from_task(current);
  281. cg_proto = sk->sk_prot->proto_cgroup(memcg);
  282. if (cg_proto && test_bit(MEMCG_SOCK_ACTIVE, &cg_proto->flags) &&
  283. css_tryget_online(&memcg->css)) {
  284. sk->sk_cgrp = cg_proto;
  285. }
  286. rcu_read_unlock();
  287. }
  288. }
  289. EXPORT_SYMBOL(sock_update_memcg);
  290. void sock_release_memcg(struct sock *sk)
  291. {
  292. if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
  293. struct mem_cgroup *memcg;
  294. WARN_ON(!sk->sk_cgrp->memcg);
  295. memcg = sk->sk_cgrp->memcg;
  296. css_put(&sk->sk_cgrp->memcg->css);
  297. }
  298. }
  299. struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
  300. {
  301. if (!memcg || mem_cgroup_is_root(memcg))
  302. return NULL;
  303. return &memcg->tcp_mem;
  304. }
  305. EXPORT_SYMBOL(tcp_proto_cgroup);
  306. #endif
  307. #ifdef CONFIG_MEMCG_KMEM
  308. /*
  309. * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
  310. * The main reason for not using cgroup id for this:
  311. * this works better in sparse environments, where we have a lot of memcgs,
  312. * but only a few kmem-limited. Or also, if we have, for instance, 200
  313. * memcgs, and none but the 200th is kmem-limited, we'd have to have a
  314. * 200 entry array for that.
  315. *
  316. * The current size of the caches array is stored in memcg_nr_cache_ids. It
  317. * will double each time we have to increase it.
  318. */
  319. static DEFINE_IDA(memcg_cache_ida);
  320. int memcg_nr_cache_ids;
  321. /* Protects memcg_nr_cache_ids */
  322. static DECLARE_RWSEM(memcg_cache_ids_sem);
  323. void memcg_get_cache_ids(void)
  324. {
  325. down_read(&memcg_cache_ids_sem);
  326. }
  327. void memcg_put_cache_ids(void)
  328. {
  329. up_read(&memcg_cache_ids_sem);
  330. }
  331. /*
  332. * MIN_SIZE is different than 1, because we would like to avoid going through
  333. * the alloc/free process all the time. In a small machine, 4 kmem-limited
  334. * cgroups is a reasonable guess. In the future, it could be a parameter or
  335. * tunable, but that is strictly not necessary.
  336. *
  337. * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
  338. * this constant directly from cgroup, but it is understandable that this is
  339. * better kept as an internal representation in cgroup.c. In any case, the
  340. * cgrp_id space is not getting any smaller, and we don't have to necessarily
  341. * increase ours as well if it increases.
  342. */
  343. #define MEMCG_CACHES_MIN_SIZE 4
  344. #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
  345. /*
  346. * A lot of the calls to the cache allocation functions are expected to be
  347. * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
  348. * conditional to this static branch, we'll have to allow modules that does
  349. * kmem_cache_alloc and the such to see this symbol as well
  350. */
  351. struct static_key memcg_kmem_enabled_key;
  352. EXPORT_SYMBOL(memcg_kmem_enabled_key);
  353. #endif /* CONFIG_MEMCG_KMEM */
  354. static struct mem_cgroup_per_zone *
  355. mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
  356. {
  357. int nid = zone_to_nid(zone);
  358. int zid = zone_idx(zone);
  359. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  360. }
  361. /**
  362. * mem_cgroup_css_from_page - css of the memcg associated with a page
  363. * @page: page of interest
  364. *
  365. * If memcg is bound to the default hierarchy, css of the memcg associated
  366. * with @page is returned. The returned css remains associated with @page
  367. * until it is released.
  368. *
  369. * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
  370. * is returned.
  371. *
  372. * XXX: The above description of behavior on the default hierarchy isn't
  373. * strictly true yet as replace_page_cache_page() can modify the
  374. * association before @page is released even on the default hierarchy;
  375. * however, the current and planned usages don't mix the the two functions
  376. * and replace_page_cache_page() will soon be updated to make the invariant
  377. * actually true.
  378. */
  379. struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
  380. {
  381. struct mem_cgroup *memcg;
  382. rcu_read_lock();
  383. memcg = page->mem_cgroup;
  384. if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  385. memcg = root_mem_cgroup;
  386. rcu_read_unlock();
  387. return &memcg->css;
  388. }
  389. /**
  390. * page_cgroup_ino - return inode number of the memcg a page is charged to
  391. * @page: the page
  392. *
  393. * Look up the closest online ancestor of the memory cgroup @page is charged to
  394. * and return its inode number or 0 if @page is not charged to any cgroup. It
  395. * is safe to call this function without holding a reference to @page.
  396. *
  397. * Note, this function is inherently racy, because there is nothing to prevent
  398. * the cgroup inode from getting torn down and potentially reallocated a moment
  399. * after page_cgroup_ino() returns, so it only should be used by callers that
  400. * do not care (such as procfs interfaces).
  401. */
  402. ino_t page_cgroup_ino(struct page *page)
  403. {
  404. struct mem_cgroup *memcg;
  405. unsigned long ino = 0;
  406. rcu_read_lock();
  407. memcg = READ_ONCE(page->mem_cgroup);
  408. while (memcg && !(memcg->css.flags & CSS_ONLINE))
  409. memcg = parent_mem_cgroup(memcg);
  410. if (memcg)
  411. ino = cgroup_ino(memcg->css.cgroup);
  412. rcu_read_unlock();
  413. return ino;
  414. }
  415. static struct mem_cgroup_per_zone *
  416. mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
  417. {
  418. int nid = page_to_nid(page);
  419. int zid = page_zonenum(page);
  420. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  421. }
  422. static struct mem_cgroup_tree_per_zone *
  423. soft_limit_tree_node_zone(int nid, int zid)
  424. {
  425. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  426. }
  427. static struct mem_cgroup_tree_per_zone *
  428. soft_limit_tree_from_page(struct page *page)
  429. {
  430. int nid = page_to_nid(page);
  431. int zid = page_zonenum(page);
  432. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  433. }
  434. static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
  435. struct mem_cgroup_tree_per_zone *mctz,
  436. unsigned long new_usage_in_excess)
  437. {
  438. struct rb_node **p = &mctz->rb_root.rb_node;
  439. struct rb_node *parent = NULL;
  440. struct mem_cgroup_per_zone *mz_node;
  441. if (mz->on_tree)
  442. return;
  443. mz->usage_in_excess = new_usage_in_excess;
  444. if (!mz->usage_in_excess)
  445. return;
  446. while (*p) {
  447. parent = *p;
  448. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  449. tree_node);
  450. if (mz->usage_in_excess < mz_node->usage_in_excess)
  451. p = &(*p)->rb_left;
  452. /*
  453. * We can't avoid mem cgroups that are over their soft
  454. * limit by the same amount
  455. */
  456. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  457. p = &(*p)->rb_right;
  458. }
  459. rb_link_node(&mz->tree_node, parent, p);
  460. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  461. mz->on_tree = true;
  462. }
  463. static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  464. struct mem_cgroup_tree_per_zone *mctz)
  465. {
  466. if (!mz->on_tree)
  467. return;
  468. rb_erase(&mz->tree_node, &mctz->rb_root);
  469. mz->on_tree = false;
  470. }
  471. static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  472. struct mem_cgroup_tree_per_zone *mctz)
  473. {
  474. unsigned long flags;
  475. spin_lock_irqsave(&mctz->lock, flags);
  476. __mem_cgroup_remove_exceeded(mz, mctz);
  477. spin_unlock_irqrestore(&mctz->lock, flags);
  478. }
  479. static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
  480. {
  481. unsigned long nr_pages = page_counter_read(&memcg->memory);
  482. unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
  483. unsigned long excess = 0;
  484. if (nr_pages > soft_limit)
  485. excess = nr_pages - soft_limit;
  486. return excess;
  487. }
  488. static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
  489. {
  490. unsigned long excess;
  491. struct mem_cgroup_per_zone *mz;
  492. struct mem_cgroup_tree_per_zone *mctz;
  493. mctz = soft_limit_tree_from_page(page);
  494. /*
  495. * Necessary to update all ancestors when hierarchy is used.
  496. * because their event counter is not touched.
  497. */
  498. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  499. mz = mem_cgroup_page_zoneinfo(memcg, page);
  500. excess = soft_limit_excess(memcg);
  501. /*
  502. * We have to update the tree if mz is on RB-tree or
  503. * mem is over its softlimit.
  504. */
  505. if (excess || mz->on_tree) {
  506. unsigned long flags;
  507. spin_lock_irqsave(&mctz->lock, flags);
  508. /* if on-tree, remove it */
  509. if (mz->on_tree)
  510. __mem_cgroup_remove_exceeded(mz, mctz);
  511. /*
  512. * Insert again. mz->usage_in_excess will be updated.
  513. * If excess is 0, no tree ops.
  514. */
  515. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  516. spin_unlock_irqrestore(&mctz->lock, flags);
  517. }
  518. }
  519. }
  520. static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
  521. {
  522. struct mem_cgroup_tree_per_zone *mctz;
  523. struct mem_cgroup_per_zone *mz;
  524. int nid, zid;
  525. for_each_node(nid) {
  526. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  527. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  528. mctz = soft_limit_tree_node_zone(nid, zid);
  529. mem_cgroup_remove_exceeded(mz, mctz);
  530. }
  531. }
  532. }
  533. static struct mem_cgroup_per_zone *
  534. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  535. {
  536. struct rb_node *rightmost = NULL;
  537. struct mem_cgroup_per_zone *mz;
  538. retry:
  539. mz = NULL;
  540. rightmost = rb_last(&mctz->rb_root);
  541. if (!rightmost)
  542. goto done; /* Nothing to reclaim from */
  543. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  544. /*
  545. * Remove the node now but someone else can add it back,
  546. * we will to add it back at the end of reclaim to its correct
  547. * position in the tree.
  548. */
  549. __mem_cgroup_remove_exceeded(mz, mctz);
  550. if (!soft_limit_excess(mz->memcg) ||
  551. !css_tryget_online(&mz->memcg->css))
  552. goto retry;
  553. done:
  554. return mz;
  555. }
  556. static struct mem_cgroup_per_zone *
  557. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  558. {
  559. struct mem_cgroup_per_zone *mz;
  560. spin_lock_irq(&mctz->lock);
  561. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  562. spin_unlock_irq(&mctz->lock);
  563. return mz;
  564. }
  565. /*
  566. * Return page count for single (non recursive) @memcg.
  567. *
  568. * Implementation Note: reading percpu statistics for memcg.
  569. *
  570. * Both of vmstat[] and percpu_counter has threshold and do periodic
  571. * synchronization to implement "quick" read. There are trade-off between
  572. * reading cost and precision of value. Then, we may have a chance to implement
  573. * a periodic synchronization of counter in memcg's counter.
  574. *
  575. * But this _read() function is used for user interface now. The user accounts
  576. * memory usage by memory cgroup and he _always_ requires exact value because
  577. * he accounts memory. Even if we provide quick-and-fuzzy read, we always
  578. * have to visit all online cpus and make sum. So, for now, unnecessary
  579. * synchronization is not implemented. (just implemented for cpu hotplug)
  580. *
  581. * If there are kernel internal actions which can make use of some not-exact
  582. * value, and reading all cpu value can be performance bottleneck in some
  583. * common workload, threshold and synchronization as vmstat[] should be
  584. * implemented.
  585. */
  586. static unsigned long
  587. mem_cgroup_read_stat(struct mem_cgroup *memcg, enum mem_cgroup_stat_index idx)
  588. {
  589. long val = 0;
  590. int cpu;
  591. /* Per-cpu values can be negative, use a signed accumulator */
  592. for_each_possible_cpu(cpu)
  593. val += per_cpu(memcg->stat->count[idx], cpu);
  594. /*
  595. * Summing races with updates, so val may be negative. Avoid exposing
  596. * transient negative values.
  597. */
  598. if (val < 0)
  599. val = 0;
  600. return val;
  601. }
  602. static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
  603. enum mem_cgroup_events_index idx)
  604. {
  605. unsigned long val = 0;
  606. int cpu;
  607. for_each_possible_cpu(cpu)
  608. val += per_cpu(memcg->stat->events[idx], cpu);
  609. return val;
  610. }
  611. static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
  612. struct page *page,
  613. int nr_pages)
  614. {
  615. /*
  616. * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
  617. * counted as CACHE even if it's on ANON LRU.
  618. */
  619. if (PageAnon(page))
  620. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
  621. nr_pages);
  622. else
  623. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
  624. nr_pages);
  625. if (PageTransHuge(page))
  626. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  627. nr_pages);
  628. /* pagein of a big page is an event. So, ignore page size */
  629. if (nr_pages > 0)
  630. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
  631. else {
  632. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
  633. nr_pages = -nr_pages; /* for event */
  634. }
  635. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  636. }
  637. static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  638. int nid,
  639. unsigned int lru_mask)
  640. {
  641. unsigned long nr = 0;
  642. int zid;
  643. VM_BUG_ON((unsigned)nid >= nr_node_ids);
  644. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  645. struct mem_cgroup_per_zone *mz;
  646. enum lru_list lru;
  647. for_each_lru(lru) {
  648. if (!(BIT(lru) & lru_mask))
  649. continue;
  650. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  651. nr += mz->lru_size[lru];
  652. }
  653. }
  654. return nr;
  655. }
  656. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  657. unsigned int lru_mask)
  658. {
  659. unsigned long nr = 0;
  660. int nid;
  661. for_each_node_state(nid, N_MEMORY)
  662. nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
  663. return nr;
  664. }
  665. static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
  666. enum mem_cgroup_events_target target)
  667. {
  668. unsigned long val, next;
  669. val = __this_cpu_read(memcg->stat->nr_page_events);
  670. next = __this_cpu_read(memcg->stat->targets[target]);
  671. /* from time_after() in jiffies.h */
  672. if ((long)next - (long)val < 0) {
  673. switch (target) {
  674. case MEM_CGROUP_TARGET_THRESH:
  675. next = val + THRESHOLDS_EVENTS_TARGET;
  676. break;
  677. case MEM_CGROUP_TARGET_SOFTLIMIT:
  678. next = val + SOFTLIMIT_EVENTS_TARGET;
  679. break;
  680. case MEM_CGROUP_TARGET_NUMAINFO:
  681. next = val + NUMAINFO_EVENTS_TARGET;
  682. break;
  683. default:
  684. break;
  685. }
  686. __this_cpu_write(memcg->stat->targets[target], next);
  687. return true;
  688. }
  689. return false;
  690. }
  691. /*
  692. * Check events in order.
  693. *
  694. */
  695. static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
  696. {
  697. /* threshold event is triggered in finer grain than soft limit */
  698. if (unlikely(mem_cgroup_event_ratelimit(memcg,
  699. MEM_CGROUP_TARGET_THRESH))) {
  700. bool do_softlimit;
  701. bool do_numainfo __maybe_unused;
  702. do_softlimit = mem_cgroup_event_ratelimit(memcg,
  703. MEM_CGROUP_TARGET_SOFTLIMIT);
  704. #if MAX_NUMNODES > 1
  705. do_numainfo = mem_cgroup_event_ratelimit(memcg,
  706. MEM_CGROUP_TARGET_NUMAINFO);
  707. #endif
  708. mem_cgroup_threshold(memcg);
  709. if (unlikely(do_softlimit))
  710. mem_cgroup_update_tree(memcg, page);
  711. #if MAX_NUMNODES > 1
  712. if (unlikely(do_numainfo))
  713. atomic_inc(&memcg->numainfo_events);
  714. #endif
  715. }
  716. }
  717. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  718. {
  719. /*
  720. * mm_update_next_owner() may clear mm->owner to NULL
  721. * if it races with swapoff, page migration, etc.
  722. * So this can be called with p == NULL.
  723. */
  724. if (unlikely(!p))
  725. return NULL;
  726. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  727. }
  728. EXPORT_SYMBOL(mem_cgroup_from_task);
  729. static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  730. {
  731. struct mem_cgroup *memcg = NULL;
  732. rcu_read_lock();
  733. do {
  734. /*
  735. * Page cache insertions can happen withou an
  736. * actual mm context, e.g. during disk probing
  737. * on boot, loopback IO, acct() writes etc.
  738. */
  739. if (unlikely(!mm))
  740. memcg = root_mem_cgroup;
  741. else {
  742. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  743. if (unlikely(!memcg))
  744. memcg = root_mem_cgroup;
  745. }
  746. } while (!css_tryget_online(&memcg->css));
  747. rcu_read_unlock();
  748. return memcg;
  749. }
  750. /**
  751. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  752. * @root: hierarchy root
  753. * @prev: previously returned memcg, NULL on first invocation
  754. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  755. *
  756. * Returns references to children of the hierarchy below @root, or
  757. * @root itself, or %NULL after a full round-trip.
  758. *
  759. * Caller must pass the return value in @prev on subsequent
  760. * invocations for reference counting, or use mem_cgroup_iter_break()
  761. * to cancel a hierarchy walk before the round-trip is complete.
  762. *
  763. * Reclaimers can specify a zone and a priority level in @reclaim to
  764. * divide up the memcgs in the hierarchy among all concurrent
  765. * reclaimers operating on the same zone and priority.
  766. */
  767. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  768. struct mem_cgroup *prev,
  769. struct mem_cgroup_reclaim_cookie *reclaim)
  770. {
  771. struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
  772. struct cgroup_subsys_state *css = NULL;
  773. struct mem_cgroup *memcg = NULL;
  774. struct mem_cgroup *pos = NULL;
  775. if (mem_cgroup_disabled())
  776. return NULL;
  777. if (!root)
  778. root = root_mem_cgroup;
  779. if (prev && !reclaim)
  780. pos = prev;
  781. if (!root->use_hierarchy && root != root_mem_cgroup) {
  782. if (prev)
  783. goto out;
  784. return root;
  785. }
  786. rcu_read_lock();
  787. if (reclaim) {
  788. struct mem_cgroup_per_zone *mz;
  789. mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
  790. iter = &mz->iter[reclaim->priority];
  791. if (prev && reclaim->generation != iter->generation)
  792. goto out_unlock;
  793. do {
  794. pos = READ_ONCE(iter->position);
  795. /*
  796. * A racing update may change the position and
  797. * put the last reference, hence css_tryget(),
  798. * or retry to see the updated position.
  799. */
  800. } while (pos && !css_tryget(&pos->css));
  801. }
  802. if (pos)
  803. css = &pos->css;
  804. for (;;) {
  805. css = css_next_descendant_pre(css, &root->css);
  806. if (!css) {
  807. /*
  808. * Reclaimers share the hierarchy walk, and a
  809. * new one might jump in right at the end of
  810. * the hierarchy - make sure they see at least
  811. * one group and restart from the beginning.
  812. */
  813. if (!prev)
  814. continue;
  815. break;
  816. }
  817. /*
  818. * Verify the css and acquire a reference. The root
  819. * is provided by the caller, so we know it's alive
  820. * and kicking, and don't take an extra reference.
  821. */
  822. memcg = mem_cgroup_from_css(css);
  823. if (css == &root->css)
  824. break;
  825. if (css_tryget(css)) {
  826. /*
  827. * Make sure the memcg is initialized:
  828. * mem_cgroup_css_online() orders the the
  829. * initialization against setting the flag.
  830. */
  831. if (smp_load_acquire(&memcg->initialized))
  832. break;
  833. css_put(css);
  834. }
  835. memcg = NULL;
  836. }
  837. if (reclaim) {
  838. if (cmpxchg(&iter->position, pos, memcg) == pos) {
  839. if (memcg)
  840. css_get(&memcg->css);
  841. if (pos)
  842. css_put(&pos->css);
  843. }
  844. /*
  845. * pairs with css_tryget when dereferencing iter->position
  846. * above.
  847. */
  848. if (pos)
  849. css_put(&pos->css);
  850. if (!memcg)
  851. iter->generation++;
  852. else if (!prev)
  853. reclaim->generation = iter->generation;
  854. }
  855. out_unlock:
  856. rcu_read_unlock();
  857. out:
  858. if (prev && prev != root)
  859. css_put(&prev->css);
  860. return memcg;
  861. }
  862. /**
  863. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  864. * @root: hierarchy root
  865. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  866. */
  867. void mem_cgroup_iter_break(struct mem_cgroup *root,
  868. struct mem_cgroup *prev)
  869. {
  870. if (!root)
  871. root = root_mem_cgroup;
  872. if (prev && prev != root)
  873. css_put(&prev->css);
  874. }
  875. /*
  876. * Iteration constructs for visiting all cgroups (under a tree). If
  877. * loops are exited prematurely (break), mem_cgroup_iter_break() must
  878. * be used for reference counting.
  879. */
  880. #define for_each_mem_cgroup_tree(iter, root) \
  881. for (iter = mem_cgroup_iter(root, NULL, NULL); \
  882. iter != NULL; \
  883. iter = mem_cgroup_iter(root, iter, NULL))
  884. #define for_each_mem_cgroup(iter) \
  885. for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
  886. iter != NULL; \
  887. iter = mem_cgroup_iter(NULL, iter, NULL))
  888. /**
  889. * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
  890. * @zone: zone of the wanted lruvec
  891. * @memcg: memcg of the wanted lruvec
  892. *
  893. * Returns the lru list vector holding pages for the given @zone and
  894. * @mem. This can be the global zone lruvec, if the memory controller
  895. * is disabled.
  896. */
  897. struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
  898. struct mem_cgroup *memcg)
  899. {
  900. struct mem_cgroup_per_zone *mz;
  901. struct lruvec *lruvec;
  902. if (mem_cgroup_disabled()) {
  903. lruvec = &zone->lruvec;
  904. goto out;
  905. }
  906. mz = mem_cgroup_zone_zoneinfo(memcg, zone);
  907. lruvec = &mz->lruvec;
  908. out:
  909. /*
  910. * Since a node can be onlined after the mem_cgroup was created,
  911. * we have to be prepared to initialize lruvec->zone here;
  912. * and if offlined then reonlined, we need to reinitialize it.
  913. */
  914. if (unlikely(lruvec->zone != zone))
  915. lruvec->zone = zone;
  916. return lruvec;
  917. }
  918. /**
  919. * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
  920. * @page: the page
  921. * @zone: zone of the page
  922. *
  923. * This function is only safe when following the LRU page isolation
  924. * and putback protocol: the LRU lock must be held, and the page must
  925. * either be PageLRU() or the caller must have isolated/allocated it.
  926. */
  927. struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
  928. {
  929. struct mem_cgroup_per_zone *mz;
  930. struct mem_cgroup *memcg;
  931. struct lruvec *lruvec;
  932. if (mem_cgroup_disabled()) {
  933. lruvec = &zone->lruvec;
  934. goto out;
  935. }
  936. memcg = page->mem_cgroup;
  937. /*
  938. * Swapcache readahead pages are added to the LRU - and
  939. * possibly migrated - before they are charged.
  940. */
  941. if (!memcg)
  942. memcg = root_mem_cgroup;
  943. mz = mem_cgroup_page_zoneinfo(memcg, page);
  944. lruvec = &mz->lruvec;
  945. out:
  946. /*
  947. * Since a node can be onlined after the mem_cgroup was created,
  948. * we have to be prepared to initialize lruvec->zone here;
  949. * and if offlined then reonlined, we need to reinitialize it.
  950. */
  951. if (unlikely(lruvec->zone != zone))
  952. lruvec->zone = zone;
  953. return lruvec;
  954. }
  955. /**
  956. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  957. * @lruvec: mem_cgroup per zone lru vector
  958. * @lru: index of lru list the page is sitting on
  959. * @nr_pages: positive when adding or negative when removing
  960. *
  961. * This function must be called when a page is added to or removed from an
  962. * lru list.
  963. */
  964. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  965. int nr_pages)
  966. {
  967. struct mem_cgroup_per_zone *mz;
  968. unsigned long *lru_size;
  969. if (mem_cgroup_disabled())
  970. return;
  971. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  972. lru_size = mz->lru_size + lru;
  973. *lru_size += nr_pages;
  974. VM_BUG_ON((long)(*lru_size) < 0);
  975. }
  976. bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
  977. {
  978. struct mem_cgroup *task_memcg;
  979. struct task_struct *p;
  980. bool ret;
  981. p = find_lock_task_mm(task);
  982. if (p) {
  983. task_memcg = get_mem_cgroup_from_mm(p->mm);
  984. task_unlock(p);
  985. } else {
  986. /*
  987. * All threads may have already detached their mm's, but the oom
  988. * killer still needs to detect if they have already been oom
  989. * killed to prevent needlessly killing additional tasks.
  990. */
  991. rcu_read_lock();
  992. task_memcg = mem_cgroup_from_task(task);
  993. css_get(&task_memcg->css);
  994. rcu_read_unlock();
  995. }
  996. ret = mem_cgroup_is_descendant(task_memcg, memcg);
  997. css_put(&task_memcg->css);
  998. return ret;
  999. }
  1000. #define mem_cgroup_from_counter(counter, member) \
  1001. container_of(counter, struct mem_cgroup, member)
  1002. /**
  1003. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1004. * @memcg: the memory cgroup
  1005. *
  1006. * Returns the maximum amount of memory @mem can be charged with, in
  1007. * pages.
  1008. */
  1009. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1010. {
  1011. unsigned long margin = 0;
  1012. unsigned long count;
  1013. unsigned long limit;
  1014. count = page_counter_read(&memcg->memory);
  1015. limit = READ_ONCE(memcg->memory.limit);
  1016. if (count < limit)
  1017. margin = limit - count;
  1018. if (do_swap_account) {
  1019. count = page_counter_read(&memcg->memsw);
  1020. limit = READ_ONCE(memcg->memsw.limit);
  1021. if (count <= limit)
  1022. margin = min(margin, limit - count);
  1023. }
  1024. return margin;
  1025. }
  1026. /*
  1027. * A routine for checking "mem" is under move_account() or not.
  1028. *
  1029. * Checking a cgroup is mc.from or mc.to or under hierarchy of
  1030. * moving cgroups. This is for waiting at high-memory pressure
  1031. * caused by "move".
  1032. */
  1033. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1034. {
  1035. struct mem_cgroup *from;
  1036. struct mem_cgroup *to;
  1037. bool ret = false;
  1038. /*
  1039. * Unlike task_move routines, we access mc.to, mc.from not under
  1040. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1041. */
  1042. spin_lock(&mc.lock);
  1043. from = mc.from;
  1044. to = mc.to;
  1045. if (!from)
  1046. goto unlock;
  1047. ret = mem_cgroup_is_descendant(from, memcg) ||
  1048. mem_cgroup_is_descendant(to, memcg);
  1049. unlock:
  1050. spin_unlock(&mc.lock);
  1051. return ret;
  1052. }
  1053. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1054. {
  1055. if (mc.moving_task && current != mc.moving_task) {
  1056. if (mem_cgroup_under_move(memcg)) {
  1057. DEFINE_WAIT(wait);
  1058. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1059. /* moving charge context might have finished. */
  1060. if (mc.moving_task)
  1061. schedule();
  1062. finish_wait(&mc.waitq, &wait);
  1063. return true;
  1064. }
  1065. }
  1066. return false;
  1067. }
  1068. #define K(x) ((x) << (PAGE_SHIFT-10))
  1069. /**
  1070. * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
  1071. * @memcg: The memory cgroup that went over limit
  1072. * @p: Task that is going to be killed
  1073. *
  1074. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1075. * enabled
  1076. */
  1077. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1078. {
  1079. /* oom_info_lock ensures that parallel ooms do not interleave */
  1080. static DEFINE_MUTEX(oom_info_lock);
  1081. struct mem_cgroup *iter;
  1082. unsigned int i;
  1083. mutex_lock(&oom_info_lock);
  1084. rcu_read_lock();
  1085. if (p) {
  1086. pr_info("Task in ");
  1087. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1088. pr_cont(" killed as a result of limit of ");
  1089. } else {
  1090. pr_info("Memory limit reached of cgroup ");
  1091. }
  1092. pr_cont_cgroup_path(memcg->css.cgroup);
  1093. pr_cont("\n");
  1094. rcu_read_unlock();
  1095. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1096. K((u64)page_counter_read(&memcg->memory)),
  1097. K((u64)memcg->memory.limit), memcg->memory.failcnt);
  1098. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1099. K((u64)page_counter_read(&memcg->memsw)),
  1100. K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
  1101. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1102. K((u64)page_counter_read(&memcg->kmem)),
  1103. K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
  1104. for_each_mem_cgroup_tree(iter, memcg) {
  1105. pr_info("Memory cgroup stats for ");
  1106. pr_cont_cgroup_path(iter->css.cgroup);
  1107. pr_cont(":");
  1108. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1109. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  1110. continue;
  1111. pr_cont(" %s:%luKB", mem_cgroup_stat_names[i],
  1112. K(mem_cgroup_read_stat(iter, i)));
  1113. }
  1114. for (i = 0; i < NR_LRU_LISTS; i++)
  1115. pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
  1116. K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
  1117. pr_cont("\n");
  1118. }
  1119. mutex_unlock(&oom_info_lock);
  1120. }
  1121. /*
  1122. * This function returns the number of memcg under hierarchy tree. Returns
  1123. * 1(self count) if no children.
  1124. */
  1125. static int mem_cgroup_count_children(struct mem_cgroup *memcg)
  1126. {
  1127. int num = 0;
  1128. struct mem_cgroup *iter;
  1129. for_each_mem_cgroup_tree(iter, memcg)
  1130. num++;
  1131. return num;
  1132. }
  1133. /*
  1134. * Return the memory (and swap, if configured) limit for a memcg.
  1135. */
  1136. static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1137. {
  1138. unsigned long limit;
  1139. limit = memcg->memory.limit;
  1140. if (mem_cgroup_swappiness(memcg)) {
  1141. unsigned long memsw_limit;
  1142. memsw_limit = memcg->memsw.limit;
  1143. limit = min(limit + total_swap_pages, memsw_limit);
  1144. }
  1145. return limit;
  1146. }
  1147. static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1148. int order)
  1149. {
  1150. struct oom_control oc = {
  1151. .zonelist = NULL,
  1152. .nodemask = NULL,
  1153. .gfp_mask = gfp_mask,
  1154. .order = order,
  1155. };
  1156. struct mem_cgroup *iter;
  1157. unsigned long chosen_points = 0;
  1158. unsigned long totalpages;
  1159. unsigned int points = 0;
  1160. struct task_struct *chosen = NULL;
  1161. mutex_lock(&oom_lock);
  1162. /*
  1163. * If current has a pending SIGKILL or is exiting, then automatically
  1164. * select it. The goal is to allow it to allocate so that it may
  1165. * quickly exit and free its memory.
  1166. */
  1167. if (fatal_signal_pending(current) || task_will_free_mem(current)) {
  1168. mark_oom_victim(current);
  1169. goto unlock;
  1170. }
  1171. check_panic_on_oom(&oc, CONSTRAINT_MEMCG, memcg);
  1172. totalpages = mem_cgroup_get_limit(memcg) ? : 1;
  1173. for_each_mem_cgroup_tree(iter, memcg) {
  1174. struct css_task_iter it;
  1175. struct task_struct *task;
  1176. css_task_iter_start(&iter->css, &it);
  1177. while ((task = css_task_iter_next(&it))) {
  1178. switch (oom_scan_process_thread(&oc, task, totalpages)) {
  1179. case OOM_SCAN_SELECT:
  1180. if (chosen)
  1181. put_task_struct(chosen);
  1182. chosen = task;
  1183. chosen_points = ULONG_MAX;
  1184. get_task_struct(chosen);
  1185. /* fall through */
  1186. case OOM_SCAN_CONTINUE:
  1187. continue;
  1188. case OOM_SCAN_ABORT:
  1189. css_task_iter_end(&it);
  1190. mem_cgroup_iter_break(memcg, iter);
  1191. if (chosen)
  1192. put_task_struct(chosen);
  1193. goto unlock;
  1194. case OOM_SCAN_OK:
  1195. break;
  1196. };
  1197. points = oom_badness(task, memcg, NULL, totalpages);
  1198. if (!points || points < chosen_points)
  1199. continue;
  1200. /* Prefer thread group leaders for display purposes */
  1201. if (points == chosen_points &&
  1202. thread_group_leader(chosen))
  1203. continue;
  1204. if (chosen)
  1205. put_task_struct(chosen);
  1206. chosen = task;
  1207. chosen_points = points;
  1208. get_task_struct(chosen);
  1209. }
  1210. css_task_iter_end(&it);
  1211. }
  1212. if (chosen) {
  1213. points = chosen_points * 1000 / totalpages;
  1214. oom_kill_process(&oc, chosen, points, totalpages, memcg,
  1215. "Memory cgroup out of memory");
  1216. }
  1217. unlock:
  1218. mutex_unlock(&oom_lock);
  1219. }
  1220. #if MAX_NUMNODES > 1
  1221. /**
  1222. * test_mem_cgroup_node_reclaimable
  1223. * @memcg: the target memcg
  1224. * @nid: the node ID to be checked.
  1225. * @noswap : specify true here if the user wants flle only information.
  1226. *
  1227. * This function returns whether the specified memcg contains any
  1228. * reclaimable pages on a node. Returns true if there are any reclaimable
  1229. * pages in the node.
  1230. */
  1231. static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
  1232. int nid, bool noswap)
  1233. {
  1234. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
  1235. return true;
  1236. if (noswap || !total_swap_pages)
  1237. return false;
  1238. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
  1239. return true;
  1240. return false;
  1241. }
  1242. /*
  1243. * Always updating the nodemask is not very good - even if we have an empty
  1244. * list or the wrong list here, we can start from some node and traverse all
  1245. * nodes based on the zonelist. So update the list loosely once per 10 secs.
  1246. *
  1247. */
  1248. static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
  1249. {
  1250. int nid;
  1251. /*
  1252. * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
  1253. * pagein/pageout changes since the last update.
  1254. */
  1255. if (!atomic_read(&memcg->numainfo_events))
  1256. return;
  1257. if (atomic_inc_return(&memcg->numainfo_updating) > 1)
  1258. return;
  1259. /* make a nodemask where this memcg uses memory from */
  1260. memcg->scan_nodes = node_states[N_MEMORY];
  1261. for_each_node_mask(nid, node_states[N_MEMORY]) {
  1262. if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
  1263. node_clear(nid, memcg->scan_nodes);
  1264. }
  1265. atomic_set(&memcg->numainfo_events, 0);
  1266. atomic_set(&memcg->numainfo_updating, 0);
  1267. }
  1268. /*
  1269. * Selecting a node where we start reclaim from. Because what we need is just
  1270. * reducing usage counter, start from anywhere is O,K. Considering
  1271. * memory reclaim from current node, there are pros. and cons.
  1272. *
  1273. * Freeing memory from current node means freeing memory from a node which
  1274. * we'll use or we've used. So, it may make LRU bad. And if several threads
  1275. * hit limits, it will see a contention on a node. But freeing from remote
  1276. * node means more costs for memory reclaim because of memory latency.
  1277. *
  1278. * Now, we use round-robin. Better algorithm is welcomed.
  1279. */
  1280. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1281. {
  1282. int node;
  1283. mem_cgroup_may_update_nodemask(memcg);
  1284. node = memcg->last_scanned_node;
  1285. node = next_node(node, memcg->scan_nodes);
  1286. if (node == MAX_NUMNODES)
  1287. node = first_node(memcg->scan_nodes);
  1288. /*
  1289. * We call this when we hit limit, not when pages are added to LRU.
  1290. * No LRU may hold pages because all pages are UNEVICTABLE or
  1291. * memcg is too small and all pages are not on LRU. In that case,
  1292. * we use curret node.
  1293. */
  1294. if (unlikely(node == MAX_NUMNODES))
  1295. node = numa_node_id();
  1296. memcg->last_scanned_node = node;
  1297. return node;
  1298. }
  1299. #else
  1300. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1301. {
  1302. return 0;
  1303. }
  1304. #endif
  1305. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1306. struct zone *zone,
  1307. gfp_t gfp_mask,
  1308. unsigned long *total_scanned)
  1309. {
  1310. struct mem_cgroup *victim = NULL;
  1311. int total = 0;
  1312. int loop = 0;
  1313. unsigned long excess;
  1314. unsigned long nr_scanned;
  1315. struct mem_cgroup_reclaim_cookie reclaim = {
  1316. .zone = zone,
  1317. .priority = 0,
  1318. };
  1319. excess = soft_limit_excess(root_memcg);
  1320. while (1) {
  1321. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1322. if (!victim) {
  1323. loop++;
  1324. if (loop >= 2) {
  1325. /*
  1326. * If we have not been able to reclaim
  1327. * anything, it might because there are
  1328. * no reclaimable pages under this hierarchy
  1329. */
  1330. if (!total)
  1331. break;
  1332. /*
  1333. * We want to do more targeted reclaim.
  1334. * excess >> 2 is not to excessive so as to
  1335. * reclaim too much, nor too less that we keep
  1336. * coming back to reclaim from this cgroup
  1337. */
  1338. if (total >= (excess >> 2) ||
  1339. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1340. break;
  1341. }
  1342. continue;
  1343. }
  1344. total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
  1345. zone, &nr_scanned);
  1346. *total_scanned += nr_scanned;
  1347. if (!soft_limit_excess(root_memcg))
  1348. break;
  1349. }
  1350. mem_cgroup_iter_break(root_memcg, victim);
  1351. return total;
  1352. }
  1353. #ifdef CONFIG_LOCKDEP
  1354. static struct lockdep_map memcg_oom_lock_dep_map = {
  1355. .name = "memcg_oom_lock",
  1356. };
  1357. #endif
  1358. static DEFINE_SPINLOCK(memcg_oom_lock);
  1359. /*
  1360. * Check OOM-Killer is already running under our hierarchy.
  1361. * If someone is running, return false.
  1362. */
  1363. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1364. {
  1365. struct mem_cgroup *iter, *failed = NULL;
  1366. spin_lock(&memcg_oom_lock);
  1367. for_each_mem_cgroup_tree(iter, memcg) {
  1368. if (iter->oom_lock) {
  1369. /*
  1370. * this subtree of our hierarchy is already locked
  1371. * so we cannot give a lock.
  1372. */
  1373. failed = iter;
  1374. mem_cgroup_iter_break(memcg, iter);
  1375. break;
  1376. } else
  1377. iter->oom_lock = true;
  1378. }
  1379. if (failed) {
  1380. /*
  1381. * OK, we failed to lock the whole subtree so we have
  1382. * to clean up what we set up to the failing subtree
  1383. */
  1384. for_each_mem_cgroup_tree(iter, memcg) {
  1385. if (iter == failed) {
  1386. mem_cgroup_iter_break(memcg, iter);
  1387. break;
  1388. }
  1389. iter->oom_lock = false;
  1390. }
  1391. } else
  1392. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1393. spin_unlock(&memcg_oom_lock);
  1394. return !failed;
  1395. }
  1396. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1397. {
  1398. struct mem_cgroup *iter;
  1399. spin_lock(&memcg_oom_lock);
  1400. mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
  1401. for_each_mem_cgroup_tree(iter, memcg)
  1402. iter->oom_lock = false;
  1403. spin_unlock(&memcg_oom_lock);
  1404. }
  1405. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1406. {
  1407. struct mem_cgroup *iter;
  1408. spin_lock(&memcg_oom_lock);
  1409. for_each_mem_cgroup_tree(iter, memcg)
  1410. iter->under_oom++;
  1411. spin_unlock(&memcg_oom_lock);
  1412. }
  1413. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1414. {
  1415. struct mem_cgroup *iter;
  1416. /*
  1417. * When a new child is created while the hierarchy is under oom,
  1418. * mem_cgroup_oom_lock() may not be called. Watch for underflow.
  1419. */
  1420. spin_lock(&memcg_oom_lock);
  1421. for_each_mem_cgroup_tree(iter, memcg)
  1422. if (iter->under_oom > 0)
  1423. iter->under_oom--;
  1424. spin_unlock(&memcg_oom_lock);
  1425. }
  1426. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1427. struct oom_wait_info {
  1428. struct mem_cgroup *memcg;
  1429. wait_queue_t wait;
  1430. };
  1431. static int memcg_oom_wake_function(wait_queue_t *wait,
  1432. unsigned mode, int sync, void *arg)
  1433. {
  1434. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1435. struct mem_cgroup *oom_wait_memcg;
  1436. struct oom_wait_info *oom_wait_info;
  1437. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1438. oom_wait_memcg = oom_wait_info->memcg;
  1439. if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
  1440. !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
  1441. return 0;
  1442. return autoremove_wake_function(wait, mode, sync, arg);
  1443. }
  1444. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1445. {
  1446. /*
  1447. * For the following lockless ->under_oom test, the only required
  1448. * guarantee is that it must see the state asserted by an OOM when
  1449. * this function is called as a result of userland actions
  1450. * triggered by the notification of the OOM. This is trivially
  1451. * achieved by invoking mem_cgroup_mark_under_oom() before
  1452. * triggering notification.
  1453. */
  1454. if (memcg && memcg->under_oom)
  1455. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1456. }
  1457. static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1458. {
  1459. if (!current->memcg_may_oom)
  1460. return;
  1461. /*
  1462. * We are in the middle of the charge context here, so we
  1463. * don't want to block when potentially sitting on a callstack
  1464. * that holds all kinds of filesystem and mm locks.
  1465. *
  1466. * Also, the caller may handle a failed allocation gracefully
  1467. * (like optional page cache readahead) and so an OOM killer
  1468. * invocation might not even be necessary.
  1469. *
  1470. * That's why we don't do anything here except remember the
  1471. * OOM context and then deal with it at the end of the page
  1472. * fault when the stack is unwound, the locks are released,
  1473. * and when we know whether the fault was overall successful.
  1474. */
  1475. css_get(&memcg->css);
  1476. current->memcg_in_oom = memcg;
  1477. current->memcg_oom_gfp_mask = mask;
  1478. current->memcg_oom_order = order;
  1479. }
  1480. /**
  1481. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1482. * @handle: actually kill/wait or just clean up the OOM state
  1483. *
  1484. * This has to be called at the end of a page fault if the memcg OOM
  1485. * handler was enabled.
  1486. *
  1487. * Memcg supports userspace OOM handling where failed allocations must
  1488. * sleep on a waitqueue until the userspace task resolves the
  1489. * situation. Sleeping directly in the charge context with all kinds
  1490. * of locks held is not a good idea, instead we remember an OOM state
  1491. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1492. * the end of the page fault to complete the OOM handling.
  1493. *
  1494. * Returns %true if an ongoing memcg OOM situation was detected and
  1495. * completed, %false otherwise.
  1496. */
  1497. bool mem_cgroup_oom_synchronize(bool handle)
  1498. {
  1499. struct mem_cgroup *memcg = current->memcg_in_oom;
  1500. struct oom_wait_info owait;
  1501. bool locked;
  1502. /* OOM is global, do not handle */
  1503. if (!memcg)
  1504. return false;
  1505. if (!handle || oom_killer_disabled)
  1506. goto cleanup;
  1507. owait.memcg = memcg;
  1508. owait.wait.flags = 0;
  1509. owait.wait.func = memcg_oom_wake_function;
  1510. owait.wait.private = current;
  1511. INIT_LIST_HEAD(&owait.wait.task_list);
  1512. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1513. mem_cgroup_mark_under_oom(memcg);
  1514. locked = mem_cgroup_oom_trylock(memcg);
  1515. if (locked)
  1516. mem_cgroup_oom_notify(memcg);
  1517. if (locked && !memcg->oom_kill_disable) {
  1518. mem_cgroup_unmark_under_oom(memcg);
  1519. finish_wait(&memcg_oom_waitq, &owait.wait);
  1520. mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
  1521. current->memcg_oom_order);
  1522. } else {
  1523. schedule();
  1524. mem_cgroup_unmark_under_oom(memcg);
  1525. finish_wait(&memcg_oom_waitq, &owait.wait);
  1526. }
  1527. if (locked) {
  1528. mem_cgroup_oom_unlock(memcg);
  1529. /*
  1530. * There is no guarantee that an OOM-lock contender
  1531. * sees the wakeups triggered by the OOM kill
  1532. * uncharges. Wake any sleepers explicitely.
  1533. */
  1534. memcg_oom_recover(memcg);
  1535. }
  1536. cleanup:
  1537. current->memcg_in_oom = NULL;
  1538. css_put(&memcg->css);
  1539. return true;
  1540. }
  1541. /**
  1542. * mem_cgroup_begin_page_stat - begin a page state statistics transaction
  1543. * @page: page that is going to change accounted state
  1544. *
  1545. * This function must mark the beginning of an accounted page state
  1546. * change to prevent double accounting when the page is concurrently
  1547. * being moved to another memcg:
  1548. *
  1549. * memcg = mem_cgroup_begin_page_stat(page);
  1550. * if (TestClearPageState(page))
  1551. * mem_cgroup_update_page_stat(memcg, state, -1);
  1552. * mem_cgroup_end_page_stat(memcg);
  1553. */
  1554. struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page)
  1555. {
  1556. struct mem_cgroup *memcg;
  1557. unsigned long flags;
  1558. /*
  1559. * The RCU lock is held throughout the transaction. The fast
  1560. * path can get away without acquiring the memcg->move_lock
  1561. * because page moving starts with an RCU grace period.
  1562. *
  1563. * The RCU lock also protects the memcg from being freed when
  1564. * the page state that is going to change is the only thing
  1565. * preventing the page from being uncharged.
  1566. * E.g. end-writeback clearing PageWriteback(), which allows
  1567. * migration to go ahead and uncharge the page before the
  1568. * account transaction might be complete.
  1569. */
  1570. rcu_read_lock();
  1571. if (mem_cgroup_disabled())
  1572. return NULL;
  1573. again:
  1574. memcg = page->mem_cgroup;
  1575. if (unlikely(!memcg))
  1576. return NULL;
  1577. if (atomic_read(&memcg->moving_account) <= 0)
  1578. return memcg;
  1579. spin_lock_irqsave(&memcg->move_lock, flags);
  1580. if (memcg != page->mem_cgroup) {
  1581. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1582. goto again;
  1583. }
  1584. /*
  1585. * When charge migration first begins, we can have locked and
  1586. * unlocked page stat updates happening concurrently. Track
  1587. * the task who has the lock for mem_cgroup_end_page_stat().
  1588. */
  1589. memcg->move_lock_task = current;
  1590. memcg->move_lock_flags = flags;
  1591. return memcg;
  1592. }
  1593. EXPORT_SYMBOL(mem_cgroup_begin_page_stat);
  1594. /**
  1595. * mem_cgroup_end_page_stat - finish a page state statistics transaction
  1596. * @memcg: the memcg that was accounted against
  1597. */
  1598. void mem_cgroup_end_page_stat(struct mem_cgroup *memcg)
  1599. {
  1600. if (memcg && memcg->move_lock_task == current) {
  1601. unsigned long flags = memcg->move_lock_flags;
  1602. memcg->move_lock_task = NULL;
  1603. memcg->move_lock_flags = 0;
  1604. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1605. }
  1606. rcu_read_unlock();
  1607. }
  1608. EXPORT_SYMBOL(mem_cgroup_end_page_stat);
  1609. /*
  1610. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1611. * TODO: maybe necessary to use big numbers in big irons.
  1612. */
  1613. #define CHARGE_BATCH 32U
  1614. struct memcg_stock_pcp {
  1615. struct mem_cgroup *cached; /* this never be root cgroup */
  1616. unsigned int nr_pages;
  1617. struct work_struct work;
  1618. unsigned long flags;
  1619. #define FLUSHING_CACHED_CHARGE 0
  1620. };
  1621. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1622. static DEFINE_MUTEX(percpu_charge_mutex);
  1623. /**
  1624. * consume_stock: Try to consume stocked charge on this cpu.
  1625. * @memcg: memcg to consume from.
  1626. * @nr_pages: how many pages to charge.
  1627. *
  1628. * The charges will only happen if @memcg matches the current cpu's memcg
  1629. * stock, and at least @nr_pages are available in that stock. Failure to
  1630. * service an allocation will refill the stock.
  1631. *
  1632. * returns true if successful, false otherwise.
  1633. */
  1634. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1635. {
  1636. struct memcg_stock_pcp *stock;
  1637. bool ret = false;
  1638. if (nr_pages > CHARGE_BATCH)
  1639. return ret;
  1640. stock = &get_cpu_var(memcg_stock);
  1641. if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
  1642. stock->nr_pages -= nr_pages;
  1643. ret = true;
  1644. }
  1645. put_cpu_var(memcg_stock);
  1646. return ret;
  1647. }
  1648. /*
  1649. * Returns stocks cached in percpu and reset cached information.
  1650. */
  1651. static void drain_stock(struct memcg_stock_pcp *stock)
  1652. {
  1653. struct mem_cgroup *old = stock->cached;
  1654. if (stock->nr_pages) {
  1655. page_counter_uncharge(&old->memory, stock->nr_pages);
  1656. if (do_swap_account)
  1657. page_counter_uncharge(&old->memsw, stock->nr_pages);
  1658. css_put_many(&old->css, stock->nr_pages);
  1659. stock->nr_pages = 0;
  1660. }
  1661. stock->cached = NULL;
  1662. }
  1663. /*
  1664. * This must be called under preempt disabled or must be called by
  1665. * a thread which is pinned to local cpu.
  1666. */
  1667. static void drain_local_stock(struct work_struct *dummy)
  1668. {
  1669. struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
  1670. drain_stock(stock);
  1671. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1672. }
  1673. /*
  1674. * Cache charges(val) to local per_cpu area.
  1675. * This will be consumed by consume_stock() function, later.
  1676. */
  1677. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1678. {
  1679. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1680. if (stock->cached != memcg) { /* reset if necessary */
  1681. drain_stock(stock);
  1682. stock->cached = memcg;
  1683. }
  1684. stock->nr_pages += nr_pages;
  1685. put_cpu_var(memcg_stock);
  1686. }
  1687. /*
  1688. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1689. * of the hierarchy under it.
  1690. */
  1691. static void drain_all_stock(struct mem_cgroup *root_memcg)
  1692. {
  1693. int cpu, curcpu;
  1694. /* If someone's already draining, avoid adding running more workers. */
  1695. if (!mutex_trylock(&percpu_charge_mutex))
  1696. return;
  1697. /* Notify other cpus that system-wide "drain" is running */
  1698. get_online_cpus();
  1699. curcpu = get_cpu();
  1700. for_each_online_cpu(cpu) {
  1701. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1702. struct mem_cgroup *memcg;
  1703. memcg = stock->cached;
  1704. if (!memcg || !stock->nr_pages)
  1705. continue;
  1706. if (!mem_cgroup_is_descendant(memcg, root_memcg))
  1707. continue;
  1708. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1709. if (cpu == curcpu)
  1710. drain_local_stock(&stock->work);
  1711. else
  1712. schedule_work_on(cpu, &stock->work);
  1713. }
  1714. }
  1715. put_cpu();
  1716. put_online_cpus();
  1717. mutex_unlock(&percpu_charge_mutex);
  1718. }
  1719. static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1720. unsigned long action,
  1721. void *hcpu)
  1722. {
  1723. int cpu = (unsigned long)hcpu;
  1724. struct memcg_stock_pcp *stock;
  1725. if (action == CPU_ONLINE)
  1726. return NOTIFY_OK;
  1727. if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
  1728. return NOTIFY_OK;
  1729. stock = &per_cpu(memcg_stock, cpu);
  1730. drain_stock(stock);
  1731. return NOTIFY_OK;
  1732. }
  1733. /*
  1734. * Scheduled by try_charge() to be executed from the userland return path
  1735. * and reclaims memory over the high limit.
  1736. */
  1737. void mem_cgroup_handle_over_high(void)
  1738. {
  1739. unsigned int nr_pages = current->memcg_nr_pages_over_high;
  1740. struct mem_cgroup *memcg, *pos;
  1741. if (likely(!nr_pages))
  1742. return;
  1743. pos = memcg = get_mem_cgroup_from_mm(current->mm);
  1744. do {
  1745. if (page_counter_read(&pos->memory) <= pos->high)
  1746. continue;
  1747. mem_cgroup_events(pos, MEMCG_HIGH, 1);
  1748. try_to_free_mem_cgroup_pages(pos, nr_pages, GFP_KERNEL, true);
  1749. } while ((pos = parent_mem_cgroup(pos)));
  1750. css_put(&memcg->css);
  1751. current->memcg_nr_pages_over_high = 0;
  1752. }
  1753. static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1754. unsigned int nr_pages)
  1755. {
  1756. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  1757. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1758. struct mem_cgroup *mem_over_limit;
  1759. struct page_counter *counter;
  1760. unsigned long nr_reclaimed;
  1761. bool may_swap = true;
  1762. bool drained = false;
  1763. if (mem_cgroup_is_root(memcg))
  1764. return 0;
  1765. retry:
  1766. if (consume_stock(memcg, nr_pages))
  1767. return 0;
  1768. if (!do_swap_account ||
  1769. page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  1770. if (page_counter_try_charge(&memcg->memory, batch, &counter))
  1771. goto done_restock;
  1772. if (do_swap_account)
  1773. page_counter_uncharge(&memcg->memsw, batch);
  1774. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  1775. } else {
  1776. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  1777. may_swap = false;
  1778. }
  1779. if (batch > nr_pages) {
  1780. batch = nr_pages;
  1781. goto retry;
  1782. }
  1783. /*
  1784. * Unlike in global OOM situations, memcg is not in a physical
  1785. * memory shortage. Allow dying and OOM-killed tasks to
  1786. * bypass the last charges so that they can exit quickly and
  1787. * free their memory.
  1788. */
  1789. if (unlikely(test_thread_flag(TIF_MEMDIE) ||
  1790. fatal_signal_pending(current) ||
  1791. current->flags & PF_EXITING))
  1792. goto force;
  1793. if (unlikely(task_in_memcg_oom(current)))
  1794. goto nomem;
  1795. if (!gfpflags_allow_blocking(gfp_mask))
  1796. goto nomem;
  1797. mem_cgroup_events(mem_over_limit, MEMCG_MAX, 1);
  1798. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  1799. gfp_mask, may_swap);
  1800. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  1801. goto retry;
  1802. if (!drained) {
  1803. drain_all_stock(mem_over_limit);
  1804. drained = true;
  1805. goto retry;
  1806. }
  1807. if (gfp_mask & __GFP_NORETRY)
  1808. goto nomem;
  1809. /*
  1810. * Even though the limit is exceeded at this point, reclaim
  1811. * may have been able to free some pages. Retry the charge
  1812. * before killing the task.
  1813. *
  1814. * Only for regular pages, though: huge pages are rather
  1815. * unlikely to succeed so close to the limit, and we fall back
  1816. * to regular pages anyway in case of failure.
  1817. */
  1818. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  1819. goto retry;
  1820. /*
  1821. * At task move, charge accounts can be doubly counted. So, it's
  1822. * better to wait until the end of task_move if something is going on.
  1823. */
  1824. if (mem_cgroup_wait_acct_move(mem_over_limit))
  1825. goto retry;
  1826. if (nr_retries--)
  1827. goto retry;
  1828. if (gfp_mask & __GFP_NOFAIL)
  1829. goto force;
  1830. if (fatal_signal_pending(current))
  1831. goto force;
  1832. mem_cgroup_events(mem_over_limit, MEMCG_OOM, 1);
  1833. mem_cgroup_oom(mem_over_limit, gfp_mask,
  1834. get_order(nr_pages * PAGE_SIZE));
  1835. nomem:
  1836. if (!(gfp_mask & __GFP_NOFAIL))
  1837. return -ENOMEM;
  1838. force:
  1839. /*
  1840. * The allocation either can't fail or will lead to more memory
  1841. * being freed very soon. Allow memory usage go over the limit
  1842. * temporarily by force charging it.
  1843. */
  1844. page_counter_charge(&memcg->memory, nr_pages);
  1845. if (do_swap_account)
  1846. page_counter_charge(&memcg->memsw, nr_pages);
  1847. css_get_many(&memcg->css, nr_pages);
  1848. return 0;
  1849. done_restock:
  1850. css_get_many(&memcg->css, batch);
  1851. if (batch > nr_pages)
  1852. refill_stock(memcg, batch - nr_pages);
  1853. /*
  1854. * If the hierarchy is above the normal consumption range, schedule
  1855. * reclaim on returning to userland. We can perform reclaim here
  1856. * if __GFP_RECLAIM but let's always punt for simplicity and so that
  1857. * GFP_KERNEL can consistently be used during reclaim. @memcg is
  1858. * not recorded as it most likely matches current's and won't
  1859. * change in the meantime. As high limit is checked again before
  1860. * reclaim, the cost of mismatch is negligible.
  1861. */
  1862. do {
  1863. if (page_counter_read(&memcg->memory) > memcg->high) {
  1864. current->memcg_nr_pages_over_high += nr_pages;
  1865. set_notify_resume(current);
  1866. break;
  1867. }
  1868. } while ((memcg = parent_mem_cgroup(memcg)));
  1869. return 0;
  1870. }
  1871. static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  1872. {
  1873. if (mem_cgroup_is_root(memcg))
  1874. return;
  1875. page_counter_uncharge(&memcg->memory, nr_pages);
  1876. if (do_swap_account)
  1877. page_counter_uncharge(&memcg->memsw, nr_pages);
  1878. css_put_many(&memcg->css, nr_pages);
  1879. }
  1880. static void lock_page_lru(struct page *page, int *isolated)
  1881. {
  1882. struct zone *zone = page_zone(page);
  1883. spin_lock_irq(&zone->lru_lock);
  1884. if (PageLRU(page)) {
  1885. struct lruvec *lruvec;
  1886. lruvec = mem_cgroup_page_lruvec(page, zone);
  1887. ClearPageLRU(page);
  1888. del_page_from_lru_list(page, lruvec, page_lru(page));
  1889. *isolated = 1;
  1890. } else
  1891. *isolated = 0;
  1892. }
  1893. static void unlock_page_lru(struct page *page, int isolated)
  1894. {
  1895. struct zone *zone = page_zone(page);
  1896. if (isolated) {
  1897. struct lruvec *lruvec;
  1898. lruvec = mem_cgroup_page_lruvec(page, zone);
  1899. VM_BUG_ON_PAGE(PageLRU(page), page);
  1900. SetPageLRU(page);
  1901. add_page_to_lru_list(page, lruvec, page_lru(page));
  1902. }
  1903. spin_unlock_irq(&zone->lru_lock);
  1904. }
  1905. static void commit_charge(struct page *page, struct mem_cgroup *memcg,
  1906. bool lrucare)
  1907. {
  1908. int isolated;
  1909. VM_BUG_ON_PAGE(page->mem_cgroup, page);
  1910. /*
  1911. * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
  1912. * may already be on some other mem_cgroup's LRU. Take care of it.
  1913. */
  1914. if (lrucare)
  1915. lock_page_lru(page, &isolated);
  1916. /*
  1917. * Nobody should be changing or seriously looking at
  1918. * page->mem_cgroup at this point:
  1919. *
  1920. * - the page is uncharged
  1921. *
  1922. * - the page is off-LRU
  1923. *
  1924. * - an anonymous fault has exclusive page access, except for
  1925. * a locked page table
  1926. *
  1927. * - a page cache insertion, a swapin fault, or a migration
  1928. * have the page locked
  1929. */
  1930. page->mem_cgroup = memcg;
  1931. if (lrucare)
  1932. unlock_page_lru(page, isolated);
  1933. }
  1934. #ifdef CONFIG_MEMCG_KMEM
  1935. static int memcg_alloc_cache_id(void)
  1936. {
  1937. int id, size;
  1938. int err;
  1939. id = ida_simple_get(&memcg_cache_ida,
  1940. 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
  1941. if (id < 0)
  1942. return id;
  1943. if (id < memcg_nr_cache_ids)
  1944. return id;
  1945. /*
  1946. * There's no space for the new id in memcg_caches arrays,
  1947. * so we have to grow them.
  1948. */
  1949. down_write(&memcg_cache_ids_sem);
  1950. size = 2 * (id + 1);
  1951. if (size < MEMCG_CACHES_MIN_SIZE)
  1952. size = MEMCG_CACHES_MIN_SIZE;
  1953. else if (size > MEMCG_CACHES_MAX_SIZE)
  1954. size = MEMCG_CACHES_MAX_SIZE;
  1955. err = memcg_update_all_caches(size);
  1956. if (!err)
  1957. err = memcg_update_all_list_lrus(size);
  1958. if (!err)
  1959. memcg_nr_cache_ids = size;
  1960. up_write(&memcg_cache_ids_sem);
  1961. if (err) {
  1962. ida_simple_remove(&memcg_cache_ida, id);
  1963. return err;
  1964. }
  1965. return id;
  1966. }
  1967. static void memcg_free_cache_id(int id)
  1968. {
  1969. ida_simple_remove(&memcg_cache_ida, id);
  1970. }
  1971. struct memcg_kmem_cache_create_work {
  1972. struct mem_cgroup *memcg;
  1973. struct kmem_cache *cachep;
  1974. struct work_struct work;
  1975. };
  1976. static void memcg_kmem_cache_create_func(struct work_struct *w)
  1977. {
  1978. struct memcg_kmem_cache_create_work *cw =
  1979. container_of(w, struct memcg_kmem_cache_create_work, work);
  1980. struct mem_cgroup *memcg = cw->memcg;
  1981. struct kmem_cache *cachep = cw->cachep;
  1982. memcg_create_kmem_cache(memcg, cachep);
  1983. css_put(&memcg->css);
  1984. kfree(cw);
  1985. }
  1986. /*
  1987. * Enqueue the creation of a per-memcg kmem_cache.
  1988. */
  1989. static void __memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  1990. struct kmem_cache *cachep)
  1991. {
  1992. struct memcg_kmem_cache_create_work *cw;
  1993. cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
  1994. if (!cw)
  1995. return;
  1996. css_get(&memcg->css);
  1997. cw->memcg = memcg;
  1998. cw->cachep = cachep;
  1999. INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
  2000. schedule_work(&cw->work);
  2001. }
  2002. static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  2003. struct kmem_cache *cachep)
  2004. {
  2005. /*
  2006. * We need to stop accounting when we kmalloc, because if the
  2007. * corresponding kmalloc cache is not yet created, the first allocation
  2008. * in __memcg_schedule_kmem_cache_create will recurse.
  2009. *
  2010. * However, it is better to enclose the whole function. Depending on
  2011. * the debugging options enabled, INIT_WORK(), for instance, can
  2012. * trigger an allocation. This too, will make us recurse. Because at
  2013. * this point we can't allow ourselves back into memcg_kmem_get_cache,
  2014. * the safest choice is to do it like this, wrapping the whole function.
  2015. */
  2016. current->memcg_kmem_skip_account = 1;
  2017. __memcg_schedule_kmem_cache_create(memcg, cachep);
  2018. current->memcg_kmem_skip_account = 0;
  2019. }
  2020. /*
  2021. * Return the kmem_cache we're supposed to use for a slab allocation.
  2022. * We try to use the current memcg's version of the cache.
  2023. *
  2024. * If the cache does not exist yet, if we are the first user of it,
  2025. * we either create it immediately, if possible, or create it asynchronously
  2026. * in a workqueue.
  2027. * In the latter case, we will let the current allocation go through with
  2028. * the original cache.
  2029. *
  2030. * Can't be called in interrupt context or from kernel threads.
  2031. * This function needs to be called with rcu_read_lock() held.
  2032. */
  2033. struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep)
  2034. {
  2035. struct mem_cgroup *memcg;
  2036. struct kmem_cache *memcg_cachep;
  2037. int kmemcg_id;
  2038. VM_BUG_ON(!is_root_cache(cachep));
  2039. if (current->memcg_kmem_skip_account)
  2040. return cachep;
  2041. memcg = get_mem_cgroup_from_mm(current->mm);
  2042. kmemcg_id = READ_ONCE(memcg->kmemcg_id);
  2043. if (kmemcg_id < 0)
  2044. goto out;
  2045. memcg_cachep = cache_from_memcg_idx(cachep, kmemcg_id);
  2046. if (likely(memcg_cachep))
  2047. return memcg_cachep;
  2048. /*
  2049. * If we are in a safe context (can wait, and not in interrupt
  2050. * context), we could be be predictable and return right away.
  2051. * This would guarantee that the allocation being performed
  2052. * already belongs in the new cache.
  2053. *
  2054. * However, there are some clashes that can arrive from locking.
  2055. * For instance, because we acquire the slab_mutex while doing
  2056. * memcg_create_kmem_cache, this means no further allocation
  2057. * could happen with the slab_mutex held. So it's better to
  2058. * defer everything.
  2059. */
  2060. memcg_schedule_kmem_cache_create(memcg, cachep);
  2061. out:
  2062. css_put(&memcg->css);
  2063. return cachep;
  2064. }
  2065. void __memcg_kmem_put_cache(struct kmem_cache *cachep)
  2066. {
  2067. if (!is_root_cache(cachep))
  2068. css_put(&cachep->memcg_params.memcg->css);
  2069. }
  2070. int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
  2071. struct mem_cgroup *memcg)
  2072. {
  2073. unsigned int nr_pages = 1 << order;
  2074. struct page_counter *counter;
  2075. int ret;
  2076. if (!memcg_kmem_is_active(memcg))
  2077. return 0;
  2078. if (!page_counter_try_charge(&memcg->kmem, nr_pages, &counter))
  2079. return -ENOMEM;
  2080. ret = try_charge(memcg, gfp, nr_pages);
  2081. if (ret) {
  2082. page_counter_uncharge(&memcg->kmem, nr_pages);
  2083. return ret;
  2084. }
  2085. page->mem_cgroup = memcg;
  2086. return 0;
  2087. }
  2088. int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
  2089. {
  2090. struct mem_cgroup *memcg;
  2091. int ret;
  2092. memcg = get_mem_cgroup_from_mm(current->mm);
  2093. ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
  2094. css_put(&memcg->css);
  2095. return ret;
  2096. }
  2097. void __memcg_kmem_uncharge(struct page *page, int order)
  2098. {
  2099. struct mem_cgroup *memcg = page->mem_cgroup;
  2100. unsigned int nr_pages = 1 << order;
  2101. if (!memcg)
  2102. return;
  2103. VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
  2104. page_counter_uncharge(&memcg->kmem, nr_pages);
  2105. page_counter_uncharge(&memcg->memory, nr_pages);
  2106. if (do_swap_account)
  2107. page_counter_uncharge(&memcg->memsw, nr_pages);
  2108. page->mem_cgroup = NULL;
  2109. css_put_many(&memcg->css, nr_pages);
  2110. }
  2111. #endif /* CONFIG_MEMCG_KMEM */
  2112. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2113. /*
  2114. * Because tail pages are not marked as "used", set it. We're under
  2115. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2116. * charge/uncharge will be never happen and move_account() is done under
  2117. * compound_lock(), so we don't have to take care of races.
  2118. */
  2119. void mem_cgroup_split_huge_fixup(struct page *head)
  2120. {
  2121. int i;
  2122. if (mem_cgroup_disabled())
  2123. return;
  2124. for (i = 1; i < HPAGE_PMD_NR; i++)
  2125. head[i].mem_cgroup = head->mem_cgroup;
  2126. __this_cpu_sub(head->mem_cgroup->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  2127. HPAGE_PMD_NR);
  2128. }
  2129. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2130. #ifdef CONFIG_MEMCG_SWAP
  2131. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  2132. bool charge)
  2133. {
  2134. int val = (charge) ? 1 : -1;
  2135. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  2136. }
  2137. /**
  2138. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2139. * @entry: swap entry to be moved
  2140. * @from: mem_cgroup which the entry is moved from
  2141. * @to: mem_cgroup which the entry is moved to
  2142. *
  2143. * It succeeds only when the swap_cgroup's record for this entry is the same
  2144. * as the mem_cgroup's id of @from.
  2145. *
  2146. * Returns 0 on success, -EINVAL on failure.
  2147. *
  2148. * The caller must have charged to @to, IOW, called page_counter_charge() about
  2149. * both res and memsw, and called css_get().
  2150. */
  2151. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2152. struct mem_cgroup *from, struct mem_cgroup *to)
  2153. {
  2154. unsigned short old_id, new_id;
  2155. old_id = mem_cgroup_id(from);
  2156. new_id = mem_cgroup_id(to);
  2157. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2158. mem_cgroup_swap_statistics(from, false);
  2159. mem_cgroup_swap_statistics(to, true);
  2160. return 0;
  2161. }
  2162. return -EINVAL;
  2163. }
  2164. #else
  2165. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2166. struct mem_cgroup *from, struct mem_cgroup *to)
  2167. {
  2168. return -EINVAL;
  2169. }
  2170. #endif
  2171. static DEFINE_MUTEX(memcg_limit_mutex);
  2172. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2173. unsigned long limit)
  2174. {
  2175. unsigned long curusage;
  2176. unsigned long oldusage;
  2177. bool enlarge = false;
  2178. int retry_count;
  2179. int ret;
  2180. /*
  2181. * For keeping hierarchical_reclaim simple, how long we should retry
  2182. * is depends on callers. We set our retry-count to be function
  2183. * of # of children which we should visit in this loop.
  2184. */
  2185. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2186. mem_cgroup_count_children(memcg);
  2187. oldusage = page_counter_read(&memcg->memory);
  2188. do {
  2189. if (signal_pending(current)) {
  2190. ret = -EINTR;
  2191. break;
  2192. }
  2193. mutex_lock(&memcg_limit_mutex);
  2194. if (limit > memcg->memsw.limit) {
  2195. mutex_unlock(&memcg_limit_mutex);
  2196. ret = -EINVAL;
  2197. break;
  2198. }
  2199. if (limit > memcg->memory.limit)
  2200. enlarge = true;
  2201. ret = page_counter_limit(&memcg->memory, limit);
  2202. mutex_unlock(&memcg_limit_mutex);
  2203. if (!ret)
  2204. break;
  2205. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
  2206. curusage = page_counter_read(&memcg->memory);
  2207. /* Usage is reduced ? */
  2208. if (curusage >= oldusage)
  2209. retry_count--;
  2210. else
  2211. oldusage = curusage;
  2212. } while (retry_count);
  2213. if (!ret && enlarge)
  2214. memcg_oom_recover(memcg);
  2215. return ret;
  2216. }
  2217. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2218. unsigned long limit)
  2219. {
  2220. unsigned long curusage;
  2221. unsigned long oldusage;
  2222. bool enlarge = false;
  2223. int retry_count;
  2224. int ret;
  2225. /* see mem_cgroup_resize_res_limit */
  2226. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2227. mem_cgroup_count_children(memcg);
  2228. oldusage = page_counter_read(&memcg->memsw);
  2229. do {
  2230. if (signal_pending(current)) {
  2231. ret = -EINTR;
  2232. break;
  2233. }
  2234. mutex_lock(&memcg_limit_mutex);
  2235. if (limit < memcg->memory.limit) {
  2236. mutex_unlock(&memcg_limit_mutex);
  2237. ret = -EINVAL;
  2238. break;
  2239. }
  2240. if (limit > memcg->memsw.limit)
  2241. enlarge = true;
  2242. ret = page_counter_limit(&memcg->memsw, limit);
  2243. mutex_unlock(&memcg_limit_mutex);
  2244. if (!ret)
  2245. break;
  2246. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
  2247. curusage = page_counter_read(&memcg->memsw);
  2248. /* Usage is reduced ? */
  2249. if (curusage >= oldusage)
  2250. retry_count--;
  2251. else
  2252. oldusage = curusage;
  2253. } while (retry_count);
  2254. if (!ret && enlarge)
  2255. memcg_oom_recover(memcg);
  2256. return ret;
  2257. }
  2258. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2259. gfp_t gfp_mask,
  2260. unsigned long *total_scanned)
  2261. {
  2262. unsigned long nr_reclaimed = 0;
  2263. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2264. unsigned long reclaimed;
  2265. int loop = 0;
  2266. struct mem_cgroup_tree_per_zone *mctz;
  2267. unsigned long excess;
  2268. unsigned long nr_scanned;
  2269. if (order > 0)
  2270. return 0;
  2271. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  2272. /*
  2273. * This loop can run a while, specially if mem_cgroup's continuously
  2274. * keep exceeding their soft limit and putting the system under
  2275. * pressure
  2276. */
  2277. do {
  2278. if (next_mz)
  2279. mz = next_mz;
  2280. else
  2281. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2282. if (!mz)
  2283. break;
  2284. nr_scanned = 0;
  2285. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  2286. gfp_mask, &nr_scanned);
  2287. nr_reclaimed += reclaimed;
  2288. *total_scanned += nr_scanned;
  2289. spin_lock_irq(&mctz->lock);
  2290. __mem_cgroup_remove_exceeded(mz, mctz);
  2291. /*
  2292. * If we failed to reclaim anything from this memory cgroup
  2293. * it is time to move on to the next cgroup
  2294. */
  2295. next_mz = NULL;
  2296. if (!reclaimed)
  2297. next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
  2298. excess = soft_limit_excess(mz->memcg);
  2299. /*
  2300. * One school of thought says that we should not add
  2301. * back the node to the tree if reclaim returns 0.
  2302. * But our reclaim could return 0, simply because due
  2303. * to priority we are exposing a smaller subset of
  2304. * memory to reclaim from. Consider this as a longer
  2305. * term TODO.
  2306. */
  2307. /* If excess == 0, no tree ops */
  2308. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  2309. spin_unlock_irq(&mctz->lock);
  2310. css_put(&mz->memcg->css);
  2311. loop++;
  2312. /*
  2313. * Could not reclaim anything and there are no more
  2314. * mem cgroups to try or we seem to be looping without
  2315. * reclaiming anything.
  2316. */
  2317. if (!nr_reclaimed &&
  2318. (next_mz == NULL ||
  2319. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2320. break;
  2321. } while (!nr_reclaimed);
  2322. if (next_mz)
  2323. css_put(&next_mz->memcg->css);
  2324. return nr_reclaimed;
  2325. }
  2326. /*
  2327. * Test whether @memcg has children, dead or alive. Note that this
  2328. * function doesn't care whether @memcg has use_hierarchy enabled and
  2329. * returns %true if there are child csses according to the cgroup
  2330. * hierarchy. Testing use_hierarchy is the caller's responsiblity.
  2331. */
  2332. static inline bool memcg_has_children(struct mem_cgroup *memcg)
  2333. {
  2334. bool ret;
  2335. /*
  2336. * The lock does not prevent addition or deletion of children, but
  2337. * it prevents a new child from being initialized based on this
  2338. * parent in css_online(), so it's enough to decide whether
  2339. * hierarchically inherited attributes can still be changed or not.
  2340. */
  2341. lockdep_assert_held(&memcg_create_mutex);
  2342. rcu_read_lock();
  2343. ret = css_next_child(NULL, &memcg->css);
  2344. rcu_read_unlock();
  2345. return ret;
  2346. }
  2347. /*
  2348. * Reclaims as many pages from the given memcg as possible and moves
  2349. * the rest to the parent.
  2350. *
  2351. * Caller is responsible for holding css reference for memcg.
  2352. */
  2353. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  2354. {
  2355. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2356. /* we call try-to-free pages for make this cgroup empty */
  2357. lru_add_drain_all();
  2358. /* try to free all pages in this cgroup */
  2359. while (nr_retries && page_counter_read(&memcg->memory)) {
  2360. int progress;
  2361. if (signal_pending(current))
  2362. return -EINTR;
  2363. progress = try_to_free_mem_cgroup_pages(memcg, 1,
  2364. GFP_KERNEL, true);
  2365. if (!progress) {
  2366. nr_retries--;
  2367. /* maybe some writeback is necessary */
  2368. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2369. }
  2370. }
  2371. return 0;
  2372. }
  2373. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  2374. char *buf, size_t nbytes,
  2375. loff_t off)
  2376. {
  2377. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2378. if (mem_cgroup_is_root(memcg))
  2379. return -EINVAL;
  2380. return mem_cgroup_force_empty(memcg) ?: nbytes;
  2381. }
  2382. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  2383. struct cftype *cft)
  2384. {
  2385. return mem_cgroup_from_css(css)->use_hierarchy;
  2386. }
  2387. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  2388. struct cftype *cft, u64 val)
  2389. {
  2390. int retval = 0;
  2391. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2392. struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
  2393. mutex_lock(&memcg_create_mutex);
  2394. if (memcg->use_hierarchy == val)
  2395. goto out;
  2396. /*
  2397. * If parent's use_hierarchy is set, we can't make any modifications
  2398. * in the child subtrees. If it is unset, then the change can
  2399. * occur, provided the current cgroup has no children.
  2400. *
  2401. * For the root cgroup, parent_mem is NULL, we allow value to be
  2402. * set if there are no children.
  2403. */
  2404. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  2405. (val == 1 || val == 0)) {
  2406. if (!memcg_has_children(memcg))
  2407. memcg->use_hierarchy = val;
  2408. else
  2409. retval = -EBUSY;
  2410. } else
  2411. retval = -EINVAL;
  2412. out:
  2413. mutex_unlock(&memcg_create_mutex);
  2414. return retval;
  2415. }
  2416. static unsigned long tree_stat(struct mem_cgroup *memcg,
  2417. enum mem_cgroup_stat_index idx)
  2418. {
  2419. struct mem_cgroup *iter;
  2420. unsigned long val = 0;
  2421. for_each_mem_cgroup_tree(iter, memcg)
  2422. val += mem_cgroup_read_stat(iter, idx);
  2423. return val;
  2424. }
  2425. static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  2426. {
  2427. unsigned long val;
  2428. if (mem_cgroup_is_root(memcg)) {
  2429. val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
  2430. val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
  2431. if (swap)
  2432. val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
  2433. } else {
  2434. if (!swap)
  2435. val = page_counter_read(&memcg->memory);
  2436. else
  2437. val = page_counter_read(&memcg->memsw);
  2438. }
  2439. return val;
  2440. }
  2441. enum {
  2442. RES_USAGE,
  2443. RES_LIMIT,
  2444. RES_MAX_USAGE,
  2445. RES_FAILCNT,
  2446. RES_SOFT_LIMIT,
  2447. };
  2448. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  2449. struct cftype *cft)
  2450. {
  2451. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2452. struct page_counter *counter;
  2453. switch (MEMFILE_TYPE(cft->private)) {
  2454. case _MEM:
  2455. counter = &memcg->memory;
  2456. break;
  2457. case _MEMSWAP:
  2458. counter = &memcg->memsw;
  2459. break;
  2460. case _KMEM:
  2461. counter = &memcg->kmem;
  2462. break;
  2463. default:
  2464. BUG();
  2465. }
  2466. switch (MEMFILE_ATTR(cft->private)) {
  2467. case RES_USAGE:
  2468. if (counter == &memcg->memory)
  2469. return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
  2470. if (counter == &memcg->memsw)
  2471. return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
  2472. return (u64)page_counter_read(counter) * PAGE_SIZE;
  2473. case RES_LIMIT:
  2474. return (u64)counter->limit * PAGE_SIZE;
  2475. case RES_MAX_USAGE:
  2476. return (u64)counter->watermark * PAGE_SIZE;
  2477. case RES_FAILCNT:
  2478. return counter->failcnt;
  2479. case RES_SOFT_LIMIT:
  2480. return (u64)memcg->soft_limit * PAGE_SIZE;
  2481. default:
  2482. BUG();
  2483. }
  2484. }
  2485. #ifdef CONFIG_MEMCG_KMEM
  2486. static int memcg_activate_kmem(struct mem_cgroup *memcg,
  2487. unsigned long nr_pages)
  2488. {
  2489. int err = 0;
  2490. int memcg_id;
  2491. BUG_ON(memcg->kmemcg_id >= 0);
  2492. BUG_ON(memcg->kmem_acct_activated);
  2493. BUG_ON(memcg->kmem_acct_active);
  2494. /*
  2495. * For simplicity, we won't allow this to be disabled. It also can't
  2496. * be changed if the cgroup has children already, or if tasks had
  2497. * already joined.
  2498. *
  2499. * If tasks join before we set the limit, a person looking at
  2500. * kmem.usage_in_bytes will have no way to determine when it took
  2501. * place, which makes the value quite meaningless.
  2502. *
  2503. * After it first became limited, changes in the value of the limit are
  2504. * of course permitted.
  2505. */
  2506. mutex_lock(&memcg_create_mutex);
  2507. if (cgroup_is_populated(memcg->css.cgroup) ||
  2508. (memcg->use_hierarchy && memcg_has_children(memcg)))
  2509. err = -EBUSY;
  2510. mutex_unlock(&memcg_create_mutex);
  2511. if (err)
  2512. goto out;
  2513. memcg_id = memcg_alloc_cache_id();
  2514. if (memcg_id < 0) {
  2515. err = memcg_id;
  2516. goto out;
  2517. }
  2518. /*
  2519. * We couldn't have accounted to this cgroup, because it hasn't got
  2520. * activated yet, so this should succeed.
  2521. */
  2522. err = page_counter_limit(&memcg->kmem, nr_pages);
  2523. VM_BUG_ON(err);
  2524. static_key_slow_inc(&memcg_kmem_enabled_key);
  2525. /*
  2526. * A memory cgroup is considered kmem-active as soon as it gets
  2527. * kmemcg_id. Setting the id after enabling static branching will
  2528. * guarantee no one starts accounting before all call sites are
  2529. * patched.
  2530. */
  2531. memcg->kmemcg_id = memcg_id;
  2532. memcg->kmem_acct_activated = true;
  2533. memcg->kmem_acct_active = true;
  2534. out:
  2535. return err;
  2536. }
  2537. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2538. unsigned long limit)
  2539. {
  2540. int ret;
  2541. mutex_lock(&memcg_limit_mutex);
  2542. if (!memcg_kmem_is_active(memcg))
  2543. ret = memcg_activate_kmem(memcg, limit);
  2544. else
  2545. ret = page_counter_limit(&memcg->kmem, limit);
  2546. mutex_unlock(&memcg_limit_mutex);
  2547. return ret;
  2548. }
  2549. static int memcg_propagate_kmem(struct mem_cgroup *memcg)
  2550. {
  2551. int ret = 0;
  2552. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  2553. if (!parent)
  2554. return 0;
  2555. mutex_lock(&memcg_limit_mutex);
  2556. /*
  2557. * If the parent cgroup is not kmem-active now, it cannot be activated
  2558. * after this point, because it has at least one child already.
  2559. */
  2560. if (memcg_kmem_is_active(parent))
  2561. ret = memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
  2562. mutex_unlock(&memcg_limit_mutex);
  2563. return ret;
  2564. }
  2565. #else
  2566. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2567. unsigned long limit)
  2568. {
  2569. return -EINVAL;
  2570. }
  2571. #endif /* CONFIG_MEMCG_KMEM */
  2572. /*
  2573. * The user of this function is...
  2574. * RES_LIMIT.
  2575. */
  2576. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  2577. char *buf, size_t nbytes, loff_t off)
  2578. {
  2579. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2580. unsigned long nr_pages;
  2581. int ret;
  2582. buf = strstrip(buf);
  2583. ret = page_counter_memparse(buf, "-1", &nr_pages);
  2584. if (ret)
  2585. return ret;
  2586. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  2587. case RES_LIMIT:
  2588. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  2589. ret = -EINVAL;
  2590. break;
  2591. }
  2592. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2593. case _MEM:
  2594. ret = mem_cgroup_resize_limit(memcg, nr_pages);
  2595. break;
  2596. case _MEMSWAP:
  2597. ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
  2598. break;
  2599. case _KMEM:
  2600. ret = memcg_update_kmem_limit(memcg, nr_pages);
  2601. break;
  2602. }
  2603. break;
  2604. case RES_SOFT_LIMIT:
  2605. memcg->soft_limit = nr_pages;
  2606. ret = 0;
  2607. break;
  2608. }
  2609. return ret ?: nbytes;
  2610. }
  2611. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  2612. size_t nbytes, loff_t off)
  2613. {
  2614. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2615. struct page_counter *counter;
  2616. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2617. case _MEM:
  2618. counter = &memcg->memory;
  2619. break;
  2620. case _MEMSWAP:
  2621. counter = &memcg->memsw;
  2622. break;
  2623. case _KMEM:
  2624. counter = &memcg->kmem;
  2625. break;
  2626. default:
  2627. BUG();
  2628. }
  2629. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  2630. case RES_MAX_USAGE:
  2631. page_counter_reset_watermark(counter);
  2632. break;
  2633. case RES_FAILCNT:
  2634. counter->failcnt = 0;
  2635. break;
  2636. default:
  2637. BUG();
  2638. }
  2639. return nbytes;
  2640. }
  2641. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  2642. struct cftype *cft)
  2643. {
  2644. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  2645. }
  2646. #ifdef CONFIG_MMU
  2647. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  2648. struct cftype *cft, u64 val)
  2649. {
  2650. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2651. if (val & ~MOVE_MASK)
  2652. return -EINVAL;
  2653. /*
  2654. * No kind of locking is needed in here, because ->can_attach() will
  2655. * check this value once in the beginning of the process, and then carry
  2656. * on with stale data. This means that changes to this value will only
  2657. * affect task migrations starting after the change.
  2658. */
  2659. memcg->move_charge_at_immigrate = val;
  2660. return 0;
  2661. }
  2662. #else
  2663. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  2664. struct cftype *cft, u64 val)
  2665. {
  2666. return -ENOSYS;
  2667. }
  2668. #endif
  2669. #ifdef CONFIG_NUMA
  2670. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  2671. {
  2672. struct numa_stat {
  2673. const char *name;
  2674. unsigned int lru_mask;
  2675. };
  2676. static const struct numa_stat stats[] = {
  2677. { "total", LRU_ALL },
  2678. { "file", LRU_ALL_FILE },
  2679. { "anon", LRU_ALL_ANON },
  2680. { "unevictable", BIT(LRU_UNEVICTABLE) },
  2681. };
  2682. const struct numa_stat *stat;
  2683. int nid;
  2684. unsigned long nr;
  2685. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2686. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  2687. nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
  2688. seq_printf(m, "%s=%lu", stat->name, nr);
  2689. for_each_node_state(nid, N_MEMORY) {
  2690. nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  2691. stat->lru_mask);
  2692. seq_printf(m, " N%d=%lu", nid, nr);
  2693. }
  2694. seq_putc(m, '\n');
  2695. }
  2696. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  2697. struct mem_cgroup *iter;
  2698. nr = 0;
  2699. for_each_mem_cgroup_tree(iter, memcg)
  2700. nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
  2701. seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
  2702. for_each_node_state(nid, N_MEMORY) {
  2703. nr = 0;
  2704. for_each_mem_cgroup_tree(iter, memcg)
  2705. nr += mem_cgroup_node_nr_lru_pages(
  2706. iter, nid, stat->lru_mask);
  2707. seq_printf(m, " N%d=%lu", nid, nr);
  2708. }
  2709. seq_putc(m, '\n');
  2710. }
  2711. return 0;
  2712. }
  2713. #endif /* CONFIG_NUMA */
  2714. static int memcg_stat_show(struct seq_file *m, void *v)
  2715. {
  2716. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2717. unsigned long memory, memsw;
  2718. struct mem_cgroup *mi;
  2719. unsigned int i;
  2720. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_stat_names) !=
  2721. MEM_CGROUP_STAT_NSTATS);
  2722. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_events_names) !=
  2723. MEM_CGROUP_EVENTS_NSTATS);
  2724. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  2725. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  2726. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  2727. continue;
  2728. seq_printf(m, "%s %lu\n", mem_cgroup_stat_names[i],
  2729. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  2730. }
  2731. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  2732. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  2733. mem_cgroup_read_events(memcg, i));
  2734. for (i = 0; i < NR_LRU_LISTS; i++)
  2735. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  2736. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  2737. /* Hierarchical information */
  2738. memory = memsw = PAGE_COUNTER_MAX;
  2739. for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
  2740. memory = min(memory, mi->memory.limit);
  2741. memsw = min(memsw, mi->memsw.limit);
  2742. }
  2743. seq_printf(m, "hierarchical_memory_limit %llu\n",
  2744. (u64)memory * PAGE_SIZE);
  2745. if (do_swap_account)
  2746. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  2747. (u64)memsw * PAGE_SIZE);
  2748. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  2749. unsigned long long val = 0;
  2750. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  2751. continue;
  2752. for_each_mem_cgroup_tree(mi, memcg)
  2753. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  2754. seq_printf(m, "total_%s %llu\n", mem_cgroup_stat_names[i], val);
  2755. }
  2756. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  2757. unsigned long long val = 0;
  2758. for_each_mem_cgroup_tree(mi, memcg)
  2759. val += mem_cgroup_read_events(mi, i);
  2760. seq_printf(m, "total_%s %llu\n",
  2761. mem_cgroup_events_names[i], val);
  2762. }
  2763. for (i = 0; i < NR_LRU_LISTS; i++) {
  2764. unsigned long long val = 0;
  2765. for_each_mem_cgroup_tree(mi, memcg)
  2766. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  2767. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  2768. }
  2769. #ifdef CONFIG_DEBUG_VM
  2770. {
  2771. int nid, zid;
  2772. struct mem_cgroup_per_zone *mz;
  2773. struct zone_reclaim_stat *rstat;
  2774. unsigned long recent_rotated[2] = {0, 0};
  2775. unsigned long recent_scanned[2] = {0, 0};
  2776. for_each_online_node(nid)
  2777. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  2778. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  2779. rstat = &mz->lruvec.reclaim_stat;
  2780. recent_rotated[0] += rstat->recent_rotated[0];
  2781. recent_rotated[1] += rstat->recent_rotated[1];
  2782. recent_scanned[0] += rstat->recent_scanned[0];
  2783. recent_scanned[1] += rstat->recent_scanned[1];
  2784. }
  2785. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  2786. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  2787. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  2788. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  2789. }
  2790. #endif
  2791. return 0;
  2792. }
  2793. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  2794. struct cftype *cft)
  2795. {
  2796. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2797. return mem_cgroup_swappiness(memcg);
  2798. }
  2799. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  2800. struct cftype *cft, u64 val)
  2801. {
  2802. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2803. if (val > 100)
  2804. return -EINVAL;
  2805. if (css->parent)
  2806. memcg->swappiness = val;
  2807. else
  2808. vm_swappiness = val;
  2809. return 0;
  2810. }
  2811. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  2812. {
  2813. struct mem_cgroup_threshold_ary *t;
  2814. unsigned long usage;
  2815. int i;
  2816. rcu_read_lock();
  2817. if (!swap)
  2818. t = rcu_dereference(memcg->thresholds.primary);
  2819. else
  2820. t = rcu_dereference(memcg->memsw_thresholds.primary);
  2821. if (!t)
  2822. goto unlock;
  2823. usage = mem_cgroup_usage(memcg, swap);
  2824. /*
  2825. * current_threshold points to threshold just below or equal to usage.
  2826. * If it's not true, a threshold was crossed after last
  2827. * call of __mem_cgroup_threshold().
  2828. */
  2829. i = t->current_threshold;
  2830. /*
  2831. * Iterate backward over array of thresholds starting from
  2832. * current_threshold and check if a threshold is crossed.
  2833. * If none of thresholds below usage is crossed, we read
  2834. * only one element of the array here.
  2835. */
  2836. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  2837. eventfd_signal(t->entries[i].eventfd, 1);
  2838. /* i = current_threshold + 1 */
  2839. i++;
  2840. /*
  2841. * Iterate forward over array of thresholds starting from
  2842. * current_threshold+1 and check if a threshold is crossed.
  2843. * If none of thresholds above usage is crossed, we read
  2844. * only one element of the array here.
  2845. */
  2846. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  2847. eventfd_signal(t->entries[i].eventfd, 1);
  2848. /* Update current_threshold */
  2849. t->current_threshold = i - 1;
  2850. unlock:
  2851. rcu_read_unlock();
  2852. }
  2853. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  2854. {
  2855. while (memcg) {
  2856. __mem_cgroup_threshold(memcg, false);
  2857. if (do_swap_account)
  2858. __mem_cgroup_threshold(memcg, true);
  2859. memcg = parent_mem_cgroup(memcg);
  2860. }
  2861. }
  2862. static int compare_thresholds(const void *a, const void *b)
  2863. {
  2864. const struct mem_cgroup_threshold *_a = a;
  2865. const struct mem_cgroup_threshold *_b = b;
  2866. if (_a->threshold > _b->threshold)
  2867. return 1;
  2868. if (_a->threshold < _b->threshold)
  2869. return -1;
  2870. return 0;
  2871. }
  2872. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  2873. {
  2874. struct mem_cgroup_eventfd_list *ev;
  2875. spin_lock(&memcg_oom_lock);
  2876. list_for_each_entry(ev, &memcg->oom_notify, list)
  2877. eventfd_signal(ev->eventfd, 1);
  2878. spin_unlock(&memcg_oom_lock);
  2879. return 0;
  2880. }
  2881. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  2882. {
  2883. struct mem_cgroup *iter;
  2884. for_each_mem_cgroup_tree(iter, memcg)
  2885. mem_cgroup_oom_notify_cb(iter);
  2886. }
  2887. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  2888. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  2889. {
  2890. struct mem_cgroup_thresholds *thresholds;
  2891. struct mem_cgroup_threshold_ary *new;
  2892. unsigned long threshold;
  2893. unsigned long usage;
  2894. int i, size, ret;
  2895. ret = page_counter_memparse(args, "-1", &threshold);
  2896. if (ret)
  2897. return ret;
  2898. mutex_lock(&memcg->thresholds_lock);
  2899. if (type == _MEM) {
  2900. thresholds = &memcg->thresholds;
  2901. usage = mem_cgroup_usage(memcg, false);
  2902. } else if (type == _MEMSWAP) {
  2903. thresholds = &memcg->memsw_thresholds;
  2904. usage = mem_cgroup_usage(memcg, true);
  2905. } else
  2906. BUG();
  2907. /* Check if a threshold crossed before adding a new one */
  2908. if (thresholds->primary)
  2909. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  2910. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  2911. /* Allocate memory for new array of thresholds */
  2912. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  2913. GFP_KERNEL);
  2914. if (!new) {
  2915. ret = -ENOMEM;
  2916. goto unlock;
  2917. }
  2918. new->size = size;
  2919. /* Copy thresholds (if any) to new array */
  2920. if (thresholds->primary) {
  2921. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  2922. sizeof(struct mem_cgroup_threshold));
  2923. }
  2924. /* Add new threshold */
  2925. new->entries[size - 1].eventfd = eventfd;
  2926. new->entries[size - 1].threshold = threshold;
  2927. /* Sort thresholds. Registering of new threshold isn't time-critical */
  2928. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  2929. compare_thresholds, NULL);
  2930. /* Find current threshold */
  2931. new->current_threshold = -1;
  2932. for (i = 0; i < size; i++) {
  2933. if (new->entries[i].threshold <= usage) {
  2934. /*
  2935. * new->current_threshold will not be used until
  2936. * rcu_assign_pointer(), so it's safe to increment
  2937. * it here.
  2938. */
  2939. ++new->current_threshold;
  2940. } else
  2941. break;
  2942. }
  2943. /* Free old spare buffer and save old primary buffer as spare */
  2944. kfree(thresholds->spare);
  2945. thresholds->spare = thresholds->primary;
  2946. rcu_assign_pointer(thresholds->primary, new);
  2947. /* To be sure that nobody uses thresholds */
  2948. synchronize_rcu();
  2949. unlock:
  2950. mutex_unlock(&memcg->thresholds_lock);
  2951. return ret;
  2952. }
  2953. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  2954. struct eventfd_ctx *eventfd, const char *args)
  2955. {
  2956. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  2957. }
  2958. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  2959. struct eventfd_ctx *eventfd, const char *args)
  2960. {
  2961. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  2962. }
  2963. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  2964. struct eventfd_ctx *eventfd, enum res_type type)
  2965. {
  2966. struct mem_cgroup_thresholds *thresholds;
  2967. struct mem_cgroup_threshold_ary *new;
  2968. unsigned long usage;
  2969. int i, j, size;
  2970. mutex_lock(&memcg->thresholds_lock);
  2971. if (type == _MEM) {
  2972. thresholds = &memcg->thresholds;
  2973. usage = mem_cgroup_usage(memcg, false);
  2974. } else if (type == _MEMSWAP) {
  2975. thresholds = &memcg->memsw_thresholds;
  2976. usage = mem_cgroup_usage(memcg, true);
  2977. } else
  2978. BUG();
  2979. if (!thresholds->primary)
  2980. goto unlock;
  2981. /* Check if a threshold crossed before removing */
  2982. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  2983. /* Calculate new number of threshold */
  2984. size = 0;
  2985. for (i = 0; i < thresholds->primary->size; i++) {
  2986. if (thresholds->primary->entries[i].eventfd != eventfd)
  2987. size++;
  2988. }
  2989. new = thresholds->spare;
  2990. /* Set thresholds array to NULL if we don't have thresholds */
  2991. if (!size) {
  2992. kfree(new);
  2993. new = NULL;
  2994. goto swap_buffers;
  2995. }
  2996. new->size = size;
  2997. /* Copy thresholds and find current threshold */
  2998. new->current_threshold = -1;
  2999. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3000. if (thresholds->primary->entries[i].eventfd == eventfd)
  3001. continue;
  3002. new->entries[j] = thresholds->primary->entries[i];
  3003. if (new->entries[j].threshold <= usage) {
  3004. /*
  3005. * new->current_threshold will not be used
  3006. * until rcu_assign_pointer(), so it's safe to increment
  3007. * it here.
  3008. */
  3009. ++new->current_threshold;
  3010. }
  3011. j++;
  3012. }
  3013. swap_buffers:
  3014. /* Swap primary and spare array */
  3015. thresholds->spare = thresholds->primary;
  3016. /* If all events are unregistered, free the spare array */
  3017. if (!new) {
  3018. kfree(thresholds->spare);
  3019. thresholds->spare = NULL;
  3020. }
  3021. rcu_assign_pointer(thresholds->primary, new);
  3022. /* To be sure that nobody uses thresholds */
  3023. synchronize_rcu();
  3024. unlock:
  3025. mutex_unlock(&memcg->thresholds_lock);
  3026. }
  3027. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3028. struct eventfd_ctx *eventfd)
  3029. {
  3030. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  3031. }
  3032. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3033. struct eventfd_ctx *eventfd)
  3034. {
  3035. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  3036. }
  3037. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  3038. struct eventfd_ctx *eventfd, const char *args)
  3039. {
  3040. struct mem_cgroup_eventfd_list *event;
  3041. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3042. if (!event)
  3043. return -ENOMEM;
  3044. spin_lock(&memcg_oom_lock);
  3045. event->eventfd = eventfd;
  3046. list_add(&event->list, &memcg->oom_notify);
  3047. /* already in OOM ? */
  3048. if (memcg->under_oom)
  3049. eventfd_signal(eventfd, 1);
  3050. spin_unlock(&memcg_oom_lock);
  3051. return 0;
  3052. }
  3053. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  3054. struct eventfd_ctx *eventfd)
  3055. {
  3056. struct mem_cgroup_eventfd_list *ev, *tmp;
  3057. spin_lock(&memcg_oom_lock);
  3058. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  3059. if (ev->eventfd == eventfd) {
  3060. list_del(&ev->list);
  3061. kfree(ev);
  3062. }
  3063. }
  3064. spin_unlock(&memcg_oom_lock);
  3065. }
  3066. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  3067. {
  3068. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  3069. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  3070. seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
  3071. return 0;
  3072. }
  3073. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  3074. struct cftype *cft, u64 val)
  3075. {
  3076. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3077. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3078. if (!css->parent || !((val == 0) || (val == 1)))
  3079. return -EINVAL;
  3080. memcg->oom_kill_disable = val;
  3081. if (!val)
  3082. memcg_oom_recover(memcg);
  3083. return 0;
  3084. }
  3085. #ifdef CONFIG_MEMCG_KMEM
  3086. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3087. {
  3088. int ret;
  3089. ret = memcg_propagate_kmem(memcg);
  3090. if (ret)
  3091. return ret;
  3092. return mem_cgroup_sockets_init(memcg, ss);
  3093. }
  3094. static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
  3095. {
  3096. struct cgroup_subsys_state *css;
  3097. struct mem_cgroup *parent, *child;
  3098. int kmemcg_id;
  3099. if (!memcg->kmem_acct_active)
  3100. return;
  3101. /*
  3102. * Clear the 'active' flag before clearing memcg_caches arrays entries.
  3103. * Since we take the slab_mutex in memcg_deactivate_kmem_caches(), it
  3104. * guarantees no cache will be created for this cgroup after we are
  3105. * done (see memcg_create_kmem_cache()).
  3106. */
  3107. memcg->kmem_acct_active = false;
  3108. memcg_deactivate_kmem_caches(memcg);
  3109. kmemcg_id = memcg->kmemcg_id;
  3110. BUG_ON(kmemcg_id < 0);
  3111. parent = parent_mem_cgroup(memcg);
  3112. if (!parent)
  3113. parent = root_mem_cgroup;
  3114. /*
  3115. * Change kmemcg_id of this cgroup and all its descendants to the
  3116. * parent's id, and then move all entries from this cgroup's list_lrus
  3117. * to ones of the parent. After we have finished, all list_lrus
  3118. * corresponding to this cgroup are guaranteed to remain empty. The
  3119. * ordering is imposed by list_lru_node->lock taken by
  3120. * memcg_drain_all_list_lrus().
  3121. */
  3122. css_for_each_descendant_pre(css, &memcg->css) {
  3123. child = mem_cgroup_from_css(css);
  3124. BUG_ON(child->kmemcg_id != kmemcg_id);
  3125. child->kmemcg_id = parent->kmemcg_id;
  3126. if (!memcg->use_hierarchy)
  3127. break;
  3128. }
  3129. memcg_drain_all_list_lrus(kmemcg_id, parent->kmemcg_id);
  3130. memcg_free_cache_id(kmemcg_id);
  3131. }
  3132. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3133. {
  3134. if (memcg->kmem_acct_activated) {
  3135. memcg_destroy_kmem_caches(memcg);
  3136. static_key_slow_dec(&memcg_kmem_enabled_key);
  3137. WARN_ON(page_counter_read(&memcg->kmem));
  3138. }
  3139. mem_cgroup_sockets_destroy(memcg);
  3140. }
  3141. #else
  3142. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3143. {
  3144. return 0;
  3145. }
  3146. static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
  3147. {
  3148. }
  3149. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3150. {
  3151. }
  3152. #endif
  3153. #ifdef CONFIG_CGROUP_WRITEBACK
  3154. struct list_head *mem_cgroup_cgwb_list(struct mem_cgroup *memcg)
  3155. {
  3156. return &memcg->cgwb_list;
  3157. }
  3158. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  3159. {
  3160. return wb_domain_init(&memcg->cgwb_domain, gfp);
  3161. }
  3162. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  3163. {
  3164. wb_domain_exit(&memcg->cgwb_domain);
  3165. }
  3166. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  3167. {
  3168. wb_domain_size_changed(&memcg->cgwb_domain);
  3169. }
  3170. struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
  3171. {
  3172. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  3173. if (!memcg->css.parent)
  3174. return NULL;
  3175. return &memcg->cgwb_domain;
  3176. }
  3177. /**
  3178. * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
  3179. * @wb: bdi_writeback in question
  3180. * @pfilepages: out parameter for number of file pages
  3181. * @pheadroom: out parameter for number of allocatable pages according to memcg
  3182. * @pdirty: out parameter for number of dirty pages
  3183. * @pwriteback: out parameter for number of pages under writeback
  3184. *
  3185. * Determine the numbers of file, headroom, dirty, and writeback pages in
  3186. * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
  3187. * is a bit more involved.
  3188. *
  3189. * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
  3190. * headroom is calculated as the lowest headroom of itself and the
  3191. * ancestors. Note that this doesn't consider the actual amount of
  3192. * available memory in the system. The caller should further cap
  3193. * *@pheadroom accordingly.
  3194. */
  3195. void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
  3196. unsigned long *pheadroom, unsigned long *pdirty,
  3197. unsigned long *pwriteback)
  3198. {
  3199. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  3200. struct mem_cgroup *parent;
  3201. *pdirty = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_DIRTY);
  3202. /* this should eventually include NR_UNSTABLE_NFS */
  3203. *pwriteback = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_WRITEBACK);
  3204. *pfilepages = mem_cgroup_nr_lru_pages(memcg, (1 << LRU_INACTIVE_FILE) |
  3205. (1 << LRU_ACTIVE_FILE));
  3206. *pheadroom = PAGE_COUNTER_MAX;
  3207. while ((parent = parent_mem_cgroup(memcg))) {
  3208. unsigned long ceiling = min(memcg->memory.limit, memcg->high);
  3209. unsigned long used = page_counter_read(&memcg->memory);
  3210. *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
  3211. memcg = parent;
  3212. }
  3213. }
  3214. #else /* CONFIG_CGROUP_WRITEBACK */
  3215. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  3216. {
  3217. return 0;
  3218. }
  3219. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  3220. {
  3221. }
  3222. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  3223. {
  3224. }
  3225. #endif /* CONFIG_CGROUP_WRITEBACK */
  3226. /*
  3227. * DO NOT USE IN NEW FILES.
  3228. *
  3229. * "cgroup.event_control" implementation.
  3230. *
  3231. * This is way over-engineered. It tries to support fully configurable
  3232. * events for each user. Such level of flexibility is completely
  3233. * unnecessary especially in the light of the planned unified hierarchy.
  3234. *
  3235. * Please deprecate this and replace with something simpler if at all
  3236. * possible.
  3237. */
  3238. /*
  3239. * Unregister event and free resources.
  3240. *
  3241. * Gets called from workqueue.
  3242. */
  3243. static void memcg_event_remove(struct work_struct *work)
  3244. {
  3245. struct mem_cgroup_event *event =
  3246. container_of(work, struct mem_cgroup_event, remove);
  3247. struct mem_cgroup *memcg = event->memcg;
  3248. remove_wait_queue(event->wqh, &event->wait);
  3249. event->unregister_event(memcg, event->eventfd);
  3250. /* Notify userspace the event is going away. */
  3251. eventfd_signal(event->eventfd, 1);
  3252. eventfd_ctx_put(event->eventfd);
  3253. kfree(event);
  3254. css_put(&memcg->css);
  3255. }
  3256. /*
  3257. * Gets called on POLLHUP on eventfd when user closes it.
  3258. *
  3259. * Called with wqh->lock held and interrupts disabled.
  3260. */
  3261. static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
  3262. int sync, void *key)
  3263. {
  3264. struct mem_cgroup_event *event =
  3265. container_of(wait, struct mem_cgroup_event, wait);
  3266. struct mem_cgroup *memcg = event->memcg;
  3267. unsigned long flags = (unsigned long)key;
  3268. if (flags & POLLHUP) {
  3269. /*
  3270. * If the event has been detached at cgroup removal, we
  3271. * can simply return knowing the other side will cleanup
  3272. * for us.
  3273. *
  3274. * We can't race against event freeing since the other
  3275. * side will require wqh->lock via remove_wait_queue(),
  3276. * which we hold.
  3277. */
  3278. spin_lock(&memcg->event_list_lock);
  3279. if (!list_empty(&event->list)) {
  3280. list_del_init(&event->list);
  3281. /*
  3282. * We are in atomic context, but cgroup_event_remove()
  3283. * may sleep, so we have to call it in workqueue.
  3284. */
  3285. schedule_work(&event->remove);
  3286. }
  3287. spin_unlock(&memcg->event_list_lock);
  3288. }
  3289. return 0;
  3290. }
  3291. static void memcg_event_ptable_queue_proc(struct file *file,
  3292. wait_queue_head_t *wqh, poll_table *pt)
  3293. {
  3294. struct mem_cgroup_event *event =
  3295. container_of(pt, struct mem_cgroup_event, pt);
  3296. event->wqh = wqh;
  3297. add_wait_queue(wqh, &event->wait);
  3298. }
  3299. /*
  3300. * DO NOT USE IN NEW FILES.
  3301. *
  3302. * Parse input and register new cgroup event handler.
  3303. *
  3304. * Input must be in format '<event_fd> <control_fd> <args>'.
  3305. * Interpretation of args is defined by control file implementation.
  3306. */
  3307. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  3308. char *buf, size_t nbytes, loff_t off)
  3309. {
  3310. struct cgroup_subsys_state *css = of_css(of);
  3311. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3312. struct mem_cgroup_event *event;
  3313. struct cgroup_subsys_state *cfile_css;
  3314. unsigned int efd, cfd;
  3315. struct fd efile;
  3316. struct fd cfile;
  3317. const char *name;
  3318. char *endp;
  3319. int ret;
  3320. buf = strstrip(buf);
  3321. efd = simple_strtoul(buf, &endp, 10);
  3322. if (*endp != ' ')
  3323. return -EINVAL;
  3324. buf = endp + 1;
  3325. cfd = simple_strtoul(buf, &endp, 10);
  3326. if ((*endp != ' ') && (*endp != '\0'))
  3327. return -EINVAL;
  3328. buf = endp + 1;
  3329. event = kzalloc(sizeof(*event), GFP_KERNEL);
  3330. if (!event)
  3331. return -ENOMEM;
  3332. event->memcg = memcg;
  3333. INIT_LIST_HEAD(&event->list);
  3334. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  3335. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  3336. INIT_WORK(&event->remove, memcg_event_remove);
  3337. efile = fdget(efd);
  3338. if (!efile.file) {
  3339. ret = -EBADF;
  3340. goto out_kfree;
  3341. }
  3342. event->eventfd = eventfd_ctx_fileget(efile.file);
  3343. if (IS_ERR(event->eventfd)) {
  3344. ret = PTR_ERR(event->eventfd);
  3345. goto out_put_efile;
  3346. }
  3347. cfile = fdget(cfd);
  3348. if (!cfile.file) {
  3349. ret = -EBADF;
  3350. goto out_put_eventfd;
  3351. }
  3352. /* the process need read permission on control file */
  3353. /* AV: shouldn't we check that it's been opened for read instead? */
  3354. ret = inode_permission(file_inode(cfile.file), MAY_READ);
  3355. if (ret < 0)
  3356. goto out_put_cfile;
  3357. /*
  3358. * Determine the event callbacks and set them in @event. This used
  3359. * to be done via struct cftype but cgroup core no longer knows
  3360. * about these events. The following is crude but the whole thing
  3361. * is for compatibility anyway.
  3362. *
  3363. * DO NOT ADD NEW FILES.
  3364. */
  3365. name = cfile.file->f_path.dentry->d_name.name;
  3366. if (!strcmp(name, "memory.usage_in_bytes")) {
  3367. event->register_event = mem_cgroup_usage_register_event;
  3368. event->unregister_event = mem_cgroup_usage_unregister_event;
  3369. } else if (!strcmp(name, "memory.oom_control")) {
  3370. event->register_event = mem_cgroup_oom_register_event;
  3371. event->unregister_event = mem_cgroup_oom_unregister_event;
  3372. } else if (!strcmp(name, "memory.pressure_level")) {
  3373. event->register_event = vmpressure_register_event;
  3374. event->unregister_event = vmpressure_unregister_event;
  3375. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  3376. event->register_event = memsw_cgroup_usage_register_event;
  3377. event->unregister_event = memsw_cgroup_usage_unregister_event;
  3378. } else {
  3379. ret = -EINVAL;
  3380. goto out_put_cfile;
  3381. }
  3382. /*
  3383. * Verify @cfile should belong to @css. Also, remaining events are
  3384. * automatically removed on cgroup destruction but the removal is
  3385. * asynchronous, so take an extra ref on @css.
  3386. */
  3387. cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
  3388. &memory_cgrp_subsys);
  3389. ret = -EINVAL;
  3390. if (IS_ERR(cfile_css))
  3391. goto out_put_cfile;
  3392. if (cfile_css != css) {
  3393. css_put(cfile_css);
  3394. goto out_put_cfile;
  3395. }
  3396. ret = event->register_event(memcg, event->eventfd, buf);
  3397. if (ret)
  3398. goto out_put_css;
  3399. efile.file->f_op->poll(efile.file, &event->pt);
  3400. spin_lock(&memcg->event_list_lock);
  3401. list_add(&event->list, &memcg->event_list);
  3402. spin_unlock(&memcg->event_list_lock);
  3403. fdput(cfile);
  3404. fdput(efile);
  3405. return nbytes;
  3406. out_put_css:
  3407. css_put(css);
  3408. out_put_cfile:
  3409. fdput(cfile);
  3410. out_put_eventfd:
  3411. eventfd_ctx_put(event->eventfd);
  3412. out_put_efile:
  3413. fdput(efile);
  3414. out_kfree:
  3415. kfree(event);
  3416. return ret;
  3417. }
  3418. static struct cftype mem_cgroup_legacy_files[] = {
  3419. {
  3420. .name = "usage_in_bytes",
  3421. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3422. .read_u64 = mem_cgroup_read_u64,
  3423. },
  3424. {
  3425. .name = "max_usage_in_bytes",
  3426. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3427. .write = mem_cgroup_reset,
  3428. .read_u64 = mem_cgroup_read_u64,
  3429. },
  3430. {
  3431. .name = "limit_in_bytes",
  3432. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3433. .write = mem_cgroup_write,
  3434. .read_u64 = mem_cgroup_read_u64,
  3435. },
  3436. {
  3437. .name = "soft_limit_in_bytes",
  3438. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3439. .write = mem_cgroup_write,
  3440. .read_u64 = mem_cgroup_read_u64,
  3441. },
  3442. {
  3443. .name = "failcnt",
  3444. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3445. .write = mem_cgroup_reset,
  3446. .read_u64 = mem_cgroup_read_u64,
  3447. },
  3448. {
  3449. .name = "stat",
  3450. .seq_show = memcg_stat_show,
  3451. },
  3452. {
  3453. .name = "force_empty",
  3454. .write = mem_cgroup_force_empty_write,
  3455. },
  3456. {
  3457. .name = "use_hierarchy",
  3458. .write_u64 = mem_cgroup_hierarchy_write,
  3459. .read_u64 = mem_cgroup_hierarchy_read,
  3460. },
  3461. {
  3462. .name = "cgroup.event_control", /* XXX: for compat */
  3463. .write = memcg_write_event_control,
  3464. .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
  3465. },
  3466. {
  3467. .name = "swappiness",
  3468. .read_u64 = mem_cgroup_swappiness_read,
  3469. .write_u64 = mem_cgroup_swappiness_write,
  3470. },
  3471. {
  3472. .name = "move_charge_at_immigrate",
  3473. .read_u64 = mem_cgroup_move_charge_read,
  3474. .write_u64 = mem_cgroup_move_charge_write,
  3475. },
  3476. {
  3477. .name = "oom_control",
  3478. .seq_show = mem_cgroup_oom_control_read,
  3479. .write_u64 = mem_cgroup_oom_control_write,
  3480. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3481. },
  3482. {
  3483. .name = "pressure_level",
  3484. },
  3485. #ifdef CONFIG_NUMA
  3486. {
  3487. .name = "numa_stat",
  3488. .seq_show = memcg_numa_stat_show,
  3489. },
  3490. #endif
  3491. #ifdef CONFIG_MEMCG_KMEM
  3492. {
  3493. .name = "kmem.limit_in_bytes",
  3494. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  3495. .write = mem_cgroup_write,
  3496. .read_u64 = mem_cgroup_read_u64,
  3497. },
  3498. {
  3499. .name = "kmem.usage_in_bytes",
  3500. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  3501. .read_u64 = mem_cgroup_read_u64,
  3502. },
  3503. {
  3504. .name = "kmem.failcnt",
  3505. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  3506. .write = mem_cgroup_reset,
  3507. .read_u64 = mem_cgroup_read_u64,
  3508. },
  3509. {
  3510. .name = "kmem.max_usage_in_bytes",
  3511. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  3512. .write = mem_cgroup_reset,
  3513. .read_u64 = mem_cgroup_read_u64,
  3514. },
  3515. #ifdef CONFIG_SLABINFO
  3516. {
  3517. .name = "kmem.slabinfo",
  3518. .seq_start = slab_start,
  3519. .seq_next = slab_next,
  3520. .seq_stop = slab_stop,
  3521. .seq_show = memcg_slab_show,
  3522. },
  3523. #endif
  3524. #endif
  3525. { }, /* terminate */
  3526. };
  3527. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3528. {
  3529. struct mem_cgroup_per_node *pn;
  3530. struct mem_cgroup_per_zone *mz;
  3531. int zone, tmp = node;
  3532. /*
  3533. * This routine is called against possible nodes.
  3534. * But it's BUG to call kmalloc() against offline node.
  3535. *
  3536. * TODO: this routine can waste much memory for nodes which will
  3537. * never be onlined. It's better to use memory hotplug callback
  3538. * function.
  3539. */
  3540. if (!node_state(node, N_NORMAL_MEMORY))
  3541. tmp = -1;
  3542. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3543. if (!pn)
  3544. return 1;
  3545. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3546. mz = &pn->zoneinfo[zone];
  3547. lruvec_init(&mz->lruvec);
  3548. mz->usage_in_excess = 0;
  3549. mz->on_tree = false;
  3550. mz->memcg = memcg;
  3551. }
  3552. memcg->nodeinfo[node] = pn;
  3553. return 0;
  3554. }
  3555. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3556. {
  3557. kfree(memcg->nodeinfo[node]);
  3558. }
  3559. static struct mem_cgroup *mem_cgroup_alloc(void)
  3560. {
  3561. struct mem_cgroup *memcg;
  3562. size_t size;
  3563. size = sizeof(struct mem_cgroup);
  3564. size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
  3565. memcg = kzalloc(size, GFP_KERNEL);
  3566. if (!memcg)
  3567. return NULL;
  3568. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3569. if (!memcg->stat)
  3570. goto out_free;
  3571. if (memcg_wb_domain_init(memcg, GFP_KERNEL))
  3572. goto out_free_stat;
  3573. return memcg;
  3574. out_free_stat:
  3575. free_percpu(memcg->stat);
  3576. out_free:
  3577. kfree(memcg);
  3578. return NULL;
  3579. }
  3580. /*
  3581. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3582. * (scanning all at force_empty is too costly...)
  3583. *
  3584. * Instead of clearing all references at force_empty, we remember
  3585. * the number of reference from swap_cgroup and free mem_cgroup when
  3586. * it goes down to 0.
  3587. *
  3588. * Removal of cgroup itself succeeds regardless of refs from swap.
  3589. */
  3590. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  3591. {
  3592. int node;
  3593. mem_cgroup_remove_from_trees(memcg);
  3594. for_each_node(node)
  3595. free_mem_cgroup_per_zone_info(memcg, node);
  3596. free_percpu(memcg->stat);
  3597. memcg_wb_domain_exit(memcg);
  3598. kfree(memcg);
  3599. }
  3600. /*
  3601. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3602. */
  3603. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  3604. {
  3605. if (!memcg->memory.parent)
  3606. return NULL;
  3607. return mem_cgroup_from_counter(memcg->memory.parent, memory);
  3608. }
  3609. EXPORT_SYMBOL(parent_mem_cgroup);
  3610. static struct cgroup_subsys_state * __ref
  3611. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  3612. {
  3613. struct mem_cgroup *memcg;
  3614. long error = -ENOMEM;
  3615. int node;
  3616. memcg = mem_cgroup_alloc();
  3617. if (!memcg)
  3618. return ERR_PTR(error);
  3619. for_each_node(node)
  3620. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  3621. goto free_out;
  3622. /* root ? */
  3623. if (parent_css == NULL) {
  3624. root_mem_cgroup = memcg;
  3625. mem_cgroup_root_css = &memcg->css;
  3626. page_counter_init(&memcg->memory, NULL);
  3627. memcg->high = PAGE_COUNTER_MAX;
  3628. memcg->soft_limit = PAGE_COUNTER_MAX;
  3629. page_counter_init(&memcg->memsw, NULL);
  3630. page_counter_init(&memcg->kmem, NULL);
  3631. }
  3632. memcg->last_scanned_node = MAX_NUMNODES;
  3633. INIT_LIST_HEAD(&memcg->oom_notify);
  3634. memcg->move_charge_at_immigrate = 0;
  3635. mutex_init(&memcg->thresholds_lock);
  3636. spin_lock_init(&memcg->move_lock);
  3637. vmpressure_init(&memcg->vmpressure);
  3638. INIT_LIST_HEAD(&memcg->event_list);
  3639. spin_lock_init(&memcg->event_list_lock);
  3640. #ifdef CONFIG_MEMCG_KMEM
  3641. memcg->kmemcg_id = -1;
  3642. #endif
  3643. #ifdef CONFIG_CGROUP_WRITEBACK
  3644. INIT_LIST_HEAD(&memcg->cgwb_list);
  3645. #endif
  3646. return &memcg->css;
  3647. free_out:
  3648. __mem_cgroup_free(memcg);
  3649. return ERR_PTR(error);
  3650. }
  3651. static int
  3652. mem_cgroup_css_online(struct cgroup_subsys_state *css)
  3653. {
  3654. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3655. struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
  3656. int ret;
  3657. if (css->id > MEM_CGROUP_ID_MAX)
  3658. return -ENOSPC;
  3659. if (!parent)
  3660. return 0;
  3661. mutex_lock(&memcg_create_mutex);
  3662. memcg->use_hierarchy = parent->use_hierarchy;
  3663. memcg->oom_kill_disable = parent->oom_kill_disable;
  3664. memcg->swappiness = mem_cgroup_swappiness(parent);
  3665. if (parent->use_hierarchy) {
  3666. page_counter_init(&memcg->memory, &parent->memory);
  3667. memcg->high = PAGE_COUNTER_MAX;
  3668. memcg->soft_limit = PAGE_COUNTER_MAX;
  3669. page_counter_init(&memcg->memsw, &parent->memsw);
  3670. page_counter_init(&memcg->kmem, &parent->kmem);
  3671. /*
  3672. * No need to take a reference to the parent because cgroup
  3673. * core guarantees its existence.
  3674. */
  3675. } else {
  3676. page_counter_init(&memcg->memory, NULL);
  3677. memcg->high = PAGE_COUNTER_MAX;
  3678. memcg->soft_limit = PAGE_COUNTER_MAX;
  3679. page_counter_init(&memcg->memsw, NULL);
  3680. page_counter_init(&memcg->kmem, NULL);
  3681. /*
  3682. * Deeper hierachy with use_hierarchy == false doesn't make
  3683. * much sense so let cgroup subsystem know about this
  3684. * unfortunate state in our controller.
  3685. */
  3686. if (parent != root_mem_cgroup)
  3687. memory_cgrp_subsys.broken_hierarchy = true;
  3688. }
  3689. mutex_unlock(&memcg_create_mutex);
  3690. ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
  3691. if (ret)
  3692. return ret;
  3693. /*
  3694. * Make sure the memcg is initialized: mem_cgroup_iter()
  3695. * orders reading memcg->initialized against its callers
  3696. * reading the memcg members.
  3697. */
  3698. smp_store_release(&memcg->initialized, 1);
  3699. return 0;
  3700. }
  3701. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  3702. {
  3703. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3704. struct mem_cgroup_event *event, *tmp;
  3705. /*
  3706. * Unregister events and notify userspace.
  3707. * Notify userspace about cgroup removing only after rmdir of cgroup
  3708. * directory to avoid race between userspace and kernelspace.
  3709. */
  3710. spin_lock(&memcg->event_list_lock);
  3711. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  3712. list_del_init(&event->list);
  3713. schedule_work(&event->remove);
  3714. }
  3715. spin_unlock(&memcg->event_list_lock);
  3716. vmpressure_cleanup(&memcg->vmpressure);
  3717. memcg_deactivate_kmem(memcg);
  3718. wb_memcg_offline(memcg);
  3719. }
  3720. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  3721. {
  3722. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3723. memcg_destroy_kmem(memcg);
  3724. __mem_cgroup_free(memcg);
  3725. }
  3726. /**
  3727. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  3728. * @css: the target css
  3729. *
  3730. * Reset the states of the mem_cgroup associated with @css. This is
  3731. * invoked when the userland requests disabling on the default hierarchy
  3732. * but the memcg is pinned through dependency. The memcg should stop
  3733. * applying policies and should revert to the vanilla state as it may be
  3734. * made visible again.
  3735. *
  3736. * The current implementation only resets the essential configurations.
  3737. * This needs to be expanded to cover all the visible parts.
  3738. */
  3739. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  3740. {
  3741. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3742. mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
  3743. mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
  3744. memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
  3745. memcg->low = 0;
  3746. memcg->high = PAGE_COUNTER_MAX;
  3747. memcg->soft_limit = PAGE_COUNTER_MAX;
  3748. memcg_wb_domain_size_changed(memcg);
  3749. }
  3750. #ifdef CONFIG_MMU
  3751. /* Handlers for move charge at task migration. */
  3752. static int mem_cgroup_do_precharge(unsigned long count)
  3753. {
  3754. int ret;
  3755. /* Try a single bulk charge without reclaim first, kswapd may wake */
  3756. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
  3757. if (!ret) {
  3758. mc.precharge += count;
  3759. return ret;
  3760. }
  3761. /* Try charges one by one with reclaim */
  3762. while (count--) {
  3763. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
  3764. if (ret)
  3765. return ret;
  3766. mc.precharge++;
  3767. cond_resched();
  3768. }
  3769. return 0;
  3770. }
  3771. /**
  3772. * get_mctgt_type - get target type of moving charge
  3773. * @vma: the vma the pte to be checked belongs
  3774. * @addr: the address corresponding to the pte to be checked
  3775. * @ptent: the pte to be checked
  3776. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  3777. *
  3778. * Returns
  3779. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  3780. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  3781. * move charge. if @target is not NULL, the page is stored in target->page
  3782. * with extra refcnt got(Callers should handle it).
  3783. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  3784. * target for charge migration. if @target is not NULL, the entry is stored
  3785. * in target->ent.
  3786. *
  3787. * Called with pte lock held.
  3788. */
  3789. union mc_target {
  3790. struct page *page;
  3791. swp_entry_t ent;
  3792. };
  3793. enum mc_target_type {
  3794. MC_TARGET_NONE = 0,
  3795. MC_TARGET_PAGE,
  3796. MC_TARGET_SWAP,
  3797. };
  3798. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  3799. unsigned long addr, pte_t ptent)
  3800. {
  3801. struct page *page = vm_normal_page(vma, addr, ptent);
  3802. if (!page || !page_mapped(page))
  3803. return NULL;
  3804. if (PageAnon(page)) {
  3805. if (!(mc.flags & MOVE_ANON))
  3806. return NULL;
  3807. } else {
  3808. if (!(mc.flags & MOVE_FILE))
  3809. return NULL;
  3810. }
  3811. if (!get_page_unless_zero(page))
  3812. return NULL;
  3813. return page;
  3814. }
  3815. #ifdef CONFIG_SWAP
  3816. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  3817. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3818. {
  3819. struct page *page = NULL;
  3820. swp_entry_t ent = pte_to_swp_entry(ptent);
  3821. if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
  3822. return NULL;
  3823. /*
  3824. * Because lookup_swap_cache() updates some statistics counter,
  3825. * we call find_get_page() with swapper_space directly.
  3826. */
  3827. page = find_get_page(swap_address_space(ent), ent.val);
  3828. if (do_swap_account)
  3829. entry->val = ent.val;
  3830. return page;
  3831. }
  3832. #else
  3833. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  3834. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3835. {
  3836. return NULL;
  3837. }
  3838. #endif
  3839. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  3840. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3841. {
  3842. struct page *page = NULL;
  3843. struct address_space *mapping;
  3844. pgoff_t pgoff;
  3845. if (!vma->vm_file) /* anonymous vma */
  3846. return NULL;
  3847. if (!(mc.flags & MOVE_FILE))
  3848. return NULL;
  3849. mapping = vma->vm_file->f_mapping;
  3850. pgoff = linear_page_index(vma, addr);
  3851. /* page is moved even if it's not RSS of this task(page-faulted). */
  3852. #ifdef CONFIG_SWAP
  3853. /* shmem/tmpfs may report page out on swap: account for that too. */
  3854. if (shmem_mapping(mapping)) {
  3855. page = find_get_entry(mapping, pgoff);
  3856. if (radix_tree_exceptional_entry(page)) {
  3857. swp_entry_t swp = radix_to_swp_entry(page);
  3858. if (do_swap_account)
  3859. *entry = swp;
  3860. page = find_get_page(swap_address_space(swp), swp.val);
  3861. }
  3862. } else
  3863. page = find_get_page(mapping, pgoff);
  3864. #else
  3865. page = find_get_page(mapping, pgoff);
  3866. #endif
  3867. return page;
  3868. }
  3869. /**
  3870. * mem_cgroup_move_account - move account of the page
  3871. * @page: the page
  3872. * @nr_pages: number of regular pages (>1 for huge pages)
  3873. * @from: mem_cgroup which the page is moved from.
  3874. * @to: mem_cgroup which the page is moved to. @from != @to.
  3875. *
  3876. * The caller must confirm following.
  3877. * - page is not on LRU (isolate_page() is useful.)
  3878. * - compound_lock is held when nr_pages > 1
  3879. *
  3880. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  3881. * from old cgroup.
  3882. */
  3883. static int mem_cgroup_move_account(struct page *page,
  3884. unsigned int nr_pages,
  3885. struct mem_cgroup *from,
  3886. struct mem_cgroup *to)
  3887. {
  3888. unsigned long flags;
  3889. int ret;
  3890. bool anon;
  3891. VM_BUG_ON(from == to);
  3892. VM_BUG_ON_PAGE(PageLRU(page), page);
  3893. /*
  3894. * The page is isolated from LRU. So, collapse function
  3895. * will not handle this page. But page splitting can happen.
  3896. * Do this check under compound_page_lock(). The caller should
  3897. * hold it.
  3898. */
  3899. ret = -EBUSY;
  3900. if (nr_pages > 1 && !PageTransHuge(page))
  3901. goto out;
  3902. /*
  3903. * Prevent mem_cgroup_replace_page() from looking at
  3904. * page->mem_cgroup of its source page while we change it.
  3905. */
  3906. if (!trylock_page(page))
  3907. goto out;
  3908. ret = -EINVAL;
  3909. if (page->mem_cgroup != from)
  3910. goto out_unlock;
  3911. anon = PageAnon(page);
  3912. spin_lock_irqsave(&from->move_lock, flags);
  3913. if (!anon && page_mapped(page)) {
  3914. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  3915. nr_pages);
  3916. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  3917. nr_pages);
  3918. }
  3919. /*
  3920. * move_lock grabbed above and caller set from->moving_account, so
  3921. * mem_cgroup_update_page_stat() will serialize updates to PageDirty.
  3922. * So mapping should be stable for dirty pages.
  3923. */
  3924. if (!anon && PageDirty(page)) {
  3925. struct address_space *mapping = page_mapping(page);
  3926. if (mapping_cap_account_dirty(mapping)) {
  3927. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_DIRTY],
  3928. nr_pages);
  3929. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_DIRTY],
  3930. nr_pages);
  3931. }
  3932. }
  3933. if (PageWriteback(page)) {
  3934. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  3935. nr_pages);
  3936. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  3937. nr_pages);
  3938. }
  3939. /*
  3940. * It is safe to change page->mem_cgroup here because the page
  3941. * is referenced, charged, and isolated - we can't race with
  3942. * uncharging, charging, migration, or LRU putback.
  3943. */
  3944. /* caller should have done css_get */
  3945. page->mem_cgroup = to;
  3946. spin_unlock_irqrestore(&from->move_lock, flags);
  3947. ret = 0;
  3948. local_irq_disable();
  3949. mem_cgroup_charge_statistics(to, page, nr_pages);
  3950. memcg_check_events(to, page);
  3951. mem_cgroup_charge_statistics(from, page, -nr_pages);
  3952. memcg_check_events(from, page);
  3953. local_irq_enable();
  3954. out_unlock:
  3955. unlock_page(page);
  3956. out:
  3957. return ret;
  3958. }
  3959. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  3960. unsigned long addr, pte_t ptent, union mc_target *target)
  3961. {
  3962. struct page *page = NULL;
  3963. enum mc_target_type ret = MC_TARGET_NONE;
  3964. swp_entry_t ent = { .val = 0 };
  3965. if (pte_present(ptent))
  3966. page = mc_handle_present_pte(vma, addr, ptent);
  3967. else if (is_swap_pte(ptent))
  3968. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  3969. else if (pte_none(ptent))
  3970. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  3971. if (!page && !ent.val)
  3972. return ret;
  3973. if (page) {
  3974. /*
  3975. * Do only loose check w/o serialization.
  3976. * mem_cgroup_move_account() checks the page is valid or
  3977. * not under LRU exclusion.
  3978. */
  3979. if (page->mem_cgroup == mc.from) {
  3980. ret = MC_TARGET_PAGE;
  3981. if (target)
  3982. target->page = page;
  3983. }
  3984. if (!ret || !target)
  3985. put_page(page);
  3986. }
  3987. /* There is a swap entry and a page doesn't exist or isn't charged */
  3988. if (ent.val && !ret &&
  3989. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  3990. ret = MC_TARGET_SWAP;
  3991. if (target)
  3992. target->ent = ent;
  3993. }
  3994. return ret;
  3995. }
  3996. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3997. /*
  3998. * We don't consider swapping or file mapped pages because THP does not
  3999. * support them for now.
  4000. * Caller should make sure that pmd_trans_huge(pmd) is true.
  4001. */
  4002. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4003. unsigned long addr, pmd_t pmd, union mc_target *target)
  4004. {
  4005. struct page *page = NULL;
  4006. enum mc_target_type ret = MC_TARGET_NONE;
  4007. page = pmd_page(pmd);
  4008. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  4009. if (!(mc.flags & MOVE_ANON))
  4010. return ret;
  4011. if (page->mem_cgroup == mc.from) {
  4012. ret = MC_TARGET_PAGE;
  4013. if (target) {
  4014. get_page(page);
  4015. target->page = page;
  4016. }
  4017. }
  4018. return ret;
  4019. }
  4020. #else
  4021. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4022. unsigned long addr, pmd_t pmd, union mc_target *target)
  4023. {
  4024. return MC_TARGET_NONE;
  4025. }
  4026. #endif
  4027. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4028. unsigned long addr, unsigned long end,
  4029. struct mm_walk *walk)
  4030. {
  4031. struct vm_area_struct *vma = walk->vma;
  4032. pte_t *pte;
  4033. spinlock_t *ptl;
  4034. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4035. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  4036. mc.precharge += HPAGE_PMD_NR;
  4037. spin_unlock(ptl);
  4038. return 0;
  4039. }
  4040. if (pmd_trans_unstable(pmd))
  4041. return 0;
  4042. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4043. for (; addr != end; pte++, addr += PAGE_SIZE)
  4044. if (get_mctgt_type(vma, addr, *pte, NULL))
  4045. mc.precharge++; /* increment precharge temporarily */
  4046. pte_unmap_unlock(pte - 1, ptl);
  4047. cond_resched();
  4048. return 0;
  4049. }
  4050. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4051. {
  4052. unsigned long precharge;
  4053. struct mm_walk mem_cgroup_count_precharge_walk = {
  4054. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4055. .mm = mm,
  4056. };
  4057. down_read(&mm->mmap_sem);
  4058. walk_page_range(0, ~0UL, &mem_cgroup_count_precharge_walk);
  4059. up_read(&mm->mmap_sem);
  4060. precharge = mc.precharge;
  4061. mc.precharge = 0;
  4062. return precharge;
  4063. }
  4064. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4065. {
  4066. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4067. VM_BUG_ON(mc.moving_task);
  4068. mc.moving_task = current;
  4069. return mem_cgroup_do_precharge(precharge);
  4070. }
  4071. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4072. static void __mem_cgroup_clear_mc(void)
  4073. {
  4074. struct mem_cgroup *from = mc.from;
  4075. struct mem_cgroup *to = mc.to;
  4076. /* we must uncharge all the leftover precharges from mc.to */
  4077. if (mc.precharge) {
  4078. cancel_charge(mc.to, mc.precharge);
  4079. mc.precharge = 0;
  4080. }
  4081. /*
  4082. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4083. * we must uncharge here.
  4084. */
  4085. if (mc.moved_charge) {
  4086. cancel_charge(mc.from, mc.moved_charge);
  4087. mc.moved_charge = 0;
  4088. }
  4089. /* we must fixup refcnts and charges */
  4090. if (mc.moved_swap) {
  4091. /* uncharge swap account from the old cgroup */
  4092. if (!mem_cgroup_is_root(mc.from))
  4093. page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
  4094. /*
  4095. * we charged both to->memory and to->memsw, so we
  4096. * should uncharge to->memory.
  4097. */
  4098. if (!mem_cgroup_is_root(mc.to))
  4099. page_counter_uncharge(&mc.to->memory, mc.moved_swap);
  4100. css_put_many(&mc.from->css, mc.moved_swap);
  4101. /* we've already done css_get(mc.to) */
  4102. mc.moved_swap = 0;
  4103. }
  4104. memcg_oom_recover(from);
  4105. memcg_oom_recover(to);
  4106. wake_up_all(&mc.waitq);
  4107. }
  4108. static void mem_cgroup_clear_mc(void)
  4109. {
  4110. /*
  4111. * we must clear moving_task before waking up waiters at the end of
  4112. * task migration.
  4113. */
  4114. mc.moving_task = NULL;
  4115. __mem_cgroup_clear_mc();
  4116. spin_lock(&mc.lock);
  4117. mc.from = NULL;
  4118. mc.to = NULL;
  4119. spin_unlock(&mc.lock);
  4120. }
  4121. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4122. struct cgroup_taskset *tset)
  4123. {
  4124. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4125. struct mem_cgroup *from;
  4126. struct task_struct *leader, *p;
  4127. struct mm_struct *mm;
  4128. unsigned long move_flags;
  4129. int ret = 0;
  4130. /*
  4131. * We are now commited to this value whatever it is. Changes in this
  4132. * tunable will only affect upcoming migrations, not the current one.
  4133. * So we need to save it, and keep it going.
  4134. */
  4135. move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
  4136. if (!move_flags)
  4137. return 0;
  4138. /*
  4139. * Multi-process migrations only happen on the default hierarchy
  4140. * where charge immigration is not used. Perform charge
  4141. * immigration if @tset contains a leader and whine if there are
  4142. * multiple.
  4143. */
  4144. p = NULL;
  4145. cgroup_taskset_for_each_leader(leader, tset) {
  4146. WARN_ON_ONCE(p);
  4147. p = leader;
  4148. }
  4149. if (!p)
  4150. return 0;
  4151. from = mem_cgroup_from_task(p);
  4152. VM_BUG_ON(from == memcg);
  4153. mm = get_task_mm(p);
  4154. if (!mm)
  4155. return 0;
  4156. /* We move charges only when we move a owner of the mm */
  4157. if (mm->owner == p) {
  4158. VM_BUG_ON(mc.from);
  4159. VM_BUG_ON(mc.to);
  4160. VM_BUG_ON(mc.precharge);
  4161. VM_BUG_ON(mc.moved_charge);
  4162. VM_BUG_ON(mc.moved_swap);
  4163. spin_lock(&mc.lock);
  4164. mc.from = from;
  4165. mc.to = memcg;
  4166. mc.flags = move_flags;
  4167. spin_unlock(&mc.lock);
  4168. /* We set mc.moving_task later */
  4169. ret = mem_cgroup_precharge_mc(mm);
  4170. if (ret)
  4171. mem_cgroup_clear_mc();
  4172. }
  4173. mmput(mm);
  4174. return ret;
  4175. }
  4176. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4177. struct cgroup_taskset *tset)
  4178. {
  4179. if (mc.to)
  4180. mem_cgroup_clear_mc();
  4181. }
  4182. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4183. unsigned long addr, unsigned long end,
  4184. struct mm_walk *walk)
  4185. {
  4186. int ret = 0;
  4187. struct vm_area_struct *vma = walk->vma;
  4188. pte_t *pte;
  4189. spinlock_t *ptl;
  4190. enum mc_target_type target_type;
  4191. union mc_target target;
  4192. struct page *page;
  4193. /*
  4194. * We don't take compound_lock() here but no race with splitting thp
  4195. * happens because:
  4196. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  4197. * under splitting, which means there's no concurrent thp split,
  4198. * - if another thread runs into split_huge_page() just after we
  4199. * entered this if-block, the thread must wait for page table lock
  4200. * to be unlocked in __split_huge_page_splitting(), where the main
  4201. * part of thp split is not executed yet.
  4202. */
  4203. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4204. if (mc.precharge < HPAGE_PMD_NR) {
  4205. spin_unlock(ptl);
  4206. return 0;
  4207. }
  4208. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  4209. if (target_type == MC_TARGET_PAGE) {
  4210. page = target.page;
  4211. if (!isolate_lru_page(page)) {
  4212. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  4213. mc.from, mc.to)) {
  4214. mc.precharge -= HPAGE_PMD_NR;
  4215. mc.moved_charge += HPAGE_PMD_NR;
  4216. }
  4217. putback_lru_page(page);
  4218. }
  4219. put_page(page);
  4220. }
  4221. spin_unlock(ptl);
  4222. return 0;
  4223. }
  4224. if (pmd_trans_unstable(pmd))
  4225. return 0;
  4226. retry:
  4227. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4228. for (; addr != end; addr += PAGE_SIZE) {
  4229. pte_t ptent = *(pte++);
  4230. swp_entry_t ent;
  4231. if (!mc.precharge)
  4232. break;
  4233. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  4234. case MC_TARGET_PAGE:
  4235. page = target.page;
  4236. if (isolate_lru_page(page))
  4237. goto put;
  4238. if (!mem_cgroup_move_account(page, 1, mc.from, mc.to)) {
  4239. mc.precharge--;
  4240. /* we uncharge from mc.from later. */
  4241. mc.moved_charge++;
  4242. }
  4243. putback_lru_page(page);
  4244. put: /* get_mctgt_type() gets the page */
  4245. put_page(page);
  4246. break;
  4247. case MC_TARGET_SWAP:
  4248. ent = target.ent;
  4249. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  4250. mc.precharge--;
  4251. /* we fixup refcnts and charges later. */
  4252. mc.moved_swap++;
  4253. }
  4254. break;
  4255. default:
  4256. break;
  4257. }
  4258. }
  4259. pte_unmap_unlock(pte - 1, ptl);
  4260. cond_resched();
  4261. if (addr != end) {
  4262. /*
  4263. * We have consumed all precharges we got in can_attach().
  4264. * We try charge one by one, but don't do any additional
  4265. * charges to mc.to if we have failed in charge once in attach()
  4266. * phase.
  4267. */
  4268. ret = mem_cgroup_do_precharge(1);
  4269. if (!ret)
  4270. goto retry;
  4271. }
  4272. return ret;
  4273. }
  4274. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4275. {
  4276. struct mm_walk mem_cgroup_move_charge_walk = {
  4277. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4278. .mm = mm,
  4279. };
  4280. lru_add_drain_all();
  4281. /*
  4282. * Signal mem_cgroup_begin_page_stat() to take the memcg's
  4283. * move_lock while we're moving its pages to another memcg.
  4284. * Then wait for already started RCU-only updates to finish.
  4285. */
  4286. atomic_inc(&mc.from->moving_account);
  4287. synchronize_rcu();
  4288. retry:
  4289. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4290. /*
  4291. * Someone who are holding the mmap_sem might be waiting in
  4292. * waitq. So we cancel all extra charges, wake up all waiters,
  4293. * and retry. Because we cancel precharges, we might not be able
  4294. * to move enough charges, but moving charge is a best-effort
  4295. * feature anyway, so it wouldn't be a big problem.
  4296. */
  4297. __mem_cgroup_clear_mc();
  4298. cond_resched();
  4299. goto retry;
  4300. }
  4301. /*
  4302. * When we have consumed all precharges and failed in doing
  4303. * additional charge, the page walk just aborts.
  4304. */
  4305. walk_page_range(0, ~0UL, &mem_cgroup_move_charge_walk);
  4306. up_read(&mm->mmap_sem);
  4307. atomic_dec(&mc.from->moving_account);
  4308. }
  4309. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4310. struct cgroup_taskset *tset)
  4311. {
  4312. struct task_struct *p = cgroup_taskset_first(tset);
  4313. struct mm_struct *mm = get_task_mm(p);
  4314. if (mm) {
  4315. if (mc.to)
  4316. mem_cgroup_move_charge(mm);
  4317. mmput(mm);
  4318. }
  4319. if (mc.to)
  4320. mem_cgroup_clear_mc();
  4321. }
  4322. #else /* !CONFIG_MMU */
  4323. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4324. struct cgroup_taskset *tset)
  4325. {
  4326. return 0;
  4327. }
  4328. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4329. struct cgroup_taskset *tset)
  4330. {
  4331. }
  4332. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4333. struct cgroup_taskset *tset)
  4334. {
  4335. }
  4336. #endif
  4337. /*
  4338. * Cgroup retains root cgroups across [un]mount cycles making it necessary
  4339. * to verify whether we're attached to the default hierarchy on each mount
  4340. * attempt.
  4341. */
  4342. static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
  4343. {
  4344. /*
  4345. * use_hierarchy is forced on the default hierarchy. cgroup core
  4346. * guarantees that @root doesn't have any children, so turning it
  4347. * on for the root memcg is enough.
  4348. */
  4349. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4350. root_mem_cgroup->use_hierarchy = true;
  4351. else
  4352. root_mem_cgroup->use_hierarchy = false;
  4353. }
  4354. static u64 memory_current_read(struct cgroup_subsys_state *css,
  4355. struct cftype *cft)
  4356. {
  4357. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4358. return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
  4359. }
  4360. static int memory_low_show(struct seq_file *m, void *v)
  4361. {
  4362. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4363. unsigned long low = READ_ONCE(memcg->low);
  4364. if (low == PAGE_COUNTER_MAX)
  4365. seq_puts(m, "max\n");
  4366. else
  4367. seq_printf(m, "%llu\n", (u64)low * PAGE_SIZE);
  4368. return 0;
  4369. }
  4370. static ssize_t memory_low_write(struct kernfs_open_file *of,
  4371. char *buf, size_t nbytes, loff_t off)
  4372. {
  4373. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4374. unsigned long low;
  4375. int err;
  4376. buf = strstrip(buf);
  4377. err = page_counter_memparse(buf, "max", &low);
  4378. if (err)
  4379. return err;
  4380. memcg->low = low;
  4381. return nbytes;
  4382. }
  4383. static int memory_high_show(struct seq_file *m, void *v)
  4384. {
  4385. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4386. unsigned long high = READ_ONCE(memcg->high);
  4387. if (high == PAGE_COUNTER_MAX)
  4388. seq_puts(m, "max\n");
  4389. else
  4390. seq_printf(m, "%llu\n", (u64)high * PAGE_SIZE);
  4391. return 0;
  4392. }
  4393. static ssize_t memory_high_write(struct kernfs_open_file *of,
  4394. char *buf, size_t nbytes, loff_t off)
  4395. {
  4396. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4397. unsigned long high;
  4398. int err;
  4399. buf = strstrip(buf);
  4400. err = page_counter_memparse(buf, "max", &high);
  4401. if (err)
  4402. return err;
  4403. memcg->high = high;
  4404. memcg_wb_domain_size_changed(memcg);
  4405. return nbytes;
  4406. }
  4407. static int memory_max_show(struct seq_file *m, void *v)
  4408. {
  4409. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4410. unsigned long max = READ_ONCE(memcg->memory.limit);
  4411. if (max == PAGE_COUNTER_MAX)
  4412. seq_puts(m, "max\n");
  4413. else
  4414. seq_printf(m, "%llu\n", (u64)max * PAGE_SIZE);
  4415. return 0;
  4416. }
  4417. static ssize_t memory_max_write(struct kernfs_open_file *of,
  4418. char *buf, size_t nbytes, loff_t off)
  4419. {
  4420. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4421. unsigned long max;
  4422. int err;
  4423. buf = strstrip(buf);
  4424. err = page_counter_memparse(buf, "max", &max);
  4425. if (err)
  4426. return err;
  4427. err = mem_cgroup_resize_limit(memcg, max);
  4428. if (err)
  4429. return err;
  4430. memcg_wb_domain_size_changed(memcg);
  4431. return nbytes;
  4432. }
  4433. static int memory_events_show(struct seq_file *m, void *v)
  4434. {
  4435. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4436. seq_printf(m, "low %lu\n", mem_cgroup_read_events(memcg, MEMCG_LOW));
  4437. seq_printf(m, "high %lu\n", mem_cgroup_read_events(memcg, MEMCG_HIGH));
  4438. seq_printf(m, "max %lu\n", mem_cgroup_read_events(memcg, MEMCG_MAX));
  4439. seq_printf(m, "oom %lu\n", mem_cgroup_read_events(memcg, MEMCG_OOM));
  4440. return 0;
  4441. }
  4442. static struct cftype memory_files[] = {
  4443. {
  4444. .name = "current",
  4445. .flags = CFTYPE_NOT_ON_ROOT,
  4446. .read_u64 = memory_current_read,
  4447. },
  4448. {
  4449. .name = "low",
  4450. .flags = CFTYPE_NOT_ON_ROOT,
  4451. .seq_show = memory_low_show,
  4452. .write = memory_low_write,
  4453. },
  4454. {
  4455. .name = "high",
  4456. .flags = CFTYPE_NOT_ON_ROOT,
  4457. .seq_show = memory_high_show,
  4458. .write = memory_high_write,
  4459. },
  4460. {
  4461. .name = "max",
  4462. .flags = CFTYPE_NOT_ON_ROOT,
  4463. .seq_show = memory_max_show,
  4464. .write = memory_max_write,
  4465. },
  4466. {
  4467. .name = "events",
  4468. .flags = CFTYPE_NOT_ON_ROOT,
  4469. .file_offset = offsetof(struct mem_cgroup, events_file),
  4470. .seq_show = memory_events_show,
  4471. },
  4472. { } /* terminate */
  4473. };
  4474. struct cgroup_subsys memory_cgrp_subsys = {
  4475. .css_alloc = mem_cgroup_css_alloc,
  4476. .css_online = mem_cgroup_css_online,
  4477. .css_offline = mem_cgroup_css_offline,
  4478. .css_free = mem_cgroup_css_free,
  4479. .css_reset = mem_cgroup_css_reset,
  4480. .can_attach = mem_cgroup_can_attach,
  4481. .cancel_attach = mem_cgroup_cancel_attach,
  4482. .attach = mem_cgroup_move_task,
  4483. .bind = mem_cgroup_bind,
  4484. .dfl_cftypes = memory_files,
  4485. .legacy_cftypes = mem_cgroup_legacy_files,
  4486. .early_init = 0,
  4487. };
  4488. /**
  4489. * mem_cgroup_low - check if memory consumption is below the normal range
  4490. * @root: the highest ancestor to consider
  4491. * @memcg: the memory cgroup to check
  4492. *
  4493. * Returns %true if memory consumption of @memcg, and that of all
  4494. * configurable ancestors up to @root, is below the normal range.
  4495. */
  4496. bool mem_cgroup_low(struct mem_cgroup *root, struct mem_cgroup *memcg)
  4497. {
  4498. if (mem_cgroup_disabled())
  4499. return false;
  4500. /*
  4501. * The toplevel group doesn't have a configurable range, so
  4502. * it's never low when looked at directly, and it is not
  4503. * considered an ancestor when assessing the hierarchy.
  4504. */
  4505. if (memcg == root_mem_cgroup)
  4506. return false;
  4507. if (page_counter_read(&memcg->memory) >= memcg->low)
  4508. return false;
  4509. while (memcg != root) {
  4510. memcg = parent_mem_cgroup(memcg);
  4511. if (memcg == root_mem_cgroup)
  4512. break;
  4513. if (page_counter_read(&memcg->memory) >= memcg->low)
  4514. return false;
  4515. }
  4516. return true;
  4517. }
  4518. /**
  4519. * mem_cgroup_try_charge - try charging a page
  4520. * @page: page to charge
  4521. * @mm: mm context of the victim
  4522. * @gfp_mask: reclaim mode
  4523. * @memcgp: charged memcg return
  4524. *
  4525. * Try to charge @page to the memcg that @mm belongs to, reclaiming
  4526. * pages according to @gfp_mask if necessary.
  4527. *
  4528. * Returns 0 on success, with *@memcgp pointing to the charged memcg.
  4529. * Otherwise, an error code is returned.
  4530. *
  4531. * After page->mapping has been set up, the caller must finalize the
  4532. * charge with mem_cgroup_commit_charge(). Or abort the transaction
  4533. * with mem_cgroup_cancel_charge() in case page instantiation fails.
  4534. */
  4535. int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
  4536. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  4537. {
  4538. struct mem_cgroup *memcg = NULL;
  4539. unsigned int nr_pages = 1;
  4540. int ret = 0;
  4541. if (mem_cgroup_disabled())
  4542. goto out;
  4543. if (PageSwapCache(page)) {
  4544. /*
  4545. * Every swap fault against a single page tries to charge the
  4546. * page, bail as early as possible. shmem_unuse() encounters
  4547. * already charged pages, too. The USED bit is protected by
  4548. * the page lock, which serializes swap cache removal, which
  4549. * in turn serializes uncharging.
  4550. */
  4551. VM_BUG_ON_PAGE(!PageLocked(page), page);
  4552. if (page->mem_cgroup)
  4553. goto out;
  4554. if (do_swap_account) {
  4555. swp_entry_t ent = { .val = page_private(page), };
  4556. unsigned short id = lookup_swap_cgroup_id(ent);
  4557. rcu_read_lock();
  4558. memcg = mem_cgroup_from_id(id);
  4559. if (memcg && !css_tryget_online(&memcg->css))
  4560. memcg = NULL;
  4561. rcu_read_unlock();
  4562. }
  4563. }
  4564. if (PageTransHuge(page)) {
  4565. nr_pages <<= compound_order(page);
  4566. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4567. }
  4568. if (!memcg)
  4569. memcg = get_mem_cgroup_from_mm(mm);
  4570. ret = try_charge(memcg, gfp_mask, nr_pages);
  4571. css_put(&memcg->css);
  4572. out:
  4573. *memcgp = memcg;
  4574. return ret;
  4575. }
  4576. /**
  4577. * mem_cgroup_commit_charge - commit a page charge
  4578. * @page: page to charge
  4579. * @memcg: memcg to charge the page to
  4580. * @lrucare: page might be on LRU already
  4581. *
  4582. * Finalize a charge transaction started by mem_cgroup_try_charge(),
  4583. * after page->mapping has been set up. This must happen atomically
  4584. * as part of the page instantiation, i.e. under the page table lock
  4585. * for anonymous pages, under the page lock for page and swap cache.
  4586. *
  4587. * In addition, the page must not be on the LRU during the commit, to
  4588. * prevent racing with task migration. If it might be, use @lrucare.
  4589. *
  4590. * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
  4591. */
  4592. void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
  4593. bool lrucare)
  4594. {
  4595. unsigned int nr_pages = 1;
  4596. VM_BUG_ON_PAGE(!page->mapping, page);
  4597. VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
  4598. if (mem_cgroup_disabled())
  4599. return;
  4600. /*
  4601. * Swap faults will attempt to charge the same page multiple
  4602. * times. But reuse_swap_page() might have removed the page
  4603. * from swapcache already, so we can't check PageSwapCache().
  4604. */
  4605. if (!memcg)
  4606. return;
  4607. commit_charge(page, memcg, lrucare);
  4608. if (PageTransHuge(page)) {
  4609. nr_pages <<= compound_order(page);
  4610. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4611. }
  4612. local_irq_disable();
  4613. mem_cgroup_charge_statistics(memcg, page, nr_pages);
  4614. memcg_check_events(memcg, page);
  4615. local_irq_enable();
  4616. if (do_swap_account && PageSwapCache(page)) {
  4617. swp_entry_t entry = { .val = page_private(page) };
  4618. /*
  4619. * The swap entry might not get freed for a long time,
  4620. * let's not wait for it. The page already received a
  4621. * memory+swap charge, drop the swap entry duplicate.
  4622. */
  4623. mem_cgroup_uncharge_swap(entry);
  4624. }
  4625. }
  4626. /**
  4627. * mem_cgroup_cancel_charge - cancel a page charge
  4628. * @page: page to charge
  4629. * @memcg: memcg to charge the page to
  4630. *
  4631. * Cancel a charge transaction started by mem_cgroup_try_charge().
  4632. */
  4633. void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
  4634. {
  4635. unsigned int nr_pages = 1;
  4636. if (mem_cgroup_disabled())
  4637. return;
  4638. /*
  4639. * Swap faults will attempt to charge the same page multiple
  4640. * times. But reuse_swap_page() might have removed the page
  4641. * from swapcache already, so we can't check PageSwapCache().
  4642. */
  4643. if (!memcg)
  4644. return;
  4645. if (PageTransHuge(page)) {
  4646. nr_pages <<= compound_order(page);
  4647. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4648. }
  4649. cancel_charge(memcg, nr_pages);
  4650. }
  4651. static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  4652. unsigned long nr_anon, unsigned long nr_file,
  4653. unsigned long nr_huge, struct page *dummy_page)
  4654. {
  4655. unsigned long nr_pages = nr_anon + nr_file;
  4656. unsigned long flags;
  4657. if (!mem_cgroup_is_root(memcg)) {
  4658. page_counter_uncharge(&memcg->memory, nr_pages);
  4659. if (do_swap_account)
  4660. page_counter_uncharge(&memcg->memsw, nr_pages);
  4661. memcg_oom_recover(memcg);
  4662. }
  4663. local_irq_save(flags);
  4664. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
  4665. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
  4666. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
  4667. __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
  4668. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  4669. memcg_check_events(memcg, dummy_page);
  4670. local_irq_restore(flags);
  4671. if (!mem_cgroup_is_root(memcg))
  4672. css_put_many(&memcg->css, nr_pages);
  4673. }
  4674. static void uncharge_list(struct list_head *page_list)
  4675. {
  4676. struct mem_cgroup *memcg = NULL;
  4677. unsigned long nr_anon = 0;
  4678. unsigned long nr_file = 0;
  4679. unsigned long nr_huge = 0;
  4680. unsigned long pgpgout = 0;
  4681. struct list_head *next;
  4682. struct page *page;
  4683. next = page_list->next;
  4684. do {
  4685. unsigned int nr_pages = 1;
  4686. page = list_entry(next, struct page, lru);
  4687. next = page->lru.next;
  4688. VM_BUG_ON_PAGE(PageLRU(page), page);
  4689. VM_BUG_ON_PAGE(page_count(page), page);
  4690. if (!page->mem_cgroup)
  4691. continue;
  4692. /*
  4693. * Nobody should be changing or seriously looking at
  4694. * page->mem_cgroup at this point, we have fully
  4695. * exclusive access to the page.
  4696. */
  4697. if (memcg != page->mem_cgroup) {
  4698. if (memcg) {
  4699. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4700. nr_huge, page);
  4701. pgpgout = nr_anon = nr_file = nr_huge = 0;
  4702. }
  4703. memcg = page->mem_cgroup;
  4704. }
  4705. if (PageTransHuge(page)) {
  4706. nr_pages <<= compound_order(page);
  4707. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4708. nr_huge += nr_pages;
  4709. }
  4710. if (PageAnon(page))
  4711. nr_anon += nr_pages;
  4712. else
  4713. nr_file += nr_pages;
  4714. page->mem_cgroup = NULL;
  4715. pgpgout++;
  4716. } while (next != page_list);
  4717. if (memcg)
  4718. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4719. nr_huge, page);
  4720. }
  4721. /**
  4722. * mem_cgroup_uncharge - uncharge a page
  4723. * @page: page to uncharge
  4724. *
  4725. * Uncharge a page previously charged with mem_cgroup_try_charge() and
  4726. * mem_cgroup_commit_charge().
  4727. */
  4728. void mem_cgroup_uncharge(struct page *page)
  4729. {
  4730. if (mem_cgroup_disabled())
  4731. return;
  4732. /* Don't touch page->lru of any random page, pre-check: */
  4733. if (!page->mem_cgroup)
  4734. return;
  4735. INIT_LIST_HEAD(&page->lru);
  4736. uncharge_list(&page->lru);
  4737. }
  4738. /**
  4739. * mem_cgroup_uncharge_list - uncharge a list of page
  4740. * @page_list: list of pages to uncharge
  4741. *
  4742. * Uncharge a list of pages previously charged with
  4743. * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
  4744. */
  4745. void mem_cgroup_uncharge_list(struct list_head *page_list)
  4746. {
  4747. if (mem_cgroup_disabled())
  4748. return;
  4749. if (!list_empty(page_list))
  4750. uncharge_list(page_list);
  4751. }
  4752. /**
  4753. * mem_cgroup_replace_page - migrate a charge to another page
  4754. * @oldpage: currently charged page
  4755. * @newpage: page to transfer the charge to
  4756. * @lrucare: either or both pages might be on the LRU already
  4757. *
  4758. * Migrate the charge from @oldpage to @newpage.
  4759. *
  4760. * Both pages must be locked, @newpage->mapping must be set up.
  4761. */
  4762. void mem_cgroup_replace_page(struct page *oldpage, struct page *newpage)
  4763. {
  4764. struct mem_cgroup *memcg;
  4765. int isolated;
  4766. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  4767. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  4768. VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
  4769. VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
  4770. newpage);
  4771. if (mem_cgroup_disabled())
  4772. return;
  4773. /* Page cache replacement: new page already charged? */
  4774. if (newpage->mem_cgroup)
  4775. return;
  4776. /* Swapcache readahead pages can get replaced before being charged */
  4777. memcg = oldpage->mem_cgroup;
  4778. if (!memcg)
  4779. return;
  4780. lock_page_lru(oldpage, &isolated);
  4781. oldpage->mem_cgroup = NULL;
  4782. unlock_page_lru(oldpage, isolated);
  4783. commit_charge(newpage, memcg, true);
  4784. }
  4785. /*
  4786. * subsys_initcall() for memory controller.
  4787. *
  4788. * Some parts like hotcpu_notifier() have to be initialized from this context
  4789. * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
  4790. * everything that doesn't depend on a specific mem_cgroup structure should
  4791. * be initialized from here.
  4792. */
  4793. static int __init mem_cgroup_init(void)
  4794. {
  4795. int cpu, node;
  4796. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4797. for_each_possible_cpu(cpu)
  4798. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  4799. drain_local_stock);
  4800. for_each_node(node) {
  4801. struct mem_cgroup_tree_per_node *rtpn;
  4802. int zone;
  4803. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
  4804. node_online(node) ? node : NUMA_NO_NODE);
  4805. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4806. struct mem_cgroup_tree_per_zone *rtpz;
  4807. rtpz = &rtpn->rb_tree_per_zone[zone];
  4808. rtpz->rb_root = RB_ROOT;
  4809. spin_lock_init(&rtpz->lock);
  4810. }
  4811. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4812. }
  4813. return 0;
  4814. }
  4815. subsys_initcall(mem_cgroup_init);
  4816. #ifdef CONFIG_MEMCG_SWAP
  4817. /**
  4818. * mem_cgroup_swapout - transfer a memsw charge to swap
  4819. * @page: page whose memsw charge to transfer
  4820. * @entry: swap entry to move the charge to
  4821. *
  4822. * Transfer the memsw charge of @page to @entry.
  4823. */
  4824. void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
  4825. {
  4826. struct mem_cgroup *memcg;
  4827. unsigned short oldid;
  4828. VM_BUG_ON_PAGE(PageLRU(page), page);
  4829. VM_BUG_ON_PAGE(page_count(page), page);
  4830. if (!do_swap_account)
  4831. return;
  4832. memcg = page->mem_cgroup;
  4833. /* Readahead page, never charged */
  4834. if (!memcg)
  4835. return;
  4836. oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg));
  4837. VM_BUG_ON_PAGE(oldid, page);
  4838. mem_cgroup_swap_statistics(memcg, true);
  4839. page->mem_cgroup = NULL;
  4840. if (!mem_cgroup_is_root(memcg))
  4841. page_counter_uncharge(&memcg->memory, 1);
  4842. /*
  4843. * Interrupts should be disabled here because the caller holds the
  4844. * mapping->tree_lock lock which is taken with interrupts-off. It is
  4845. * important here to have the interrupts disabled because it is the
  4846. * only synchronisation we have for udpating the per-CPU variables.
  4847. */
  4848. VM_BUG_ON(!irqs_disabled());
  4849. mem_cgroup_charge_statistics(memcg, page, -1);
  4850. memcg_check_events(memcg, page);
  4851. }
  4852. /**
  4853. * mem_cgroup_uncharge_swap - uncharge a swap entry
  4854. * @entry: swap entry to uncharge
  4855. *
  4856. * Drop the memsw charge associated with @entry.
  4857. */
  4858. void mem_cgroup_uncharge_swap(swp_entry_t entry)
  4859. {
  4860. struct mem_cgroup *memcg;
  4861. unsigned short id;
  4862. if (!do_swap_account)
  4863. return;
  4864. id = swap_cgroup_record(entry, 0);
  4865. rcu_read_lock();
  4866. memcg = mem_cgroup_from_id(id);
  4867. if (memcg) {
  4868. if (!mem_cgroup_is_root(memcg))
  4869. page_counter_uncharge(&memcg->memsw, 1);
  4870. mem_cgroup_swap_statistics(memcg, false);
  4871. css_put(&memcg->css);
  4872. }
  4873. rcu_read_unlock();
  4874. }
  4875. /* for remember boot option*/
  4876. #ifdef CONFIG_MEMCG_SWAP_ENABLED
  4877. static int really_do_swap_account __initdata = 1;
  4878. #else
  4879. static int really_do_swap_account __initdata;
  4880. #endif
  4881. static int __init enable_swap_account(char *s)
  4882. {
  4883. if (!strcmp(s, "1"))
  4884. really_do_swap_account = 1;
  4885. else if (!strcmp(s, "0"))
  4886. really_do_swap_account = 0;
  4887. return 1;
  4888. }
  4889. __setup("swapaccount=", enable_swap_account);
  4890. static struct cftype memsw_cgroup_files[] = {
  4891. {
  4892. .name = "memsw.usage_in_bytes",
  4893. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4894. .read_u64 = mem_cgroup_read_u64,
  4895. },
  4896. {
  4897. .name = "memsw.max_usage_in_bytes",
  4898. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4899. .write = mem_cgroup_reset,
  4900. .read_u64 = mem_cgroup_read_u64,
  4901. },
  4902. {
  4903. .name = "memsw.limit_in_bytes",
  4904. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4905. .write = mem_cgroup_write,
  4906. .read_u64 = mem_cgroup_read_u64,
  4907. },
  4908. {
  4909. .name = "memsw.failcnt",
  4910. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4911. .write = mem_cgroup_reset,
  4912. .read_u64 = mem_cgroup_read_u64,
  4913. },
  4914. { }, /* terminate */
  4915. };
  4916. static int __init mem_cgroup_swap_init(void)
  4917. {
  4918. if (!mem_cgroup_disabled() && really_do_swap_account) {
  4919. do_swap_account = 1;
  4920. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
  4921. memsw_cgroup_files));
  4922. }
  4923. return 0;
  4924. }
  4925. subsys_initcall(mem_cgroup_swap_init);
  4926. #endif /* CONFIG_MEMCG_SWAP */