memcontrol.c 143 KB

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