memcontrol.c 142 KB

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