memcontrol.c 144 KB

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