memcontrol.c 132 KB

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