memcontrol.c 145 KB

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