memcontrol.c 145 KB

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