memcontrol.c 146 KB

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