memcontrol.c 119 KB

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