memcontrol.c 145 KB

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