memcontrol.c 145 KB

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