memcontrol.c 145 KB

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