memcontrol.c 143 KB

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