memcontrol.c 148 KB

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