memcontrol.c 130 KB

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