memcontrol.c 150 KB

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