memcontrol.c 149 KB

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