memcontrol.c 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000
  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. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. */
  23. #include <linux/res_counter.h>
  24. #include <linux/memcontrol.h>
  25. #include <linux/cgroup.h>
  26. #include <linux/mm.h>
  27. #include <linux/hugetlb.h>
  28. #include <linux/pagemap.h>
  29. #include <linux/smp.h>
  30. #include <linux/page-flags.h>
  31. #include <linux/backing-dev.h>
  32. #include <linux/bit_spinlock.h>
  33. #include <linux/rcupdate.h>
  34. #include <linux/limits.h>
  35. #include <linux/mutex.h>
  36. #include <linux/rbtree.h>
  37. #include <linux/slab.h>
  38. #include <linux/swap.h>
  39. #include <linux/swapops.h>
  40. #include <linux/spinlock.h>
  41. #include <linux/eventfd.h>
  42. #include <linux/sort.h>
  43. #include <linux/fs.h>
  44. #include <linux/seq_file.h>
  45. #include <linux/vmalloc.h>
  46. #include <linux/mm_inline.h>
  47. #include <linux/page_cgroup.h>
  48. #include <linux/cpu.h>
  49. #include <linux/oom.h>
  50. #include "internal.h"
  51. #include <asm/uaccess.h>
  52. #include <trace/events/vmscan.h>
  53. struct cgroup_subsys mem_cgroup_subsys __read_mostly;
  54. #define MEM_CGROUP_RECLAIM_RETRIES 5
  55. struct mem_cgroup *root_mem_cgroup __read_mostly;
  56. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  57. /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
  58. int do_swap_account __read_mostly;
  59. /* for remember boot option*/
  60. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
  61. static int really_do_swap_account __initdata = 1;
  62. #else
  63. static int really_do_swap_account __initdata = 0;
  64. #endif
  65. #else
  66. #define do_swap_account (0)
  67. #endif
  68. /*
  69. * Per memcg event counter is incremented at every pagein/pageout. This counter
  70. * is used for trigger some periodic events. This is straightforward and better
  71. * than using jiffies etc. to handle periodic memcg event.
  72. *
  73. * These values will be used as !((event) & ((1 <<(thresh)) - 1))
  74. */
  75. #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
  76. #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
  77. /*
  78. * Statistics for memory cgroup.
  79. */
  80. enum mem_cgroup_stat_index {
  81. /*
  82. * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
  83. */
  84. MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
  85. MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
  86. MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
  87. MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
  88. MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
  89. MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
  90. MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
  91. /* incremented at every pagein/pageout */
  92. MEM_CGROUP_EVENTS = MEM_CGROUP_STAT_DATA,
  93. MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
  94. MEM_CGROUP_STAT_NSTATS,
  95. };
  96. struct mem_cgroup_stat_cpu {
  97. s64 count[MEM_CGROUP_STAT_NSTATS];
  98. };
  99. /*
  100. * per-zone information in memory controller.
  101. */
  102. struct mem_cgroup_per_zone {
  103. /*
  104. * spin_lock to protect the per cgroup LRU
  105. */
  106. struct list_head lists[NR_LRU_LISTS];
  107. unsigned long count[NR_LRU_LISTS];
  108. struct zone_reclaim_stat reclaim_stat;
  109. struct rb_node tree_node; /* RB tree node */
  110. unsigned long long usage_in_excess;/* Set to the value by which */
  111. /* the soft limit is exceeded*/
  112. bool on_tree;
  113. struct mem_cgroup *mem; /* Back pointer, we cannot */
  114. /* use container_of */
  115. };
  116. /* Macro for accessing counter */
  117. #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
  118. struct mem_cgroup_per_node {
  119. struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
  120. };
  121. struct mem_cgroup_lru_info {
  122. struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
  123. };
  124. /*
  125. * Cgroups above their limits are maintained in a RB-Tree, independent of
  126. * their hierarchy representation
  127. */
  128. struct mem_cgroup_tree_per_zone {
  129. struct rb_root rb_root;
  130. spinlock_t lock;
  131. };
  132. struct mem_cgroup_tree_per_node {
  133. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  134. };
  135. struct mem_cgroup_tree {
  136. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  137. };
  138. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  139. struct mem_cgroup_threshold {
  140. struct eventfd_ctx *eventfd;
  141. u64 threshold;
  142. };
  143. /* For threshold */
  144. struct mem_cgroup_threshold_ary {
  145. /* An array index points to threshold just below usage. */
  146. int current_threshold;
  147. /* Size of entries[] */
  148. unsigned int size;
  149. /* Array of thresholds */
  150. struct mem_cgroup_threshold entries[0];
  151. };
  152. struct mem_cgroup_thresholds {
  153. /* Primary thresholds array */
  154. struct mem_cgroup_threshold_ary *primary;
  155. /*
  156. * Spare threshold array.
  157. * This is needed to make mem_cgroup_unregister_event() "never fail".
  158. * It must be able to store at least primary->size - 1 entries.
  159. */
  160. struct mem_cgroup_threshold_ary *spare;
  161. };
  162. /* for OOM */
  163. struct mem_cgroup_eventfd_list {
  164. struct list_head list;
  165. struct eventfd_ctx *eventfd;
  166. };
  167. static void mem_cgroup_threshold(struct mem_cgroup *mem);
  168. static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
  169. /*
  170. * The memory controller data structure. The memory controller controls both
  171. * page cache and RSS per cgroup. We would eventually like to provide
  172. * statistics based on the statistics developed by Rik Van Riel for clock-pro,
  173. * to help the administrator determine what knobs to tune.
  174. *
  175. * TODO: Add a water mark for the memory controller. Reclaim will begin when
  176. * we hit the water mark. May be even add a low water mark, such that
  177. * no reclaim occurs from a cgroup at it's low water mark, this is
  178. * a feature that will be implemented much later in the future.
  179. */
  180. struct mem_cgroup {
  181. struct cgroup_subsys_state css;
  182. /*
  183. * the counter to account for memory usage
  184. */
  185. struct res_counter res;
  186. /*
  187. * the counter to account for mem+swap usage.
  188. */
  189. struct res_counter memsw;
  190. /*
  191. * Per cgroup active and inactive list, similar to the
  192. * per zone LRU lists.
  193. */
  194. struct mem_cgroup_lru_info info;
  195. /*
  196. protect against reclaim related member.
  197. */
  198. spinlock_t reclaim_param_lock;
  199. /*
  200. * While reclaiming in a hierarchy, we cache the last child we
  201. * reclaimed from.
  202. */
  203. int last_scanned_child;
  204. /*
  205. * Should the accounting and control be hierarchical, per subtree?
  206. */
  207. bool use_hierarchy;
  208. atomic_t oom_lock;
  209. atomic_t refcnt;
  210. unsigned int swappiness;
  211. /* OOM-Killer disable */
  212. int oom_kill_disable;
  213. /* set when res.limit == memsw.limit */
  214. bool memsw_is_minimum;
  215. /* protect arrays of thresholds */
  216. struct mutex thresholds_lock;
  217. /* thresholds for memory usage. RCU-protected */
  218. struct mem_cgroup_thresholds thresholds;
  219. /* thresholds for mem+swap usage. RCU-protected */
  220. struct mem_cgroup_thresholds memsw_thresholds;
  221. /* For oom notifier event fd */
  222. struct list_head oom_notify;
  223. /*
  224. * Should we move charges of a task when a task is moved into this
  225. * mem_cgroup ? And what type of charges should we move ?
  226. */
  227. unsigned long move_charge_at_immigrate;
  228. /*
  229. * percpu counter.
  230. */
  231. struct mem_cgroup_stat_cpu *stat;
  232. /*
  233. * used when a cpu is offlined or other synchronizations
  234. * See mem_cgroup_read_stat().
  235. */
  236. struct mem_cgroup_stat_cpu nocpu_base;
  237. spinlock_t pcp_counter_lock;
  238. };
  239. /* Stuffs for move charges at task migration. */
  240. /*
  241. * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
  242. * left-shifted bitmap of these types.
  243. */
  244. enum move_type {
  245. MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
  246. MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
  247. NR_MOVE_TYPE,
  248. };
  249. /* "mc" and its members are protected by cgroup_mutex */
  250. static struct move_charge_struct {
  251. spinlock_t lock; /* for from, to */
  252. struct mem_cgroup *from;
  253. struct mem_cgroup *to;
  254. unsigned long precharge;
  255. unsigned long moved_charge;
  256. unsigned long moved_swap;
  257. struct task_struct *moving_task; /* a task moving charges */
  258. wait_queue_head_t waitq; /* a waitq for other context */
  259. } mc = {
  260. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  261. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  262. };
  263. static bool move_anon(void)
  264. {
  265. return test_bit(MOVE_CHARGE_TYPE_ANON,
  266. &mc.to->move_charge_at_immigrate);
  267. }
  268. static bool move_file(void)
  269. {
  270. return test_bit(MOVE_CHARGE_TYPE_FILE,
  271. &mc.to->move_charge_at_immigrate);
  272. }
  273. /*
  274. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  275. * limit reclaim to prevent infinite loops, if they ever occur.
  276. */
  277. #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
  278. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
  279. enum charge_type {
  280. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  281. MEM_CGROUP_CHARGE_TYPE_MAPPED,
  282. MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
  283. MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
  284. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  285. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  286. NR_CHARGE_TYPE,
  287. };
  288. /* only for here (for easy reading.) */
  289. #define PCGF_CACHE (1UL << PCG_CACHE)
  290. #define PCGF_USED (1UL << PCG_USED)
  291. #define PCGF_LOCK (1UL << PCG_LOCK)
  292. /* Not used, but added here for completeness */
  293. #define PCGF_ACCT (1UL << PCG_ACCT)
  294. /* for encoding cft->private value on file */
  295. #define _MEM (0)
  296. #define _MEMSWAP (1)
  297. #define _OOM_TYPE (2)
  298. #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
  299. #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
  300. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  301. /* Used for OOM nofiier */
  302. #define OOM_CONTROL (0)
  303. /*
  304. * Reclaim flags for mem_cgroup_hierarchical_reclaim
  305. */
  306. #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
  307. #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
  308. #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
  309. #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
  310. #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
  311. #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
  312. static void mem_cgroup_get(struct mem_cgroup *mem);
  313. static void mem_cgroup_put(struct mem_cgroup *mem);
  314. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
  315. static void drain_all_stock_async(void);
  316. static struct mem_cgroup_per_zone *
  317. mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
  318. {
  319. return &mem->info.nodeinfo[nid]->zoneinfo[zid];
  320. }
  321. struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
  322. {
  323. return &mem->css;
  324. }
  325. static struct mem_cgroup_per_zone *
  326. page_cgroup_zoneinfo(struct page_cgroup *pc)
  327. {
  328. struct mem_cgroup *mem = pc->mem_cgroup;
  329. int nid = page_cgroup_nid(pc);
  330. int zid = page_cgroup_zid(pc);
  331. if (!mem)
  332. return NULL;
  333. return mem_cgroup_zoneinfo(mem, nid, zid);
  334. }
  335. static struct mem_cgroup_tree_per_zone *
  336. soft_limit_tree_node_zone(int nid, int zid)
  337. {
  338. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  339. }
  340. static struct mem_cgroup_tree_per_zone *
  341. soft_limit_tree_from_page(struct page *page)
  342. {
  343. int nid = page_to_nid(page);
  344. int zid = page_zonenum(page);
  345. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  346. }
  347. static void
  348. __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
  349. struct mem_cgroup_per_zone *mz,
  350. struct mem_cgroup_tree_per_zone *mctz,
  351. unsigned long long new_usage_in_excess)
  352. {
  353. struct rb_node **p = &mctz->rb_root.rb_node;
  354. struct rb_node *parent = NULL;
  355. struct mem_cgroup_per_zone *mz_node;
  356. if (mz->on_tree)
  357. return;
  358. mz->usage_in_excess = new_usage_in_excess;
  359. if (!mz->usage_in_excess)
  360. return;
  361. while (*p) {
  362. parent = *p;
  363. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  364. tree_node);
  365. if (mz->usage_in_excess < mz_node->usage_in_excess)
  366. p = &(*p)->rb_left;
  367. /*
  368. * We can't avoid mem cgroups that are over their soft
  369. * limit by the same amount
  370. */
  371. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  372. p = &(*p)->rb_right;
  373. }
  374. rb_link_node(&mz->tree_node, parent, p);
  375. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  376. mz->on_tree = true;
  377. }
  378. static void
  379. __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
  380. struct mem_cgroup_per_zone *mz,
  381. struct mem_cgroup_tree_per_zone *mctz)
  382. {
  383. if (!mz->on_tree)
  384. return;
  385. rb_erase(&mz->tree_node, &mctz->rb_root);
  386. mz->on_tree = false;
  387. }
  388. static void
  389. mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
  390. struct mem_cgroup_per_zone *mz,
  391. struct mem_cgroup_tree_per_zone *mctz)
  392. {
  393. spin_lock(&mctz->lock);
  394. __mem_cgroup_remove_exceeded(mem, mz, mctz);
  395. spin_unlock(&mctz->lock);
  396. }
  397. static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
  398. {
  399. unsigned long long excess;
  400. struct mem_cgroup_per_zone *mz;
  401. struct mem_cgroup_tree_per_zone *mctz;
  402. int nid = page_to_nid(page);
  403. int zid = page_zonenum(page);
  404. mctz = soft_limit_tree_from_page(page);
  405. /*
  406. * Necessary to update all ancestors when hierarchy is used.
  407. * because their event counter is not touched.
  408. */
  409. for (; mem; mem = parent_mem_cgroup(mem)) {
  410. mz = mem_cgroup_zoneinfo(mem, nid, zid);
  411. excess = res_counter_soft_limit_excess(&mem->res);
  412. /*
  413. * We have to update the tree if mz is on RB-tree or
  414. * mem is over its softlimit.
  415. */
  416. if (excess || mz->on_tree) {
  417. spin_lock(&mctz->lock);
  418. /* if on-tree, remove it */
  419. if (mz->on_tree)
  420. __mem_cgroup_remove_exceeded(mem, mz, mctz);
  421. /*
  422. * Insert again. mz->usage_in_excess will be updated.
  423. * If excess is 0, no tree ops.
  424. */
  425. __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
  426. spin_unlock(&mctz->lock);
  427. }
  428. }
  429. }
  430. static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
  431. {
  432. int node, zone;
  433. struct mem_cgroup_per_zone *mz;
  434. struct mem_cgroup_tree_per_zone *mctz;
  435. for_each_node_state(node, N_POSSIBLE) {
  436. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  437. mz = mem_cgroup_zoneinfo(mem, node, zone);
  438. mctz = soft_limit_tree_node_zone(node, zone);
  439. mem_cgroup_remove_exceeded(mem, mz, mctz);
  440. }
  441. }
  442. }
  443. static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
  444. {
  445. return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
  446. }
  447. static struct mem_cgroup_per_zone *
  448. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  449. {
  450. struct rb_node *rightmost = NULL;
  451. struct mem_cgroup_per_zone *mz;
  452. retry:
  453. mz = NULL;
  454. rightmost = rb_last(&mctz->rb_root);
  455. if (!rightmost)
  456. goto done; /* Nothing to reclaim from */
  457. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  458. /*
  459. * Remove the node now but someone else can add it back,
  460. * we will to add it back at the end of reclaim to its correct
  461. * position in the tree.
  462. */
  463. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  464. if (!res_counter_soft_limit_excess(&mz->mem->res) ||
  465. !css_tryget(&mz->mem->css))
  466. goto retry;
  467. done:
  468. return mz;
  469. }
  470. static struct mem_cgroup_per_zone *
  471. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  472. {
  473. struct mem_cgroup_per_zone *mz;
  474. spin_lock(&mctz->lock);
  475. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  476. spin_unlock(&mctz->lock);
  477. return mz;
  478. }
  479. /*
  480. * Implementation Note: reading percpu statistics for memcg.
  481. *
  482. * Both of vmstat[] and percpu_counter has threshold and do periodic
  483. * synchronization to implement "quick" read. There are trade-off between
  484. * reading cost and precision of value. Then, we may have a chance to implement
  485. * a periodic synchronizion of counter in memcg's counter.
  486. *
  487. * But this _read() function is used for user interface now. The user accounts
  488. * memory usage by memory cgroup and he _always_ requires exact value because
  489. * he accounts memory. Even if we provide quick-and-fuzzy read, we always
  490. * have to visit all online cpus and make sum. So, for now, unnecessary
  491. * synchronization is not implemented. (just implemented for cpu hotplug)
  492. *
  493. * If there are kernel internal actions which can make use of some not-exact
  494. * value, and reading all cpu value can be performance bottleneck in some
  495. * common workload, threashold and synchonization as vmstat[] should be
  496. * implemented.
  497. */
  498. static s64 mem_cgroup_read_stat(struct mem_cgroup *mem,
  499. enum mem_cgroup_stat_index idx)
  500. {
  501. int cpu;
  502. s64 val = 0;
  503. get_online_cpus();
  504. for_each_online_cpu(cpu)
  505. val += per_cpu(mem->stat->count[idx], cpu);
  506. #ifdef CONFIG_HOTPLUG_CPU
  507. spin_lock(&mem->pcp_counter_lock);
  508. val += mem->nocpu_base.count[idx];
  509. spin_unlock(&mem->pcp_counter_lock);
  510. #endif
  511. put_online_cpus();
  512. return val;
  513. }
  514. static s64 mem_cgroup_local_usage(struct mem_cgroup *mem)
  515. {
  516. s64 ret;
  517. ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  518. ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  519. return ret;
  520. }
  521. static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
  522. bool charge)
  523. {
  524. int val = (charge) ? 1 : -1;
  525. this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
  526. }
  527. static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
  528. struct page_cgroup *pc,
  529. bool charge)
  530. {
  531. int val = (charge) ? 1 : -1;
  532. preempt_disable();
  533. if (PageCgroupCache(pc))
  534. __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], val);
  535. else
  536. __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], val);
  537. if (charge)
  538. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGIN_COUNT]);
  539. else
  540. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGOUT_COUNT]);
  541. __this_cpu_inc(mem->stat->count[MEM_CGROUP_EVENTS]);
  542. preempt_enable();
  543. }
  544. static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
  545. enum lru_list idx)
  546. {
  547. int nid, zid;
  548. struct mem_cgroup_per_zone *mz;
  549. u64 total = 0;
  550. for_each_online_node(nid)
  551. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  552. mz = mem_cgroup_zoneinfo(mem, nid, zid);
  553. total += MEM_CGROUP_ZSTAT(mz, idx);
  554. }
  555. return total;
  556. }
  557. static bool __memcg_event_check(struct mem_cgroup *mem, int event_mask_shift)
  558. {
  559. s64 val;
  560. val = this_cpu_read(mem->stat->count[MEM_CGROUP_EVENTS]);
  561. return !(val & ((1 << event_mask_shift) - 1));
  562. }
  563. /*
  564. * Check events in order.
  565. *
  566. */
  567. static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
  568. {
  569. /* threshold event is triggered in finer grain than soft limit */
  570. if (unlikely(__memcg_event_check(mem, THRESHOLDS_EVENTS_THRESH))) {
  571. mem_cgroup_threshold(mem);
  572. if (unlikely(__memcg_event_check(mem, SOFTLIMIT_EVENTS_THRESH)))
  573. mem_cgroup_update_tree(mem, page);
  574. }
  575. }
  576. static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
  577. {
  578. return container_of(cgroup_subsys_state(cont,
  579. mem_cgroup_subsys_id), struct mem_cgroup,
  580. css);
  581. }
  582. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  583. {
  584. /*
  585. * mm_update_next_owner() may clear mm->owner to NULL
  586. * if it races with swapoff, page migration, etc.
  587. * So this can be called with p == NULL.
  588. */
  589. if (unlikely(!p))
  590. return NULL;
  591. return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
  592. struct mem_cgroup, css);
  593. }
  594. static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
  595. {
  596. struct mem_cgroup *mem = NULL;
  597. if (!mm)
  598. return NULL;
  599. /*
  600. * Because we have no locks, mm->owner's may be being moved to other
  601. * cgroup. We use css_tryget() here even if this looks
  602. * pessimistic (rather than adding locks here).
  603. */
  604. rcu_read_lock();
  605. do {
  606. mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
  607. if (unlikely(!mem))
  608. break;
  609. } while (!css_tryget(&mem->css));
  610. rcu_read_unlock();
  611. return mem;
  612. }
  613. /* The caller has to guarantee "mem" exists before calling this */
  614. static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
  615. {
  616. struct cgroup_subsys_state *css;
  617. int found;
  618. if (!mem) /* ROOT cgroup has the smallest ID */
  619. return root_mem_cgroup; /*css_put/get against root is ignored*/
  620. if (!mem->use_hierarchy) {
  621. if (css_tryget(&mem->css))
  622. return mem;
  623. return NULL;
  624. }
  625. rcu_read_lock();
  626. /*
  627. * searching a memory cgroup which has the smallest ID under given
  628. * ROOT cgroup. (ID >= 1)
  629. */
  630. css = css_get_next(&mem_cgroup_subsys, 1, &mem->css, &found);
  631. if (css && css_tryget(css))
  632. mem = container_of(css, struct mem_cgroup, css);
  633. else
  634. mem = NULL;
  635. rcu_read_unlock();
  636. return mem;
  637. }
  638. static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
  639. struct mem_cgroup *root,
  640. bool cond)
  641. {
  642. int nextid = css_id(&iter->css) + 1;
  643. int found;
  644. int hierarchy_used;
  645. struct cgroup_subsys_state *css;
  646. hierarchy_used = iter->use_hierarchy;
  647. css_put(&iter->css);
  648. /* If no ROOT, walk all, ignore hierarchy */
  649. if (!cond || (root && !hierarchy_used))
  650. return NULL;
  651. if (!root)
  652. root = root_mem_cgroup;
  653. do {
  654. iter = NULL;
  655. rcu_read_lock();
  656. css = css_get_next(&mem_cgroup_subsys, nextid,
  657. &root->css, &found);
  658. if (css && css_tryget(css))
  659. iter = container_of(css, struct mem_cgroup, css);
  660. rcu_read_unlock();
  661. /* If css is NULL, no more cgroups will be found */
  662. nextid = found + 1;
  663. } while (css && !iter);
  664. return iter;
  665. }
  666. /*
  667. * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
  668. * be careful that "break" loop is not allowed. We have reference count.
  669. * Instead of that modify "cond" to be false and "continue" to exit the loop.
  670. */
  671. #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
  672. for (iter = mem_cgroup_start_loop(root);\
  673. iter != NULL;\
  674. iter = mem_cgroup_get_next(iter, root, cond))
  675. #define for_each_mem_cgroup_tree(iter, root) \
  676. for_each_mem_cgroup_tree_cond(iter, root, true)
  677. #define for_each_mem_cgroup_all(iter) \
  678. for_each_mem_cgroup_tree_cond(iter, NULL, true)
  679. static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
  680. {
  681. return (mem == root_mem_cgroup);
  682. }
  683. /*
  684. * Following LRU functions are allowed to be used without PCG_LOCK.
  685. * Operations are called by routine of global LRU independently from memcg.
  686. * What we have to take care of here is validness of pc->mem_cgroup.
  687. *
  688. * Changes to pc->mem_cgroup happens when
  689. * 1. charge
  690. * 2. moving account
  691. * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
  692. * It is added to LRU before charge.
  693. * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
  694. * When moving account, the page is not on LRU. It's isolated.
  695. */
  696. void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
  697. {
  698. struct page_cgroup *pc;
  699. struct mem_cgroup_per_zone *mz;
  700. if (mem_cgroup_disabled())
  701. return;
  702. pc = lookup_page_cgroup(page);
  703. /* can happen while we handle swapcache. */
  704. if (!TestClearPageCgroupAcctLRU(pc))
  705. return;
  706. VM_BUG_ON(!pc->mem_cgroup);
  707. /*
  708. * We don't check PCG_USED bit. It's cleared when the "page" is finally
  709. * removed from global LRU.
  710. */
  711. mz = page_cgroup_zoneinfo(pc);
  712. MEM_CGROUP_ZSTAT(mz, lru) -= 1;
  713. if (mem_cgroup_is_root(pc->mem_cgroup))
  714. return;
  715. VM_BUG_ON(list_empty(&pc->lru));
  716. list_del_init(&pc->lru);
  717. }
  718. void mem_cgroup_del_lru(struct page *page)
  719. {
  720. mem_cgroup_del_lru_list(page, page_lru(page));
  721. }
  722. void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
  723. {
  724. struct mem_cgroup_per_zone *mz;
  725. struct page_cgroup *pc;
  726. if (mem_cgroup_disabled())
  727. return;
  728. pc = lookup_page_cgroup(page);
  729. /*
  730. * Used bit is set without atomic ops but after smp_wmb().
  731. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  732. */
  733. smp_rmb();
  734. /* unused or root page is not rotated. */
  735. if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
  736. return;
  737. mz = page_cgroup_zoneinfo(pc);
  738. list_move(&pc->lru, &mz->lists[lru]);
  739. }
  740. void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
  741. {
  742. struct page_cgroup *pc;
  743. struct mem_cgroup_per_zone *mz;
  744. if (mem_cgroup_disabled())
  745. return;
  746. pc = lookup_page_cgroup(page);
  747. VM_BUG_ON(PageCgroupAcctLRU(pc));
  748. /*
  749. * Used bit is set without atomic ops but after smp_wmb().
  750. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  751. */
  752. smp_rmb();
  753. if (!PageCgroupUsed(pc))
  754. return;
  755. mz = page_cgroup_zoneinfo(pc);
  756. MEM_CGROUP_ZSTAT(mz, lru) += 1;
  757. SetPageCgroupAcctLRU(pc);
  758. if (mem_cgroup_is_root(pc->mem_cgroup))
  759. return;
  760. list_add(&pc->lru, &mz->lists[lru]);
  761. }
  762. /*
  763. * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
  764. * lru because the page may.be reused after it's fully uncharged (because of
  765. * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
  766. * it again. This function is only used to charge SwapCache. It's done under
  767. * lock_page and expected that zone->lru_lock is never held.
  768. */
  769. static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
  770. {
  771. unsigned long flags;
  772. struct zone *zone = page_zone(page);
  773. struct page_cgroup *pc = lookup_page_cgroup(page);
  774. spin_lock_irqsave(&zone->lru_lock, flags);
  775. /*
  776. * Forget old LRU when this page_cgroup is *not* used. This Used bit
  777. * is guarded by lock_page() because the page is SwapCache.
  778. */
  779. if (!PageCgroupUsed(pc))
  780. mem_cgroup_del_lru_list(page, page_lru(page));
  781. spin_unlock_irqrestore(&zone->lru_lock, flags);
  782. }
  783. static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
  784. {
  785. unsigned long flags;
  786. struct zone *zone = page_zone(page);
  787. struct page_cgroup *pc = lookup_page_cgroup(page);
  788. spin_lock_irqsave(&zone->lru_lock, flags);
  789. /* link when the page is linked to LRU but page_cgroup isn't */
  790. if (PageLRU(page) && !PageCgroupAcctLRU(pc))
  791. mem_cgroup_add_lru_list(page, page_lru(page));
  792. spin_unlock_irqrestore(&zone->lru_lock, flags);
  793. }
  794. void mem_cgroup_move_lists(struct page *page,
  795. enum lru_list from, enum lru_list to)
  796. {
  797. if (mem_cgroup_disabled())
  798. return;
  799. mem_cgroup_del_lru_list(page, from);
  800. mem_cgroup_add_lru_list(page, to);
  801. }
  802. int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
  803. {
  804. int ret;
  805. struct mem_cgroup *curr = NULL;
  806. struct task_struct *p;
  807. p = find_lock_task_mm(task);
  808. if (!p)
  809. return 0;
  810. curr = try_get_mem_cgroup_from_mm(p->mm);
  811. task_unlock(p);
  812. if (!curr)
  813. return 0;
  814. /*
  815. * We should check use_hierarchy of "mem" not "curr". Because checking
  816. * use_hierarchy of "curr" here make this function true if hierarchy is
  817. * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
  818. * hierarchy(even if use_hierarchy is disabled in "mem").
  819. */
  820. if (mem->use_hierarchy)
  821. ret = css_is_ancestor(&curr->css, &mem->css);
  822. else
  823. ret = (curr == mem);
  824. css_put(&curr->css);
  825. return ret;
  826. }
  827. static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
  828. {
  829. unsigned long active;
  830. unsigned long inactive;
  831. unsigned long gb;
  832. unsigned long inactive_ratio;
  833. inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
  834. active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
  835. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  836. if (gb)
  837. inactive_ratio = int_sqrt(10 * gb);
  838. else
  839. inactive_ratio = 1;
  840. if (present_pages) {
  841. present_pages[0] = inactive;
  842. present_pages[1] = active;
  843. }
  844. return inactive_ratio;
  845. }
  846. int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
  847. {
  848. unsigned long active;
  849. unsigned long inactive;
  850. unsigned long present_pages[2];
  851. unsigned long inactive_ratio;
  852. inactive_ratio = calc_inactive_ratio(memcg, present_pages);
  853. inactive = present_pages[0];
  854. active = present_pages[1];
  855. if (inactive * inactive_ratio < active)
  856. return 1;
  857. return 0;
  858. }
  859. int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
  860. {
  861. unsigned long active;
  862. unsigned long inactive;
  863. inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
  864. active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
  865. return (active > inactive);
  866. }
  867. unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
  868. struct zone *zone,
  869. enum lru_list lru)
  870. {
  871. int nid = zone_to_nid(zone);
  872. int zid = zone_idx(zone);
  873. struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  874. return MEM_CGROUP_ZSTAT(mz, lru);
  875. }
  876. struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
  877. struct zone *zone)
  878. {
  879. int nid = zone_to_nid(zone);
  880. int zid = zone_idx(zone);
  881. struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  882. return &mz->reclaim_stat;
  883. }
  884. struct zone_reclaim_stat *
  885. mem_cgroup_get_reclaim_stat_from_page(struct page *page)
  886. {
  887. struct page_cgroup *pc;
  888. struct mem_cgroup_per_zone *mz;
  889. if (mem_cgroup_disabled())
  890. return NULL;
  891. pc = lookup_page_cgroup(page);
  892. /*
  893. * Used bit is set without atomic ops but after smp_wmb().
  894. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  895. */
  896. smp_rmb();
  897. if (!PageCgroupUsed(pc))
  898. return NULL;
  899. mz = page_cgroup_zoneinfo(pc);
  900. if (!mz)
  901. return NULL;
  902. return &mz->reclaim_stat;
  903. }
  904. unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
  905. struct list_head *dst,
  906. unsigned long *scanned, int order,
  907. int mode, struct zone *z,
  908. struct mem_cgroup *mem_cont,
  909. int active, int file)
  910. {
  911. unsigned long nr_taken = 0;
  912. struct page *page;
  913. unsigned long scan;
  914. LIST_HEAD(pc_list);
  915. struct list_head *src;
  916. struct page_cgroup *pc, *tmp;
  917. int nid = zone_to_nid(z);
  918. int zid = zone_idx(z);
  919. struct mem_cgroup_per_zone *mz;
  920. int lru = LRU_FILE * file + active;
  921. int ret;
  922. BUG_ON(!mem_cont);
  923. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  924. src = &mz->lists[lru];
  925. scan = 0;
  926. list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
  927. if (scan >= nr_to_scan)
  928. break;
  929. page = pc->page;
  930. if (unlikely(!PageCgroupUsed(pc)))
  931. continue;
  932. if (unlikely(!PageLRU(page)))
  933. continue;
  934. scan++;
  935. ret = __isolate_lru_page(page, mode, file);
  936. switch (ret) {
  937. case 0:
  938. list_move(&page->lru, dst);
  939. mem_cgroup_del_lru(page);
  940. nr_taken += hpage_nr_pages(page);
  941. break;
  942. case -EBUSY:
  943. /* we don't affect global LRU but rotate in our LRU */
  944. mem_cgroup_rotate_lru_list(page, page_lru(page));
  945. break;
  946. default:
  947. break;
  948. }
  949. }
  950. *scanned = scan;
  951. trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
  952. 0, 0, 0, mode);
  953. return nr_taken;
  954. }
  955. #define mem_cgroup_from_res_counter(counter, member) \
  956. container_of(counter, struct mem_cgroup, member)
  957. static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
  958. {
  959. if (do_swap_account) {
  960. if (res_counter_check_under_limit(&mem->res) &&
  961. res_counter_check_under_limit(&mem->memsw))
  962. return true;
  963. } else
  964. if (res_counter_check_under_limit(&mem->res))
  965. return true;
  966. return false;
  967. }
  968. static unsigned int get_swappiness(struct mem_cgroup *memcg)
  969. {
  970. struct cgroup *cgrp = memcg->css.cgroup;
  971. unsigned int swappiness;
  972. /* root ? */
  973. if (cgrp->parent == NULL)
  974. return vm_swappiness;
  975. spin_lock(&memcg->reclaim_param_lock);
  976. swappiness = memcg->swappiness;
  977. spin_unlock(&memcg->reclaim_param_lock);
  978. return swappiness;
  979. }
  980. static void mem_cgroup_start_move(struct mem_cgroup *mem)
  981. {
  982. int cpu;
  983. get_online_cpus();
  984. spin_lock(&mem->pcp_counter_lock);
  985. for_each_online_cpu(cpu)
  986. per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
  987. mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
  988. spin_unlock(&mem->pcp_counter_lock);
  989. put_online_cpus();
  990. synchronize_rcu();
  991. }
  992. static void mem_cgroup_end_move(struct mem_cgroup *mem)
  993. {
  994. int cpu;
  995. if (!mem)
  996. return;
  997. get_online_cpus();
  998. spin_lock(&mem->pcp_counter_lock);
  999. for_each_online_cpu(cpu)
  1000. per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
  1001. mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
  1002. spin_unlock(&mem->pcp_counter_lock);
  1003. put_online_cpus();
  1004. }
  1005. /*
  1006. * 2 routines for checking "mem" is under move_account() or not.
  1007. *
  1008. * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
  1009. * for avoiding race in accounting. If true,
  1010. * pc->mem_cgroup may be overwritten.
  1011. *
  1012. * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
  1013. * under hierarchy of moving cgroups. This is for
  1014. * waiting at hith-memory prressure caused by "move".
  1015. */
  1016. static bool mem_cgroup_stealed(struct mem_cgroup *mem)
  1017. {
  1018. VM_BUG_ON(!rcu_read_lock_held());
  1019. return this_cpu_read(mem->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
  1020. }
  1021. static bool mem_cgroup_under_move(struct mem_cgroup *mem)
  1022. {
  1023. struct mem_cgroup *from;
  1024. struct mem_cgroup *to;
  1025. bool ret = false;
  1026. /*
  1027. * Unlike task_move routines, we access mc.to, mc.from not under
  1028. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1029. */
  1030. spin_lock(&mc.lock);
  1031. from = mc.from;
  1032. to = mc.to;
  1033. if (!from)
  1034. goto unlock;
  1035. if (from == mem || to == mem
  1036. || (mem->use_hierarchy && css_is_ancestor(&from->css, &mem->css))
  1037. || (mem->use_hierarchy && css_is_ancestor(&to->css, &mem->css)))
  1038. ret = true;
  1039. unlock:
  1040. spin_unlock(&mc.lock);
  1041. return ret;
  1042. }
  1043. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
  1044. {
  1045. if (mc.moving_task && current != mc.moving_task) {
  1046. if (mem_cgroup_under_move(mem)) {
  1047. DEFINE_WAIT(wait);
  1048. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1049. /* moving charge context might have finished. */
  1050. if (mc.moving_task)
  1051. schedule();
  1052. finish_wait(&mc.waitq, &wait);
  1053. return true;
  1054. }
  1055. }
  1056. return false;
  1057. }
  1058. /**
  1059. * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
  1060. * @memcg: The memory cgroup that went over limit
  1061. * @p: Task that is going to be killed
  1062. *
  1063. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1064. * enabled
  1065. */
  1066. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1067. {
  1068. struct cgroup *task_cgrp;
  1069. struct cgroup *mem_cgrp;
  1070. /*
  1071. * Need a buffer in BSS, can't rely on allocations. The code relies
  1072. * on the assumption that OOM is serialized for memory controller.
  1073. * If this assumption is broken, revisit this code.
  1074. */
  1075. static char memcg_name[PATH_MAX];
  1076. int ret;
  1077. if (!memcg || !p)
  1078. return;
  1079. rcu_read_lock();
  1080. mem_cgrp = memcg->css.cgroup;
  1081. task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
  1082. ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
  1083. if (ret < 0) {
  1084. /*
  1085. * Unfortunately, we are unable to convert to a useful name
  1086. * But we'll still print out the usage information
  1087. */
  1088. rcu_read_unlock();
  1089. goto done;
  1090. }
  1091. rcu_read_unlock();
  1092. printk(KERN_INFO "Task in %s killed", memcg_name);
  1093. rcu_read_lock();
  1094. ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
  1095. if (ret < 0) {
  1096. rcu_read_unlock();
  1097. goto done;
  1098. }
  1099. rcu_read_unlock();
  1100. /*
  1101. * Continues from above, so we don't need an KERN_ level
  1102. */
  1103. printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
  1104. done:
  1105. printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
  1106. res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
  1107. res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
  1108. res_counter_read_u64(&memcg->res, RES_FAILCNT));
  1109. printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
  1110. "failcnt %llu\n",
  1111. res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
  1112. res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
  1113. res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
  1114. }
  1115. /*
  1116. * This function returns the number of memcg under hierarchy tree. Returns
  1117. * 1(self count) if no children.
  1118. */
  1119. static int mem_cgroup_count_children(struct mem_cgroup *mem)
  1120. {
  1121. int num = 0;
  1122. struct mem_cgroup *iter;
  1123. for_each_mem_cgroup_tree(iter, mem)
  1124. num++;
  1125. return num;
  1126. }
  1127. /*
  1128. * Return the memory (and swap, if configured) limit for a memcg.
  1129. */
  1130. u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1131. {
  1132. u64 limit;
  1133. u64 memsw;
  1134. limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  1135. limit += total_swap_pages << PAGE_SHIFT;
  1136. memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  1137. /*
  1138. * If memsw is finite and limits the amount of swap space available
  1139. * to this memcg, return that limit.
  1140. */
  1141. return min(limit, memsw);
  1142. }
  1143. /*
  1144. * Visit the first child (need not be the first child as per the ordering
  1145. * of the cgroup list, since we track last_scanned_child) of @mem and use
  1146. * that to reclaim free pages from.
  1147. */
  1148. static struct mem_cgroup *
  1149. mem_cgroup_select_victim(struct mem_cgroup *root_mem)
  1150. {
  1151. struct mem_cgroup *ret = NULL;
  1152. struct cgroup_subsys_state *css;
  1153. int nextid, found;
  1154. if (!root_mem->use_hierarchy) {
  1155. css_get(&root_mem->css);
  1156. ret = root_mem;
  1157. }
  1158. while (!ret) {
  1159. rcu_read_lock();
  1160. nextid = root_mem->last_scanned_child + 1;
  1161. css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
  1162. &found);
  1163. if (css && css_tryget(css))
  1164. ret = container_of(css, struct mem_cgroup, css);
  1165. rcu_read_unlock();
  1166. /* Updates scanning parameter */
  1167. spin_lock(&root_mem->reclaim_param_lock);
  1168. if (!css) {
  1169. /* this means start scan from ID:1 */
  1170. root_mem->last_scanned_child = 0;
  1171. } else
  1172. root_mem->last_scanned_child = found;
  1173. spin_unlock(&root_mem->reclaim_param_lock);
  1174. }
  1175. return ret;
  1176. }
  1177. /*
  1178. * Scan the hierarchy if needed to reclaim memory. We remember the last child
  1179. * we reclaimed from, so that we don't end up penalizing one child extensively
  1180. * based on its position in the children list.
  1181. *
  1182. * root_mem is the original ancestor that we've been reclaim from.
  1183. *
  1184. * We give up and return to the caller when we visit root_mem twice.
  1185. * (other groups can be removed while we're walking....)
  1186. *
  1187. * If shrink==true, for avoiding to free too much, this returns immedieately.
  1188. */
  1189. static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
  1190. struct zone *zone,
  1191. gfp_t gfp_mask,
  1192. unsigned long reclaim_options)
  1193. {
  1194. struct mem_cgroup *victim;
  1195. int ret, total = 0;
  1196. int loop = 0;
  1197. bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
  1198. bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
  1199. bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
  1200. unsigned long excess = mem_cgroup_get_excess(root_mem);
  1201. /* If memsw_is_minimum==1, swap-out is of-no-use. */
  1202. if (root_mem->memsw_is_minimum)
  1203. noswap = true;
  1204. while (1) {
  1205. victim = mem_cgroup_select_victim(root_mem);
  1206. if (victim == root_mem) {
  1207. loop++;
  1208. if (loop >= 1)
  1209. drain_all_stock_async();
  1210. if (loop >= 2) {
  1211. /*
  1212. * If we have not been able to reclaim
  1213. * anything, it might because there are
  1214. * no reclaimable pages under this hierarchy
  1215. */
  1216. if (!check_soft || !total) {
  1217. css_put(&victim->css);
  1218. break;
  1219. }
  1220. /*
  1221. * We want to do more targetted reclaim.
  1222. * excess >> 2 is not to excessive so as to
  1223. * reclaim too much, nor too less that we keep
  1224. * coming back to reclaim from this cgroup
  1225. */
  1226. if (total >= (excess >> 2) ||
  1227. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
  1228. css_put(&victim->css);
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. if (!mem_cgroup_local_usage(victim)) {
  1234. /* this cgroup's local usage == 0 */
  1235. css_put(&victim->css);
  1236. continue;
  1237. }
  1238. /* we use swappiness of local cgroup */
  1239. if (check_soft)
  1240. ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
  1241. noswap, get_swappiness(victim), zone);
  1242. else
  1243. ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
  1244. noswap, get_swappiness(victim));
  1245. css_put(&victim->css);
  1246. /*
  1247. * At shrinking usage, we can't check we should stop here or
  1248. * reclaim more. It's depends on callers. last_scanned_child
  1249. * will work enough for keeping fairness under tree.
  1250. */
  1251. if (shrink)
  1252. return ret;
  1253. total += ret;
  1254. if (check_soft) {
  1255. if (res_counter_check_under_soft_limit(&root_mem->res))
  1256. return total;
  1257. } else if (mem_cgroup_check_under_limit(root_mem))
  1258. return 1 + total;
  1259. }
  1260. return total;
  1261. }
  1262. /*
  1263. * Check OOM-Killer is already running under our hierarchy.
  1264. * If someone is running, return false.
  1265. */
  1266. static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
  1267. {
  1268. int x, lock_count = 0;
  1269. struct mem_cgroup *iter;
  1270. for_each_mem_cgroup_tree(iter, mem) {
  1271. x = atomic_inc_return(&iter->oom_lock);
  1272. lock_count = max(x, lock_count);
  1273. }
  1274. if (lock_count == 1)
  1275. return true;
  1276. return false;
  1277. }
  1278. static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
  1279. {
  1280. struct mem_cgroup *iter;
  1281. /*
  1282. * When a new child is created while the hierarchy is under oom,
  1283. * mem_cgroup_oom_lock() may not be called. We have to use
  1284. * atomic_add_unless() here.
  1285. */
  1286. for_each_mem_cgroup_tree(iter, mem)
  1287. atomic_add_unless(&iter->oom_lock, -1, 0);
  1288. return 0;
  1289. }
  1290. static DEFINE_MUTEX(memcg_oom_mutex);
  1291. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1292. struct oom_wait_info {
  1293. struct mem_cgroup *mem;
  1294. wait_queue_t wait;
  1295. };
  1296. static int memcg_oom_wake_function(wait_queue_t *wait,
  1297. unsigned mode, int sync, void *arg)
  1298. {
  1299. struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
  1300. struct oom_wait_info *oom_wait_info;
  1301. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1302. if (oom_wait_info->mem == wake_mem)
  1303. goto wakeup;
  1304. /* if no hierarchy, no match */
  1305. if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
  1306. return 0;
  1307. /*
  1308. * Both of oom_wait_info->mem and wake_mem are stable under us.
  1309. * Then we can use css_is_ancestor without taking care of RCU.
  1310. */
  1311. if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
  1312. !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
  1313. return 0;
  1314. wakeup:
  1315. return autoremove_wake_function(wait, mode, sync, arg);
  1316. }
  1317. static void memcg_wakeup_oom(struct mem_cgroup *mem)
  1318. {
  1319. /* for filtering, pass "mem" as argument. */
  1320. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
  1321. }
  1322. static void memcg_oom_recover(struct mem_cgroup *mem)
  1323. {
  1324. if (mem && atomic_read(&mem->oom_lock))
  1325. memcg_wakeup_oom(mem);
  1326. }
  1327. /*
  1328. * try to call OOM killer. returns false if we should exit memory-reclaim loop.
  1329. */
  1330. bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
  1331. {
  1332. struct oom_wait_info owait;
  1333. bool locked, need_to_kill;
  1334. owait.mem = mem;
  1335. owait.wait.flags = 0;
  1336. owait.wait.func = memcg_oom_wake_function;
  1337. owait.wait.private = current;
  1338. INIT_LIST_HEAD(&owait.wait.task_list);
  1339. need_to_kill = true;
  1340. /* At first, try to OOM lock hierarchy under mem.*/
  1341. mutex_lock(&memcg_oom_mutex);
  1342. locked = mem_cgroup_oom_lock(mem);
  1343. /*
  1344. * Even if signal_pending(), we can't quit charge() loop without
  1345. * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
  1346. * under OOM is always welcomed, use TASK_KILLABLE here.
  1347. */
  1348. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1349. if (!locked || mem->oom_kill_disable)
  1350. need_to_kill = false;
  1351. if (locked)
  1352. mem_cgroup_oom_notify(mem);
  1353. mutex_unlock(&memcg_oom_mutex);
  1354. if (need_to_kill) {
  1355. finish_wait(&memcg_oom_waitq, &owait.wait);
  1356. mem_cgroup_out_of_memory(mem, mask);
  1357. } else {
  1358. schedule();
  1359. finish_wait(&memcg_oom_waitq, &owait.wait);
  1360. }
  1361. mutex_lock(&memcg_oom_mutex);
  1362. mem_cgroup_oom_unlock(mem);
  1363. memcg_wakeup_oom(mem);
  1364. mutex_unlock(&memcg_oom_mutex);
  1365. if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
  1366. return false;
  1367. /* Give chance to dying process */
  1368. schedule_timeout(1);
  1369. return true;
  1370. }
  1371. /*
  1372. * Currently used to update mapped file statistics, but the routine can be
  1373. * generalized to update other statistics as well.
  1374. *
  1375. * Notes: Race condition
  1376. *
  1377. * We usually use page_cgroup_lock() for accessing page_cgroup member but
  1378. * it tends to be costly. But considering some conditions, we doesn't need
  1379. * to do so _always_.
  1380. *
  1381. * Considering "charge", lock_page_cgroup() is not required because all
  1382. * file-stat operations happen after a page is attached to radix-tree. There
  1383. * are no race with "charge".
  1384. *
  1385. * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
  1386. * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
  1387. * if there are race with "uncharge". Statistics itself is properly handled
  1388. * by flags.
  1389. *
  1390. * Considering "move", this is an only case we see a race. To make the race
  1391. * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
  1392. * possibility of race condition. If there is, we take a lock.
  1393. */
  1394. void mem_cgroup_update_page_stat(struct page *page,
  1395. enum mem_cgroup_page_stat_item idx, int val)
  1396. {
  1397. struct mem_cgroup *mem;
  1398. struct page_cgroup *pc = lookup_page_cgroup(page);
  1399. bool need_unlock = false;
  1400. unsigned long uninitialized_var(flags);
  1401. if (unlikely(!pc))
  1402. return;
  1403. rcu_read_lock();
  1404. mem = pc->mem_cgroup;
  1405. if (unlikely(!mem || !PageCgroupUsed(pc)))
  1406. goto out;
  1407. /* pc->mem_cgroup is unstable ? */
  1408. if (unlikely(mem_cgroup_stealed(mem))) {
  1409. /* take a lock against to access pc->mem_cgroup */
  1410. move_lock_page_cgroup(pc, &flags);
  1411. need_unlock = true;
  1412. mem = pc->mem_cgroup;
  1413. if (!mem || !PageCgroupUsed(pc))
  1414. goto out;
  1415. }
  1416. switch (idx) {
  1417. case MEMCG_NR_FILE_MAPPED:
  1418. if (val > 0)
  1419. SetPageCgroupFileMapped(pc);
  1420. else if (!page_mapped(page))
  1421. ClearPageCgroupFileMapped(pc);
  1422. idx = MEM_CGROUP_STAT_FILE_MAPPED;
  1423. break;
  1424. default:
  1425. BUG();
  1426. }
  1427. this_cpu_add(mem->stat->count[idx], val);
  1428. out:
  1429. if (unlikely(need_unlock))
  1430. move_unlock_page_cgroup(pc, &flags);
  1431. rcu_read_unlock();
  1432. return;
  1433. }
  1434. EXPORT_SYMBOL(mem_cgroup_update_page_stat);
  1435. /*
  1436. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1437. * TODO: maybe necessary to use big numbers in big irons.
  1438. */
  1439. #define CHARGE_SIZE (32 * PAGE_SIZE)
  1440. struct memcg_stock_pcp {
  1441. struct mem_cgroup *cached; /* this never be root cgroup */
  1442. int charge;
  1443. struct work_struct work;
  1444. };
  1445. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1446. static atomic_t memcg_drain_count;
  1447. /*
  1448. * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
  1449. * from local stock and true is returned. If the stock is 0 or charges from a
  1450. * cgroup which is not current target, returns false. This stock will be
  1451. * refilled.
  1452. */
  1453. static bool consume_stock(struct mem_cgroup *mem)
  1454. {
  1455. struct memcg_stock_pcp *stock;
  1456. bool ret = true;
  1457. stock = &get_cpu_var(memcg_stock);
  1458. if (mem == stock->cached && stock->charge)
  1459. stock->charge -= PAGE_SIZE;
  1460. else /* need to call res_counter_charge */
  1461. ret = false;
  1462. put_cpu_var(memcg_stock);
  1463. return ret;
  1464. }
  1465. /*
  1466. * Returns stocks cached in percpu to res_counter and reset cached information.
  1467. */
  1468. static void drain_stock(struct memcg_stock_pcp *stock)
  1469. {
  1470. struct mem_cgroup *old = stock->cached;
  1471. if (stock->charge) {
  1472. res_counter_uncharge(&old->res, stock->charge);
  1473. if (do_swap_account)
  1474. res_counter_uncharge(&old->memsw, stock->charge);
  1475. }
  1476. stock->cached = NULL;
  1477. stock->charge = 0;
  1478. }
  1479. /*
  1480. * This must be called under preempt disabled or must be called by
  1481. * a thread which is pinned to local cpu.
  1482. */
  1483. static void drain_local_stock(struct work_struct *dummy)
  1484. {
  1485. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1486. drain_stock(stock);
  1487. }
  1488. /*
  1489. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1490. * This will be consumed by consume_stock() function, later.
  1491. */
  1492. static void refill_stock(struct mem_cgroup *mem, int val)
  1493. {
  1494. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1495. if (stock->cached != mem) { /* reset if necessary */
  1496. drain_stock(stock);
  1497. stock->cached = mem;
  1498. }
  1499. stock->charge += val;
  1500. put_cpu_var(memcg_stock);
  1501. }
  1502. /*
  1503. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1504. * and just put a work per cpu for draining localy on each cpu. Caller can
  1505. * expects some charges will be back to res_counter later but cannot wait for
  1506. * it.
  1507. */
  1508. static void drain_all_stock_async(void)
  1509. {
  1510. int cpu;
  1511. /* This function is for scheduling "drain" in asynchronous way.
  1512. * The result of "drain" is not directly handled by callers. Then,
  1513. * if someone is calling drain, we don't have to call drain more.
  1514. * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
  1515. * there is a race. We just do loose check here.
  1516. */
  1517. if (atomic_read(&memcg_drain_count))
  1518. return;
  1519. /* Notify other cpus that system-wide "drain" is running */
  1520. atomic_inc(&memcg_drain_count);
  1521. get_online_cpus();
  1522. for_each_online_cpu(cpu) {
  1523. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1524. schedule_work_on(cpu, &stock->work);
  1525. }
  1526. put_online_cpus();
  1527. atomic_dec(&memcg_drain_count);
  1528. /* We don't wait for flush_work */
  1529. }
  1530. /* This is a synchronous drain interface. */
  1531. static void drain_all_stock_sync(void)
  1532. {
  1533. /* called when force_empty is called */
  1534. atomic_inc(&memcg_drain_count);
  1535. schedule_on_each_cpu(drain_local_stock);
  1536. atomic_dec(&memcg_drain_count);
  1537. }
  1538. /*
  1539. * This function drains percpu counter value from DEAD cpu and
  1540. * move it to local cpu. Note that this function can be preempted.
  1541. */
  1542. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
  1543. {
  1544. int i;
  1545. spin_lock(&mem->pcp_counter_lock);
  1546. for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
  1547. s64 x = per_cpu(mem->stat->count[i], cpu);
  1548. per_cpu(mem->stat->count[i], cpu) = 0;
  1549. mem->nocpu_base.count[i] += x;
  1550. }
  1551. /* need to clear ON_MOVE value, works as a kind of lock. */
  1552. per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
  1553. spin_unlock(&mem->pcp_counter_lock);
  1554. }
  1555. static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
  1556. {
  1557. int idx = MEM_CGROUP_ON_MOVE;
  1558. spin_lock(&mem->pcp_counter_lock);
  1559. per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
  1560. spin_unlock(&mem->pcp_counter_lock);
  1561. }
  1562. static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1563. unsigned long action,
  1564. void *hcpu)
  1565. {
  1566. int cpu = (unsigned long)hcpu;
  1567. struct memcg_stock_pcp *stock;
  1568. struct mem_cgroup *iter;
  1569. if ((action == CPU_ONLINE)) {
  1570. for_each_mem_cgroup_all(iter)
  1571. synchronize_mem_cgroup_on_move(iter, cpu);
  1572. return NOTIFY_OK;
  1573. }
  1574. if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
  1575. return NOTIFY_OK;
  1576. for_each_mem_cgroup_all(iter)
  1577. mem_cgroup_drain_pcp_counter(iter, cpu);
  1578. stock = &per_cpu(memcg_stock, cpu);
  1579. drain_stock(stock);
  1580. return NOTIFY_OK;
  1581. }
  1582. /* See __mem_cgroup_try_charge() for details */
  1583. enum {
  1584. CHARGE_OK, /* success */
  1585. CHARGE_RETRY, /* need to retry but retry is not bad */
  1586. CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
  1587. CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
  1588. CHARGE_OOM_DIE, /* the current is killed because of OOM */
  1589. };
  1590. static int __mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
  1591. int csize, bool oom_check)
  1592. {
  1593. struct mem_cgroup *mem_over_limit;
  1594. struct res_counter *fail_res;
  1595. unsigned long flags = 0;
  1596. int ret;
  1597. ret = res_counter_charge(&mem->res, csize, &fail_res);
  1598. if (likely(!ret)) {
  1599. if (!do_swap_account)
  1600. return CHARGE_OK;
  1601. ret = res_counter_charge(&mem->memsw, csize, &fail_res);
  1602. if (likely(!ret))
  1603. return CHARGE_OK;
  1604. mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
  1605. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  1606. } else
  1607. mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
  1608. if (csize > PAGE_SIZE) /* change csize and retry */
  1609. return CHARGE_RETRY;
  1610. if (!(gfp_mask & __GFP_WAIT))
  1611. return CHARGE_WOULDBLOCK;
  1612. ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
  1613. gfp_mask, flags);
  1614. /*
  1615. * try_to_free_mem_cgroup_pages() might not give us a full
  1616. * picture of reclaim. Some pages are reclaimed and might be
  1617. * moved to swap cache or just unmapped from the cgroup.
  1618. * Check the limit again to see if the reclaim reduced the
  1619. * current usage of the cgroup before giving up
  1620. */
  1621. if (ret || mem_cgroup_check_under_limit(mem_over_limit))
  1622. return CHARGE_RETRY;
  1623. /*
  1624. * At task move, charge accounts can be doubly counted. So, it's
  1625. * better to wait until the end of task_move if something is going on.
  1626. */
  1627. if (mem_cgroup_wait_acct_move(mem_over_limit))
  1628. return CHARGE_RETRY;
  1629. /* If we don't need to call oom-killer at el, return immediately */
  1630. if (!oom_check)
  1631. return CHARGE_NOMEM;
  1632. /* check OOM */
  1633. if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
  1634. return CHARGE_OOM_DIE;
  1635. return CHARGE_RETRY;
  1636. }
  1637. /*
  1638. * Unlike exported interface, "oom" parameter is added. if oom==true,
  1639. * oom-killer can be invoked.
  1640. */
  1641. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  1642. gfp_t gfp_mask,
  1643. struct mem_cgroup **memcg, bool oom,
  1644. int page_size)
  1645. {
  1646. int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1647. struct mem_cgroup *mem = NULL;
  1648. int ret;
  1649. int csize = max(CHARGE_SIZE, (unsigned long) page_size);
  1650. /*
  1651. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  1652. * in system level. So, allow to go ahead dying process in addition to
  1653. * MEMDIE process.
  1654. */
  1655. if (unlikely(test_thread_flag(TIF_MEMDIE)
  1656. || fatal_signal_pending(current)))
  1657. goto bypass;
  1658. /*
  1659. * We always charge the cgroup the mm_struct belongs to.
  1660. * The mm_struct's mem_cgroup changes on task migration if the
  1661. * thread group leader migrates. It's possible that mm is not
  1662. * set, if so charge the init_mm (happens for pagecache usage).
  1663. */
  1664. if (!*memcg && !mm)
  1665. goto bypass;
  1666. again:
  1667. if (*memcg) { /* css should be a valid one */
  1668. mem = *memcg;
  1669. VM_BUG_ON(css_is_removed(&mem->css));
  1670. if (mem_cgroup_is_root(mem))
  1671. goto done;
  1672. if (page_size == PAGE_SIZE && consume_stock(mem))
  1673. goto done;
  1674. css_get(&mem->css);
  1675. } else {
  1676. struct task_struct *p;
  1677. rcu_read_lock();
  1678. p = rcu_dereference(mm->owner);
  1679. /*
  1680. * Because we don't have task_lock(), "p" can exit.
  1681. * In that case, "mem" can point to root or p can be NULL with
  1682. * race with swapoff. Then, we have small risk of mis-accouning.
  1683. * But such kind of mis-account by race always happens because
  1684. * we don't have cgroup_mutex(). It's overkill and we allo that
  1685. * small race, here.
  1686. * (*) swapoff at el will charge against mm-struct not against
  1687. * task-struct. So, mm->owner can be NULL.
  1688. */
  1689. mem = mem_cgroup_from_task(p);
  1690. if (!mem || mem_cgroup_is_root(mem)) {
  1691. rcu_read_unlock();
  1692. goto done;
  1693. }
  1694. if (page_size == PAGE_SIZE && consume_stock(mem)) {
  1695. /*
  1696. * It seems dagerous to access memcg without css_get().
  1697. * But considering how consume_stok works, it's not
  1698. * necessary. If consume_stock success, some charges
  1699. * from this memcg are cached on this cpu. So, we
  1700. * don't need to call css_get()/css_tryget() before
  1701. * calling consume_stock().
  1702. */
  1703. rcu_read_unlock();
  1704. goto done;
  1705. }
  1706. /* after here, we may be blocked. we need to get refcnt */
  1707. if (!css_tryget(&mem->css)) {
  1708. rcu_read_unlock();
  1709. goto again;
  1710. }
  1711. rcu_read_unlock();
  1712. }
  1713. do {
  1714. bool oom_check;
  1715. /* If killed, bypass charge */
  1716. if (fatal_signal_pending(current)) {
  1717. css_put(&mem->css);
  1718. goto bypass;
  1719. }
  1720. oom_check = false;
  1721. if (oom && !nr_oom_retries) {
  1722. oom_check = true;
  1723. nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1724. }
  1725. ret = __mem_cgroup_do_charge(mem, gfp_mask, csize, oom_check);
  1726. switch (ret) {
  1727. case CHARGE_OK:
  1728. break;
  1729. case CHARGE_RETRY: /* not in OOM situation but retry */
  1730. csize = page_size;
  1731. css_put(&mem->css);
  1732. mem = NULL;
  1733. goto again;
  1734. case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
  1735. css_put(&mem->css);
  1736. goto nomem;
  1737. case CHARGE_NOMEM: /* OOM routine works */
  1738. if (!oom) {
  1739. css_put(&mem->css);
  1740. goto nomem;
  1741. }
  1742. /* If oom, we never return -ENOMEM */
  1743. nr_oom_retries--;
  1744. break;
  1745. case CHARGE_OOM_DIE: /* Killed by OOM Killer */
  1746. css_put(&mem->css);
  1747. goto bypass;
  1748. }
  1749. } while (ret != CHARGE_OK);
  1750. if (csize > page_size)
  1751. refill_stock(mem, csize - page_size);
  1752. css_put(&mem->css);
  1753. done:
  1754. *memcg = mem;
  1755. return 0;
  1756. nomem:
  1757. *memcg = NULL;
  1758. return -ENOMEM;
  1759. bypass:
  1760. *memcg = NULL;
  1761. return 0;
  1762. }
  1763. /*
  1764. * Somemtimes we have to undo a charge we got by try_charge().
  1765. * This function is for that and do uncharge, put css's refcnt.
  1766. * gotten by try_charge().
  1767. */
  1768. static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  1769. unsigned long count)
  1770. {
  1771. if (!mem_cgroup_is_root(mem)) {
  1772. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  1773. if (do_swap_account)
  1774. res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
  1775. }
  1776. }
  1777. static void mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  1778. int page_size)
  1779. {
  1780. __mem_cgroup_cancel_charge(mem, page_size >> PAGE_SHIFT);
  1781. }
  1782. /*
  1783. * A helper function to get mem_cgroup from ID. must be called under
  1784. * rcu_read_lock(). The caller must check css_is_removed() or some if
  1785. * it's concern. (dropping refcnt from swap can be called against removed
  1786. * memcg.)
  1787. */
  1788. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  1789. {
  1790. struct cgroup_subsys_state *css;
  1791. /* ID 0 is unused ID */
  1792. if (!id)
  1793. return NULL;
  1794. css = css_lookup(&mem_cgroup_subsys, id);
  1795. if (!css)
  1796. return NULL;
  1797. return container_of(css, struct mem_cgroup, css);
  1798. }
  1799. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  1800. {
  1801. struct mem_cgroup *mem = NULL;
  1802. struct page_cgroup *pc;
  1803. unsigned short id;
  1804. swp_entry_t ent;
  1805. VM_BUG_ON(!PageLocked(page));
  1806. pc = lookup_page_cgroup(page);
  1807. lock_page_cgroup(pc);
  1808. if (PageCgroupUsed(pc)) {
  1809. mem = pc->mem_cgroup;
  1810. if (mem && !css_tryget(&mem->css))
  1811. mem = NULL;
  1812. } else if (PageSwapCache(page)) {
  1813. ent.val = page_private(page);
  1814. id = lookup_swap_cgroup(ent);
  1815. rcu_read_lock();
  1816. mem = mem_cgroup_lookup(id);
  1817. if (mem && !css_tryget(&mem->css))
  1818. mem = NULL;
  1819. rcu_read_unlock();
  1820. }
  1821. unlock_page_cgroup(pc);
  1822. return mem;
  1823. }
  1824. /*
  1825. * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
  1826. * USED state. If already USED, uncharge and return.
  1827. */
  1828. static void ____mem_cgroup_commit_charge(struct mem_cgroup *mem,
  1829. struct page_cgroup *pc,
  1830. enum charge_type ctype)
  1831. {
  1832. pc->mem_cgroup = mem;
  1833. /*
  1834. * We access a page_cgroup asynchronously without lock_page_cgroup().
  1835. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  1836. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  1837. * before USED bit, we need memory barrier here.
  1838. * See mem_cgroup_add_lru_list(), etc.
  1839. */
  1840. smp_wmb();
  1841. switch (ctype) {
  1842. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  1843. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  1844. SetPageCgroupCache(pc);
  1845. SetPageCgroupUsed(pc);
  1846. break;
  1847. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1848. ClearPageCgroupCache(pc);
  1849. SetPageCgroupUsed(pc);
  1850. break;
  1851. default:
  1852. break;
  1853. }
  1854. mem_cgroup_charge_statistics(mem, pc, true);
  1855. }
  1856. static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
  1857. struct page_cgroup *pc,
  1858. enum charge_type ctype,
  1859. int page_size)
  1860. {
  1861. int i;
  1862. int count = page_size >> PAGE_SHIFT;
  1863. /* try_charge() can return NULL to *memcg, taking care of it. */
  1864. if (!mem)
  1865. return;
  1866. lock_page_cgroup(pc);
  1867. if (unlikely(PageCgroupUsed(pc))) {
  1868. unlock_page_cgroup(pc);
  1869. mem_cgroup_cancel_charge(mem, page_size);
  1870. return;
  1871. }
  1872. /*
  1873. * we don't need page_cgroup_lock about tail pages, becase they are not
  1874. * accessed by any other context at this point.
  1875. */
  1876. for (i = 0; i < count; i++)
  1877. ____mem_cgroup_commit_charge(mem, pc + i, ctype);
  1878. unlock_page_cgroup(pc);
  1879. /*
  1880. * "charge_statistics" updated event counter. Then, check it.
  1881. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  1882. * if they exceeds softlimit.
  1883. */
  1884. memcg_check_events(mem, pc->page);
  1885. }
  1886. /**
  1887. * __mem_cgroup_move_account - move account of the page
  1888. * @pc: page_cgroup of the page.
  1889. * @from: mem_cgroup which the page is moved from.
  1890. * @to: mem_cgroup which the page is moved to. @from != @to.
  1891. * @uncharge: whether we should call uncharge and css_put against @from.
  1892. *
  1893. * The caller must confirm following.
  1894. * - page is not on LRU (isolate_page() is useful.)
  1895. * - the pc is locked, used, and ->mem_cgroup points to @from.
  1896. *
  1897. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  1898. * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
  1899. * true, this function does "uncharge" from old cgroup, but it doesn't if
  1900. * @uncharge is false, so a caller should do "uncharge".
  1901. */
  1902. static void __mem_cgroup_move_account(struct page_cgroup *pc,
  1903. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1904. {
  1905. VM_BUG_ON(from == to);
  1906. VM_BUG_ON(PageLRU(pc->page));
  1907. VM_BUG_ON(!page_is_cgroup_locked(pc));
  1908. VM_BUG_ON(!PageCgroupUsed(pc));
  1909. VM_BUG_ON(pc->mem_cgroup != from);
  1910. if (PageCgroupFileMapped(pc)) {
  1911. /* Update mapped_file data for mem_cgroup */
  1912. preempt_disable();
  1913. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1914. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1915. preempt_enable();
  1916. }
  1917. mem_cgroup_charge_statistics(from, pc, false);
  1918. if (uncharge)
  1919. /* This is not "cancel", but cancel_charge does all we need. */
  1920. mem_cgroup_cancel_charge(from, PAGE_SIZE);
  1921. /* caller should have done css_get */
  1922. pc->mem_cgroup = to;
  1923. mem_cgroup_charge_statistics(to, pc, true);
  1924. /*
  1925. * We charges against "to" which may not have any tasks. Then, "to"
  1926. * can be under rmdir(). But in current implementation, caller of
  1927. * this function is just force_empty() and move charge, so it's
  1928. * garanteed that "to" is never removed. So, we don't check rmdir
  1929. * status here.
  1930. */
  1931. }
  1932. /*
  1933. * check whether the @pc is valid for moving account and call
  1934. * __mem_cgroup_move_account()
  1935. */
  1936. static int mem_cgroup_move_account(struct page_cgroup *pc,
  1937. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1938. {
  1939. int ret = -EINVAL;
  1940. unsigned long flags;
  1941. lock_page_cgroup(pc);
  1942. if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
  1943. move_lock_page_cgroup(pc, &flags);
  1944. __mem_cgroup_move_account(pc, from, to, uncharge);
  1945. move_unlock_page_cgroup(pc, &flags);
  1946. ret = 0;
  1947. }
  1948. unlock_page_cgroup(pc);
  1949. /*
  1950. * check events
  1951. */
  1952. memcg_check_events(to, pc->page);
  1953. memcg_check_events(from, pc->page);
  1954. return ret;
  1955. }
  1956. /*
  1957. * move charges to its parent.
  1958. */
  1959. static int mem_cgroup_move_parent(struct page_cgroup *pc,
  1960. struct mem_cgroup *child,
  1961. gfp_t gfp_mask)
  1962. {
  1963. struct page *page = pc->page;
  1964. struct cgroup *cg = child->css.cgroup;
  1965. struct cgroup *pcg = cg->parent;
  1966. struct mem_cgroup *parent;
  1967. int ret;
  1968. /* Is ROOT ? */
  1969. if (!pcg)
  1970. return -EINVAL;
  1971. ret = -EBUSY;
  1972. if (!get_page_unless_zero(page))
  1973. goto out;
  1974. if (isolate_lru_page(page))
  1975. goto put;
  1976. parent = mem_cgroup_from_cont(pcg);
  1977. ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false,
  1978. PAGE_SIZE);
  1979. if (ret || !parent)
  1980. goto put_back;
  1981. ret = mem_cgroup_move_account(pc, child, parent, true);
  1982. if (ret)
  1983. mem_cgroup_cancel_charge(parent, PAGE_SIZE);
  1984. put_back:
  1985. putback_lru_page(page);
  1986. put:
  1987. put_page(page);
  1988. out:
  1989. return ret;
  1990. }
  1991. /*
  1992. * Charge the memory controller for page usage.
  1993. * Return
  1994. * 0 if the charge was successful
  1995. * < 0 if the cgroup is over its limit
  1996. */
  1997. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  1998. gfp_t gfp_mask, enum charge_type ctype)
  1999. {
  2000. struct mem_cgroup *mem = NULL;
  2001. struct page_cgroup *pc;
  2002. int ret;
  2003. int page_size = PAGE_SIZE;
  2004. if (PageTransHuge(page)) {
  2005. page_size <<= compound_order(page);
  2006. VM_BUG_ON(!PageTransHuge(page));
  2007. }
  2008. pc = lookup_page_cgroup(page);
  2009. /* can happen at boot */
  2010. if (unlikely(!pc))
  2011. return 0;
  2012. prefetchw(pc);
  2013. ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page_size);
  2014. if (ret || !mem)
  2015. return ret;
  2016. __mem_cgroup_commit_charge(mem, pc, ctype, page_size);
  2017. return 0;
  2018. }
  2019. int mem_cgroup_newpage_charge(struct page *page,
  2020. struct mm_struct *mm, gfp_t gfp_mask)
  2021. {
  2022. if (mem_cgroup_disabled())
  2023. return 0;
  2024. /*
  2025. * If already mapped, we don't have to account.
  2026. * If page cache, page->mapping has address_space.
  2027. * But page->mapping may have out-of-use anon_vma pointer,
  2028. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  2029. * is NULL.
  2030. */
  2031. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  2032. return 0;
  2033. if (unlikely(!mm))
  2034. mm = &init_mm;
  2035. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2036. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2037. }
  2038. static void
  2039. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2040. enum charge_type ctype);
  2041. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  2042. gfp_t gfp_mask)
  2043. {
  2044. int ret;
  2045. if (mem_cgroup_disabled())
  2046. return 0;
  2047. if (PageCompound(page))
  2048. return 0;
  2049. /*
  2050. * Corner case handling. This is called from add_to_page_cache()
  2051. * in usual. But some FS (shmem) precharges this page before calling it
  2052. * and call add_to_page_cache() with GFP_NOWAIT.
  2053. *
  2054. * For GFP_NOWAIT case, the page may be pre-charged before calling
  2055. * add_to_page_cache(). (See shmem.c) check it here and avoid to call
  2056. * charge twice. (It works but has to pay a bit larger cost.)
  2057. * And when the page is SwapCache, it should take swap information
  2058. * into account. This is under lock_page() now.
  2059. */
  2060. if (!(gfp_mask & __GFP_WAIT)) {
  2061. struct page_cgroup *pc;
  2062. pc = lookup_page_cgroup(page);
  2063. if (!pc)
  2064. return 0;
  2065. lock_page_cgroup(pc);
  2066. if (PageCgroupUsed(pc)) {
  2067. unlock_page_cgroup(pc);
  2068. return 0;
  2069. }
  2070. unlock_page_cgroup(pc);
  2071. }
  2072. if (unlikely(!mm))
  2073. mm = &init_mm;
  2074. if (page_is_file_cache(page))
  2075. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2076. MEM_CGROUP_CHARGE_TYPE_CACHE);
  2077. /* shmem */
  2078. if (PageSwapCache(page)) {
  2079. struct mem_cgroup *mem = NULL;
  2080. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2081. if (!ret)
  2082. __mem_cgroup_commit_charge_swapin(page, mem,
  2083. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2084. } else
  2085. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  2086. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2087. return ret;
  2088. }
  2089. /*
  2090. * While swap-in, try_charge -> commit or cancel, the page is locked.
  2091. * And when try_charge() successfully returns, one refcnt to memcg without
  2092. * struct page_cgroup is acquired. This refcnt will be consumed by
  2093. * "commit()" or removed by "cancel()"
  2094. */
  2095. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  2096. struct page *page,
  2097. gfp_t mask, struct mem_cgroup **ptr)
  2098. {
  2099. struct mem_cgroup *mem;
  2100. int ret;
  2101. if (mem_cgroup_disabled())
  2102. return 0;
  2103. if (!do_swap_account)
  2104. goto charge_cur_mm;
  2105. /*
  2106. * A racing thread's fault, or swapoff, may have already updated
  2107. * the pte, and even removed page from swap cache: in those cases
  2108. * do_swap_page()'s pte_same() test will fail; but there's also a
  2109. * KSM case which does need to charge the page.
  2110. */
  2111. if (!PageSwapCache(page))
  2112. goto charge_cur_mm;
  2113. mem = try_get_mem_cgroup_from_page(page);
  2114. if (!mem)
  2115. goto charge_cur_mm;
  2116. *ptr = mem;
  2117. ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, PAGE_SIZE);
  2118. css_put(&mem->css);
  2119. return ret;
  2120. charge_cur_mm:
  2121. if (unlikely(!mm))
  2122. mm = &init_mm;
  2123. return __mem_cgroup_try_charge(mm, mask, ptr, true, PAGE_SIZE);
  2124. }
  2125. static void
  2126. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2127. enum charge_type ctype)
  2128. {
  2129. struct page_cgroup *pc;
  2130. if (mem_cgroup_disabled())
  2131. return;
  2132. if (!ptr)
  2133. return;
  2134. cgroup_exclude_rmdir(&ptr->css);
  2135. pc = lookup_page_cgroup(page);
  2136. mem_cgroup_lru_del_before_commit_swapcache(page);
  2137. __mem_cgroup_commit_charge(ptr, pc, ctype, PAGE_SIZE);
  2138. mem_cgroup_lru_add_after_commit_swapcache(page);
  2139. /*
  2140. * Now swap is on-memory. This means this page may be
  2141. * counted both as mem and swap....double count.
  2142. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  2143. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  2144. * may call delete_from_swap_cache() before reach here.
  2145. */
  2146. if (do_swap_account && PageSwapCache(page)) {
  2147. swp_entry_t ent = {.val = page_private(page)};
  2148. unsigned short id;
  2149. struct mem_cgroup *memcg;
  2150. id = swap_cgroup_record(ent, 0);
  2151. rcu_read_lock();
  2152. memcg = mem_cgroup_lookup(id);
  2153. if (memcg) {
  2154. /*
  2155. * This recorded memcg can be obsolete one. So, avoid
  2156. * calling css_tryget
  2157. */
  2158. if (!mem_cgroup_is_root(memcg))
  2159. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2160. mem_cgroup_swap_statistics(memcg, false);
  2161. mem_cgroup_put(memcg);
  2162. }
  2163. rcu_read_unlock();
  2164. }
  2165. /*
  2166. * At swapin, we may charge account against cgroup which has no tasks.
  2167. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2168. * In that case, we need to call pre_destroy() again. check it here.
  2169. */
  2170. cgroup_release_and_wakeup_rmdir(&ptr->css);
  2171. }
  2172. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  2173. {
  2174. __mem_cgroup_commit_charge_swapin(page, ptr,
  2175. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2176. }
  2177. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  2178. {
  2179. if (mem_cgroup_disabled())
  2180. return;
  2181. if (!mem)
  2182. return;
  2183. mem_cgroup_cancel_charge(mem, PAGE_SIZE);
  2184. }
  2185. static void
  2186. __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype,
  2187. int page_size)
  2188. {
  2189. struct memcg_batch_info *batch = NULL;
  2190. bool uncharge_memsw = true;
  2191. /* If swapout, usage of swap doesn't decrease */
  2192. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2193. uncharge_memsw = false;
  2194. batch = &current->memcg_batch;
  2195. /*
  2196. * In usual, we do css_get() when we remember memcg pointer.
  2197. * But in this case, we keep res->usage until end of a series of
  2198. * uncharges. Then, it's ok to ignore memcg's refcnt.
  2199. */
  2200. if (!batch->memcg)
  2201. batch->memcg = mem;
  2202. /*
  2203. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  2204. * In those cases, all pages freed continously can be expected to be in
  2205. * the same cgroup and we have chance to coalesce uncharges.
  2206. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  2207. * because we want to do uncharge as soon as possible.
  2208. */
  2209. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  2210. goto direct_uncharge;
  2211. if (page_size != PAGE_SIZE)
  2212. goto direct_uncharge;
  2213. /*
  2214. * In typical case, batch->memcg == mem. This means we can
  2215. * merge a series of uncharges to an uncharge of res_counter.
  2216. * If not, we uncharge res_counter ony by one.
  2217. */
  2218. if (batch->memcg != mem)
  2219. goto direct_uncharge;
  2220. /* remember freed charge and uncharge it later */
  2221. batch->bytes += PAGE_SIZE;
  2222. if (uncharge_memsw)
  2223. batch->memsw_bytes += PAGE_SIZE;
  2224. return;
  2225. direct_uncharge:
  2226. res_counter_uncharge(&mem->res, page_size);
  2227. if (uncharge_memsw)
  2228. res_counter_uncharge(&mem->memsw, page_size);
  2229. if (unlikely(batch->memcg != mem))
  2230. memcg_oom_recover(mem);
  2231. return;
  2232. }
  2233. /*
  2234. * uncharge if !page_mapped(page)
  2235. */
  2236. static struct mem_cgroup *
  2237. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  2238. {
  2239. int i;
  2240. int count;
  2241. struct page_cgroup *pc;
  2242. struct mem_cgroup *mem = NULL;
  2243. int page_size = PAGE_SIZE;
  2244. if (mem_cgroup_disabled())
  2245. return NULL;
  2246. if (PageSwapCache(page))
  2247. return NULL;
  2248. if (PageTransHuge(page)) {
  2249. page_size <<= compound_order(page);
  2250. VM_BUG_ON(!PageTransHuge(page));
  2251. }
  2252. count = page_size >> PAGE_SHIFT;
  2253. /*
  2254. * Check if our page_cgroup is valid
  2255. */
  2256. pc = lookup_page_cgroup(page);
  2257. if (unlikely(!pc || !PageCgroupUsed(pc)))
  2258. return NULL;
  2259. lock_page_cgroup(pc);
  2260. mem = pc->mem_cgroup;
  2261. if (!PageCgroupUsed(pc))
  2262. goto unlock_out;
  2263. switch (ctype) {
  2264. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2265. case MEM_CGROUP_CHARGE_TYPE_DROP:
  2266. /* See mem_cgroup_prepare_migration() */
  2267. if (page_mapped(page) || PageCgroupMigration(pc))
  2268. goto unlock_out;
  2269. break;
  2270. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2271. if (!PageAnon(page)) { /* Shared memory */
  2272. if (page->mapping && !page_is_file_cache(page))
  2273. goto unlock_out;
  2274. } else if (page_mapped(page)) /* Anon */
  2275. goto unlock_out;
  2276. break;
  2277. default:
  2278. break;
  2279. }
  2280. for (i = 0; i < count; i++)
  2281. mem_cgroup_charge_statistics(mem, pc + i, false);
  2282. ClearPageCgroupUsed(pc);
  2283. /*
  2284. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2285. * freed from LRU. This is safe because uncharged page is expected not
  2286. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2287. * special functions.
  2288. */
  2289. unlock_page_cgroup(pc);
  2290. /*
  2291. * even after unlock, we have mem->res.usage here and this memcg
  2292. * will never be freed.
  2293. */
  2294. memcg_check_events(mem, page);
  2295. if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
  2296. mem_cgroup_swap_statistics(mem, true);
  2297. mem_cgroup_get(mem);
  2298. }
  2299. if (!mem_cgroup_is_root(mem))
  2300. __do_uncharge(mem, ctype, page_size);
  2301. return mem;
  2302. unlock_out:
  2303. unlock_page_cgroup(pc);
  2304. return NULL;
  2305. }
  2306. void mem_cgroup_uncharge_page(struct page *page)
  2307. {
  2308. /* early check. */
  2309. if (page_mapped(page))
  2310. return;
  2311. if (page->mapping && !PageAnon(page))
  2312. return;
  2313. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2314. }
  2315. void mem_cgroup_uncharge_cache_page(struct page *page)
  2316. {
  2317. VM_BUG_ON(page_mapped(page));
  2318. VM_BUG_ON(page->mapping);
  2319. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2320. }
  2321. /*
  2322. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2323. * In that cases, pages are freed continuously and we can expect pages
  2324. * are in the same memcg. All these calls itself limits the number of
  2325. * pages freed at once, then uncharge_start/end() is called properly.
  2326. * This may be called prural(2) times in a context,
  2327. */
  2328. void mem_cgroup_uncharge_start(void)
  2329. {
  2330. current->memcg_batch.do_batch++;
  2331. /* We can do nest. */
  2332. if (current->memcg_batch.do_batch == 1) {
  2333. current->memcg_batch.memcg = NULL;
  2334. current->memcg_batch.bytes = 0;
  2335. current->memcg_batch.memsw_bytes = 0;
  2336. }
  2337. }
  2338. void mem_cgroup_uncharge_end(void)
  2339. {
  2340. struct memcg_batch_info *batch = &current->memcg_batch;
  2341. if (!batch->do_batch)
  2342. return;
  2343. batch->do_batch--;
  2344. if (batch->do_batch) /* If stacked, do nothing. */
  2345. return;
  2346. if (!batch->memcg)
  2347. return;
  2348. /*
  2349. * This "batch->memcg" is valid without any css_get/put etc...
  2350. * bacause we hide charges behind us.
  2351. */
  2352. if (batch->bytes)
  2353. res_counter_uncharge(&batch->memcg->res, batch->bytes);
  2354. if (batch->memsw_bytes)
  2355. res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
  2356. memcg_oom_recover(batch->memcg);
  2357. /* forget this pointer (for sanity check) */
  2358. batch->memcg = NULL;
  2359. }
  2360. #ifdef CONFIG_SWAP
  2361. /*
  2362. * called after __delete_from_swap_cache() and drop "page" account.
  2363. * memcg information is recorded to swap_cgroup of "ent"
  2364. */
  2365. void
  2366. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2367. {
  2368. struct mem_cgroup *memcg;
  2369. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2370. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2371. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2372. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2373. /*
  2374. * record memcg information, if swapout && memcg != NULL,
  2375. * mem_cgroup_get() was called in uncharge().
  2376. */
  2377. if (do_swap_account && swapout && memcg)
  2378. swap_cgroup_record(ent, css_id(&memcg->css));
  2379. }
  2380. #endif
  2381. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2382. /*
  2383. * called from swap_entry_free(). remove record in swap_cgroup and
  2384. * uncharge "memsw" account.
  2385. */
  2386. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2387. {
  2388. struct mem_cgroup *memcg;
  2389. unsigned short id;
  2390. if (!do_swap_account)
  2391. return;
  2392. id = swap_cgroup_record(ent, 0);
  2393. rcu_read_lock();
  2394. memcg = mem_cgroup_lookup(id);
  2395. if (memcg) {
  2396. /*
  2397. * We uncharge this because swap is freed.
  2398. * This memcg can be obsolete one. We avoid calling css_tryget
  2399. */
  2400. if (!mem_cgroup_is_root(memcg))
  2401. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2402. mem_cgroup_swap_statistics(memcg, false);
  2403. mem_cgroup_put(memcg);
  2404. }
  2405. rcu_read_unlock();
  2406. }
  2407. /**
  2408. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2409. * @entry: swap entry to be moved
  2410. * @from: mem_cgroup which the entry is moved from
  2411. * @to: mem_cgroup which the entry is moved to
  2412. * @need_fixup: whether we should fixup res_counters and refcounts.
  2413. *
  2414. * It succeeds only when the swap_cgroup's record for this entry is the same
  2415. * as the mem_cgroup's id of @from.
  2416. *
  2417. * Returns 0 on success, -EINVAL on failure.
  2418. *
  2419. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2420. * both res and memsw, and called css_get().
  2421. */
  2422. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2423. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2424. {
  2425. unsigned short old_id, new_id;
  2426. old_id = css_id(&from->css);
  2427. new_id = css_id(&to->css);
  2428. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2429. mem_cgroup_swap_statistics(from, false);
  2430. mem_cgroup_swap_statistics(to, true);
  2431. /*
  2432. * This function is only called from task migration context now.
  2433. * It postpones res_counter and refcount handling till the end
  2434. * of task migration(mem_cgroup_clear_mc()) for performance
  2435. * improvement. But we cannot postpone mem_cgroup_get(to)
  2436. * because if the process that has been moved to @to does
  2437. * swap-in, the refcount of @to might be decreased to 0.
  2438. */
  2439. mem_cgroup_get(to);
  2440. if (need_fixup) {
  2441. if (!mem_cgroup_is_root(from))
  2442. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2443. mem_cgroup_put(from);
  2444. /*
  2445. * we charged both to->res and to->memsw, so we should
  2446. * uncharge to->res.
  2447. */
  2448. if (!mem_cgroup_is_root(to))
  2449. res_counter_uncharge(&to->res, PAGE_SIZE);
  2450. }
  2451. return 0;
  2452. }
  2453. return -EINVAL;
  2454. }
  2455. #else
  2456. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2457. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2458. {
  2459. return -EINVAL;
  2460. }
  2461. #endif
  2462. /*
  2463. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2464. * page belongs to.
  2465. */
  2466. int mem_cgroup_prepare_migration(struct page *page,
  2467. struct page *newpage, struct mem_cgroup **ptr)
  2468. {
  2469. struct page_cgroup *pc;
  2470. struct mem_cgroup *mem = NULL;
  2471. enum charge_type ctype;
  2472. int ret = 0;
  2473. VM_BUG_ON(PageTransHuge(page));
  2474. if (mem_cgroup_disabled())
  2475. return 0;
  2476. pc = lookup_page_cgroup(page);
  2477. lock_page_cgroup(pc);
  2478. if (PageCgroupUsed(pc)) {
  2479. mem = pc->mem_cgroup;
  2480. css_get(&mem->css);
  2481. /*
  2482. * At migrating an anonymous page, its mapcount goes down
  2483. * to 0 and uncharge() will be called. But, even if it's fully
  2484. * unmapped, migration may fail and this page has to be
  2485. * charged again. We set MIGRATION flag here and delay uncharge
  2486. * until end_migration() is called
  2487. *
  2488. * Corner Case Thinking
  2489. * A)
  2490. * When the old page was mapped as Anon and it's unmap-and-freed
  2491. * while migration was ongoing.
  2492. * If unmap finds the old page, uncharge() of it will be delayed
  2493. * until end_migration(). If unmap finds a new page, it's
  2494. * uncharged when it make mapcount to be 1->0. If unmap code
  2495. * finds swap_migration_entry, the new page will not be mapped
  2496. * and end_migration() will find it(mapcount==0).
  2497. *
  2498. * B)
  2499. * When the old page was mapped but migraion fails, the kernel
  2500. * remaps it. A charge for it is kept by MIGRATION flag even
  2501. * if mapcount goes down to 0. We can do remap successfully
  2502. * without charging it again.
  2503. *
  2504. * C)
  2505. * The "old" page is under lock_page() until the end of
  2506. * migration, so, the old page itself will not be swapped-out.
  2507. * If the new page is swapped out before end_migraton, our
  2508. * hook to usual swap-out path will catch the event.
  2509. */
  2510. if (PageAnon(page))
  2511. SetPageCgroupMigration(pc);
  2512. }
  2513. unlock_page_cgroup(pc);
  2514. /*
  2515. * If the page is not charged at this point,
  2516. * we return here.
  2517. */
  2518. if (!mem)
  2519. return 0;
  2520. *ptr = mem;
  2521. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false, PAGE_SIZE);
  2522. css_put(&mem->css);/* drop extra refcnt */
  2523. if (ret || *ptr == NULL) {
  2524. if (PageAnon(page)) {
  2525. lock_page_cgroup(pc);
  2526. ClearPageCgroupMigration(pc);
  2527. unlock_page_cgroup(pc);
  2528. /*
  2529. * The old page may be fully unmapped while we kept it.
  2530. */
  2531. mem_cgroup_uncharge_page(page);
  2532. }
  2533. return -ENOMEM;
  2534. }
  2535. /*
  2536. * We charge new page before it's used/mapped. So, even if unlock_page()
  2537. * is called before end_migration, we can catch all events on this new
  2538. * page. In the case new page is migrated but not remapped, new page's
  2539. * mapcount will be finally 0 and we call uncharge in end_migration().
  2540. */
  2541. pc = lookup_page_cgroup(newpage);
  2542. if (PageAnon(page))
  2543. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  2544. else if (page_is_file_cache(page))
  2545. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  2546. else
  2547. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  2548. __mem_cgroup_commit_charge(mem, pc, ctype, PAGE_SIZE);
  2549. return ret;
  2550. }
  2551. /* remove redundant charge if migration failed*/
  2552. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  2553. struct page *oldpage, struct page *newpage, bool migration_ok)
  2554. {
  2555. struct page *used, *unused;
  2556. struct page_cgroup *pc;
  2557. if (!mem)
  2558. return;
  2559. /* blocks rmdir() */
  2560. cgroup_exclude_rmdir(&mem->css);
  2561. if (!migration_ok) {
  2562. used = oldpage;
  2563. unused = newpage;
  2564. } else {
  2565. used = newpage;
  2566. unused = oldpage;
  2567. }
  2568. /*
  2569. * We disallowed uncharge of pages under migration because mapcount
  2570. * of the page goes down to zero, temporarly.
  2571. * Clear the flag and check the page should be charged.
  2572. */
  2573. pc = lookup_page_cgroup(oldpage);
  2574. lock_page_cgroup(pc);
  2575. ClearPageCgroupMigration(pc);
  2576. unlock_page_cgroup(pc);
  2577. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  2578. /*
  2579. * If a page is a file cache, radix-tree replacement is very atomic
  2580. * and we can skip this check. When it was an Anon page, its mapcount
  2581. * goes down to 0. But because we added MIGRATION flage, it's not
  2582. * uncharged yet. There are several case but page->mapcount check
  2583. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  2584. * check. (see prepare_charge() also)
  2585. */
  2586. if (PageAnon(used))
  2587. mem_cgroup_uncharge_page(used);
  2588. /*
  2589. * At migration, we may charge account against cgroup which has no
  2590. * tasks.
  2591. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2592. * In that case, we need to call pre_destroy() again. check it here.
  2593. */
  2594. cgroup_release_and_wakeup_rmdir(&mem->css);
  2595. }
  2596. /*
  2597. * A call to try to shrink memory usage on charge failure at shmem's swapin.
  2598. * Calling hierarchical_reclaim is not enough because we should update
  2599. * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
  2600. * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
  2601. * not from the memcg which this page would be charged to.
  2602. * try_charge_swapin does all of these works properly.
  2603. */
  2604. int mem_cgroup_shmem_charge_fallback(struct page *page,
  2605. struct mm_struct *mm,
  2606. gfp_t gfp_mask)
  2607. {
  2608. struct mem_cgroup *mem = NULL;
  2609. int ret;
  2610. if (mem_cgroup_disabled())
  2611. return 0;
  2612. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2613. if (!ret)
  2614. mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
  2615. return ret;
  2616. }
  2617. static DEFINE_MUTEX(set_limit_mutex);
  2618. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2619. unsigned long long val)
  2620. {
  2621. int retry_count;
  2622. u64 memswlimit, memlimit;
  2623. int ret = 0;
  2624. int children = mem_cgroup_count_children(memcg);
  2625. u64 curusage, oldusage;
  2626. int enlarge;
  2627. /*
  2628. * For keeping hierarchical_reclaim simple, how long we should retry
  2629. * is depends on callers. We set our retry-count to be function
  2630. * of # of children which we should visit in this loop.
  2631. */
  2632. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  2633. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2634. enlarge = 0;
  2635. while (retry_count) {
  2636. if (signal_pending(current)) {
  2637. ret = -EINTR;
  2638. break;
  2639. }
  2640. /*
  2641. * Rather than hide all in some function, I do this in
  2642. * open coded manner. You see what this really does.
  2643. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2644. */
  2645. mutex_lock(&set_limit_mutex);
  2646. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2647. if (memswlimit < val) {
  2648. ret = -EINVAL;
  2649. mutex_unlock(&set_limit_mutex);
  2650. break;
  2651. }
  2652. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2653. if (memlimit < val)
  2654. enlarge = 1;
  2655. ret = res_counter_set_limit(&memcg->res, val);
  2656. if (!ret) {
  2657. if (memswlimit == val)
  2658. memcg->memsw_is_minimum = true;
  2659. else
  2660. memcg->memsw_is_minimum = false;
  2661. }
  2662. mutex_unlock(&set_limit_mutex);
  2663. if (!ret)
  2664. break;
  2665. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2666. MEM_CGROUP_RECLAIM_SHRINK);
  2667. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2668. /* Usage is reduced ? */
  2669. if (curusage >= oldusage)
  2670. retry_count--;
  2671. else
  2672. oldusage = curusage;
  2673. }
  2674. if (!ret && enlarge)
  2675. memcg_oom_recover(memcg);
  2676. return ret;
  2677. }
  2678. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2679. unsigned long long val)
  2680. {
  2681. int retry_count;
  2682. u64 memlimit, memswlimit, oldusage, curusage;
  2683. int children = mem_cgroup_count_children(memcg);
  2684. int ret = -EBUSY;
  2685. int enlarge = 0;
  2686. /* see mem_cgroup_resize_res_limit */
  2687. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  2688. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2689. while (retry_count) {
  2690. if (signal_pending(current)) {
  2691. ret = -EINTR;
  2692. break;
  2693. }
  2694. /*
  2695. * Rather than hide all in some function, I do this in
  2696. * open coded manner. You see what this really does.
  2697. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2698. */
  2699. mutex_lock(&set_limit_mutex);
  2700. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2701. if (memlimit > val) {
  2702. ret = -EINVAL;
  2703. mutex_unlock(&set_limit_mutex);
  2704. break;
  2705. }
  2706. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2707. if (memswlimit < val)
  2708. enlarge = 1;
  2709. ret = res_counter_set_limit(&memcg->memsw, val);
  2710. if (!ret) {
  2711. if (memlimit == val)
  2712. memcg->memsw_is_minimum = true;
  2713. else
  2714. memcg->memsw_is_minimum = false;
  2715. }
  2716. mutex_unlock(&set_limit_mutex);
  2717. if (!ret)
  2718. break;
  2719. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2720. MEM_CGROUP_RECLAIM_NOSWAP |
  2721. MEM_CGROUP_RECLAIM_SHRINK);
  2722. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2723. /* Usage is reduced ? */
  2724. if (curusage >= oldusage)
  2725. retry_count--;
  2726. else
  2727. oldusage = curusage;
  2728. }
  2729. if (!ret && enlarge)
  2730. memcg_oom_recover(memcg);
  2731. return ret;
  2732. }
  2733. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2734. gfp_t gfp_mask)
  2735. {
  2736. unsigned long nr_reclaimed = 0;
  2737. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2738. unsigned long reclaimed;
  2739. int loop = 0;
  2740. struct mem_cgroup_tree_per_zone *mctz;
  2741. unsigned long long excess;
  2742. if (order > 0)
  2743. return 0;
  2744. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  2745. /*
  2746. * This loop can run a while, specially if mem_cgroup's continuously
  2747. * keep exceeding their soft limit and putting the system under
  2748. * pressure
  2749. */
  2750. do {
  2751. if (next_mz)
  2752. mz = next_mz;
  2753. else
  2754. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2755. if (!mz)
  2756. break;
  2757. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  2758. gfp_mask,
  2759. MEM_CGROUP_RECLAIM_SOFT);
  2760. nr_reclaimed += reclaimed;
  2761. spin_lock(&mctz->lock);
  2762. /*
  2763. * If we failed to reclaim anything from this memory cgroup
  2764. * it is time to move on to the next cgroup
  2765. */
  2766. next_mz = NULL;
  2767. if (!reclaimed) {
  2768. do {
  2769. /*
  2770. * Loop until we find yet another one.
  2771. *
  2772. * By the time we get the soft_limit lock
  2773. * again, someone might have aded the
  2774. * group back on the RB tree. Iterate to
  2775. * make sure we get a different mem.
  2776. * mem_cgroup_largest_soft_limit_node returns
  2777. * NULL if no other cgroup is present on
  2778. * the tree
  2779. */
  2780. next_mz =
  2781. __mem_cgroup_largest_soft_limit_node(mctz);
  2782. if (next_mz == mz) {
  2783. css_put(&next_mz->mem->css);
  2784. next_mz = NULL;
  2785. } else /* next_mz == NULL or other memcg */
  2786. break;
  2787. } while (1);
  2788. }
  2789. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  2790. excess = res_counter_soft_limit_excess(&mz->mem->res);
  2791. /*
  2792. * One school of thought says that we should not add
  2793. * back the node to the tree if reclaim returns 0.
  2794. * But our reclaim could return 0, simply because due
  2795. * to priority we are exposing a smaller subset of
  2796. * memory to reclaim from. Consider this as a longer
  2797. * term TODO.
  2798. */
  2799. /* If excess == 0, no tree ops */
  2800. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  2801. spin_unlock(&mctz->lock);
  2802. css_put(&mz->mem->css);
  2803. loop++;
  2804. /*
  2805. * Could not reclaim anything and there are no more
  2806. * mem cgroups to try or we seem to be looping without
  2807. * reclaiming anything.
  2808. */
  2809. if (!nr_reclaimed &&
  2810. (next_mz == NULL ||
  2811. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2812. break;
  2813. } while (!nr_reclaimed);
  2814. if (next_mz)
  2815. css_put(&next_mz->mem->css);
  2816. return nr_reclaimed;
  2817. }
  2818. /*
  2819. * This routine traverse page_cgroup in given list and drop them all.
  2820. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  2821. */
  2822. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  2823. int node, int zid, enum lru_list lru)
  2824. {
  2825. struct zone *zone;
  2826. struct mem_cgroup_per_zone *mz;
  2827. struct page_cgroup *pc, *busy;
  2828. unsigned long flags, loop;
  2829. struct list_head *list;
  2830. int ret = 0;
  2831. zone = &NODE_DATA(node)->node_zones[zid];
  2832. mz = mem_cgroup_zoneinfo(mem, node, zid);
  2833. list = &mz->lists[lru];
  2834. loop = MEM_CGROUP_ZSTAT(mz, lru);
  2835. /* give some margin against EBUSY etc...*/
  2836. loop += 256;
  2837. busy = NULL;
  2838. while (loop--) {
  2839. ret = 0;
  2840. spin_lock_irqsave(&zone->lru_lock, flags);
  2841. if (list_empty(list)) {
  2842. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2843. break;
  2844. }
  2845. pc = list_entry(list->prev, struct page_cgroup, lru);
  2846. if (busy == pc) {
  2847. list_move(&pc->lru, list);
  2848. busy = NULL;
  2849. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2850. continue;
  2851. }
  2852. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2853. ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
  2854. if (ret == -ENOMEM)
  2855. break;
  2856. if (ret == -EBUSY || ret == -EINVAL) {
  2857. /* found lock contention or "pc" is obsolete. */
  2858. busy = pc;
  2859. cond_resched();
  2860. } else
  2861. busy = NULL;
  2862. }
  2863. if (!ret && !list_empty(list))
  2864. return -EBUSY;
  2865. return ret;
  2866. }
  2867. /*
  2868. * make mem_cgroup's charge to be 0 if there is no task.
  2869. * This enables deleting this mem_cgroup.
  2870. */
  2871. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  2872. {
  2873. int ret;
  2874. int node, zid, shrink;
  2875. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2876. struct cgroup *cgrp = mem->css.cgroup;
  2877. css_get(&mem->css);
  2878. shrink = 0;
  2879. /* should free all ? */
  2880. if (free_all)
  2881. goto try_to_free;
  2882. move_account:
  2883. do {
  2884. ret = -EBUSY;
  2885. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  2886. goto out;
  2887. ret = -EINTR;
  2888. if (signal_pending(current))
  2889. goto out;
  2890. /* This is for making all *used* pages to be on LRU. */
  2891. lru_add_drain_all();
  2892. drain_all_stock_sync();
  2893. ret = 0;
  2894. mem_cgroup_start_move(mem);
  2895. for_each_node_state(node, N_HIGH_MEMORY) {
  2896. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  2897. enum lru_list l;
  2898. for_each_lru(l) {
  2899. ret = mem_cgroup_force_empty_list(mem,
  2900. node, zid, l);
  2901. if (ret)
  2902. break;
  2903. }
  2904. }
  2905. if (ret)
  2906. break;
  2907. }
  2908. mem_cgroup_end_move(mem);
  2909. memcg_oom_recover(mem);
  2910. /* it seems parent cgroup doesn't have enough mem */
  2911. if (ret == -ENOMEM)
  2912. goto try_to_free;
  2913. cond_resched();
  2914. /* "ret" should also be checked to ensure all lists are empty. */
  2915. } while (mem->res.usage > 0 || ret);
  2916. out:
  2917. css_put(&mem->css);
  2918. return ret;
  2919. try_to_free:
  2920. /* returns EBUSY if there is a task or if we come here twice. */
  2921. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  2922. ret = -EBUSY;
  2923. goto out;
  2924. }
  2925. /* we call try-to-free pages for make this cgroup empty */
  2926. lru_add_drain_all();
  2927. /* try to free all pages in this cgroup */
  2928. shrink = 1;
  2929. while (nr_retries && mem->res.usage > 0) {
  2930. int progress;
  2931. if (signal_pending(current)) {
  2932. ret = -EINTR;
  2933. goto out;
  2934. }
  2935. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  2936. false, get_swappiness(mem));
  2937. if (!progress) {
  2938. nr_retries--;
  2939. /* maybe some writeback is necessary */
  2940. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2941. }
  2942. }
  2943. lru_add_drain();
  2944. /* try move_account...there may be some *locked* pages. */
  2945. goto move_account;
  2946. }
  2947. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  2948. {
  2949. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  2950. }
  2951. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  2952. {
  2953. return mem_cgroup_from_cont(cont)->use_hierarchy;
  2954. }
  2955. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  2956. u64 val)
  2957. {
  2958. int retval = 0;
  2959. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  2960. struct cgroup *parent = cont->parent;
  2961. struct mem_cgroup *parent_mem = NULL;
  2962. if (parent)
  2963. parent_mem = mem_cgroup_from_cont(parent);
  2964. cgroup_lock();
  2965. /*
  2966. * If parent's use_hierarchy is set, we can't make any modifications
  2967. * in the child subtrees. If it is unset, then the change can
  2968. * occur, provided the current cgroup has no children.
  2969. *
  2970. * For the root cgroup, parent_mem is NULL, we allow value to be
  2971. * set if there are no children.
  2972. */
  2973. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  2974. (val == 1 || val == 0)) {
  2975. if (list_empty(&cont->children))
  2976. mem->use_hierarchy = val;
  2977. else
  2978. retval = -EBUSY;
  2979. } else
  2980. retval = -EINVAL;
  2981. cgroup_unlock();
  2982. return retval;
  2983. }
  2984. static u64 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
  2985. enum mem_cgroup_stat_index idx)
  2986. {
  2987. struct mem_cgroup *iter;
  2988. s64 val = 0;
  2989. /* each per cpu's value can be minus.Then, use s64 */
  2990. for_each_mem_cgroup_tree(iter, mem)
  2991. val += mem_cgroup_read_stat(iter, idx);
  2992. if (val < 0) /* race ? */
  2993. val = 0;
  2994. return val;
  2995. }
  2996. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  2997. {
  2998. u64 val;
  2999. if (!mem_cgroup_is_root(mem)) {
  3000. if (!swap)
  3001. return res_counter_read_u64(&mem->res, RES_USAGE);
  3002. else
  3003. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  3004. }
  3005. val = mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE);
  3006. val += mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS);
  3007. if (swap)
  3008. val += mem_cgroup_get_recursive_idx_stat(mem,
  3009. MEM_CGROUP_STAT_SWAPOUT);
  3010. return val << PAGE_SHIFT;
  3011. }
  3012. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  3013. {
  3014. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3015. u64 val;
  3016. int type, name;
  3017. type = MEMFILE_TYPE(cft->private);
  3018. name = MEMFILE_ATTR(cft->private);
  3019. switch (type) {
  3020. case _MEM:
  3021. if (name == RES_USAGE)
  3022. val = mem_cgroup_usage(mem, false);
  3023. else
  3024. val = res_counter_read_u64(&mem->res, name);
  3025. break;
  3026. case _MEMSWAP:
  3027. if (name == RES_USAGE)
  3028. val = mem_cgroup_usage(mem, true);
  3029. else
  3030. val = res_counter_read_u64(&mem->memsw, name);
  3031. break;
  3032. default:
  3033. BUG();
  3034. break;
  3035. }
  3036. return val;
  3037. }
  3038. /*
  3039. * The user of this function is...
  3040. * RES_LIMIT.
  3041. */
  3042. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  3043. const char *buffer)
  3044. {
  3045. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3046. int type, name;
  3047. unsigned long long val;
  3048. int ret;
  3049. type = MEMFILE_TYPE(cft->private);
  3050. name = MEMFILE_ATTR(cft->private);
  3051. switch (name) {
  3052. case RES_LIMIT:
  3053. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3054. ret = -EINVAL;
  3055. break;
  3056. }
  3057. /* This function does all necessary parse...reuse it */
  3058. ret = res_counter_memparse_write_strategy(buffer, &val);
  3059. if (ret)
  3060. break;
  3061. if (type == _MEM)
  3062. ret = mem_cgroup_resize_limit(memcg, val);
  3063. else
  3064. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3065. break;
  3066. case RES_SOFT_LIMIT:
  3067. ret = res_counter_memparse_write_strategy(buffer, &val);
  3068. if (ret)
  3069. break;
  3070. /*
  3071. * For memsw, soft limits are hard to implement in terms
  3072. * of semantics, for now, we support soft limits for
  3073. * control without swap
  3074. */
  3075. if (type == _MEM)
  3076. ret = res_counter_set_soft_limit(&memcg->res, val);
  3077. else
  3078. ret = -EINVAL;
  3079. break;
  3080. default:
  3081. ret = -EINVAL; /* should be BUG() ? */
  3082. break;
  3083. }
  3084. return ret;
  3085. }
  3086. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3087. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3088. {
  3089. struct cgroup *cgroup;
  3090. unsigned long long min_limit, min_memsw_limit, tmp;
  3091. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3092. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3093. cgroup = memcg->css.cgroup;
  3094. if (!memcg->use_hierarchy)
  3095. goto out;
  3096. while (cgroup->parent) {
  3097. cgroup = cgroup->parent;
  3098. memcg = mem_cgroup_from_cont(cgroup);
  3099. if (!memcg->use_hierarchy)
  3100. break;
  3101. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3102. min_limit = min(min_limit, tmp);
  3103. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3104. min_memsw_limit = min(min_memsw_limit, tmp);
  3105. }
  3106. out:
  3107. *mem_limit = min_limit;
  3108. *memsw_limit = min_memsw_limit;
  3109. return;
  3110. }
  3111. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  3112. {
  3113. struct mem_cgroup *mem;
  3114. int type, name;
  3115. mem = mem_cgroup_from_cont(cont);
  3116. type = MEMFILE_TYPE(event);
  3117. name = MEMFILE_ATTR(event);
  3118. switch (name) {
  3119. case RES_MAX_USAGE:
  3120. if (type == _MEM)
  3121. res_counter_reset_max(&mem->res);
  3122. else
  3123. res_counter_reset_max(&mem->memsw);
  3124. break;
  3125. case RES_FAILCNT:
  3126. if (type == _MEM)
  3127. res_counter_reset_failcnt(&mem->res);
  3128. else
  3129. res_counter_reset_failcnt(&mem->memsw);
  3130. break;
  3131. }
  3132. return 0;
  3133. }
  3134. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  3135. struct cftype *cft)
  3136. {
  3137. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  3138. }
  3139. #ifdef CONFIG_MMU
  3140. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3141. struct cftype *cft, u64 val)
  3142. {
  3143. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3144. if (val >= (1 << NR_MOVE_TYPE))
  3145. return -EINVAL;
  3146. /*
  3147. * We check this value several times in both in can_attach() and
  3148. * attach(), so we need cgroup lock to prevent this value from being
  3149. * inconsistent.
  3150. */
  3151. cgroup_lock();
  3152. mem->move_charge_at_immigrate = val;
  3153. cgroup_unlock();
  3154. return 0;
  3155. }
  3156. #else
  3157. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3158. struct cftype *cft, u64 val)
  3159. {
  3160. return -ENOSYS;
  3161. }
  3162. #endif
  3163. /* For read statistics */
  3164. enum {
  3165. MCS_CACHE,
  3166. MCS_RSS,
  3167. MCS_FILE_MAPPED,
  3168. MCS_PGPGIN,
  3169. MCS_PGPGOUT,
  3170. MCS_SWAP,
  3171. MCS_INACTIVE_ANON,
  3172. MCS_ACTIVE_ANON,
  3173. MCS_INACTIVE_FILE,
  3174. MCS_ACTIVE_FILE,
  3175. MCS_UNEVICTABLE,
  3176. NR_MCS_STAT,
  3177. };
  3178. struct mcs_total_stat {
  3179. s64 stat[NR_MCS_STAT];
  3180. };
  3181. struct {
  3182. char *local_name;
  3183. char *total_name;
  3184. } memcg_stat_strings[NR_MCS_STAT] = {
  3185. {"cache", "total_cache"},
  3186. {"rss", "total_rss"},
  3187. {"mapped_file", "total_mapped_file"},
  3188. {"pgpgin", "total_pgpgin"},
  3189. {"pgpgout", "total_pgpgout"},
  3190. {"swap", "total_swap"},
  3191. {"inactive_anon", "total_inactive_anon"},
  3192. {"active_anon", "total_active_anon"},
  3193. {"inactive_file", "total_inactive_file"},
  3194. {"active_file", "total_active_file"},
  3195. {"unevictable", "total_unevictable"}
  3196. };
  3197. static void
  3198. mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3199. {
  3200. s64 val;
  3201. /* per cpu stat */
  3202. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  3203. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  3204. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  3205. s->stat[MCS_RSS] += val * PAGE_SIZE;
  3206. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  3207. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  3208. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
  3209. s->stat[MCS_PGPGIN] += val;
  3210. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
  3211. s->stat[MCS_PGPGOUT] += val;
  3212. if (do_swap_account) {
  3213. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3214. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  3215. }
  3216. /* per zone stat */
  3217. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
  3218. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  3219. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
  3220. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  3221. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
  3222. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  3223. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
  3224. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  3225. val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
  3226. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  3227. }
  3228. static void
  3229. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3230. {
  3231. struct mem_cgroup *iter;
  3232. for_each_mem_cgroup_tree(iter, mem)
  3233. mem_cgroup_get_local_stat(iter, s);
  3234. }
  3235. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  3236. struct cgroup_map_cb *cb)
  3237. {
  3238. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3239. struct mcs_total_stat mystat;
  3240. int i;
  3241. memset(&mystat, 0, sizeof(mystat));
  3242. mem_cgroup_get_local_stat(mem_cont, &mystat);
  3243. for (i = 0; i < NR_MCS_STAT; i++) {
  3244. if (i == MCS_SWAP && !do_swap_account)
  3245. continue;
  3246. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  3247. }
  3248. /* Hierarchical information */
  3249. {
  3250. unsigned long long limit, memsw_limit;
  3251. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  3252. cb->fill(cb, "hierarchical_memory_limit", limit);
  3253. if (do_swap_account)
  3254. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  3255. }
  3256. memset(&mystat, 0, sizeof(mystat));
  3257. mem_cgroup_get_total_stat(mem_cont, &mystat);
  3258. for (i = 0; i < NR_MCS_STAT; i++) {
  3259. if (i == MCS_SWAP && !do_swap_account)
  3260. continue;
  3261. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  3262. }
  3263. #ifdef CONFIG_DEBUG_VM
  3264. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3265. {
  3266. int nid, zid;
  3267. struct mem_cgroup_per_zone *mz;
  3268. unsigned long recent_rotated[2] = {0, 0};
  3269. unsigned long recent_scanned[2] = {0, 0};
  3270. for_each_online_node(nid)
  3271. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3272. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3273. recent_rotated[0] +=
  3274. mz->reclaim_stat.recent_rotated[0];
  3275. recent_rotated[1] +=
  3276. mz->reclaim_stat.recent_rotated[1];
  3277. recent_scanned[0] +=
  3278. mz->reclaim_stat.recent_scanned[0];
  3279. recent_scanned[1] +=
  3280. mz->reclaim_stat.recent_scanned[1];
  3281. }
  3282. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3283. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3284. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3285. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3286. }
  3287. #endif
  3288. return 0;
  3289. }
  3290. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3291. {
  3292. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3293. return get_swappiness(memcg);
  3294. }
  3295. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3296. u64 val)
  3297. {
  3298. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3299. struct mem_cgroup *parent;
  3300. if (val > 100)
  3301. return -EINVAL;
  3302. if (cgrp->parent == NULL)
  3303. return -EINVAL;
  3304. parent = mem_cgroup_from_cont(cgrp->parent);
  3305. cgroup_lock();
  3306. /* If under hierarchy, only empty-root can set this value */
  3307. if ((parent->use_hierarchy) ||
  3308. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3309. cgroup_unlock();
  3310. return -EINVAL;
  3311. }
  3312. spin_lock(&memcg->reclaim_param_lock);
  3313. memcg->swappiness = val;
  3314. spin_unlock(&memcg->reclaim_param_lock);
  3315. cgroup_unlock();
  3316. return 0;
  3317. }
  3318. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3319. {
  3320. struct mem_cgroup_threshold_ary *t;
  3321. u64 usage;
  3322. int i;
  3323. rcu_read_lock();
  3324. if (!swap)
  3325. t = rcu_dereference(memcg->thresholds.primary);
  3326. else
  3327. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3328. if (!t)
  3329. goto unlock;
  3330. usage = mem_cgroup_usage(memcg, swap);
  3331. /*
  3332. * current_threshold points to threshold just below usage.
  3333. * If it's not true, a threshold was crossed after last
  3334. * call of __mem_cgroup_threshold().
  3335. */
  3336. i = t->current_threshold;
  3337. /*
  3338. * Iterate backward over array of thresholds starting from
  3339. * current_threshold and check if a threshold is crossed.
  3340. * If none of thresholds below usage is crossed, we read
  3341. * only one element of the array here.
  3342. */
  3343. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3344. eventfd_signal(t->entries[i].eventfd, 1);
  3345. /* i = current_threshold + 1 */
  3346. i++;
  3347. /*
  3348. * Iterate forward over array of thresholds starting from
  3349. * current_threshold+1 and check if a threshold is crossed.
  3350. * If none of thresholds above usage is crossed, we read
  3351. * only one element of the array here.
  3352. */
  3353. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3354. eventfd_signal(t->entries[i].eventfd, 1);
  3355. /* Update current_threshold */
  3356. t->current_threshold = i - 1;
  3357. unlock:
  3358. rcu_read_unlock();
  3359. }
  3360. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3361. {
  3362. while (memcg) {
  3363. __mem_cgroup_threshold(memcg, false);
  3364. if (do_swap_account)
  3365. __mem_cgroup_threshold(memcg, true);
  3366. memcg = parent_mem_cgroup(memcg);
  3367. }
  3368. }
  3369. static int compare_thresholds(const void *a, const void *b)
  3370. {
  3371. const struct mem_cgroup_threshold *_a = a;
  3372. const struct mem_cgroup_threshold *_b = b;
  3373. return _a->threshold - _b->threshold;
  3374. }
  3375. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
  3376. {
  3377. struct mem_cgroup_eventfd_list *ev;
  3378. list_for_each_entry(ev, &mem->oom_notify, list)
  3379. eventfd_signal(ev->eventfd, 1);
  3380. return 0;
  3381. }
  3382. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3383. {
  3384. struct mem_cgroup *iter;
  3385. for_each_mem_cgroup_tree(iter, mem)
  3386. mem_cgroup_oom_notify_cb(iter);
  3387. }
  3388. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3389. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3390. {
  3391. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3392. struct mem_cgroup_thresholds *thresholds;
  3393. struct mem_cgroup_threshold_ary *new;
  3394. int type = MEMFILE_TYPE(cft->private);
  3395. u64 threshold, usage;
  3396. int i, size, ret;
  3397. ret = res_counter_memparse_write_strategy(args, &threshold);
  3398. if (ret)
  3399. return ret;
  3400. mutex_lock(&memcg->thresholds_lock);
  3401. if (type == _MEM)
  3402. thresholds = &memcg->thresholds;
  3403. else if (type == _MEMSWAP)
  3404. thresholds = &memcg->memsw_thresholds;
  3405. else
  3406. BUG();
  3407. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3408. /* Check if a threshold crossed before adding a new one */
  3409. if (thresholds->primary)
  3410. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3411. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3412. /* Allocate memory for new array of thresholds */
  3413. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3414. GFP_KERNEL);
  3415. if (!new) {
  3416. ret = -ENOMEM;
  3417. goto unlock;
  3418. }
  3419. new->size = size;
  3420. /* Copy thresholds (if any) to new array */
  3421. if (thresholds->primary) {
  3422. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3423. sizeof(struct mem_cgroup_threshold));
  3424. }
  3425. /* Add new threshold */
  3426. new->entries[size - 1].eventfd = eventfd;
  3427. new->entries[size - 1].threshold = threshold;
  3428. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3429. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3430. compare_thresholds, NULL);
  3431. /* Find current threshold */
  3432. new->current_threshold = -1;
  3433. for (i = 0; i < size; i++) {
  3434. if (new->entries[i].threshold < usage) {
  3435. /*
  3436. * new->current_threshold will not be used until
  3437. * rcu_assign_pointer(), so it's safe to increment
  3438. * it here.
  3439. */
  3440. ++new->current_threshold;
  3441. }
  3442. }
  3443. /* Free old spare buffer and save old primary buffer as spare */
  3444. kfree(thresholds->spare);
  3445. thresholds->spare = thresholds->primary;
  3446. rcu_assign_pointer(thresholds->primary, new);
  3447. /* To be sure that nobody uses thresholds */
  3448. synchronize_rcu();
  3449. unlock:
  3450. mutex_unlock(&memcg->thresholds_lock);
  3451. return ret;
  3452. }
  3453. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3454. struct cftype *cft, struct eventfd_ctx *eventfd)
  3455. {
  3456. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3457. struct mem_cgroup_thresholds *thresholds;
  3458. struct mem_cgroup_threshold_ary *new;
  3459. int type = MEMFILE_TYPE(cft->private);
  3460. u64 usage;
  3461. int i, j, size;
  3462. mutex_lock(&memcg->thresholds_lock);
  3463. if (type == _MEM)
  3464. thresholds = &memcg->thresholds;
  3465. else if (type == _MEMSWAP)
  3466. thresholds = &memcg->memsw_thresholds;
  3467. else
  3468. BUG();
  3469. /*
  3470. * Something went wrong if we trying to unregister a threshold
  3471. * if we don't have thresholds
  3472. */
  3473. BUG_ON(!thresholds);
  3474. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3475. /* Check if a threshold crossed before removing */
  3476. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3477. /* Calculate new number of threshold */
  3478. size = 0;
  3479. for (i = 0; i < thresholds->primary->size; i++) {
  3480. if (thresholds->primary->entries[i].eventfd != eventfd)
  3481. size++;
  3482. }
  3483. new = thresholds->spare;
  3484. /* Set thresholds array to NULL if we don't have thresholds */
  3485. if (!size) {
  3486. kfree(new);
  3487. new = NULL;
  3488. goto swap_buffers;
  3489. }
  3490. new->size = size;
  3491. /* Copy thresholds and find current threshold */
  3492. new->current_threshold = -1;
  3493. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3494. if (thresholds->primary->entries[i].eventfd == eventfd)
  3495. continue;
  3496. new->entries[j] = thresholds->primary->entries[i];
  3497. if (new->entries[j].threshold < usage) {
  3498. /*
  3499. * new->current_threshold will not be used
  3500. * until rcu_assign_pointer(), so it's safe to increment
  3501. * it here.
  3502. */
  3503. ++new->current_threshold;
  3504. }
  3505. j++;
  3506. }
  3507. swap_buffers:
  3508. /* Swap primary and spare array */
  3509. thresholds->spare = thresholds->primary;
  3510. rcu_assign_pointer(thresholds->primary, new);
  3511. /* To be sure that nobody uses thresholds */
  3512. synchronize_rcu();
  3513. mutex_unlock(&memcg->thresholds_lock);
  3514. }
  3515. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  3516. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3517. {
  3518. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3519. struct mem_cgroup_eventfd_list *event;
  3520. int type = MEMFILE_TYPE(cft->private);
  3521. BUG_ON(type != _OOM_TYPE);
  3522. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3523. if (!event)
  3524. return -ENOMEM;
  3525. mutex_lock(&memcg_oom_mutex);
  3526. event->eventfd = eventfd;
  3527. list_add(&event->list, &memcg->oom_notify);
  3528. /* already in OOM ? */
  3529. if (atomic_read(&memcg->oom_lock))
  3530. eventfd_signal(eventfd, 1);
  3531. mutex_unlock(&memcg_oom_mutex);
  3532. return 0;
  3533. }
  3534. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  3535. struct cftype *cft, struct eventfd_ctx *eventfd)
  3536. {
  3537. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3538. struct mem_cgroup_eventfd_list *ev, *tmp;
  3539. int type = MEMFILE_TYPE(cft->private);
  3540. BUG_ON(type != _OOM_TYPE);
  3541. mutex_lock(&memcg_oom_mutex);
  3542. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  3543. if (ev->eventfd == eventfd) {
  3544. list_del(&ev->list);
  3545. kfree(ev);
  3546. }
  3547. }
  3548. mutex_unlock(&memcg_oom_mutex);
  3549. }
  3550. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  3551. struct cftype *cft, struct cgroup_map_cb *cb)
  3552. {
  3553. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3554. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  3555. if (atomic_read(&mem->oom_lock))
  3556. cb->fill(cb, "under_oom", 1);
  3557. else
  3558. cb->fill(cb, "under_oom", 0);
  3559. return 0;
  3560. }
  3561. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  3562. struct cftype *cft, u64 val)
  3563. {
  3564. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3565. struct mem_cgroup *parent;
  3566. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3567. if (!cgrp->parent || !((val == 0) || (val == 1)))
  3568. return -EINVAL;
  3569. parent = mem_cgroup_from_cont(cgrp->parent);
  3570. cgroup_lock();
  3571. /* oom-kill-disable is a flag for subhierarchy. */
  3572. if ((parent->use_hierarchy) ||
  3573. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  3574. cgroup_unlock();
  3575. return -EINVAL;
  3576. }
  3577. mem->oom_kill_disable = val;
  3578. if (!val)
  3579. memcg_oom_recover(mem);
  3580. cgroup_unlock();
  3581. return 0;
  3582. }
  3583. static struct cftype mem_cgroup_files[] = {
  3584. {
  3585. .name = "usage_in_bytes",
  3586. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3587. .read_u64 = mem_cgroup_read,
  3588. .register_event = mem_cgroup_usage_register_event,
  3589. .unregister_event = mem_cgroup_usage_unregister_event,
  3590. },
  3591. {
  3592. .name = "max_usage_in_bytes",
  3593. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3594. .trigger = mem_cgroup_reset,
  3595. .read_u64 = mem_cgroup_read,
  3596. },
  3597. {
  3598. .name = "limit_in_bytes",
  3599. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3600. .write_string = mem_cgroup_write,
  3601. .read_u64 = mem_cgroup_read,
  3602. },
  3603. {
  3604. .name = "soft_limit_in_bytes",
  3605. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3606. .write_string = mem_cgroup_write,
  3607. .read_u64 = mem_cgroup_read,
  3608. },
  3609. {
  3610. .name = "failcnt",
  3611. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3612. .trigger = mem_cgroup_reset,
  3613. .read_u64 = mem_cgroup_read,
  3614. },
  3615. {
  3616. .name = "stat",
  3617. .read_map = mem_control_stat_show,
  3618. },
  3619. {
  3620. .name = "force_empty",
  3621. .trigger = mem_cgroup_force_empty_write,
  3622. },
  3623. {
  3624. .name = "use_hierarchy",
  3625. .write_u64 = mem_cgroup_hierarchy_write,
  3626. .read_u64 = mem_cgroup_hierarchy_read,
  3627. },
  3628. {
  3629. .name = "swappiness",
  3630. .read_u64 = mem_cgroup_swappiness_read,
  3631. .write_u64 = mem_cgroup_swappiness_write,
  3632. },
  3633. {
  3634. .name = "move_charge_at_immigrate",
  3635. .read_u64 = mem_cgroup_move_charge_read,
  3636. .write_u64 = mem_cgroup_move_charge_write,
  3637. },
  3638. {
  3639. .name = "oom_control",
  3640. .read_map = mem_cgroup_oom_control_read,
  3641. .write_u64 = mem_cgroup_oom_control_write,
  3642. .register_event = mem_cgroup_oom_register_event,
  3643. .unregister_event = mem_cgroup_oom_unregister_event,
  3644. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3645. },
  3646. };
  3647. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3648. static struct cftype memsw_cgroup_files[] = {
  3649. {
  3650. .name = "memsw.usage_in_bytes",
  3651. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  3652. .read_u64 = mem_cgroup_read,
  3653. .register_event = mem_cgroup_usage_register_event,
  3654. .unregister_event = mem_cgroup_usage_unregister_event,
  3655. },
  3656. {
  3657. .name = "memsw.max_usage_in_bytes",
  3658. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  3659. .trigger = mem_cgroup_reset,
  3660. .read_u64 = mem_cgroup_read,
  3661. },
  3662. {
  3663. .name = "memsw.limit_in_bytes",
  3664. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  3665. .write_string = mem_cgroup_write,
  3666. .read_u64 = mem_cgroup_read,
  3667. },
  3668. {
  3669. .name = "memsw.failcnt",
  3670. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  3671. .trigger = mem_cgroup_reset,
  3672. .read_u64 = mem_cgroup_read,
  3673. },
  3674. };
  3675. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3676. {
  3677. if (!do_swap_account)
  3678. return 0;
  3679. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  3680. ARRAY_SIZE(memsw_cgroup_files));
  3681. };
  3682. #else
  3683. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3684. {
  3685. return 0;
  3686. }
  3687. #endif
  3688. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3689. {
  3690. struct mem_cgroup_per_node *pn;
  3691. struct mem_cgroup_per_zone *mz;
  3692. enum lru_list l;
  3693. int zone, tmp = node;
  3694. /*
  3695. * This routine is called against possible nodes.
  3696. * But it's BUG to call kmalloc() against offline node.
  3697. *
  3698. * TODO: this routine can waste much memory for nodes which will
  3699. * never be onlined. It's better to use memory hotplug callback
  3700. * function.
  3701. */
  3702. if (!node_state(node, N_NORMAL_MEMORY))
  3703. tmp = -1;
  3704. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3705. if (!pn)
  3706. return 1;
  3707. mem->info.nodeinfo[node] = pn;
  3708. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3709. mz = &pn->zoneinfo[zone];
  3710. for_each_lru(l)
  3711. INIT_LIST_HEAD(&mz->lists[l]);
  3712. mz->usage_in_excess = 0;
  3713. mz->on_tree = false;
  3714. mz->mem = mem;
  3715. }
  3716. return 0;
  3717. }
  3718. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3719. {
  3720. kfree(mem->info.nodeinfo[node]);
  3721. }
  3722. static struct mem_cgroup *mem_cgroup_alloc(void)
  3723. {
  3724. struct mem_cgroup *mem;
  3725. int size = sizeof(struct mem_cgroup);
  3726. /* Can be very big if MAX_NUMNODES is very big */
  3727. if (size < PAGE_SIZE)
  3728. mem = kzalloc(size, GFP_KERNEL);
  3729. else
  3730. mem = vzalloc(size);
  3731. if (!mem)
  3732. return NULL;
  3733. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3734. if (!mem->stat)
  3735. goto out_free;
  3736. spin_lock_init(&mem->pcp_counter_lock);
  3737. return mem;
  3738. out_free:
  3739. if (size < PAGE_SIZE)
  3740. kfree(mem);
  3741. else
  3742. vfree(mem);
  3743. return NULL;
  3744. }
  3745. /*
  3746. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3747. * (scanning all at force_empty is too costly...)
  3748. *
  3749. * Instead of clearing all references at force_empty, we remember
  3750. * the number of reference from swap_cgroup and free mem_cgroup when
  3751. * it goes down to 0.
  3752. *
  3753. * Removal of cgroup itself succeeds regardless of refs from swap.
  3754. */
  3755. static void __mem_cgroup_free(struct mem_cgroup *mem)
  3756. {
  3757. int node;
  3758. mem_cgroup_remove_from_trees(mem);
  3759. free_css_id(&mem_cgroup_subsys, &mem->css);
  3760. for_each_node_state(node, N_POSSIBLE)
  3761. free_mem_cgroup_per_zone_info(mem, node);
  3762. free_percpu(mem->stat);
  3763. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  3764. kfree(mem);
  3765. else
  3766. vfree(mem);
  3767. }
  3768. static void mem_cgroup_get(struct mem_cgroup *mem)
  3769. {
  3770. atomic_inc(&mem->refcnt);
  3771. }
  3772. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  3773. {
  3774. if (atomic_sub_and_test(count, &mem->refcnt)) {
  3775. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  3776. __mem_cgroup_free(mem);
  3777. if (parent)
  3778. mem_cgroup_put(parent);
  3779. }
  3780. }
  3781. static void mem_cgroup_put(struct mem_cgroup *mem)
  3782. {
  3783. __mem_cgroup_put(mem, 1);
  3784. }
  3785. /*
  3786. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3787. */
  3788. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  3789. {
  3790. if (!mem->res.parent)
  3791. return NULL;
  3792. return mem_cgroup_from_res_counter(mem->res.parent, res);
  3793. }
  3794. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3795. static void __init enable_swap_cgroup(void)
  3796. {
  3797. if (!mem_cgroup_disabled() && really_do_swap_account)
  3798. do_swap_account = 1;
  3799. }
  3800. #else
  3801. static void __init enable_swap_cgroup(void)
  3802. {
  3803. }
  3804. #endif
  3805. static int mem_cgroup_soft_limit_tree_init(void)
  3806. {
  3807. struct mem_cgroup_tree_per_node *rtpn;
  3808. struct mem_cgroup_tree_per_zone *rtpz;
  3809. int tmp, node, zone;
  3810. for_each_node_state(node, N_POSSIBLE) {
  3811. tmp = node;
  3812. if (!node_state(node, N_NORMAL_MEMORY))
  3813. tmp = -1;
  3814. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  3815. if (!rtpn)
  3816. return 1;
  3817. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  3818. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3819. rtpz = &rtpn->rb_tree_per_zone[zone];
  3820. rtpz->rb_root = RB_ROOT;
  3821. spin_lock_init(&rtpz->lock);
  3822. }
  3823. }
  3824. return 0;
  3825. }
  3826. static struct cgroup_subsys_state * __ref
  3827. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  3828. {
  3829. struct mem_cgroup *mem, *parent;
  3830. long error = -ENOMEM;
  3831. int node;
  3832. mem = mem_cgroup_alloc();
  3833. if (!mem)
  3834. return ERR_PTR(error);
  3835. for_each_node_state(node, N_POSSIBLE)
  3836. if (alloc_mem_cgroup_per_zone_info(mem, node))
  3837. goto free_out;
  3838. /* root ? */
  3839. if (cont->parent == NULL) {
  3840. int cpu;
  3841. enable_swap_cgroup();
  3842. parent = NULL;
  3843. root_mem_cgroup = mem;
  3844. if (mem_cgroup_soft_limit_tree_init())
  3845. goto free_out;
  3846. for_each_possible_cpu(cpu) {
  3847. struct memcg_stock_pcp *stock =
  3848. &per_cpu(memcg_stock, cpu);
  3849. INIT_WORK(&stock->work, drain_local_stock);
  3850. }
  3851. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  3852. } else {
  3853. parent = mem_cgroup_from_cont(cont->parent);
  3854. mem->use_hierarchy = parent->use_hierarchy;
  3855. mem->oom_kill_disable = parent->oom_kill_disable;
  3856. }
  3857. if (parent && parent->use_hierarchy) {
  3858. res_counter_init(&mem->res, &parent->res);
  3859. res_counter_init(&mem->memsw, &parent->memsw);
  3860. /*
  3861. * We increment refcnt of the parent to ensure that we can
  3862. * safely access it on res_counter_charge/uncharge.
  3863. * This refcnt will be decremented when freeing this
  3864. * mem_cgroup(see mem_cgroup_put).
  3865. */
  3866. mem_cgroup_get(parent);
  3867. } else {
  3868. res_counter_init(&mem->res, NULL);
  3869. res_counter_init(&mem->memsw, NULL);
  3870. }
  3871. mem->last_scanned_child = 0;
  3872. spin_lock_init(&mem->reclaim_param_lock);
  3873. INIT_LIST_HEAD(&mem->oom_notify);
  3874. if (parent)
  3875. mem->swappiness = get_swappiness(parent);
  3876. atomic_set(&mem->refcnt, 1);
  3877. mem->move_charge_at_immigrate = 0;
  3878. mutex_init(&mem->thresholds_lock);
  3879. return &mem->css;
  3880. free_out:
  3881. __mem_cgroup_free(mem);
  3882. root_mem_cgroup = NULL;
  3883. return ERR_PTR(error);
  3884. }
  3885. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  3886. struct cgroup *cont)
  3887. {
  3888. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3889. return mem_cgroup_force_empty(mem, false);
  3890. }
  3891. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  3892. struct cgroup *cont)
  3893. {
  3894. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3895. mem_cgroup_put(mem);
  3896. }
  3897. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  3898. struct cgroup *cont)
  3899. {
  3900. int ret;
  3901. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  3902. ARRAY_SIZE(mem_cgroup_files));
  3903. if (!ret)
  3904. ret = register_memsw_files(cont, ss);
  3905. return ret;
  3906. }
  3907. #ifdef CONFIG_MMU
  3908. /* Handlers for move charge at task migration. */
  3909. #define PRECHARGE_COUNT_AT_ONCE 256
  3910. static int mem_cgroup_do_precharge(unsigned long count)
  3911. {
  3912. int ret = 0;
  3913. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  3914. struct mem_cgroup *mem = mc.to;
  3915. if (mem_cgroup_is_root(mem)) {
  3916. mc.precharge += count;
  3917. /* we don't need css_get for root */
  3918. return ret;
  3919. }
  3920. /* try to charge at once */
  3921. if (count > 1) {
  3922. struct res_counter *dummy;
  3923. /*
  3924. * "mem" cannot be under rmdir() because we've already checked
  3925. * by cgroup_lock_live_cgroup() that it is not removed and we
  3926. * are still under the same cgroup_mutex. So we can postpone
  3927. * css_get().
  3928. */
  3929. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  3930. goto one_by_one;
  3931. if (do_swap_account && res_counter_charge(&mem->memsw,
  3932. PAGE_SIZE * count, &dummy)) {
  3933. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  3934. goto one_by_one;
  3935. }
  3936. mc.precharge += count;
  3937. return ret;
  3938. }
  3939. one_by_one:
  3940. /* fall back to one by one charge */
  3941. while (count--) {
  3942. if (signal_pending(current)) {
  3943. ret = -EINTR;
  3944. break;
  3945. }
  3946. if (!batch_count--) {
  3947. batch_count = PRECHARGE_COUNT_AT_ONCE;
  3948. cond_resched();
  3949. }
  3950. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
  3951. PAGE_SIZE);
  3952. if (ret || !mem)
  3953. /* mem_cgroup_clear_mc() will do uncharge later */
  3954. return -ENOMEM;
  3955. mc.precharge++;
  3956. }
  3957. return ret;
  3958. }
  3959. /**
  3960. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  3961. * @vma: the vma the pte to be checked belongs
  3962. * @addr: the address corresponding to the pte to be checked
  3963. * @ptent: the pte to be checked
  3964. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  3965. *
  3966. * Returns
  3967. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  3968. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  3969. * move charge. if @target is not NULL, the page is stored in target->page
  3970. * with extra refcnt got(Callers should handle it).
  3971. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  3972. * target for charge migration. if @target is not NULL, the entry is stored
  3973. * in target->ent.
  3974. *
  3975. * Called with pte lock held.
  3976. */
  3977. union mc_target {
  3978. struct page *page;
  3979. swp_entry_t ent;
  3980. };
  3981. enum mc_target_type {
  3982. MC_TARGET_NONE, /* not used */
  3983. MC_TARGET_PAGE,
  3984. MC_TARGET_SWAP,
  3985. };
  3986. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  3987. unsigned long addr, pte_t ptent)
  3988. {
  3989. struct page *page = vm_normal_page(vma, addr, ptent);
  3990. if (!page || !page_mapped(page))
  3991. return NULL;
  3992. if (PageAnon(page)) {
  3993. /* we don't move shared anon */
  3994. if (!move_anon() || page_mapcount(page) > 2)
  3995. return NULL;
  3996. } else if (!move_file())
  3997. /* we ignore mapcount for file pages */
  3998. return NULL;
  3999. if (!get_page_unless_zero(page))
  4000. return NULL;
  4001. return page;
  4002. }
  4003. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4004. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4005. {
  4006. int usage_count;
  4007. struct page *page = NULL;
  4008. swp_entry_t ent = pte_to_swp_entry(ptent);
  4009. if (!move_anon() || non_swap_entry(ent))
  4010. return NULL;
  4011. usage_count = mem_cgroup_count_swap_user(ent, &page);
  4012. if (usage_count > 1) { /* we don't move shared anon */
  4013. if (page)
  4014. put_page(page);
  4015. return NULL;
  4016. }
  4017. if (do_swap_account)
  4018. entry->val = ent.val;
  4019. return page;
  4020. }
  4021. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4022. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4023. {
  4024. struct page *page = NULL;
  4025. struct inode *inode;
  4026. struct address_space *mapping;
  4027. pgoff_t pgoff;
  4028. if (!vma->vm_file) /* anonymous vma */
  4029. return NULL;
  4030. if (!move_file())
  4031. return NULL;
  4032. inode = vma->vm_file->f_path.dentry->d_inode;
  4033. mapping = vma->vm_file->f_mapping;
  4034. if (pte_none(ptent))
  4035. pgoff = linear_page_index(vma, addr);
  4036. else /* pte_file(ptent) is true */
  4037. pgoff = pte_to_pgoff(ptent);
  4038. /* page is moved even if it's not RSS of this task(page-faulted). */
  4039. if (!mapping_cap_swap_backed(mapping)) { /* normal file */
  4040. page = find_get_page(mapping, pgoff);
  4041. } else { /* shmem/tmpfs file. we should take account of swap too. */
  4042. swp_entry_t ent;
  4043. mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
  4044. if (do_swap_account)
  4045. entry->val = ent.val;
  4046. }
  4047. return page;
  4048. }
  4049. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  4050. unsigned long addr, pte_t ptent, union mc_target *target)
  4051. {
  4052. struct page *page = NULL;
  4053. struct page_cgroup *pc;
  4054. int ret = 0;
  4055. swp_entry_t ent = { .val = 0 };
  4056. if (pte_present(ptent))
  4057. page = mc_handle_present_pte(vma, addr, ptent);
  4058. else if (is_swap_pte(ptent))
  4059. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4060. else if (pte_none(ptent) || pte_file(ptent))
  4061. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4062. if (!page && !ent.val)
  4063. return 0;
  4064. if (page) {
  4065. pc = lookup_page_cgroup(page);
  4066. /*
  4067. * Do only loose check w/o page_cgroup lock.
  4068. * mem_cgroup_move_account() checks the pc is valid or not under
  4069. * the lock.
  4070. */
  4071. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  4072. ret = MC_TARGET_PAGE;
  4073. if (target)
  4074. target->page = page;
  4075. }
  4076. if (!ret || !target)
  4077. put_page(page);
  4078. }
  4079. /* There is a swap entry and a page doesn't exist or isn't charged */
  4080. if (ent.val && !ret &&
  4081. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  4082. ret = MC_TARGET_SWAP;
  4083. if (target)
  4084. target->ent = ent;
  4085. }
  4086. return ret;
  4087. }
  4088. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4089. unsigned long addr, unsigned long end,
  4090. struct mm_walk *walk)
  4091. {
  4092. struct vm_area_struct *vma = walk->private;
  4093. pte_t *pte;
  4094. spinlock_t *ptl;
  4095. VM_BUG_ON(pmd_trans_huge(*pmd));
  4096. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4097. for (; addr != end; pte++, addr += PAGE_SIZE)
  4098. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  4099. mc.precharge++; /* increment precharge temporarily */
  4100. pte_unmap_unlock(pte - 1, ptl);
  4101. cond_resched();
  4102. return 0;
  4103. }
  4104. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4105. {
  4106. unsigned long precharge;
  4107. struct vm_area_struct *vma;
  4108. down_read(&mm->mmap_sem);
  4109. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4110. struct mm_walk mem_cgroup_count_precharge_walk = {
  4111. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4112. .mm = mm,
  4113. .private = vma,
  4114. };
  4115. if (is_vm_hugetlb_page(vma))
  4116. continue;
  4117. walk_page_range(vma->vm_start, vma->vm_end,
  4118. &mem_cgroup_count_precharge_walk);
  4119. }
  4120. up_read(&mm->mmap_sem);
  4121. precharge = mc.precharge;
  4122. mc.precharge = 0;
  4123. return precharge;
  4124. }
  4125. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4126. {
  4127. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4128. VM_BUG_ON(mc.moving_task);
  4129. mc.moving_task = current;
  4130. return mem_cgroup_do_precharge(precharge);
  4131. }
  4132. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4133. static void __mem_cgroup_clear_mc(void)
  4134. {
  4135. struct mem_cgroup *from = mc.from;
  4136. struct mem_cgroup *to = mc.to;
  4137. /* we must uncharge all the leftover precharges from mc.to */
  4138. if (mc.precharge) {
  4139. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  4140. mc.precharge = 0;
  4141. }
  4142. /*
  4143. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4144. * we must uncharge here.
  4145. */
  4146. if (mc.moved_charge) {
  4147. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  4148. mc.moved_charge = 0;
  4149. }
  4150. /* we must fixup refcnts and charges */
  4151. if (mc.moved_swap) {
  4152. /* uncharge swap account from the old cgroup */
  4153. if (!mem_cgroup_is_root(mc.from))
  4154. res_counter_uncharge(&mc.from->memsw,
  4155. PAGE_SIZE * mc.moved_swap);
  4156. __mem_cgroup_put(mc.from, mc.moved_swap);
  4157. if (!mem_cgroup_is_root(mc.to)) {
  4158. /*
  4159. * we charged both to->res and to->memsw, so we should
  4160. * uncharge to->res.
  4161. */
  4162. res_counter_uncharge(&mc.to->res,
  4163. PAGE_SIZE * mc.moved_swap);
  4164. }
  4165. /* we've already done mem_cgroup_get(mc.to) */
  4166. mc.moved_swap = 0;
  4167. }
  4168. memcg_oom_recover(from);
  4169. memcg_oom_recover(to);
  4170. wake_up_all(&mc.waitq);
  4171. }
  4172. static void mem_cgroup_clear_mc(void)
  4173. {
  4174. struct mem_cgroup *from = mc.from;
  4175. /*
  4176. * we must clear moving_task before waking up waiters at the end of
  4177. * task migration.
  4178. */
  4179. mc.moving_task = NULL;
  4180. __mem_cgroup_clear_mc();
  4181. spin_lock(&mc.lock);
  4182. mc.from = NULL;
  4183. mc.to = NULL;
  4184. spin_unlock(&mc.lock);
  4185. mem_cgroup_end_move(from);
  4186. }
  4187. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4188. struct cgroup *cgroup,
  4189. struct task_struct *p,
  4190. bool threadgroup)
  4191. {
  4192. int ret = 0;
  4193. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  4194. if (mem->move_charge_at_immigrate) {
  4195. struct mm_struct *mm;
  4196. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4197. VM_BUG_ON(from == mem);
  4198. mm = get_task_mm(p);
  4199. if (!mm)
  4200. return 0;
  4201. /* We move charges only when we move a owner of the mm */
  4202. if (mm->owner == p) {
  4203. VM_BUG_ON(mc.from);
  4204. VM_BUG_ON(mc.to);
  4205. VM_BUG_ON(mc.precharge);
  4206. VM_BUG_ON(mc.moved_charge);
  4207. VM_BUG_ON(mc.moved_swap);
  4208. mem_cgroup_start_move(from);
  4209. spin_lock(&mc.lock);
  4210. mc.from = from;
  4211. mc.to = mem;
  4212. spin_unlock(&mc.lock);
  4213. /* We set mc.moving_task later */
  4214. ret = mem_cgroup_precharge_mc(mm);
  4215. if (ret)
  4216. mem_cgroup_clear_mc();
  4217. }
  4218. mmput(mm);
  4219. }
  4220. return ret;
  4221. }
  4222. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4223. struct cgroup *cgroup,
  4224. struct task_struct *p,
  4225. bool threadgroup)
  4226. {
  4227. mem_cgroup_clear_mc();
  4228. }
  4229. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4230. unsigned long addr, unsigned long end,
  4231. struct mm_walk *walk)
  4232. {
  4233. int ret = 0;
  4234. struct vm_area_struct *vma = walk->private;
  4235. pte_t *pte;
  4236. spinlock_t *ptl;
  4237. retry:
  4238. VM_BUG_ON(pmd_trans_huge(*pmd));
  4239. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4240. for (; addr != end; addr += PAGE_SIZE) {
  4241. pte_t ptent = *(pte++);
  4242. union mc_target target;
  4243. int type;
  4244. struct page *page;
  4245. struct page_cgroup *pc;
  4246. swp_entry_t ent;
  4247. if (!mc.precharge)
  4248. break;
  4249. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  4250. switch (type) {
  4251. case MC_TARGET_PAGE:
  4252. page = target.page;
  4253. if (isolate_lru_page(page))
  4254. goto put;
  4255. pc = lookup_page_cgroup(page);
  4256. if (!mem_cgroup_move_account(pc,
  4257. mc.from, mc.to, false)) {
  4258. mc.precharge--;
  4259. /* we uncharge from mc.from later. */
  4260. mc.moved_charge++;
  4261. }
  4262. putback_lru_page(page);
  4263. put: /* is_target_pte_for_mc() gets the page */
  4264. put_page(page);
  4265. break;
  4266. case MC_TARGET_SWAP:
  4267. ent = target.ent;
  4268. if (!mem_cgroup_move_swap_account(ent,
  4269. mc.from, mc.to, false)) {
  4270. mc.precharge--;
  4271. /* we fixup refcnts and charges later. */
  4272. mc.moved_swap++;
  4273. }
  4274. break;
  4275. default:
  4276. break;
  4277. }
  4278. }
  4279. pte_unmap_unlock(pte - 1, ptl);
  4280. cond_resched();
  4281. if (addr != end) {
  4282. /*
  4283. * We have consumed all precharges we got in can_attach().
  4284. * We try charge one by one, but don't do any additional
  4285. * charges to mc.to if we have failed in charge once in attach()
  4286. * phase.
  4287. */
  4288. ret = mem_cgroup_do_precharge(1);
  4289. if (!ret)
  4290. goto retry;
  4291. }
  4292. return ret;
  4293. }
  4294. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4295. {
  4296. struct vm_area_struct *vma;
  4297. lru_add_drain_all();
  4298. retry:
  4299. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4300. /*
  4301. * Someone who are holding the mmap_sem might be waiting in
  4302. * waitq. So we cancel all extra charges, wake up all waiters,
  4303. * and retry. Because we cancel precharges, we might not be able
  4304. * to move enough charges, but moving charge is a best-effort
  4305. * feature anyway, so it wouldn't be a big problem.
  4306. */
  4307. __mem_cgroup_clear_mc();
  4308. cond_resched();
  4309. goto retry;
  4310. }
  4311. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4312. int ret;
  4313. struct mm_walk mem_cgroup_move_charge_walk = {
  4314. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4315. .mm = mm,
  4316. .private = vma,
  4317. };
  4318. if (is_vm_hugetlb_page(vma))
  4319. continue;
  4320. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4321. &mem_cgroup_move_charge_walk);
  4322. if (ret)
  4323. /*
  4324. * means we have consumed all precharges and failed in
  4325. * doing additional charge. Just abandon here.
  4326. */
  4327. break;
  4328. }
  4329. up_read(&mm->mmap_sem);
  4330. }
  4331. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4332. struct cgroup *cont,
  4333. struct cgroup *old_cont,
  4334. struct task_struct *p,
  4335. bool threadgroup)
  4336. {
  4337. struct mm_struct *mm;
  4338. if (!mc.to)
  4339. /* no need to move charge */
  4340. return;
  4341. mm = get_task_mm(p);
  4342. if (mm) {
  4343. mem_cgroup_move_charge(mm);
  4344. mmput(mm);
  4345. }
  4346. mem_cgroup_clear_mc();
  4347. }
  4348. #else /* !CONFIG_MMU */
  4349. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4350. struct cgroup *cgroup,
  4351. struct task_struct *p,
  4352. bool threadgroup)
  4353. {
  4354. return 0;
  4355. }
  4356. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4357. struct cgroup *cgroup,
  4358. struct task_struct *p,
  4359. bool threadgroup)
  4360. {
  4361. }
  4362. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4363. struct cgroup *cont,
  4364. struct cgroup *old_cont,
  4365. struct task_struct *p,
  4366. bool threadgroup)
  4367. {
  4368. }
  4369. #endif
  4370. struct cgroup_subsys mem_cgroup_subsys = {
  4371. .name = "memory",
  4372. .subsys_id = mem_cgroup_subsys_id,
  4373. .create = mem_cgroup_create,
  4374. .pre_destroy = mem_cgroup_pre_destroy,
  4375. .destroy = mem_cgroup_destroy,
  4376. .populate = mem_cgroup_populate,
  4377. .can_attach = mem_cgroup_can_attach,
  4378. .cancel_attach = mem_cgroup_cancel_attach,
  4379. .attach = mem_cgroup_move_task,
  4380. .early_init = 0,
  4381. .use_id = 1,
  4382. };
  4383. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4384. static int __init enable_swap_account(char *s)
  4385. {
  4386. /* consider enabled if no parameter or 1 is given */
  4387. if (!s || !strcmp(s, "1"))
  4388. really_do_swap_account = 1;
  4389. else if (!strcmp(s, "0"))
  4390. really_do_swap_account = 0;
  4391. return 1;
  4392. }
  4393. __setup("swapaccount", enable_swap_account);
  4394. static int __init disable_swap_account(char *s)
  4395. {
  4396. enable_swap_account("0");
  4397. return 1;
  4398. }
  4399. __setup("noswapaccount", disable_swap_account);
  4400. #endif