memcontrol.c 113 KB

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