memcontrol.c 143 KB

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