memcontrol.c 131 KB

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