memcontrol.c 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /* memcontrol.c - Memory Controller
  3. *
  4. * Copyright IBM Corporation, 2007
  5. * Author Balbir Singh <balbir@linux.vnet.ibm.com>
  6. *
  7. * Copyright 2007 OpenVZ SWsoft Inc
  8. * Author: Pavel Emelianov <xemul@openvz.org>
  9. *
  10. * Memory thresholds
  11. * Copyright (C) 2009 Nokia Corporation
  12. * Author: Kirill A. Shutemov
  13. *
  14. * Kernel Memory Controller
  15. * Copyright (C) 2012 Parallels Inc. and Google Inc.
  16. * Authors: Glauber Costa and Suleiman Souhlal
  17. *
  18. * Native page reclaim
  19. * Charge lifetime sanitation
  20. * Lockless page tracking & accounting
  21. * Unified hierarchy configuration model
  22. * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
  23. *
  24. * Per memcg lru locking
  25. * Copyright (C) 2020 Alibaba, Inc, Alex Shi
  26. */
  27. #include <linux/cgroup-defs.h>
  28. #include <linux/page_counter.h>
  29. #include <linux/memcontrol.h>
  30. #include <linux/cgroup.h>
  31. #include <linux/sched/mm.h>
  32. #include <linux/shmem_fs.h>
  33. #include <linux/hugetlb.h>
  34. #include <linux/pagemap.h>
  35. #include <linux/pagevec.h>
  36. #include <linux/vm_event_item.h>
  37. #include <linux/smp.h>
  38. #include <linux/page-flags.h>
  39. #include <linux/backing-dev.h>
  40. #include <linux/bit_spinlock.h>
  41. #include <linux/rcupdate.h>
  42. #include <linux/limits.h>
  43. #include <linux/export.h>
  44. #include <linux/list.h>
  45. #include <linux/mutex.h>
  46. #include <linux/rbtree.h>
  47. #include <linux/slab.h>
  48. #include <linux/swapops.h>
  49. #include <linux/spinlock.h>
  50. #include <linux/fs.h>
  51. #include <linux/seq_file.h>
  52. #include <linux/parser.h>
  53. #include <linux/vmpressure.h>
  54. #include <linux/memremap.h>
  55. #include <linux/mm_inline.h>
  56. #include <linux/swap_cgroup.h>
  57. #include <linux/cpu.h>
  58. #include <linux/oom.h>
  59. #include <linux/lockdep.h>
  60. #include <linux/resume_user_mode.h>
  61. #include <linux/psi.h>
  62. #include <linux/seq_buf.h>
  63. #include <linux/sched/isolation.h>
  64. #include <linux/kmemleak.h>
  65. #include "internal.h"
  66. #include <net/sock.h>
  67. #include <net/ip.h>
  68. #include "slab.h"
  69. #include "memcontrol-v1.h"
  70. #include <linux/uaccess.h>
  71. #include <trace/events/vmscan.h>
  72. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  73. EXPORT_SYMBOL(memory_cgrp_subsys);
  74. struct mem_cgroup *root_mem_cgroup __read_mostly;
  75. /* Active memory cgroup to use from an interrupt context */
  76. DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
  77. EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
  78. /* Socket memory accounting disabled? */
  79. static bool cgroup_memory_nosocket __ro_after_init;
  80. /* Kernel memory accounting disabled? */
  81. static bool cgroup_memory_nokmem __ro_after_init;
  82. /* BPF memory accounting disabled? */
  83. static bool cgroup_memory_nobpf __ro_after_init;
  84. #ifdef CONFIG_CGROUP_WRITEBACK
  85. static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
  86. #endif
  87. static inline bool task_is_dying(void)
  88. {
  89. return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
  90. (current->flags & PF_EXITING);
  91. }
  92. /* Some nice accessors for the vmpressure. */
  93. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  94. {
  95. if (!memcg)
  96. memcg = root_mem_cgroup;
  97. return &memcg->vmpressure;
  98. }
  99. struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
  100. {
  101. return container_of(vmpr, struct mem_cgroup, vmpressure);
  102. }
  103. #define CURRENT_OBJCG_UPDATE_BIT 0
  104. #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
  105. static DEFINE_SPINLOCK(objcg_lock);
  106. bool mem_cgroup_kmem_disabled(void)
  107. {
  108. return cgroup_memory_nokmem;
  109. }
  110. static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
  111. unsigned int nr_pages);
  112. static void obj_cgroup_release(struct percpu_ref *ref)
  113. {
  114. struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
  115. unsigned int nr_bytes;
  116. unsigned int nr_pages;
  117. unsigned long flags;
  118. /*
  119. * At this point all allocated objects are freed, and
  120. * objcg->nr_charged_bytes can't have an arbitrary byte value.
  121. * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
  122. *
  123. * The following sequence can lead to it:
  124. * 1) CPU0: objcg == stock->cached_objcg
  125. * 2) CPU1: we do a small allocation (e.g. 92 bytes),
  126. * PAGE_SIZE bytes are charged
  127. * 3) CPU1: a process from another memcg is allocating something,
  128. * the stock if flushed,
  129. * objcg->nr_charged_bytes = PAGE_SIZE - 92
  130. * 5) CPU0: we do release this object,
  131. * 92 bytes are added to stock->nr_bytes
  132. * 6) CPU0: stock is flushed,
  133. * 92 bytes are added to objcg->nr_charged_bytes
  134. *
  135. * In the result, nr_charged_bytes == PAGE_SIZE.
  136. * This page will be uncharged in obj_cgroup_release().
  137. */
  138. nr_bytes = atomic_read(&objcg->nr_charged_bytes);
  139. WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
  140. nr_pages = nr_bytes >> PAGE_SHIFT;
  141. if (nr_pages)
  142. obj_cgroup_uncharge_pages(objcg, nr_pages);
  143. spin_lock_irqsave(&objcg_lock, flags);
  144. list_del(&objcg->list);
  145. spin_unlock_irqrestore(&objcg_lock, flags);
  146. percpu_ref_exit(ref);
  147. kfree_rcu(objcg, rcu);
  148. }
  149. static struct obj_cgroup *obj_cgroup_alloc(void)
  150. {
  151. struct obj_cgroup *objcg;
  152. int ret;
  153. objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
  154. if (!objcg)
  155. return NULL;
  156. ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
  157. GFP_KERNEL);
  158. if (ret) {
  159. kfree(objcg);
  160. return NULL;
  161. }
  162. INIT_LIST_HEAD(&objcg->list);
  163. return objcg;
  164. }
  165. static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
  166. struct mem_cgroup *parent)
  167. {
  168. struct obj_cgroup *objcg, *iter;
  169. objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
  170. spin_lock_irq(&objcg_lock);
  171. /* 1) Ready to reparent active objcg. */
  172. list_add(&objcg->list, &memcg->objcg_list);
  173. /* 2) Reparent active objcg and already reparented objcgs to parent. */
  174. list_for_each_entry(iter, &memcg->objcg_list, list)
  175. WRITE_ONCE(iter->memcg, parent);
  176. /* 3) Move already reparented objcgs to the parent's list */
  177. list_splice(&memcg->objcg_list, &parent->objcg_list);
  178. spin_unlock_irq(&objcg_lock);
  179. percpu_ref_kill(&objcg->refcnt);
  180. }
  181. /*
  182. * A lot of the calls to the cache allocation functions are expected to be
  183. * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
  184. * conditional to this static branch, we'll have to allow modules that does
  185. * kmem_cache_alloc and the such to see this symbol as well
  186. */
  187. DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
  188. EXPORT_SYMBOL(memcg_kmem_online_key);
  189. DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
  190. EXPORT_SYMBOL(memcg_bpf_enabled_key);
  191. /**
  192. * mem_cgroup_css_from_folio - css of the memcg associated with a folio
  193. * @folio: folio of interest
  194. *
  195. * If memcg is bound to the default hierarchy, css of the memcg associated
  196. * with @folio is returned. The returned css remains associated with @folio
  197. * until it is released.
  198. *
  199. * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
  200. * is returned.
  201. */
  202. struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
  203. {
  204. struct mem_cgroup *memcg = folio_memcg(folio);
  205. if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  206. memcg = root_mem_cgroup;
  207. return &memcg->css;
  208. }
  209. /**
  210. * page_cgroup_ino - return inode number of the memcg a page is charged to
  211. * @page: the page
  212. *
  213. * Look up the closest online ancestor of the memory cgroup @page is charged to
  214. * and return its inode number or 0 if @page is not charged to any cgroup. It
  215. * is safe to call this function without holding a reference to @page.
  216. *
  217. * Note, this function is inherently racy, because there is nothing to prevent
  218. * the cgroup inode from getting torn down and potentially reallocated a moment
  219. * after page_cgroup_ino() returns, so it only should be used by callers that
  220. * do not care (such as procfs interfaces).
  221. */
  222. ino_t page_cgroup_ino(struct page *page)
  223. {
  224. struct mem_cgroup *memcg;
  225. unsigned long ino = 0;
  226. rcu_read_lock();
  227. /* page_folio() is racy here, but the entire function is racy anyway */
  228. memcg = folio_memcg_check(page_folio(page));
  229. while (memcg && !(memcg->css.flags & CSS_ONLINE))
  230. memcg = parent_mem_cgroup(memcg);
  231. if (memcg)
  232. ino = cgroup_ino(memcg->css.cgroup);
  233. rcu_read_unlock();
  234. return ino;
  235. }
  236. /* Subset of node_stat_item for memcg stats */
  237. static const unsigned int memcg_node_stat_items[] = {
  238. NR_INACTIVE_ANON,
  239. NR_ACTIVE_ANON,
  240. NR_INACTIVE_FILE,
  241. NR_ACTIVE_FILE,
  242. NR_UNEVICTABLE,
  243. NR_SLAB_RECLAIMABLE_B,
  244. NR_SLAB_UNRECLAIMABLE_B,
  245. WORKINGSET_REFAULT_ANON,
  246. WORKINGSET_REFAULT_FILE,
  247. WORKINGSET_ACTIVATE_ANON,
  248. WORKINGSET_ACTIVATE_FILE,
  249. WORKINGSET_RESTORE_ANON,
  250. WORKINGSET_RESTORE_FILE,
  251. WORKINGSET_NODERECLAIM,
  252. NR_ANON_MAPPED,
  253. NR_FILE_MAPPED,
  254. NR_FILE_PAGES,
  255. NR_FILE_DIRTY,
  256. NR_WRITEBACK,
  257. NR_SHMEM,
  258. NR_SHMEM_THPS,
  259. NR_FILE_THPS,
  260. NR_ANON_THPS,
  261. NR_KERNEL_STACK_KB,
  262. NR_PAGETABLE,
  263. NR_SECONDARY_PAGETABLE,
  264. #ifdef CONFIG_SWAP
  265. NR_SWAPCACHE,
  266. #endif
  267. #ifdef CONFIG_NUMA_BALANCING
  268. PGPROMOTE_SUCCESS,
  269. #endif
  270. PGDEMOTE_KSWAPD,
  271. PGDEMOTE_DIRECT,
  272. PGDEMOTE_KHUGEPAGED,
  273. };
  274. static const unsigned int memcg_stat_items[] = {
  275. MEMCG_SWAP,
  276. MEMCG_SOCK,
  277. MEMCG_PERCPU_B,
  278. MEMCG_VMALLOC,
  279. MEMCG_KMEM,
  280. MEMCG_ZSWAP_B,
  281. MEMCG_ZSWAPPED,
  282. };
  283. #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
  284. #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
  285. ARRAY_SIZE(memcg_stat_items))
  286. #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
  287. static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
  288. static void init_memcg_stats(void)
  289. {
  290. u8 i, j = 0;
  291. BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
  292. memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
  293. for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
  294. mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
  295. for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
  296. mem_cgroup_stats_index[memcg_stat_items[i]] = j;
  297. }
  298. static inline int memcg_stats_index(int idx)
  299. {
  300. return mem_cgroup_stats_index[idx];
  301. }
  302. struct lruvec_stats_percpu {
  303. /* Local (CPU and cgroup) state */
  304. long state[NR_MEMCG_NODE_STAT_ITEMS];
  305. /* Delta calculation for lockless upward propagation */
  306. long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
  307. };
  308. struct lruvec_stats {
  309. /* Aggregated (CPU and subtree) state */
  310. long state[NR_MEMCG_NODE_STAT_ITEMS];
  311. /* Non-hierarchical (CPU aggregated) state */
  312. long state_local[NR_MEMCG_NODE_STAT_ITEMS];
  313. /* Pending child counts during tree propagation */
  314. long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
  315. };
  316. unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
  317. {
  318. struct mem_cgroup_per_node *pn;
  319. long x;
  320. int i;
  321. if (mem_cgroup_disabled())
  322. return node_page_state(lruvec_pgdat(lruvec), idx);
  323. i = memcg_stats_index(idx);
  324. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  325. return 0;
  326. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  327. x = READ_ONCE(pn->lruvec_stats->state[i]);
  328. #ifdef CONFIG_SMP
  329. if (x < 0)
  330. x = 0;
  331. #endif
  332. return x;
  333. }
  334. unsigned long lruvec_page_state_local(struct lruvec *lruvec,
  335. enum node_stat_item idx)
  336. {
  337. struct mem_cgroup_per_node *pn;
  338. long x;
  339. int i;
  340. if (mem_cgroup_disabled())
  341. return node_page_state(lruvec_pgdat(lruvec), idx);
  342. i = memcg_stats_index(idx);
  343. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  344. return 0;
  345. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  346. x = READ_ONCE(pn->lruvec_stats->state_local[i]);
  347. #ifdef CONFIG_SMP
  348. if (x < 0)
  349. x = 0;
  350. #endif
  351. return x;
  352. }
  353. /* Subset of vm_event_item to report for memcg event stats */
  354. static const unsigned int memcg_vm_event_stat[] = {
  355. #ifdef CONFIG_MEMCG_V1
  356. PGPGIN,
  357. PGPGOUT,
  358. #endif
  359. PGSCAN_KSWAPD,
  360. PGSCAN_DIRECT,
  361. PGSCAN_KHUGEPAGED,
  362. PGSTEAL_KSWAPD,
  363. PGSTEAL_DIRECT,
  364. PGSTEAL_KHUGEPAGED,
  365. PGFAULT,
  366. PGMAJFAULT,
  367. PGREFILL,
  368. PGACTIVATE,
  369. PGDEACTIVATE,
  370. PGLAZYFREE,
  371. PGLAZYFREED,
  372. #ifdef CONFIG_SWAP
  373. SWPIN_ZERO,
  374. SWPOUT_ZERO,
  375. #endif
  376. #ifdef CONFIG_ZSWAP
  377. ZSWPIN,
  378. ZSWPOUT,
  379. ZSWPWB,
  380. #endif
  381. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  382. THP_FAULT_ALLOC,
  383. THP_COLLAPSE_ALLOC,
  384. THP_SWPOUT,
  385. THP_SWPOUT_FALLBACK,
  386. #endif
  387. #ifdef CONFIG_NUMA_BALANCING
  388. NUMA_PAGE_MIGRATE,
  389. NUMA_PTE_UPDATES,
  390. NUMA_HINT_FAULTS,
  391. #endif
  392. };
  393. #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
  394. static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
  395. static void init_memcg_events(void)
  396. {
  397. u8 i;
  398. BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
  399. memset(mem_cgroup_events_index, U8_MAX,
  400. sizeof(mem_cgroup_events_index));
  401. for (i = 0; i < NR_MEMCG_EVENTS; ++i)
  402. mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
  403. }
  404. static inline int memcg_events_index(enum vm_event_item idx)
  405. {
  406. return mem_cgroup_events_index[idx];
  407. }
  408. struct memcg_vmstats_percpu {
  409. /* Stats updates since the last flush */
  410. unsigned int stats_updates;
  411. /* Cached pointers for fast iteration in memcg_rstat_updated() */
  412. struct memcg_vmstats_percpu *parent;
  413. struct memcg_vmstats *vmstats;
  414. /* The above should fit a single cacheline for memcg_rstat_updated() */
  415. /* Local (CPU and cgroup) page state & events */
  416. long state[MEMCG_VMSTAT_SIZE];
  417. unsigned long events[NR_MEMCG_EVENTS];
  418. /* Delta calculation for lockless upward propagation */
  419. long state_prev[MEMCG_VMSTAT_SIZE];
  420. unsigned long events_prev[NR_MEMCG_EVENTS];
  421. } ____cacheline_aligned;
  422. struct memcg_vmstats {
  423. /* Aggregated (CPU and subtree) page state & events */
  424. long state[MEMCG_VMSTAT_SIZE];
  425. unsigned long events[NR_MEMCG_EVENTS];
  426. /* Non-hierarchical (CPU aggregated) page state & events */
  427. long state_local[MEMCG_VMSTAT_SIZE];
  428. unsigned long events_local[NR_MEMCG_EVENTS];
  429. /* Pending child counts during tree propagation */
  430. long state_pending[MEMCG_VMSTAT_SIZE];
  431. unsigned long events_pending[NR_MEMCG_EVENTS];
  432. /* Stats updates since the last flush */
  433. atomic64_t stats_updates;
  434. };
  435. /*
  436. * memcg and lruvec stats flushing
  437. *
  438. * Many codepaths leading to stats update or read are performance sensitive and
  439. * adding stats flushing in such codepaths is not desirable. So, to optimize the
  440. * flushing the kernel does:
  441. *
  442. * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
  443. * rstat update tree grow unbounded.
  444. *
  445. * 2) Flush the stats synchronously on reader side only when there are more than
  446. * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
  447. * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
  448. * only for 2 seconds due to (1).
  449. */
  450. static void flush_memcg_stats_dwork(struct work_struct *w);
  451. static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
  452. static u64 flush_last_time;
  453. #define FLUSH_TIME (2UL*HZ)
  454. /*
  455. * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
  456. * not rely on this as part of an acquired spinlock_t lock. These functions are
  457. * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
  458. * is sufficient.
  459. */
  460. static void memcg_stats_lock(void)
  461. {
  462. preempt_disable_nested();
  463. VM_WARN_ON_IRQS_ENABLED();
  464. }
  465. static void __memcg_stats_lock(void)
  466. {
  467. preempt_disable_nested();
  468. }
  469. static void memcg_stats_unlock(void)
  470. {
  471. preempt_enable_nested();
  472. }
  473. static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
  474. {
  475. return atomic64_read(&vmstats->stats_updates) >
  476. MEMCG_CHARGE_BATCH * num_online_cpus();
  477. }
  478. static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
  479. {
  480. struct memcg_vmstats_percpu *statc;
  481. int cpu = smp_processor_id();
  482. unsigned int stats_updates;
  483. if (!val)
  484. return;
  485. cgroup_rstat_updated(memcg->css.cgroup, cpu);
  486. statc = this_cpu_ptr(memcg->vmstats_percpu);
  487. for (; statc; statc = statc->parent) {
  488. stats_updates = READ_ONCE(statc->stats_updates) + abs(val);
  489. WRITE_ONCE(statc->stats_updates, stats_updates);
  490. if (stats_updates < MEMCG_CHARGE_BATCH)
  491. continue;
  492. /*
  493. * If @memcg is already flush-able, increasing stats_updates is
  494. * redundant. Avoid the overhead of the atomic update.
  495. */
  496. if (!memcg_vmstats_needs_flush(statc->vmstats))
  497. atomic64_add(stats_updates,
  498. &statc->vmstats->stats_updates);
  499. WRITE_ONCE(statc->stats_updates, 0);
  500. }
  501. }
  502. static void do_flush_stats(struct mem_cgroup *memcg)
  503. {
  504. if (mem_cgroup_is_root(memcg))
  505. WRITE_ONCE(flush_last_time, jiffies_64);
  506. cgroup_rstat_flush(memcg->css.cgroup);
  507. }
  508. /*
  509. * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
  510. * @memcg: root of the subtree to flush
  511. *
  512. * Flushing is serialized by the underlying global rstat lock. There is also a
  513. * minimum amount of work to be done even if there are no stat updates to flush.
  514. * Hence, we only flush the stats if the updates delta exceeds a threshold. This
  515. * avoids unnecessary work and contention on the underlying lock.
  516. */
  517. void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
  518. {
  519. if (mem_cgroup_disabled())
  520. return;
  521. if (!memcg)
  522. memcg = root_mem_cgroup;
  523. if (memcg_vmstats_needs_flush(memcg->vmstats))
  524. do_flush_stats(memcg);
  525. }
  526. void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
  527. {
  528. /* Only flush if the periodic flusher is one full cycle late */
  529. if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
  530. mem_cgroup_flush_stats(memcg);
  531. }
  532. static void flush_memcg_stats_dwork(struct work_struct *w)
  533. {
  534. /*
  535. * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
  536. * in latency-sensitive paths is as cheap as possible.
  537. */
  538. do_flush_stats(root_mem_cgroup);
  539. queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
  540. }
  541. unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
  542. {
  543. long x;
  544. int i = memcg_stats_index(idx);
  545. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  546. return 0;
  547. x = READ_ONCE(memcg->vmstats->state[i]);
  548. #ifdef CONFIG_SMP
  549. if (x < 0)
  550. x = 0;
  551. #endif
  552. return x;
  553. }
  554. static int memcg_page_state_unit(int item);
  555. /*
  556. * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
  557. * up non-zero sub-page updates to 1 page as zero page updates are ignored.
  558. */
  559. static int memcg_state_val_in_pages(int idx, int val)
  560. {
  561. int unit = memcg_page_state_unit(idx);
  562. if (!val || unit == PAGE_SIZE)
  563. return val;
  564. else
  565. return max(val * unit / PAGE_SIZE, 1UL);
  566. }
  567. /**
  568. * __mod_memcg_state - update cgroup memory statistics
  569. * @memcg: the memory cgroup
  570. * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
  571. * @val: delta to add to the counter, can be negative
  572. */
  573. void __mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
  574. int val)
  575. {
  576. int i = memcg_stats_index(idx);
  577. if (mem_cgroup_disabled())
  578. return;
  579. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  580. return;
  581. __this_cpu_add(memcg->vmstats_percpu->state[i], val);
  582. memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
  583. }
  584. /* idx can be of type enum memcg_stat_item or node_stat_item. */
  585. unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
  586. {
  587. long x;
  588. int i = memcg_stats_index(idx);
  589. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  590. return 0;
  591. x = READ_ONCE(memcg->vmstats->state_local[i]);
  592. #ifdef CONFIG_SMP
  593. if (x < 0)
  594. x = 0;
  595. #endif
  596. return x;
  597. }
  598. static void __mod_memcg_lruvec_state(struct lruvec *lruvec,
  599. enum node_stat_item idx,
  600. int val)
  601. {
  602. struct mem_cgroup_per_node *pn;
  603. struct mem_cgroup *memcg;
  604. int i = memcg_stats_index(idx);
  605. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  606. return;
  607. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  608. memcg = pn->memcg;
  609. /*
  610. * The caller from rmap relies on disabled preemption because they never
  611. * update their counter from in-interrupt context. For these two
  612. * counters we check that the update is never performed from an
  613. * interrupt context while other caller need to have disabled interrupt.
  614. */
  615. __memcg_stats_lock();
  616. if (IS_ENABLED(CONFIG_DEBUG_VM)) {
  617. switch (idx) {
  618. case NR_ANON_MAPPED:
  619. case NR_FILE_MAPPED:
  620. case NR_ANON_THPS:
  621. WARN_ON_ONCE(!in_task());
  622. break;
  623. default:
  624. VM_WARN_ON_IRQS_ENABLED();
  625. }
  626. }
  627. /* Update memcg */
  628. __this_cpu_add(memcg->vmstats_percpu->state[i], val);
  629. /* Update lruvec */
  630. __this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
  631. memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
  632. memcg_stats_unlock();
  633. }
  634. /**
  635. * __mod_lruvec_state - update lruvec memory statistics
  636. * @lruvec: the lruvec
  637. * @idx: the stat item
  638. * @val: delta to add to the counter, can be negative
  639. *
  640. * The lruvec is the intersection of the NUMA node and a cgroup. This
  641. * function updates the all three counters that are affected by a
  642. * change of state at this level: per-node, per-cgroup, per-lruvec.
  643. */
  644. void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
  645. int val)
  646. {
  647. /* Update node */
  648. __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
  649. /* Update memcg and lruvec */
  650. if (!mem_cgroup_disabled())
  651. __mod_memcg_lruvec_state(lruvec, idx, val);
  652. }
  653. void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
  654. int val)
  655. {
  656. struct mem_cgroup *memcg;
  657. pg_data_t *pgdat = folio_pgdat(folio);
  658. struct lruvec *lruvec;
  659. rcu_read_lock();
  660. memcg = folio_memcg(folio);
  661. /* Untracked pages have no memcg, no lruvec. Update only the node */
  662. if (!memcg) {
  663. rcu_read_unlock();
  664. __mod_node_page_state(pgdat, idx, val);
  665. return;
  666. }
  667. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  668. __mod_lruvec_state(lruvec, idx, val);
  669. rcu_read_unlock();
  670. }
  671. EXPORT_SYMBOL(__lruvec_stat_mod_folio);
  672. void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
  673. {
  674. pg_data_t *pgdat = page_pgdat(virt_to_page(p));
  675. struct mem_cgroup *memcg;
  676. struct lruvec *lruvec;
  677. rcu_read_lock();
  678. memcg = mem_cgroup_from_slab_obj(p);
  679. /*
  680. * Untracked pages have no memcg, no lruvec. Update only the
  681. * node. If we reparent the slab objects to the root memcg,
  682. * when we free the slab object, we need to update the per-memcg
  683. * vmstats to keep it correct for the root memcg.
  684. */
  685. if (!memcg) {
  686. __mod_node_page_state(pgdat, idx, val);
  687. } else {
  688. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  689. __mod_lruvec_state(lruvec, idx, val);
  690. }
  691. rcu_read_unlock();
  692. }
  693. /**
  694. * __count_memcg_events - account VM events in a cgroup
  695. * @memcg: the memory cgroup
  696. * @idx: the event item
  697. * @count: the number of events that occurred
  698. */
  699. void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
  700. unsigned long count)
  701. {
  702. int i = memcg_events_index(idx);
  703. if (mem_cgroup_disabled())
  704. return;
  705. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  706. return;
  707. memcg_stats_lock();
  708. __this_cpu_add(memcg->vmstats_percpu->events[i], count);
  709. memcg_rstat_updated(memcg, count);
  710. memcg_stats_unlock();
  711. }
  712. unsigned long memcg_events(struct mem_cgroup *memcg, int event)
  713. {
  714. int i = memcg_events_index(event);
  715. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
  716. return 0;
  717. return READ_ONCE(memcg->vmstats->events[i]);
  718. }
  719. unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
  720. {
  721. int i = memcg_events_index(event);
  722. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
  723. return 0;
  724. return READ_ONCE(memcg->vmstats->events_local[i]);
  725. }
  726. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  727. {
  728. /*
  729. * mm_update_next_owner() may clear mm->owner to NULL
  730. * if it races with swapoff, page migration, etc.
  731. * So this can be called with p == NULL.
  732. */
  733. if (unlikely(!p))
  734. return NULL;
  735. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  736. }
  737. EXPORT_SYMBOL(mem_cgroup_from_task);
  738. static __always_inline struct mem_cgroup *active_memcg(void)
  739. {
  740. if (!in_task())
  741. return this_cpu_read(int_active_memcg);
  742. else
  743. return current->active_memcg;
  744. }
  745. /**
  746. * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
  747. * @mm: mm from which memcg should be extracted. It can be NULL.
  748. *
  749. * Obtain a reference on mm->memcg and returns it if successful. If mm
  750. * is NULL, then the memcg is chosen as follows:
  751. * 1) The active memcg, if set.
  752. * 2) current->mm->memcg, if available
  753. * 3) root memcg
  754. * If mem_cgroup is disabled, NULL is returned.
  755. */
  756. struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  757. {
  758. struct mem_cgroup *memcg;
  759. if (mem_cgroup_disabled())
  760. return NULL;
  761. /*
  762. * Page cache insertions can happen without an
  763. * actual mm context, e.g. during disk probing
  764. * on boot, loopback IO, acct() writes etc.
  765. *
  766. * No need to css_get on root memcg as the reference
  767. * counting is disabled on the root level in the
  768. * cgroup core. See CSS_NO_REF.
  769. */
  770. if (unlikely(!mm)) {
  771. memcg = active_memcg();
  772. if (unlikely(memcg)) {
  773. /* remote memcg must hold a ref */
  774. css_get(&memcg->css);
  775. return memcg;
  776. }
  777. mm = current->mm;
  778. if (unlikely(!mm))
  779. return root_mem_cgroup;
  780. }
  781. rcu_read_lock();
  782. do {
  783. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  784. if (unlikely(!memcg))
  785. memcg = root_mem_cgroup;
  786. } while (!css_tryget(&memcg->css));
  787. rcu_read_unlock();
  788. return memcg;
  789. }
  790. EXPORT_SYMBOL(get_mem_cgroup_from_mm);
  791. /**
  792. * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
  793. */
  794. struct mem_cgroup *get_mem_cgroup_from_current(void)
  795. {
  796. struct mem_cgroup *memcg;
  797. if (mem_cgroup_disabled())
  798. return NULL;
  799. again:
  800. rcu_read_lock();
  801. memcg = mem_cgroup_from_task(current);
  802. if (!css_tryget(&memcg->css)) {
  803. rcu_read_unlock();
  804. goto again;
  805. }
  806. rcu_read_unlock();
  807. return memcg;
  808. }
  809. /**
  810. * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg.
  811. * @folio: folio from which memcg should be extracted.
  812. */
  813. struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
  814. {
  815. struct mem_cgroup *memcg = folio_memcg(folio);
  816. if (mem_cgroup_disabled())
  817. return NULL;
  818. rcu_read_lock();
  819. if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
  820. memcg = root_mem_cgroup;
  821. rcu_read_unlock();
  822. return memcg;
  823. }
  824. /**
  825. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  826. * @root: hierarchy root
  827. * @prev: previously returned memcg, NULL on first invocation
  828. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  829. *
  830. * Returns references to children of the hierarchy below @root, or
  831. * @root itself, or %NULL after a full round-trip.
  832. *
  833. * Caller must pass the return value in @prev on subsequent
  834. * invocations for reference counting, or use mem_cgroup_iter_break()
  835. * to cancel a hierarchy walk before the round-trip is complete.
  836. *
  837. * Reclaimers can specify a node in @reclaim to divide up the memcgs
  838. * in the hierarchy among all concurrent reclaimers operating on the
  839. * same node.
  840. */
  841. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  842. struct mem_cgroup *prev,
  843. struct mem_cgroup_reclaim_cookie *reclaim)
  844. {
  845. struct mem_cgroup_reclaim_iter *iter;
  846. struct cgroup_subsys_state *css;
  847. struct mem_cgroup *pos;
  848. struct mem_cgroup *next;
  849. if (mem_cgroup_disabled())
  850. return NULL;
  851. if (!root)
  852. root = root_mem_cgroup;
  853. rcu_read_lock();
  854. restart:
  855. next = NULL;
  856. if (reclaim) {
  857. int gen;
  858. int nid = reclaim->pgdat->node_id;
  859. iter = &root->nodeinfo[nid]->iter;
  860. gen = atomic_read(&iter->generation);
  861. /*
  862. * On start, join the current reclaim iteration cycle.
  863. * Exit when a concurrent walker completes it.
  864. */
  865. if (!prev)
  866. reclaim->generation = gen;
  867. else if (reclaim->generation != gen)
  868. goto out_unlock;
  869. pos = READ_ONCE(iter->position);
  870. } else
  871. pos = prev;
  872. css = pos ? &pos->css : NULL;
  873. while ((css = css_next_descendant_pre(css, &root->css))) {
  874. /*
  875. * Verify the css and acquire a reference. The root
  876. * is provided by the caller, so we know it's alive
  877. * and kicking, and don't take an extra reference.
  878. */
  879. if (css == &root->css || css_tryget(css))
  880. break;
  881. }
  882. next = mem_cgroup_from_css(css);
  883. if (reclaim) {
  884. /*
  885. * The position could have already been updated by a competing
  886. * thread, so check that the value hasn't changed since we read
  887. * it to avoid reclaiming from the same cgroup twice.
  888. */
  889. if (cmpxchg(&iter->position, pos, next) != pos) {
  890. if (css && css != &root->css)
  891. css_put(css);
  892. goto restart;
  893. }
  894. if (!next) {
  895. atomic_inc(&iter->generation);
  896. /*
  897. * Reclaimers share the hierarchy walk, and a
  898. * new one might jump in right at the end of
  899. * the hierarchy - make sure they see at least
  900. * one group and restart from the beginning.
  901. */
  902. if (!prev)
  903. goto restart;
  904. }
  905. }
  906. out_unlock:
  907. rcu_read_unlock();
  908. if (prev && prev != root)
  909. css_put(&prev->css);
  910. return next;
  911. }
  912. /**
  913. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  914. * @root: hierarchy root
  915. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  916. */
  917. void mem_cgroup_iter_break(struct mem_cgroup *root,
  918. struct mem_cgroup *prev)
  919. {
  920. if (!root)
  921. root = root_mem_cgroup;
  922. if (prev && prev != root)
  923. css_put(&prev->css);
  924. }
  925. static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
  926. struct mem_cgroup *dead_memcg)
  927. {
  928. struct mem_cgroup_reclaim_iter *iter;
  929. struct mem_cgroup_per_node *mz;
  930. int nid;
  931. for_each_node(nid) {
  932. mz = from->nodeinfo[nid];
  933. iter = &mz->iter;
  934. cmpxchg(&iter->position, dead_memcg, NULL);
  935. }
  936. }
  937. static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
  938. {
  939. struct mem_cgroup *memcg = dead_memcg;
  940. struct mem_cgroup *last;
  941. do {
  942. __invalidate_reclaim_iterators(memcg, dead_memcg);
  943. last = memcg;
  944. } while ((memcg = parent_mem_cgroup(memcg)));
  945. /*
  946. * When cgroup1 non-hierarchy mode is used,
  947. * parent_mem_cgroup() does not walk all the way up to the
  948. * cgroup root (root_mem_cgroup). So we have to handle
  949. * dead_memcg from cgroup root separately.
  950. */
  951. if (!mem_cgroup_is_root(last))
  952. __invalidate_reclaim_iterators(root_mem_cgroup,
  953. dead_memcg);
  954. }
  955. /**
  956. * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
  957. * @memcg: hierarchy root
  958. * @fn: function to call for each task
  959. * @arg: argument passed to @fn
  960. *
  961. * This function iterates over tasks attached to @memcg or to any of its
  962. * descendants and calls @fn for each task. If @fn returns a non-zero
  963. * value, the function breaks the iteration loop. Otherwise, it will iterate
  964. * over all tasks and return 0.
  965. *
  966. * This function must not be called for the root memory cgroup.
  967. */
  968. void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
  969. int (*fn)(struct task_struct *, void *), void *arg)
  970. {
  971. struct mem_cgroup *iter;
  972. int ret = 0;
  973. int i = 0;
  974. BUG_ON(mem_cgroup_is_root(memcg));
  975. for_each_mem_cgroup_tree(iter, memcg) {
  976. struct css_task_iter it;
  977. struct task_struct *task;
  978. css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
  979. while (!ret && (task = css_task_iter_next(&it))) {
  980. /* Avoid potential softlockup warning */
  981. if ((++i & 1023) == 0)
  982. cond_resched();
  983. ret = fn(task, arg);
  984. }
  985. css_task_iter_end(&it);
  986. if (ret) {
  987. mem_cgroup_iter_break(memcg, iter);
  988. break;
  989. }
  990. }
  991. }
  992. #ifdef CONFIG_DEBUG_VM
  993. void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
  994. {
  995. struct mem_cgroup *memcg;
  996. if (mem_cgroup_disabled())
  997. return;
  998. memcg = folio_memcg(folio);
  999. if (!memcg)
  1000. VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
  1001. else
  1002. VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
  1003. }
  1004. #endif
  1005. /**
  1006. * folio_lruvec_lock - Lock the lruvec for a folio.
  1007. * @folio: Pointer to the folio.
  1008. *
  1009. * These functions are safe to use under any of the following conditions:
  1010. * - folio locked
  1011. * - folio_test_lru false
  1012. * - folio_memcg_lock()
  1013. * - folio frozen (refcount of 0)
  1014. *
  1015. * Return: The lruvec this folio is on with its lock held.
  1016. */
  1017. struct lruvec *folio_lruvec_lock(struct folio *folio)
  1018. {
  1019. struct lruvec *lruvec = folio_lruvec(folio);
  1020. spin_lock(&lruvec->lru_lock);
  1021. lruvec_memcg_debug(lruvec, folio);
  1022. return lruvec;
  1023. }
  1024. /**
  1025. * folio_lruvec_lock_irq - Lock the lruvec for a folio.
  1026. * @folio: Pointer to the folio.
  1027. *
  1028. * These functions are safe to use under any of the following conditions:
  1029. * - folio locked
  1030. * - folio_test_lru false
  1031. * - folio_memcg_lock()
  1032. * - folio frozen (refcount of 0)
  1033. *
  1034. * Return: The lruvec this folio is on with its lock held and interrupts
  1035. * disabled.
  1036. */
  1037. struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
  1038. {
  1039. struct lruvec *lruvec = folio_lruvec(folio);
  1040. spin_lock_irq(&lruvec->lru_lock);
  1041. lruvec_memcg_debug(lruvec, folio);
  1042. return lruvec;
  1043. }
  1044. /**
  1045. * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
  1046. * @folio: Pointer to the folio.
  1047. * @flags: Pointer to irqsave flags.
  1048. *
  1049. * These functions are safe to use under any of the following conditions:
  1050. * - folio locked
  1051. * - folio_test_lru false
  1052. * - folio_memcg_lock()
  1053. * - folio frozen (refcount of 0)
  1054. *
  1055. * Return: The lruvec this folio is on with its lock held and interrupts
  1056. * disabled.
  1057. */
  1058. struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
  1059. unsigned long *flags)
  1060. {
  1061. struct lruvec *lruvec = folio_lruvec(folio);
  1062. spin_lock_irqsave(&lruvec->lru_lock, *flags);
  1063. lruvec_memcg_debug(lruvec, folio);
  1064. return lruvec;
  1065. }
  1066. /**
  1067. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  1068. * @lruvec: mem_cgroup per zone lru vector
  1069. * @lru: index of lru list the page is sitting on
  1070. * @zid: zone id of the accounted pages
  1071. * @nr_pages: positive when adding or negative when removing
  1072. *
  1073. * This function must be called under lru_lock, just before a page is added
  1074. * to or just after a page is removed from an lru list.
  1075. */
  1076. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  1077. int zid, int nr_pages)
  1078. {
  1079. struct mem_cgroup_per_node *mz;
  1080. unsigned long *lru_size;
  1081. long size;
  1082. if (mem_cgroup_disabled())
  1083. return;
  1084. mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  1085. lru_size = &mz->lru_zone_size[zid][lru];
  1086. if (nr_pages < 0)
  1087. *lru_size += nr_pages;
  1088. size = *lru_size;
  1089. if (WARN_ONCE(size < 0,
  1090. "%s(%p, %d, %d): lru_size %ld\n",
  1091. __func__, lruvec, lru, nr_pages, size)) {
  1092. VM_BUG_ON(1);
  1093. *lru_size = 0;
  1094. }
  1095. if (nr_pages > 0)
  1096. *lru_size += nr_pages;
  1097. }
  1098. /**
  1099. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1100. * @memcg: the memory cgroup
  1101. *
  1102. * Returns the maximum amount of memory @mem can be charged with, in
  1103. * pages.
  1104. */
  1105. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1106. {
  1107. unsigned long margin = 0;
  1108. unsigned long count;
  1109. unsigned long limit;
  1110. count = page_counter_read(&memcg->memory);
  1111. limit = READ_ONCE(memcg->memory.max);
  1112. if (count < limit)
  1113. margin = limit - count;
  1114. if (do_memsw_account()) {
  1115. count = page_counter_read(&memcg->memsw);
  1116. limit = READ_ONCE(memcg->memsw.max);
  1117. if (count < limit)
  1118. margin = min(margin, limit - count);
  1119. else
  1120. margin = 0;
  1121. }
  1122. return margin;
  1123. }
  1124. struct memory_stat {
  1125. const char *name;
  1126. unsigned int idx;
  1127. };
  1128. static const struct memory_stat memory_stats[] = {
  1129. { "anon", NR_ANON_MAPPED },
  1130. { "file", NR_FILE_PAGES },
  1131. { "kernel", MEMCG_KMEM },
  1132. { "kernel_stack", NR_KERNEL_STACK_KB },
  1133. { "pagetables", NR_PAGETABLE },
  1134. { "sec_pagetables", NR_SECONDARY_PAGETABLE },
  1135. { "percpu", MEMCG_PERCPU_B },
  1136. { "sock", MEMCG_SOCK },
  1137. { "vmalloc", MEMCG_VMALLOC },
  1138. { "shmem", NR_SHMEM },
  1139. #ifdef CONFIG_ZSWAP
  1140. { "zswap", MEMCG_ZSWAP_B },
  1141. { "zswapped", MEMCG_ZSWAPPED },
  1142. #endif
  1143. { "file_mapped", NR_FILE_MAPPED },
  1144. { "file_dirty", NR_FILE_DIRTY },
  1145. { "file_writeback", NR_WRITEBACK },
  1146. #ifdef CONFIG_SWAP
  1147. { "swapcached", NR_SWAPCACHE },
  1148. #endif
  1149. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1150. { "anon_thp", NR_ANON_THPS },
  1151. { "file_thp", NR_FILE_THPS },
  1152. { "shmem_thp", NR_SHMEM_THPS },
  1153. #endif
  1154. { "inactive_anon", NR_INACTIVE_ANON },
  1155. { "active_anon", NR_ACTIVE_ANON },
  1156. { "inactive_file", NR_INACTIVE_FILE },
  1157. { "active_file", NR_ACTIVE_FILE },
  1158. { "unevictable", NR_UNEVICTABLE },
  1159. { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
  1160. { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
  1161. /* The memory events */
  1162. { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
  1163. { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
  1164. { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
  1165. { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
  1166. { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
  1167. { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
  1168. { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
  1169. { "pgdemote_kswapd", PGDEMOTE_KSWAPD },
  1170. { "pgdemote_direct", PGDEMOTE_DIRECT },
  1171. { "pgdemote_khugepaged", PGDEMOTE_KHUGEPAGED },
  1172. #ifdef CONFIG_NUMA_BALANCING
  1173. { "pgpromote_success", PGPROMOTE_SUCCESS },
  1174. #endif
  1175. };
  1176. /* The actual unit of the state item, not the same as the output unit */
  1177. static int memcg_page_state_unit(int item)
  1178. {
  1179. switch (item) {
  1180. case MEMCG_PERCPU_B:
  1181. case MEMCG_ZSWAP_B:
  1182. case NR_SLAB_RECLAIMABLE_B:
  1183. case NR_SLAB_UNRECLAIMABLE_B:
  1184. return 1;
  1185. case NR_KERNEL_STACK_KB:
  1186. return SZ_1K;
  1187. default:
  1188. return PAGE_SIZE;
  1189. }
  1190. }
  1191. /* Translate stat items to the correct unit for memory.stat output */
  1192. static int memcg_page_state_output_unit(int item)
  1193. {
  1194. /*
  1195. * Workingset state is actually in pages, but we export it to userspace
  1196. * as a scalar count of events, so special case it here.
  1197. *
  1198. * Demotion and promotion activities are exported in pages, consistent
  1199. * with their global counterparts.
  1200. */
  1201. switch (item) {
  1202. case WORKINGSET_REFAULT_ANON:
  1203. case WORKINGSET_REFAULT_FILE:
  1204. case WORKINGSET_ACTIVATE_ANON:
  1205. case WORKINGSET_ACTIVATE_FILE:
  1206. case WORKINGSET_RESTORE_ANON:
  1207. case WORKINGSET_RESTORE_FILE:
  1208. case WORKINGSET_NODERECLAIM:
  1209. case PGDEMOTE_KSWAPD:
  1210. case PGDEMOTE_DIRECT:
  1211. case PGDEMOTE_KHUGEPAGED:
  1212. #ifdef CONFIG_NUMA_BALANCING
  1213. case PGPROMOTE_SUCCESS:
  1214. #endif
  1215. return 1;
  1216. default:
  1217. return memcg_page_state_unit(item);
  1218. }
  1219. }
  1220. unsigned long memcg_page_state_output(struct mem_cgroup *memcg, int item)
  1221. {
  1222. return memcg_page_state(memcg, item) *
  1223. memcg_page_state_output_unit(item);
  1224. }
  1225. unsigned long memcg_page_state_local_output(struct mem_cgroup *memcg, int item)
  1226. {
  1227. return memcg_page_state_local(memcg, item) *
  1228. memcg_page_state_output_unit(item);
  1229. }
  1230. static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
  1231. {
  1232. int i;
  1233. /*
  1234. * Provide statistics on the state of the memory subsystem as
  1235. * well as cumulative event counters that show past behavior.
  1236. *
  1237. * This list is ordered following a combination of these gradients:
  1238. * 1) generic big picture -> specifics and details
  1239. * 2) reflecting userspace activity -> reflecting kernel heuristics
  1240. *
  1241. * Current memory state:
  1242. */
  1243. mem_cgroup_flush_stats(memcg);
  1244. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  1245. u64 size;
  1246. size = memcg_page_state_output(memcg, memory_stats[i].idx);
  1247. seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
  1248. if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
  1249. size += memcg_page_state_output(memcg,
  1250. NR_SLAB_RECLAIMABLE_B);
  1251. seq_buf_printf(s, "slab %llu\n", size);
  1252. }
  1253. }
  1254. /* Accumulated memory events */
  1255. seq_buf_printf(s, "pgscan %lu\n",
  1256. memcg_events(memcg, PGSCAN_KSWAPD) +
  1257. memcg_events(memcg, PGSCAN_DIRECT) +
  1258. memcg_events(memcg, PGSCAN_KHUGEPAGED));
  1259. seq_buf_printf(s, "pgsteal %lu\n",
  1260. memcg_events(memcg, PGSTEAL_KSWAPD) +
  1261. memcg_events(memcg, PGSTEAL_DIRECT) +
  1262. memcg_events(memcg, PGSTEAL_KHUGEPAGED));
  1263. for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
  1264. #ifdef CONFIG_MEMCG_V1
  1265. if (memcg_vm_event_stat[i] == PGPGIN ||
  1266. memcg_vm_event_stat[i] == PGPGOUT)
  1267. continue;
  1268. #endif
  1269. seq_buf_printf(s, "%s %lu\n",
  1270. vm_event_name(memcg_vm_event_stat[i]),
  1271. memcg_events(memcg, memcg_vm_event_stat[i]));
  1272. }
  1273. }
  1274. static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
  1275. {
  1276. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1277. memcg_stat_format(memcg, s);
  1278. else
  1279. memcg1_stat_format(memcg, s);
  1280. if (seq_buf_has_overflowed(s))
  1281. pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__);
  1282. }
  1283. /**
  1284. * mem_cgroup_print_oom_context: Print OOM information relevant to
  1285. * memory controller.
  1286. * @memcg: The memory cgroup that went over limit
  1287. * @p: Task that is going to be killed
  1288. *
  1289. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1290. * enabled
  1291. */
  1292. void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
  1293. {
  1294. rcu_read_lock();
  1295. if (memcg) {
  1296. pr_cont(",oom_memcg=");
  1297. pr_cont_cgroup_path(memcg->css.cgroup);
  1298. } else
  1299. pr_cont(",global_oom");
  1300. if (p) {
  1301. pr_cont(",task_memcg=");
  1302. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1303. }
  1304. rcu_read_unlock();
  1305. }
  1306. /**
  1307. * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
  1308. * memory controller.
  1309. * @memcg: The memory cgroup that went over limit
  1310. */
  1311. void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
  1312. {
  1313. /* Use static buffer, for the caller is holding oom_lock. */
  1314. static char buf[PAGE_SIZE];
  1315. struct seq_buf s;
  1316. lockdep_assert_held(&oom_lock);
  1317. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1318. K((u64)page_counter_read(&memcg->memory)),
  1319. K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
  1320. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1321. pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1322. K((u64)page_counter_read(&memcg->swap)),
  1323. K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
  1324. #ifdef CONFIG_MEMCG_V1
  1325. else {
  1326. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1327. K((u64)page_counter_read(&memcg->memsw)),
  1328. K((u64)memcg->memsw.max), memcg->memsw.failcnt);
  1329. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1330. K((u64)page_counter_read(&memcg->kmem)),
  1331. K((u64)memcg->kmem.max), memcg->kmem.failcnt);
  1332. }
  1333. #endif
  1334. pr_info("Memory cgroup stats for ");
  1335. pr_cont_cgroup_path(memcg->css.cgroup);
  1336. pr_cont(":");
  1337. seq_buf_init(&s, buf, sizeof(buf));
  1338. memory_stat_format(memcg, &s);
  1339. seq_buf_do_printk(&s, KERN_INFO);
  1340. }
  1341. /*
  1342. * Return the memory (and swap, if configured) limit for a memcg.
  1343. */
  1344. unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
  1345. {
  1346. unsigned long max = READ_ONCE(memcg->memory.max);
  1347. if (do_memsw_account()) {
  1348. if (mem_cgroup_swappiness(memcg)) {
  1349. /* Calculate swap excess capacity from memsw limit */
  1350. unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
  1351. max += min(swap, (unsigned long)total_swap_pages);
  1352. }
  1353. } else {
  1354. if (mem_cgroup_swappiness(memcg))
  1355. max += min(READ_ONCE(memcg->swap.max),
  1356. (unsigned long)total_swap_pages);
  1357. }
  1358. return max;
  1359. }
  1360. unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
  1361. {
  1362. return page_counter_read(&memcg->memory);
  1363. }
  1364. static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1365. int order)
  1366. {
  1367. struct oom_control oc = {
  1368. .zonelist = NULL,
  1369. .nodemask = NULL,
  1370. .memcg = memcg,
  1371. .gfp_mask = gfp_mask,
  1372. .order = order,
  1373. };
  1374. bool ret = true;
  1375. if (mutex_lock_killable(&oom_lock))
  1376. return true;
  1377. if (mem_cgroup_margin(memcg) >= (1 << order))
  1378. goto unlock;
  1379. /*
  1380. * A few threads which were not waiting at mutex_lock_killable() can
  1381. * fail to bail out. Therefore, check again after holding oom_lock.
  1382. */
  1383. ret = task_is_dying() || out_of_memory(&oc);
  1384. unlock:
  1385. mutex_unlock(&oom_lock);
  1386. return ret;
  1387. }
  1388. /*
  1389. * Returns true if successfully killed one or more processes. Though in some
  1390. * corner cases it can return true even without killing any process.
  1391. */
  1392. static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1393. {
  1394. bool locked, ret;
  1395. if (order > PAGE_ALLOC_COSTLY_ORDER)
  1396. return false;
  1397. memcg_memory_event(memcg, MEMCG_OOM);
  1398. if (!memcg1_oom_prepare(memcg, &locked))
  1399. return false;
  1400. ret = mem_cgroup_out_of_memory(memcg, mask, order);
  1401. memcg1_oom_finish(memcg, locked);
  1402. return ret;
  1403. }
  1404. /**
  1405. * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
  1406. * @victim: task to be killed by the OOM killer
  1407. * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
  1408. *
  1409. * Returns a pointer to a memory cgroup, which has to be cleaned up
  1410. * by killing all belonging OOM-killable tasks.
  1411. *
  1412. * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
  1413. */
  1414. struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
  1415. struct mem_cgroup *oom_domain)
  1416. {
  1417. struct mem_cgroup *oom_group = NULL;
  1418. struct mem_cgroup *memcg;
  1419. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1420. return NULL;
  1421. if (!oom_domain)
  1422. oom_domain = root_mem_cgroup;
  1423. rcu_read_lock();
  1424. memcg = mem_cgroup_from_task(victim);
  1425. if (mem_cgroup_is_root(memcg))
  1426. goto out;
  1427. /*
  1428. * If the victim task has been asynchronously moved to a different
  1429. * memory cgroup, we might end up killing tasks outside oom_domain.
  1430. * In this case it's better to ignore memory.group.oom.
  1431. */
  1432. if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
  1433. goto out;
  1434. /*
  1435. * Traverse the memory cgroup hierarchy from the victim task's
  1436. * cgroup up to the OOMing cgroup (or root) to find the
  1437. * highest-level memory cgroup with oom.group set.
  1438. */
  1439. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  1440. if (READ_ONCE(memcg->oom_group))
  1441. oom_group = memcg;
  1442. if (memcg == oom_domain)
  1443. break;
  1444. }
  1445. if (oom_group)
  1446. css_get(&oom_group->css);
  1447. out:
  1448. rcu_read_unlock();
  1449. return oom_group;
  1450. }
  1451. void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
  1452. {
  1453. pr_info("Tasks in ");
  1454. pr_cont_cgroup_path(memcg->css.cgroup);
  1455. pr_cont(" are going to be killed due to memory.oom.group set\n");
  1456. }
  1457. struct memcg_stock_pcp {
  1458. local_lock_t stock_lock;
  1459. struct mem_cgroup *cached; /* this never be root cgroup */
  1460. unsigned int nr_pages;
  1461. struct obj_cgroup *cached_objcg;
  1462. struct pglist_data *cached_pgdat;
  1463. unsigned int nr_bytes;
  1464. int nr_slab_reclaimable_b;
  1465. int nr_slab_unreclaimable_b;
  1466. struct work_struct work;
  1467. unsigned long flags;
  1468. #define FLUSHING_CACHED_CHARGE 0
  1469. };
  1470. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
  1471. .stock_lock = INIT_LOCAL_LOCK(stock_lock),
  1472. };
  1473. static DEFINE_MUTEX(percpu_charge_mutex);
  1474. static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
  1475. static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
  1476. struct mem_cgroup *root_memcg);
  1477. /**
  1478. * consume_stock: Try to consume stocked charge on this cpu.
  1479. * @memcg: memcg to consume from.
  1480. * @nr_pages: how many pages to charge.
  1481. *
  1482. * The charges will only happen if @memcg matches the current cpu's memcg
  1483. * stock, and at least @nr_pages are available in that stock. Failure to
  1484. * service an allocation will refill the stock.
  1485. *
  1486. * returns true if successful, false otherwise.
  1487. */
  1488. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1489. {
  1490. struct memcg_stock_pcp *stock;
  1491. unsigned int stock_pages;
  1492. unsigned long flags;
  1493. bool ret = false;
  1494. if (nr_pages > MEMCG_CHARGE_BATCH)
  1495. return ret;
  1496. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  1497. stock = this_cpu_ptr(&memcg_stock);
  1498. stock_pages = READ_ONCE(stock->nr_pages);
  1499. if (memcg == READ_ONCE(stock->cached) && stock_pages >= nr_pages) {
  1500. WRITE_ONCE(stock->nr_pages, stock_pages - nr_pages);
  1501. ret = true;
  1502. }
  1503. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  1504. return ret;
  1505. }
  1506. /*
  1507. * Returns stocks cached in percpu and reset cached information.
  1508. */
  1509. static void drain_stock(struct memcg_stock_pcp *stock)
  1510. {
  1511. unsigned int stock_pages = READ_ONCE(stock->nr_pages);
  1512. struct mem_cgroup *old = READ_ONCE(stock->cached);
  1513. if (!old)
  1514. return;
  1515. if (stock_pages) {
  1516. page_counter_uncharge(&old->memory, stock_pages);
  1517. if (do_memsw_account())
  1518. page_counter_uncharge(&old->memsw, stock_pages);
  1519. WRITE_ONCE(stock->nr_pages, 0);
  1520. }
  1521. css_put(&old->css);
  1522. WRITE_ONCE(stock->cached, NULL);
  1523. }
  1524. static void drain_local_stock(struct work_struct *dummy)
  1525. {
  1526. struct memcg_stock_pcp *stock;
  1527. struct obj_cgroup *old = NULL;
  1528. unsigned long flags;
  1529. /*
  1530. * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
  1531. * drain_stock races is that we always operate on local CPU stock
  1532. * here with IRQ disabled
  1533. */
  1534. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  1535. stock = this_cpu_ptr(&memcg_stock);
  1536. old = drain_obj_stock(stock);
  1537. drain_stock(stock);
  1538. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1539. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  1540. obj_cgroup_put(old);
  1541. }
  1542. /*
  1543. * Cache charges(val) to local per_cpu area.
  1544. * This will be consumed by consume_stock() function, later.
  1545. */
  1546. static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1547. {
  1548. struct memcg_stock_pcp *stock;
  1549. unsigned int stock_pages;
  1550. stock = this_cpu_ptr(&memcg_stock);
  1551. if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
  1552. drain_stock(stock);
  1553. css_get(&memcg->css);
  1554. WRITE_ONCE(stock->cached, memcg);
  1555. }
  1556. stock_pages = READ_ONCE(stock->nr_pages) + nr_pages;
  1557. WRITE_ONCE(stock->nr_pages, stock_pages);
  1558. if (stock_pages > MEMCG_CHARGE_BATCH)
  1559. drain_stock(stock);
  1560. }
  1561. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1562. {
  1563. unsigned long flags;
  1564. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  1565. __refill_stock(memcg, nr_pages);
  1566. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  1567. }
  1568. /*
  1569. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1570. * of the hierarchy under it.
  1571. */
  1572. void drain_all_stock(struct mem_cgroup *root_memcg)
  1573. {
  1574. int cpu, curcpu;
  1575. /* If someone's already draining, avoid adding running more workers. */
  1576. if (!mutex_trylock(&percpu_charge_mutex))
  1577. return;
  1578. /*
  1579. * Notify other cpus that system-wide "drain" is running
  1580. * We do not care about races with the cpu hotplug because cpu down
  1581. * as well as workers from this path always operate on the local
  1582. * per-cpu data. CPU up doesn't touch memcg_stock at all.
  1583. */
  1584. migrate_disable();
  1585. curcpu = smp_processor_id();
  1586. for_each_online_cpu(cpu) {
  1587. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1588. struct mem_cgroup *memcg;
  1589. bool flush = false;
  1590. rcu_read_lock();
  1591. memcg = READ_ONCE(stock->cached);
  1592. if (memcg && READ_ONCE(stock->nr_pages) &&
  1593. mem_cgroup_is_descendant(memcg, root_memcg))
  1594. flush = true;
  1595. else if (obj_stock_flush_required(stock, root_memcg))
  1596. flush = true;
  1597. rcu_read_unlock();
  1598. if (flush &&
  1599. !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1600. if (cpu == curcpu)
  1601. drain_local_stock(&stock->work);
  1602. else if (!cpu_is_isolated(cpu))
  1603. schedule_work_on(cpu, &stock->work);
  1604. }
  1605. }
  1606. migrate_enable();
  1607. mutex_unlock(&percpu_charge_mutex);
  1608. }
  1609. static int memcg_hotplug_cpu_dead(unsigned int cpu)
  1610. {
  1611. struct memcg_stock_pcp *stock;
  1612. stock = &per_cpu(memcg_stock, cpu);
  1613. drain_stock(stock);
  1614. return 0;
  1615. }
  1616. static unsigned long reclaim_high(struct mem_cgroup *memcg,
  1617. unsigned int nr_pages,
  1618. gfp_t gfp_mask)
  1619. {
  1620. unsigned long nr_reclaimed = 0;
  1621. do {
  1622. unsigned long pflags;
  1623. if (page_counter_read(&memcg->memory) <=
  1624. READ_ONCE(memcg->memory.high))
  1625. continue;
  1626. memcg_memory_event(memcg, MEMCG_HIGH);
  1627. psi_memstall_enter(&pflags);
  1628. nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
  1629. gfp_mask,
  1630. MEMCG_RECLAIM_MAY_SWAP,
  1631. NULL);
  1632. psi_memstall_leave(&pflags);
  1633. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1634. !mem_cgroup_is_root(memcg));
  1635. return nr_reclaimed;
  1636. }
  1637. static void high_work_func(struct work_struct *work)
  1638. {
  1639. struct mem_cgroup *memcg;
  1640. memcg = container_of(work, struct mem_cgroup, high_work);
  1641. reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
  1642. }
  1643. /*
  1644. * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
  1645. * enough to still cause a significant slowdown in most cases, while still
  1646. * allowing diagnostics and tracing to proceed without becoming stuck.
  1647. */
  1648. #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
  1649. /*
  1650. * When calculating the delay, we use these either side of the exponentiation to
  1651. * maintain precision and scale to a reasonable number of jiffies (see the table
  1652. * below.
  1653. *
  1654. * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
  1655. * overage ratio to a delay.
  1656. * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
  1657. * proposed penalty in order to reduce to a reasonable number of jiffies, and
  1658. * to produce a reasonable delay curve.
  1659. *
  1660. * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
  1661. * reasonable delay curve compared to precision-adjusted overage, not
  1662. * penalising heavily at first, but still making sure that growth beyond the
  1663. * limit penalises misbehaviour cgroups by slowing them down exponentially. For
  1664. * example, with a high of 100 megabytes:
  1665. *
  1666. * +-------+------------------------+
  1667. * | usage | time to allocate in ms |
  1668. * +-------+------------------------+
  1669. * | 100M | 0 |
  1670. * | 101M | 6 |
  1671. * | 102M | 25 |
  1672. * | 103M | 57 |
  1673. * | 104M | 102 |
  1674. * | 105M | 159 |
  1675. * | 106M | 230 |
  1676. * | 107M | 313 |
  1677. * | 108M | 409 |
  1678. * | 109M | 518 |
  1679. * | 110M | 639 |
  1680. * | 111M | 774 |
  1681. * | 112M | 921 |
  1682. * | 113M | 1081 |
  1683. * | 114M | 1254 |
  1684. * | 115M | 1439 |
  1685. * | 116M | 1638 |
  1686. * | 117M | 1849 |
  1687. * | 118M | 2000 |
  1688. * | 119M | 2000 |
  1689. * | 120M | 2000 |
  1690. * +-------+------------------------+
  1691. */
  1692. #define MEMCG_DELAY_PRECISION_SHIFT 20
  1693. #define MEMCG_DELAY_SCALING_SHIFT 14
  1694. static u64 calculate_overage(unsigned long usage, unsigned long high)
  1695. {
  1696. u64 overage;
  1697. if (usage <= high)
  1698. return 0;
  1699. /*
  1700. * Prevent division by 0 in overage calculation by acting as if
  1701. * it was a threshold of 1 page
  1702. */
  1703. high = max(high, 1UL);
  1704. overage = usage - high;
  1705. overage <<= MEMCG_DELAY_PRECISION_SHIFT;
  1706. return div64_u64(overage, high);
  1707. }
  1708. static u64 mem_find_max_overage(struct mem_cgroup *memcg)
  1709. {
  1710. u64 overage, max_overage = 0;
  1711. do {
  1712. overage = calculate_overage(page_counter_read(&memcg->memory),
  1713. READ_ONCE(memcg->memory.high));
  1714. max_overage = max(overage, max_overage);
  1715. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1716. !mem_cgroup_is_root(memcg));
  1717. return max_overage;
  1718. }
  1719. static u64 swap_find_max_overage(struct mem_cgroup *memcg)
  1720. {
  1721. u64 overage, max_overage = 0;
  1722. do {
  1723. overage = calculate_overage(page_counter_read(&memcg->swap),
  1724. READ_ONCE(memcg->swap.high));
  1725. if (overage)
  1726. memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
  1727. max_overage = max(overage, max_overage);
  1728. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1729. !mem_cgroup_is_root(memcg));
  1730. return max_overage;
  1731. }
  1732. /*
  1733. * Get the number of jiffies that we should penalise a mischievous cgroup which
  1734. * is exceeding its memory.high by checking both it and its ancestors.
  1735. */
  1736. static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
  1737. unsigned int nr_pages,
  1738. u64 max_overage)
  1739. {
  1740. unsigned long penalty_jiffies;
  1741. if (!max_overage)
  1742. return 0;
  1743. /*
  1744. * We use overage compared to memory.high to calculate the number of
  1745. * jiffies to sleep (penalty_jiffies). Ideally this value should be
  1746. * fairly lenient on small overages, and increasingly harsh when the
  1747. * memcg in question makes it clear that it has no intention of stopping
  1748. * its crazy behaviour, so we exponentially increase the delay based on
  1749. * overage amount.
  1750. */
  1751. penalty_jiffies = max_overage * max_overage * HZ;
  1752. penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
  1753. penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
  1754. /*
  1755. * Factor in the task's own contribution to the overage, such that four
  1756. * N-sized allocations are throttled approximately the same as one
  1757. * 4N-sized allocation.
  1758. *
  1759. * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
  1760. * larger the current charge patch is than that.
  1761. */
  1762. return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
  1763. }
  1764. /*
  1765. * Reclaims memory over the high limit. Called directly from
  1766. * try_charge() (context permitting), as well as from the userland
  1767. * return path where reclaim is always able to block.
  1768. */
  1769. void mem_cgroup_handle_over_high(gfp_t gfp_mask)
  1770. {
  1771. unsigned long penalty_jiffies;
  1772. unsigned long pflags;
  1773. unsigned long nr_reclaimed;
  1774. unsigned int nr_pages = current->memcg_nr_pages_over_high;
  1775. int nr_retries = MAX_RECLAIM_RETRIES;
  1776. struct mem_cgroup *memcg;
  1777. bool in_retry = false;
  1778. if (likely(!nr_pages))
  1779. return;
  1780. memcg = get_mem_cgroup_from_mm(current->mm);
  1781. current->memcg_nr_pages_over_high = 0;
  1782. retry_reclaim:
  1783. /*
  1784. * Bail if the task is already exiting. Unlike memory.max,
  1785. * memory.high enforcement isn't as strict, and there is no
  1786. * OOM killer involved, which means the excess could already
  1787. * be much bigger (and still growing) than it could for
  1788. * memory.max; the dying task could get stuck in fruitless
  1789. * reclaim for a long time, which isn't desirable.
  1790. */
  1791. if (task_is_dying())
  1792. goto out;
  1793. /*
  1794. * The allocating task should reclaim at least the batch size, but for
  1795. * subsequent retries we only want to do what's necessary to prevent oom
  1796. * or breaching resource isolation.
  1797. *
  1798. * This is distinct from memory.max or page allocator behaviour because
  1799. * memory.high is currently batched, whereas memory.max and the page
  1800. * allocator run every time an allocation is made.
  1801. */
  1802. nr_reclaimed = reclaim_high(memcg,
  1803. in_retry ? SWAP_CLUSTER_MAX : nr_pages,
  1804. gfp_mask);
  1805. /*
  1806. * memory.high is breached and reclaim is unable to keep up. Throttle
  1807. * allocators proactively to slow down excessive growth.
  1808. */
  1809. penalty_jiffies = calculate_high_delay(memcg, nr_pages,
  1810. mem_find_max_overage(memcg));
  1811. penalty_jiffies += calculate_high_delay(memcg, nr_pages,
  1812. swap_find_max_overage(memcg));
  1813. /*
  1814. * Clamp the max delay per usermode return so as to still keep the
  1815. * application moving forwards and also permit diagnostics, albeit
  1816. * extremely slowly.
  1817. */
  1818. penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
  1819. /*
  1820. * Don't sleep if the amount of jiffies this memcg owes us is so low
  1821. * that it's not even worth doing, in an attempt to be nice to those who
  1822. * go only a small amount over their memory.high value and maybe haven't
  1823. * been aggressively reclaimed enough yet.
  1824. */
  1825. if (penalty_jiffies <= HZ / 100)
  1826. goto out;
  1827. /*
  1828. * If reclaim is making forward progress but we're still over
  1829. * memory.high, we want to encourage that rather than doing allocator
  1830. * throttling.
  1831. */
  1832. if (nr_reclaimed || nr_retries--) {
  1833. in_retry = true;
  1834. goto retry_reclaim;
  1835. }
  1836. /*
  1837. * Reclaim didn't manage to push usage below the limit, slow
  1838. * this allocating task down.
  1839. *
  1840. * If we exit early, we're guaranteed to die (since
  1841. * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
  1842. * need to account for any ill-begotten jiffies to pay them off later.
  1843. */
  1844. psi_memstall_enter(&pflags);
  1845. schedule_timeout_killable(penalty_jiffies);
  1846. psi_memstall_leave(&pflags);
  1847. out:
  1848. css_put(&memcg->css);
  1849. }
  1850. int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1851. unsigned int nr_pages)
  1852. {
  1853. unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
  1854. int nr_retries = MAX_RECLAIM_RETRIES;
  1855. struct mem_cgroup *mem_over_limit;
  1856. struct page_counter *counter;
  1857. unsigned long nr_reclaimed;
  1858. bool passed_oom = false;
  1859. unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
  1860. bool drained = false;
  1861. bool raised_max_event = false;
  1862. unsigned long pflags;
  1863. retry:
  1864. if (consume_stock(memcg, nr_pages))
  1865. return 0;
  1866. if (!do_memsw_account() ||
  1867. page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  1868. if (page_counter_try_charge(&memcg->memory, batch, &counter))
  1869. goto done_restock;
  1870. if (do_memsw_account())
  1871. page_counter_uncharge(&memcg->memsw, batch);
  1872. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  1873. } else {
  1874. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  1875. reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
  1876. }
  1877. if (batch > nr_pages) {
  1878. batch = nr_pages;
  1879. goto retry;
  1880. }
  1881. /*
  1882. * Prevent unbounded recursion when reclaim operations need to
  1883. * allocate memory. This might exceed the limits temporarily,
  1884. * but we prefer facilitating memory reclaim and getting back
  1885. * under the limit over triggering OOM kills in these cases.
  1886. */
  1887. if (unlikely(current->flags & PF_MEMALLOC))
  1888. goto force;
  1889. if (unlikely(task_in_memcg_oom(current)))
  1890. goto nomem;
  1891. if (!gfpflags_allow_blocking(gfp_mask))
  1892. goto nomem;
  1893. memcg_memory_event(mem_over_limit, MEMCG_MAX);
  1894. raised_max_event = true;
  1895. psi_memstall_enter(&pflags);
  1896. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  1897. gfp_mask, reclaim_options, NULL);
  1898. psi_memstall_leave(&pflags);
  1899. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  1900. goto retry;
  1901. if (!drained) {
  1902. drain_all_stock(mem_over_limit);
  1903. drained = true;
  1904. goto retry;
  1905. }
  1906. if (gfp_mask & __GFP_NORETRY)
  1907. goto nomem;
  1908. /*
  1909. * Even though the limit is exceeded at this point, reclaim
  1910. * may have been able to free some pages. Retry the charge
  1911. * before killing the task.
  1912. *
  1913. * Only for regular pages, though: huge pages are rather
  1914. * unlikely to succeed so close to the limit, and we fall back
  1915. * to regular pages anyway in case of failure.
  1916. */
  1917. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  1918. goto retry;
  1919. /*
  1920. * At task move, charge accounts can be doubly counted. So, it's
  1921. * better to wait until the end of task_move if something is going on.
  1922. */
  1923. if (memcg1_wait_acct_move(mem_over_limit))
  1924. goto retry;
  1925. if (nr_retries--)
  1926. goto retry;
  1927. if (gfp_mask & __GFP_RETRY_MAYFAIL)
  1928. goto nomem;
  1929. /* Avoid endless loop for tasks bypassed by the oom killer */
  1930. if (passed_oom && task_is_dying())
  1931. goto nomem;
  1932. /*
  1933. * keep retrying as long as the memcg oom killer is able to make
  1934. * a forward progress or bypass the charge if the oom killer
  1935. * couldn't make any progress.
  1936. */
  1937. if (mem_cgroup_oom(mem_over_limit, gfp_mask,
  1938. get_order(nr_pages * PAGE_SIZE))) {
  1939. passed_oom = true;
  1940. nr_retries = MAX_RECLAIM_RETRIES;
  1941. goto retry;
  1942. }
  1943. nomem:
  1944. /*
  1945. * Memcg doesn't have a dedicated reserve for atomic
  1946. * allocations. But like the global atomic pool, we need to
  1947. * put the burden of reclaim on regular allocation requests
  1948. * and let these go through as privileged allocations.
  1949. */
  1950. if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
  1951. return -ENOMEM;
  1952. force:
  1953. /*
  1954. * If the allocation has to be enforced, don't forget to raise
  1955. * a MEMCG_MAX event.
  1956. */
  1957. if (!raised_max_event)
  1958. memcg_memory_event(mem_over_limit, MEMCG_MAX);
  1959. /*
  1960. * The allocation either can't fail or will lead to more memory
  1961. * being freed very soon. Allow memory usage go over the limit
  1962. * temporarily by force charging it.
  1963. */
  1964. page_counter_charge(&memcg->memory, nr_pages);
  1965. if (do_memsw_account())
  1966. page_counter_charge(&memcg->memsw, nr_pages);
  1967. return 0;
  1968. done_restock:
  1969. if (batch > nr_pages)
  1970. refill_stock(memcg, batch - nr_pages);
  1971. /*
  1972. * If the hierarchy is above the normal consumption range, schedule
  1973. * reclaim on returning to userland. We can perform reclaim here
  1974. * if __GFP_RECLAIM but let's always punt for simplicity and so that
  1975. * GFP_KERNEL can consistently be used during reclaim. @memcg is
  1976. * not recorded as it most likely matches current's and won't
  1977. * change in the meantime. As high limit is checked again before
  1978. * reclaim, the cost of mismatch is negligible.
  1979. */
  1980. do {
  1981. bool mem_high, swap_high;
  1982. mem_high = page_counter_read(&memcg->memory) >
  1983. READ_ONCE(memcg->memory.high);
  1984. swap_high = page_counter_read(&memcg->swap) >
  1985. READ_ONCE(memcg->swap.high);
  1986. /* Don't bother a random interrupted task */
  1987. if (!in_task()) {
  1988. if (mem_high) {
  1989. schedule_work(&memcg->high_work);
  1990. break;
  1991. }
  1992. continue;
  1993. }
  1994. if (mem_high || swap_high) {
  1995. /*
  1996. * The allocating tasks in this cgroup will need to do
  1997. * reclaim or be throttled to prevent further growth
  1998. * of the memory or swap footprints.
  1999. *
  2000. * Target some best-effort fairness between the tasks,
  2001. * and distribute reclaim work and delay penalties
  2002. * based on how much each task is actually allocating.
  2003. */
  2004. current->memcg_nr_pages_over_high += batch;
  2005. set_notify_resume(current);
  2006. break;
  2007. }
  2008. } while ((memcg = parent_mem_cgroup(memcg)));
  2009. /*
  2010. * Reclaim is set up above to be called from the userland
  2011. * return path. But also attempt synchronous reclaim to avoid
  2012. * excessive overrun while the task is still inside the
  2013. * kernel. If this is successful, the return path will see it
  2014. * when it rechecks the overage and simply bail out.
  2015. */
  2016. if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
  2017. !(current->flags & PF_MEMALLOC) &&
  2018. gfpflags_allow_blocking(gfp_mask))
  2019. mem_cgroup_handle_over_high(gfp_mask);
  2020. return 0;
  2021. }
  2022. /**
  2023. * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
  2024. * @memcg: memcg previously charged.
  2025. * @nr_pages: number of pages previously charged.
  2026. */
  2027. void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  2028. {
  2029. if (mem_cgroup_is_root(memcg))
  2030. return;
  2031. page_counter_uncharge(&memcg->memory, nr_pages);
  2032. if (do_memsw_account())
  2033. page_counter_uncharge(&memcg->memsw, nr_pages);
  2034. }
  2035. static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
  2036. {
  2037. VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
  2038. /*
  2039. * Any of the following ensures page's memcg stability:
  2040. *
  2041. * - the page lock
  2042. * - LRU isolation
  2043. * - folio_memcg_lock()
  2044. * - exclusive reference
  2045. * - mem_cgroup_trylock_pages()
  2046. */
  2047. folio->memcg_data = (unsigned long)memcg;
  2048. }
  2049. /**
  2050. * mem_cgroup_commit_charge - commit a previously successful try_charge().
  2051. * @folio: folio to commit the charge to.
  2052. * @memcg: memcg previously charged.
  2053. */
  2054. void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
  2055. {
  2056. css_get(&memcg->css);
  2057. commit_charge(folio, memcg);
  2058. memcg1_commit_charge(folio, memcg);
  2059. }
  2060. static inline void __mod_objcg_mlstate(struct obj_cgroup *objcg,
  2061. struct pglist_data *pgdat,
  2062. enum node_stat_item idx, int nr)
  2063. {
  2064. struct mem_cgroup *memcg;
  2065. struct lruvec *lruvec;
  2066. rcu_read_lock();
  2067. memcg = obj_cgroup_memcg(objcg);
  2068. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  2069. __mod_memcg_lruvec_state(lruvec, idx, nr);
  2070. rcu_read_unlock();
  2071. }
  2072. static __always_inline
  2073. struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
  2074. {
  2075. /*
  2076. * Slab objects are accounted individually, not per-page.
  2077. * Memcg membership data for each individual object is saved in
  2078. * slab->obj_exts.
  2079. */
  2080. if (folio_test_slab(folio)) {
  2081. struct slabobj_ext *obj_exts;
  2082. struct slab *slab;
  2083. unsigned int off;
  2084. slab = folio_slab(folio);
  2085. obj_exts = slab_obj_exts(slab);
  2086. if (!obj_exts)
  2087. return NULL;
  2088. off = obj_to_index(slab->slab_cache, slab, p);
  2089. if (obj_exts[off].objcg)
  2090. return obj_cgroup_memcg(obj_exts[off].objcg);
  2091. return NULL;
  2092. }
  2093. /*
  2094. * folio_memcg_check() is used here, because in theory we can encounter
  2095. * a folio where the slab flag has been cleared already, but
  2096. * slab->obj_exts has not been freed yet
  2097. * folio_memcg_check() will guarantee that a proper memory
  2098. * cgroup pointer or NULL will be returned.
  2099. */
  2100. return folio_memcg_check(folio);
  2101. }
  2102. /*
  2103. * Returns a pointer to the memory cgroup to which the kernel object is charged.
  2104. * It is not suitable for objects allocated using vmalloc().
  2105. *
  2106. * A passed kernel object must be a slab object or a generic kernel page.
  2107. *
  2108. * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
  2109. * cgroup_mutex, etc.
  2110. */
  2111. struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
  2112. {
  2113. if (mem_cgroup_disabled())
  2114. return NULL;
  2115. return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
  2116. }
  2117. static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
  2118. {
  2119. struct obj_cgroup *objcg = NULL;
  2120. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  2121. objcg = rcu_dereference(memcg->objcg);
  2122. if (likely(objcg && obj_cgroup_tryget(objcg)))
  2123. break;
  2124. objcg = NULL;
  2125. }
  2126. return objcg;
  2127. }
  2128. static struct obj_cgroup *current_objcg_update(void)
  2129. {
  2130. struct mem_cgroup *memcg;
  2131. struct obj_cgroup *old, *objcg = NULL;
  2132. do {
  2133. /* Atomically drop the update bit. */
  2134. old = xchg(&current->objcg, NULL);
  2135. if (old) {
  2136. old = (struct obj_cgroup *)
  2137. ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
  2138. obj_cgroup_put(old);
  2139. old = NULL;
  2140. }
  2141. /* If new objcg is NULL, no reason for the second atomic update. */
  2142. if (!current->mm || (current->flags & PF_KTHREAD))
  2143. return NULL;
  2144. /*
  2145. * Release the objcg pointer from the previous iteration,
  2146. * if try_cmpxcg() below fails.
  2147. */
  2148. if (unlikely(objcg)) {
  2149. obj_cgroup_put(objcg);
  2150. objcg = NULL;
  2151. }
  2152. /*
  2153. * Obtain the new objcg pointer. The current task can be
  2154. * asynchronously moved to another memcg and the previous
  2155. * memcg can be offlined. So let's get the memcg pointer
  2156. * and try get a reference to objcg under a rcu read lock.
  2157. */
  2158. rcu_read_lock();
  2159. memcg = mem_cgroup_from_task(current);
  2160. objcg = __get_obj_cgroup_from_memcg(memcg);
  2161. rcu_read_unlock();
  2162. /*
  2163. * Try set up a new objcg pointer atomically. If it
  2164. * fails, it means the update flag was set concurrently, so
  2165. * the whole procedure should be repeated.
  2166. */
  2167. } while (!try_cmpxchg(&current->objcg, &old, objcg));
  2168. return objcg;
  2169. }
  2170. __always_inline struct obj_cgroup *current_obj_cgroup(void)
  2171. {
  2172. struct mem_cgroup *memcg;
  2173. struct obj_cgroup *objcg;
  2174. if (in_task()) {
  2175. memcg = current->active_memcg;
  2176. if (unlikely(memcg))
  2177. goto from_memcg;
  2178. objcg = READ_ONCE(current->objcg);
  2179. if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
  2180. objcg = current_objcg_update();
  2181. /*
  2182. * Objcg reference is kept by the task, so it's safe
  2183. * to use the objcg by the current task.
  2184. */
  2185. return objcg;
  2186. }
  2187. memcg = this_cpu_read(int_active_memcg);
  2188. if (unlikely(memcg))
  2189. goto from_memcg;
  2190. return NULL;
  2191. from_memcg:
  2192. objcg = NULL;
  2193. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  2194. /*
  2195. * Memcg pointer is protected by scope (see set_active_memcg())
  2196. * and is pinning the corresponding objcg, so objcg can't go
  2197. * away and can be used within the scope without any additional
  2198. * protection.
  2199. */
  2200. objcg = rcu_dereference_check(memcg->objcg, 1);
  2201. if (likely(objcg))
  2202. break;
  2203. }
  2204. return objcg;
  2205. }
  2206. struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
  2207. {
  2208. struct obj_cgroup *objcg;
  2209. if (!memcg_kmem_online())
  2210. return NULL;
  2211. if (folio_memcg_kmem(folio)) {
  2212. objcg = __folio_objcg(folio);
  2213. obj_cgroup_get(objcg);
  2214. } else {
  2215. struct mem_cgroup *memcg;
  2216. rcu_read_lock();
  2217. memcg = __folio_memcg(folio);
  2218. if (memcg)
  2219. objcg = __get_obj_cgroup_from_memcg(memcg);
  2220. else
  2221. objcg = NULL;
  2222. rcu_read_unlock();
  2223. }
  2224. return objcg;
  2225. }
  2226. /*
  2227. * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
  2228. * @objcg: object cgroup to uncharge
  2229. * @nr_pages: number of pages to uncharge
  2230. */
  2231. static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
  2232. unsigned int nr_pages)
  2233. {
  2234. struct mem_cgroup *memcg;
  2235. memcg = get_mem_cgroup_from_objcg(objcg);
  2236. mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
  2237. memcg1_account_kmem(memcg, -nr_pages);
  2238. refill_stock(memcg, nr_pages);
  2239. css_put(&memcg->css);
  2240. }
  2241. /*
  2242. * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
  2243. * @objcg: object cgroup to charge
  2244. * @gfp: reclaim mode
  2245. * @nr_pages: number of pages to charge
  2246. *
  2247. * Returns 0 on success, an error code on failure.
  2248. */
  2249. static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
  2250. unsigned int nr_pages)
  2251. {
  2252. struct mem_cgroup *memcg;
  2253. int ret;
  2254. memcg = get_mem_cgroup_from_objcg(objcg);
  2255. ret = try_charge_memcg(memcg, gfp, nr_pages);
  2256. if (ret)
  2257. goto out;
  2258. mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
  2259. memcg1_account_kmem(memcg, nr_pages);
  2260. out:
  2261. css_put(&memcg->css);
  2262. return ret;
  2263. }
  2264. /**
  2265. * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
  2266. * @page: page to charge
  2267. * @gfp: reclaim mode
  2268. * @order: allocation order
  2269. *
  2270. * Returns 0 on success, an error code on failure.
  2271. */
  2272. int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  2273. {
  2274. struct obj_cgroup *objcg;
  2275. int ret = 0;
  2276. objcg = current_obj_cgroup();
  2277. if (objcg) {
  2278. ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
  2279. if (!ret) {
  2280. obj_cgroup_get(objcg);
  2281. page->memcg_data = (unsigned long)objcg |
  2282. MEMCG_DATA_KMEM;
  2283. return 0;
  2284. }
  2285. }
  2286. return ret;
  2287. }
  2288. /**
  2289. * __memcg_kmem_uncharge_page: uncharge a kmem page
  2290. * @page: page to uncharge
  2291. * @order: allocation order
  2292. */
  2293. void __memcg_kmem_uncharge_page(struct page *page, int order)
  2294. {
  2295. struct folio *folio = page_folio(page);
  2296. struct obj_cgroup *objcg;
  2297. unsigned int nr_pages = 1 << order;
  2298. if (!folio_memcg_kmem(folio))
  2299. return;
  2300. objcg = __folio_objcg(folio);
  2301. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2302. folio->memcg_data = 0;
  2303. obj_cgroup_put(objcg);
  2304. }
  2305. static void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
  2306. enum node_stat_item idx, int nr)
  2307. {
  2308. struct memcg_stock_pcp *stock;
  2309. struct obj_cgroup *old = NULL;
  2310. unsigned long flags;
  2311. int *bytes;
  2312. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2313. stock = this_cpu_ptr(&memcg_stock);
  2314. /*
  2315. * Save vmstat data in stock and skip vmstat array update unless
  2316. * accumulating over a page of vmstat data or when pgdat or idx
  2317. * changes.
  2318. */
  2319. if (READ_ONCE(stock->cached_objcg) != objcg) {
  2320. old = drain_obj_stock(stock);
  2321. obj_cgroup_get(objcg);
  2322. stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
  2323. ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
  2324. WRITE_ONCE(stock->cached_objcg, objcg);
  2325. stock->cached_pgdat = pgdat;
  2326. } else if (stock->cached_pgdat != pgdat) {
  2327. /* Flush the existing cached vmstat data */
  2328. struct pglist_data *oldpg = stock->cached_pgdat;
  2329. if (stock->nr_slab_reclaimable_b) {
  2330. __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
  2331. stock->nr_slab_reclaimable_b);
  2332. stock->nr_slab_reclaimable_b = 0;
  2333. }
  2334. if (stock->nr_slab_unreclaimable_b) {
  2335. __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
  2336. stock->nr_slab_unreclaimable_b);
  2337. stock->nr_slab_unreclaimable_b = 0;
  2338. }
  2339. stock->cached_pgdat = pgdat;
  2340. }
  2341. bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
  2342. : &stock->nr_slab_unreclaimable_b;
  2343. /*
  2344. * Even for large object >= PAGE_SIZE, the vmstat data will still be
  2345. * cached locally at least once before pushing it out.
  2346. */
  2347. if (!*bytes) {
  2348. *bytes = nr;
  2349. nr = 0;
  2350. } else {
  2351. *bytes += nr;
  2352. if (abs(*bytes) > PAGE_SIZE) {
  2353. nr = *bytes;
  2354. *bytes = 0;
  2355. } else {
  2356. nr = 0;
  2357. }
  2358. }
  2359. if (nr)
  2360. __mod_objcg_mlstate(objcg, pgdat, idx, nr);
  2361. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2362. obj_cgroup_put(old);
  2363. }
  2364. static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
  2365. {
  2366. struct memcg_stock_pcp *stock;
  2367. unsigned long flags;
  2368. bool ret = false;
  2369. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2370. stock = this_cpu_ptr(&memcg_stock);
  2371. if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
  2372. stock->nr_bytes -= nr_bytes;
  2373. ret = true;
  2374. }
  2375. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2376. return ret;
  2377. }
  2378. static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
  2379. {
  2380. struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
  2381. if (!old)
  2382. return NULL;
  2383. if (stock->nr_bytes) {
  2384. unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2385. unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
  2386. if (nr_pages) {
  2387. struct mem_cgroup *memcg;
  2388. memcg = get_mem_cgroup_from_objcg(old);
  2389. mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
  2390. memcg1_account_kmem(memcg, -nr_pages);
  2391. __refill_stock(memcg, nr_pages);
  2392. css_put(&memcg->css);
  2393. }
  2394. /*
  2395. * The leftover is flushed to the centralized per-memcg value.
  2396. * On the next attempt to refill obj stock it will be moved
  2397. * to a per-cpu stock (probably, on an other CPU), see
  2398. * refill_obj_stock().
  2399. *
  2400. * How often it's flushed is a trade-off between the memory
  2401. * limit enforcement accuracy and potential CPU contention,
  2402. * so it might be changed in the future.
  2403. */
  2404. atomic_add(nr_bytes, &old->nr_charged_bytes);
  2405. stock->nr_bytes = 0;
  2406. }
  2407. /*
  2408. * Flush the vmstat data in current stock
  2409. */
  2410. if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
  2411. if (stock->nr_slab_reclaimable_b) {
  2412. __mod_objcg_mlstate(old, stock->cached_pgdat,
  2413. NR_SLAB_RECLAIMABLE_B,
  2414. stock->nr_slab_reclaimable_b);
  2415. stock->nr_slab_reclaimable_b = 0;
  2416. }
  2417. if (stock->nr_slab_unreclaimable_b) {
  2418. __mod_objcg_mlstate(old, stock->cached_pgdat,
  2419. NR_SLAB_UNRECLAIMABLE_B,
  2420. stock->nr_slab_unreclaimable_b);
  2421. stock->nr_slab_unreclaimable_b = 0;
  2422. }
  2423. stock->cached_pgdat = NULL;
  2424. }
  2425. WRITE_ONCE(stock->cached_objcg, NULL);
  2426. /*
  2427. * The `old' objects needs to be released by the caller via
  2428. * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
  2429. */
  2430. return old;
  2431. }
  2432. static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
  2433. struct mem_cgroup *root_memcg)
  2434. {
  2435. struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
  2436. struct mem_cgroup *memcg;
  2437. if (objcg) {
  2438. memcg = obj_cgroup_memcg(objcg);
  2439. if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
  2440. return true;
  2441. }
  2442. return false;
  2443. }
  2444. static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
  2445. bool allow_uncharge)
  2446. {
  2447. struct memcg_stock_pcp *stock;
  2448. struct obj_cgroup *old = NULL;
  2449. unsigned long flags;
  2450. unsigned int nr_pages = 0;
  2451. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2452. stock = this_cpu_ptr(&memcg_stock);
  2453. if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
  2454. old = drain_obj_stock(stock);
  2455. obj_cgroup_get(objcg);
  2456. WRITE_ONCE(stock->cached_objcg, objcg);
  2457. stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
  2458. ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
  2459. allow_uncharge = true; /* Allow uncharge when objcg changes */
  2460. }
  2461. stock->nr_bytes += nr_bytes;
  2462. if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
  2463. nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2464. stock->nr_bytes &= (PAGE_SIZE - 1);
  2465. }
  2466. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2467. obj_cgroup_put(old);
  2468. if (nr_pages)
  2469. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2470. }
  2471. int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
  2472. {
  2473. unsigned int nr_pages, nr_bytes;
  2474. int ret;
  2475. if (consume_obj_stock(objcg, size))
  2476. return 0;
  2477. /*
  2478. * In theory, objcg->nr_charged_bytes can have enough
  2479. * pre-charged bytes to satisfy the allocation. However,
  2480. * flushing objcg->nr_charged_bytes requires two atomic
  2481. * operations, and objcg->nr_charged_bytes can't be big.
  2482. * The shared objcg->nr_charged_bytes can also become a
  2483. * performance bottleneck if all tasks of the same memcg are
  2484. * trying to update it. So it's better to ignore it and try
  2485. * grab some new pages. The stock's nr_bytes will be flushed to
  2486. * objcg->nr_charged_bytes later on when objcg changes.
  2487. *
  2488. * The stock's nr_bytes may contain enough pre-charged bytes
  2489. * to allow one less page from being charged, but we can't rely
  2490. * on the pre-charged bytes not being changed outside of
  2491. * consume_obj_stock() or refill_obj_stock(). So ignore those
  2492. * pre-charged bytes as well when charging pages. To avoid a
  2493. * page uncharge right after a page charge, we set the
  2494. * allow_uncharge flag to false when calling refill_obj_stock()
  2495. * to temporarily allow the pre-charged bytes to exceed the page
  2496. * size limit. The maximum reachable value of the pre-charged
  2497. * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
  2498. * race.
  2499. */
  2500. nr_pages = size >> PAGE_SHIFT;
  2501. nr_bytes = size & (PAGE_SIZE - 1);
  2502. if (nr_bytes)
  2503. nr_pages += 1;
  2504. ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
  2505. if (!ret && nr_bytes)
  2506. refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
  2507. return ret;
  2508. }
  2509. void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
  2510. {
  2511. refill_obj_stock(objcg, size, true);
  2512. }
  2513. static inline size_t obj_full_size(struct kmem_cache *s)
  2514. {
  2515. /*
  2516. * For each accounted object there is an extra space which is used
  2517. * to store obj_cgroup membership. Charge it too.
  2518. */
  2519. return s->size + sizeof(struct obj_cgroup *);
  2520. }
  2521. bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
  2522. gfp_t flags, size_t size, void **p)
  2523. {
  2524. struct obj_cgroup *objcg;
  2525. struct slab *slab;
  2526. unsigned long off;
  2527. size_t i;
  2528. /*
  2529. * The obtained objcg pointer is safe to use within the current scope,
  2530. * defined by current task or set_active_memcg() pair.
  2531. * obj_cgroup_get() is used to get a permanent reference.
  2532. */
  2533. objcg = current_obj_cgroup();
  2534. if (!objcg)
  2535. return true;
  2536. /*
  2537. * slab_alloc_node() avoids the NULL check, so we might be called with a
  2538. * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
  2539. * the whole requested size.
  2540. * return success as there's nothing to free back
  2541. */
  2542. if (unlikely(*p == NULL))
  2543. return true;
  2544. flags &= gfp_allowed_mask;
  2545. if (lru) {
  2546. int ret;
  2547. struct mem_cgroup *memcg;
  2548. memcg = get_mem_cgroup_from_objcg(objcg);
  2549. ret = memcg_list_lru_alloc(memcg, lru, flags);
  2550. css_put(&memcg->css);
  2551. if (ret)
  2552. return false;
  2553. }
  2554. if (obj_cgroup_charge(objcg, flags, size * obj_full_size(s)))
  2555. return false;
  2556. for (i = 0; i < size; i++) {
  2557. slab = virt_to_slab(p[i]);
  2558. if (!slab_obj_exts(slab) &&
  2559. alloc_slab_obj_exts(slab, s, flags, false)) {
  2560. obj_cgroup_uncharge(objcg, obj_full_size(s));
  2561. continue;
  2562. }
  2563. off = obj_to_index(s, slab, p[i]);
  2564. obj_cgroup_get(objcg);
  2565. slab_obj_exts(slab)[off].objcg = objcg;
  2566. mod_objcg_state(objcg, slab_pgdat(slab),
  2567. cache_vmstat_idx(s), obj_full_size(s));
  2568. }
  2569. return true;
  2570. }
  2571. void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
  2572. void **p, int objects, struct slabobj_ext *obj_exts)
  2573. {
  2574. for (int i = 0; i < objects; i++) {
  2575. struct obj_cgroup *objcg;
  2576. unsigned int off;
  2577. off = obj_to_index(s, slab, p[i]);
  2578. objcg = obj_exts[off].objcg;
  2579. if (!objcg)
  2580. continue;
  2581. obj_exts[off].objcg = NULL;
  2582. obj_cgroup_uncharge(objcg, obj_full_size(s));
  2583. mod_objcg_state(objcg, slab_pgdat(slab), cache_vmstat_idx(s),
  2584. -obj_full_size(s));
  2585. obj_cgroup_put(objcg);
  2586. }
  2587. }
  2588. /*
  2589. * Because folio_memcg(head) is not set on tails, set it now.
  2590. */
  2591. void split_page_memcg(struct page *head, int old_order, int new_order)
  2592. {
  2593. struct folio *folio = page_folio(head);
  2594. int i;
  2595. unsigned int old_nr = 1 << old_order;
  2596. unsigned int new_nr = 1 << new_order;
  2597. if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
  2598. return;
  2599. for (i = new_nr; i < old_nr; i += new_nr)
  2600. folio_page(folio, i)->memcg_data = folio->memcg_data;
  2601. if (folio_memcg_kmem(folio))
  2602. obj_cgroup_get_many(__folio_objcg(folio), old_nr / new_nr - 1);
  2603. else
  2604. css_get_many(&folio_memcg(folio)->css, old_nr / new_nr - 1);
  2605. }
  2606. unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  2607. {
  2608. unsigned long val;
  2609. if (mem_cgroup_is_root(memcg)) {
  2610. /*
  2611. * Approximate root's usage from global state. This isn't
  2612. * perfect, but the root usage was always an approximation.
  2613. */
  2614. val = global_node_page_state(NR_FILE_PAGES) +
  2615. global_node_page_state(NR_ANON_MAPPED);
  2616. if (swap)
  2617. val += total_swap_pages - get_nr_swap_pages();
  2618. } else {
  2619. if (!swap)
  2620. val = page_counter_read(&memcg->memory);
  2621. else
  2622. val = page_counter_read(&memcg->memsw);
  2623. }
  2624. return val;
  2625. }
  2626. static int memcg_online_kmem(struct mem_cgroup *memcg)
  2627. {
  2628. struct obj_cgroup *objcg;
  2629. if (mem_cgroup_kmem_disabled())
  2630. return 0;
  2631. if (unlikely(mem_cgroup_is_root(memcg)))
  2632. return 0;
  2633. objcg = obj_cgroup_alloc();
  2634. if (!objcg)
  2635. return -ENOMEM;
  2636. objcg->memcg = memcg;
  2637. rcu_assign_pointer(memcg->objcg, objcg);
  2638. obj_cgroup_get(objcg);
  2639. memcg->orig_objcg = objcg;
  2640. static_branch_enable(&memcg_kmem_online_key);
  2641. memcg->kmemcg_id = memcg->id.id;
  2642. return 0;
  2643. }
  2644. static void memcg_offline_kmem(struct mem_cgroup *memcg)
  2645. {
  2646. struct mem_cgroup *parent;
  2647. if (mem_cgroup_kmem_disabled())
  2648. return;
  2649. if (unlikely(mem_cgroup_is_root(memcg)))
  2650. return;
  2651. parent = parent_mem_cgroup(memcg);
  2652. if (!parent)
  2653. parent = root_mem_cgroup;
  2654. memcg_reparent_objcgs(memcg, parent);
  2655. /*
  2656. * After we have finished memcg_reparent_objcgs(), all list_lrus
  2657. * corresponding to this cgroup are guaranteed to remain empty.
  2658. * The ordering is imposed by list_lru_node->lock taken by
  2659. * memcg_reparent_list_lrus().
  2660. */
  2661. memcg_reparent_list_lrus(memcg, parent);
  2662. }
  2663. #ifdef CONFIG_CGROUP_WRITEBACK
  2664. #include <trace/events/writeback.h>
  2665. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  2666. {
  2667. return wb_domain_init(&memcg->cgwb_domain, gfp);
  2668. }
  2669. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  2670. {
  2671. wb_domain_exit(&memcg->cgwb_domain);
  2672. }
  2673. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  2674. {
  2675. wb_domain_size_changed(&memcg->cgwb_domain);
  2676. }
  2677. struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
  2678. {
  2679. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  2680. if (!memcg->css.parent)
  2681. return NULL;
  2682. return &memcg->cgwb_domain;
  2683. }
  2684. /**
  2685. * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
  2686. * @wb: bdi_writeback in question
  2687. * @pfilepages: out parameter for number of file pages
  2688. * @pheadroom: out parameter for number of allocatable pages according to memcg
  2689. * @pdirty: out parameter for number of dirty pages
  2690. * @pwriteback: out parameter for number of pages under writeback
  2691. *
  2692. * Determine the numbers of file, headroom, dirty, and writeback pages in
  2693. * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
  2694. * is a bit more involved.
  2695. *
  2696. * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
  2697. * headroom is calculated as the lowest headroom of itself and the
  2698. * ancestors. Note that this doesn't consider the actual amount of
  2699. * available memory in the system. The caller should further cap
  2700. * *@pheadroom accordingly.
  2701. */
  2702. void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
  2703. unsigned long *pheadroom, unsigned long *pdirty,
  2704. unsigned long *pwriteback)
  2705. {
  2706. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  2707. struct mem_cgroup *parent;
  2708. mem_cgroup_flush_stats_ratelimited(memcg);
  2709. *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
  2710. *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
  2711. *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
  2712. memcg_page_state(memcg, NR_ACTIVE_FILE);
  2713. *pheadroom = PAGE_COUNTER_MAX;
  2714. while ((parent = parent_mem_cgroup(memcg))) {
  2715. unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
  2716. READ_ONCE(memcg->memory.high));
  2717. unsigned long used = page_counter_read(&memcg->memory);
  2718. *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
  2719. memcg = parent;
  2720. }
  2721. }
  2722. /*
  2723. * Foreign dirty flushing
  2724. *
  2725. * There's an inherent mismatch between memcg and writeback. The former
  2726. * tracks ownership per-page while the latter per-inode. This was a
  2727. * deliberate design decision because honoring per-page ownership in the
  2728. * writeback path is complicated, may lead to higher CPU and IO overheads
  2729. * and deemed unnecessary given that write-sharing an inode across
  2730. * different cgroups isn't a common use-case.
  2731. *
  2732. * Combined with inode majority-writer ownership switching, this works well
  2733. * enough in most cases but there are some pathological cases. For
  2734. * example, let's say there are two cgroups A and B which keep writing to
  2735. * different but confined parts of the same inode. B owns the inode and
  2736. * A's memory is limited far below B's. A's dirty ratio can rise enough to
  2737. * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
  2738. * triggering background writeback. A will be slowed down without a way to
  2739. * make writeback of the dirty pages happen.
  2740. *
  2741. * Conditions like the above can lead to a cgroup getting repeatedly and
  2742. * severely throttled after making some progress after each
  2743. * dirty_expire_interval while the underlying IO device is almost
  2744. * completely idle.
  2745. *
  2746. * Solving this problem completely requires matching the ownership tracking
  2747. * granularities between memcg and writeback in either direction. However,
  2748. * the more egregious behaviors can be avoided by simply remembering the
  2749. * most recent foreign dirtying events and initiating remote flushes on
  2750. * them when local writeback isn't enough to keep the memory clean enough.
  2751. *
  2752. * The following two functions implement such mechanism. When a foreign
  2753. * page - a page whose memcg and writeback ownerships don't match - is
  2754. * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
  2755. * bdi_writeback on the page owning memcg. When balance_dirty_pages()
  2756. * decides that the memcg needs to sleep due to high dirty ratio, it calls
  2757. * mem_cgroup_flush_foreign() which queues writeback on the recorded
  2758. * foreign bdi_writebacks which haven't expired. Both the numbers of
  2759. * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
  2760. * limited to MEMCG_CGWB_FRN_CNT.
  2761. *
  2762. * The mechanism only remembers IDs and doesn't hold any object references.
  2763. * As being wrong occasionally doesn't matter, updates and accesses to the
  2764. * records are lockless and racy.
  2765. */
  2766. void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
  2767. struct bdi_writeback *wb)
  2768. {
  2769. struct mem_cgroup *memcg = folio_memcg(folio);
  2770. struct memcg_cgwb_frn *frn;
  2771. u64 now = get_jiffies_64();
  2772. u64 oldest_at = now;
  2773. int oldest = -1;
  2774. int i;
  2775. trace_track_foreign_dirty(folio, wb);
  2776. /*
  2777. * Pick the slot to use. If there is already a slot for @wb, keep
  2778. * using it. If not replace the oldest one which isn't being
  2779. * written out.
  2780. */
  2781. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  2782. frn = &memcg->cgwb_frn[i];
  2783. if (frn->bdi_id == wb->bdi->id &&
  2784. frn->memcg_id == wb->memcg_css->id)
  2785. break;
  2786. if (time_before64(frn->at, oldest_at) &&
  2787. atomic_read(&frn->done.cnt) == 1) {
  2788. oldest = i;
  2789. oldest_at = frn->at;
  2790. }
  2791. }
  2792. if (i < MEMCG_CGWB_FRN_CNT) {
  2793. /*
  2794. * Re-using an existing one. Update timestamp lazily to
  2795. * avoid making the cacheline hot. We want them to be
  2796. * reasonably up-to-date and significantly shorter than
  2797. * dirty_expire_interval as that's what expires the record.
  2798. * Use the shorter of 1s and dirty_expire_interval / 8.
  2799. */
  2800. unsigned long update_intv =
  2801. min_t(unsigned long, HZ,
  2802. msecs_to_jiffies(dirty_expire_interval * 10) / 8);
  2803. if (time_before64(frn->at, now - update_intv))
  2804. frn->at = now;
  2805. } else if (oldest >= 0) {
  2806. /* replace the oldest free one */
  2807. frn = &memcg->cgwb_frn[oldest];
  2808. frn->bdi_id = wb->bdi->id;
  2809. frn->memcg_id = wb->memcg_css->id;
  2810. frn->at = now;
  2811. }
  2812. }
  2813. /* issue foreign writeback flushes for recorded foreign dirtying events */
  2814. void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
  2815. {
  2816. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  2817. unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
  2818. u64 now = jiffies_64;
  2819. int i;
  2820. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  2821. struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
  2822. /*
  2823. * If the record is older than dirty_expire_interval,
  2824. * writeback on it has already started. No need to kick it
  2825. * off again. Also, don't start a new one if there's
  2826. * already one in flight.
  2827. */
  2828. if (time_after64(frn->at, now - intv) &&
  2829. atomic_read(&frn->done.cnt) == 1) {
  2830. frn->at = 0;
  2831. trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
  2832. cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
  2833. WB_REASON_FOREIGN_FLUSH,
  2834. &frn->done);
  2835. }
  2836. }
  2837. }
  2838. #else /* CONFIG_CGROUP_WRITEBACK */
  2839. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  2840. {
  2841. return 0;
  2842. }
  2843. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  2844. {
  2845. }
  2846. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  2847. {
  2848. }
  2849. #endif /* CONFIG_CGROUP_WRITEBACK */
  2850. /*
  2851. * Private memory cgroup IDR
  2852. *
  2853. * Swap-out records and page cache shadow entries need to store memcg
  2854. * references in constrained space, so we maintain an ID space that is
  2855. * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
  2856. * memory-controlled cgroups to 64k.
  2857. *
  2858. * However, there usually are many references to the offline CSS after
  2859. * the cgroup has been destroyed, such as page cache or reclaimable
  2860. * slab objects, that don't need to hang on to the ID. We want to keep
  2861. * those dead CSS from occupying IDs, or we might quickly exhaust the
  2862. * relatively small ID space and prevent the creation of new cgroups
  2863. * even when there are much fewer than 64k cgroups - possibly none.
  2864. *
  2865. * Maintain a private 16-bit ID space for memcg, and allow the ID to
  2866. * be freed and recycled when it's no longer needed, which is usually
  2867. * when the CSS is offlined.
  2868. *
  2869. * The only exception to that are records of swapped out tmpfs/shmem
  2870. * pages that need to be attributed to live ancestors on swapin. But
  2871. * those references are manageable from userspace.
  2872. */
  2873. #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
  2874. static DEFINE_XARRAY_ALLOC1(mem_cgroup_ids);
  2875. static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
  2876. {
  2877. if (memcg->id.id > 0) {
  2878. xa_erase(&mem_cgroup_ids, memcg->id.id);
  2879. memcg->id.id = 0;
  2880. }
  2881. }
  2882. void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
  2883. unsigned int n)
  2884. {
  2885. refcount_add(n, &memcg->id.ref);
  2886. }
  2887. void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
  2888. {
  2889. if (refcount_sub_and_test(n, &memcg->id.ref)) {
  2890. mem_cgroup_id_remove(memcg);
  2891. /* Memcg ID pins CSS */
  2892. css_put(&memcg->css);
  2893. }
  2894. }
  2895. static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
  2896. {
  2897. mem_cgroup_id_put_many(memcg, 1);
  2898. }
  2899. /**
  2900. * mem_cgroup_from_id - look up a memcg from a memcg id
  2901. * @id: the memcg id to look up
  2902. *
  2903. * Caller must hold rcu_read_lock().
  2904. */
  2905. struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
  2906. {
  2907. WARN_ON_ONCE(!rcu_read_lock_held());
  2908. return xa_load(&mem_cgroup_ids, id);
  2909. }
  2910. #ifdef CONFIG_SHRINKER_DEBUG
  2911. struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
  2912. {
  2913. struct cgroup *cgrp;
  2914. struct cgroup_subsys_state *css;
  2915. struct mem_cgroup *memcg;
  2916. cgrp = cgroup_get_from_id(ino);
  2917. if (IS_ERR(cgrp))
  2918. return ERR_CAST(cgrp);
  2919. css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
  2920. if (css)
  2921. memcg = container_of(css, struct mem_cgroup, css);
  2922. else
  2923. memcg = ERR_PTR(-ENOENT);
  2924. cgroup_put(cgrp);
  2925. return memcg;
  2926. }
  2927. #endif
  2928. static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
  2929. {
  2930. struct mem_cgroup_per_node *pn;
  2931. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
  2932. if (!pn)
  2933. return false;
  2934. pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
  2935. GFP_KERNEL_ACCOUNT, node);
  2936. if (!pn->lruvec_stats)
  2937. goto fail;
  2938. pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
  2939. GFP_KERNEL_ACCOUNT);
  2940. if (!pn->lruvec_stats_percpu)
  2941. goto fail;
  2942. lruvec_init(&pn->lruvec);
  2943. pn->memcg = memcg;
  2944. memcg->nodeinfo[node] = pn;
  2945. return true;
  2946. fail:
  2947. kfree(pn->lruvec_stats);
  2948. kfree(pn);
  2949. return false;
  2950. }
  2951. static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
  2952. {
  2953. struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
  2954. if (!pn)
  2955. return;
  2956. free_percpu(pn->lruvec_stats_percpu);
  2957. kfree(pn->lruvec_stats);
  2958. kfree(pn);
  2959. }
  2960. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  2961. {
  2962. int node;
  2963. obj_cgroup_put(memcg->orig_objcg);
  2964. for_each_node(node)
  2965. free_mem_cgroup_per_node_info(memcg, node);
  2966. memcg1_free_events(memcg);
  2967. kfree(memcg->vmstats);
  2968. free_percpu(memcg->vmstats_percpu);
  2969. kfree(memcg);
  2970. }
  2971. static void mem_cgroup_free(struct mem_cgroup *memcg)
  2972. {
  2973. lru_gen_exit_memcg(memcg);
  2974. memcg_wb_domain_exit(memcg);
  2975. __mem_cgroup_free(memcg);
  2976. }
  2977. static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
  2978. {
  2979. struct memcg_vmstats_percpu *statc, *pstatc;
  2980. struct mem_cgroup *memcg;
  2981. int node, cpu;
  2982. int __maybe_unused i;
  2983. long error;
  2984. memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
  2985. if (!memcg)
  2986. return ERR_PTR(-ENOMEM);
  2987. error = xa_alloc(&mem_cgroup_ids, &memcg->id.id, NULL,
  2988. XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
  2989. if (error)
  2990. goto fail;
  2991. error = -ENOMEM;
  2992. memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
  2993. GFP_KERNEL_ACCOUNT);
  2994. if (!memcg->vmstats)
  2995. goto fail;
  2996. memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
  2997. GFP_KERNEL_ACCOUNT);
  2998. if (!memcg->vmstats_percpu)
  2999. goto fail;
  3000. if (!memcg1_alloc_events(memcg))
  3001. goto fail;
  3002. for_each_possible_cpu(cpu) {
  3003. if (parent)
  3004. pstatc = per_cpu_ptr(parent->vmstats_percpu, cpu);
  3005. statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
  3006. statc->parent = parent ? pstatc : NULL;
  3007. statc->vmstats = memcg->vmstats;
  3008. }
  3009. for_each_node(node)
  3010. if (!alloc_mem_cgroup_per_node_info(memcg, node))
  3011. goto fail;
  3012. if (memcg_wb_domain_init(memcg, GFP_KERNEL))
  3013. goto fail;
  3014. INIT_WORK(&memcg->high_work, high_work_func);
  3015. vmpressure_init(&memcg->vmpressure);
  3016. INIT_LIST_HEAD(&memcg->memory_peaks);
  3017. INIT_LIST_HEAD(&memcg->swap_peaks);
  3018. spin_lock_init(&memcg->peaks_lock);
  3019. memcg->socket_pressure = jiffies;
  3020. memcg1_memcg_init(memcg);
  3021. memcg->kmemcg_id = -1;
  3022. INIT_LIST_HEAD(&memcg->objcg_list);
  3023. #ifdef CONFIG_CGROUP_WRITEBACK
  3024. INIT_LIST_HEAD(&memcg->cgwb_list);
  3025. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  3026. memcg->cgwb_frn[i].done =
  3027. __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
  3028. #endif
  3029. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3030. spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
  3031. INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
  3032. memcg->deferred_split_queue.split_queue_len = 0;
  3033. #endif
  3034. lru_gen_init_memcg(memcg);
  3035. return memcg;
  3036. fail:
  3037. mem_cgroup_id_remove(memcg);
  3038. __mem_cgroup_free(memcg);
  3039. return ERR_PTR(error);
  3040. }
  3041. static struct cgroup_subsys_state * __ref
  3042. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  3043. {
  3044. struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
  3045. struct mem_cgroup *memcg, *old_memcg;
  3046. old_memcg = set_active_memcg(parent);
  3047. memcg = mem_cgroup_alloc(parent);
  3048. set_active_memcg(old_memcg);
  3049. if (IS_ERR(memcg))
  3050. return ERR_CAST(memcg);
  3051. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  3052. memcg1_soft_limit_reset(memcg);
  3053. #ifdef CONFIG_ZSWAP
  3054. memcg->zswap_max = PAGE_COUNTER_MAX;
  3055. WRITE_ONCE(memcg->zswap_writeback, true);
  3056. #endif
  3057. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  3058. if (parent) {
  3059. WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
  3060. page_counter_init(&memcg->memory, &parent->memory, true);
  3061. page_counter_init(&memcg->swap, &parent->swap, false);
  3062. #ifdef CONFIG_MEMCG_V1
  3063. WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
  3064. page_counter_init(&memcg->kmem, &parent->kmem, false);
  3065. page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
  3066. #endif
  3067. } else {
  3068. init_memcg_stats();
  3069. init_memcg_events();
  3070. page_counter_init(&memcg->memory, NULL, true);
  3071. page_counter_init(&memcg->swap, NULL, false);
  3072. #ifdef CONFIG_MEMCG_V1
  3073. page_counter_init(&memcg->kmem, NULL, false);
  3074. page_counter_init(&memcg->tcpmem, NULL, false);
  3075. #endif
  3076. root_mem_cgroup = memcg;
  3077. return &memcg->css;
  3078. }
  3079. if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
  3080. static_branch_inc(&memcg_sockets_enabled_key);
  3081. if (!cgroup_memory_nobpf)
  3082. static_branch_inc(&memcg_bpf_enabled_key);
  3083. return &memcg->css;
  3084. }
  3085. static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  3086. {
  3087. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3088. if (memcg_online_kmem(memcg))
  3089. goto remove_id;
  3090. /*
  3091. * A memcg must be visible for expand_shrinker_info()
  3092. * by the time the maps are allocated. So, we allocate maps
  3093. * here, when for_each_mem_cgroup() can't skip it.
  3094. */
  3095. if (alloc_shrinker_info(memcg))
  3096. goto offline_kmem;
  3097. if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
  3098. queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
  3099. FLUSH_TIME);
  3100. lru_gen_online_memcg(memcg);
  3101. /* Online state pins memcg ID, memcg ID pins CSS */
  3102. refcount_set(&memcg->id.ref, 1);
  3103. css_get(css);
  3104. /*
  3105. * Ensure mem_cgroup_from_id() works once we're fully online.
  3106. *
  3107. * We could do this earlier and require callers to filter with
  3108. * css_tryget_online(). But right now there are no users that
  3109. * need earlier access, and the workingset code relies on the
  3110. * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
  3111. * publish it here at the end of onlining. This matches the
  3112. * regular ID destruction during offlining.
  3113. */
  3114. xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
  3115. return 0;
  3116. offline_kmem:
  3117. memcg_offline_kmem(memcg);
  3118. remove_id:
  3119. mem_cgroup_id_remove(memcg);
  3120. return -ENOMEM;
  3121. }
  3122. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  3123. {
  3124. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3125. memcg1_css_offline(memcg);
  3126. page_counter_set_min(&memcg->memory, 0);
  3127. page_counter_set_low(&memcg->memory, 0);
  3128. zswap_memcg_offline_cleanup(memcg);
  3129. memcg_offline_kmem(memcg);
  3130. reparent_shrinker_deferred(memcg);
  3131. wb_memcg_offline(memcg);
  3132. lru_gen_offline_memcg(memcg);
  3133. drain_all_stock(memcg);
  3134. mem_cgroup_id_put(memcg);
  3135. }
  3136. static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
  3137. {
  3138. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3139. invalidate_reclaim_iterators(memcg);
  3140. lru_gen_release_memcg(memcg);
  3141. }
  3142. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  3143. {
  3144. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3145. int __maybe_unused i;
  3146. #ifdef CONFIG_CGROUP_WRITEBACK
  3147. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  3148. wb_wait_for_completion(&memcg->cgwb_frn[i].done);
  3149. #endif
  3150. if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
  3151. static_branch_dec(&memcg_sockets_enabled_key);
  3152. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
  3153. static_branch_dec(&memcg_sockets_enabled_key);
  3154. if (!cgroup_memory_nobpf)
  3155. static_branch_dec(&memcg_bpf_enabled_key);
  3156. vmpressure_cleanup(&memcg->vmpressure);
  3157. cancel_work_sync(&memcg->high_work);
  3158. memcg1_remove_from_trees(memcg);
  3159. free_shrinker_info(memcg);
  3160. mem_cgroup_free(memcg);
  3161. }
  3162. /**
  3163. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  3164. * @css: the target css
  3165. *
  3166. * Reset the states of the mem_cgroup associated with @css. This is
  3167. * invoked when the userland requests disabling on the default hierarchy
  3168. * but the memcg is pinned through dependency. The memcg should stop
  3169. * applying policies and should revert to the vanilla state as it may be
  3170. * made visible again.
  3171. *
  3172. * The current implementation only resets the essential configurations.
  3173. * This needs to be expanded to cover all the visible parts.
  3174. */
  3175. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  3176. {
  3177. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3178. page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
  3179. page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
  3180. #ifdef CONFIG_MEMCG_V1
  3181. page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
  3182. page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
  3183. #endif
  3184. page_counter_set_min(&memcg->memory, 0);
  3185. page_counter_set_low(&memcg->memory, 0);
  3186. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  3187. memcg1_soft_limit_reset(memcg);
  3188. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  3189. memcg_wb_domain_size_changed(memcg);
  3190. }
  3191. static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
  3192. {
  3193. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3194. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  3195. struct memcg_vmstats_percpu *statc;
  3196. long delta, delta_cpu, v;
  3197. int i, nid;
  3198. statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
  3199. for (i = 0; i < MEMCG_VMSTAT_SIZE; i++) {
  3200. /*
  3201. * Collect the aggregated propagation counts of groups
  3202. * below us. We're in a per-cpu loop here and this is
  3203. * a global counter, so the first cycle will get them.
  3204. */
  3205. delta = memcg->vmstats->state_pending[i];
  3206. if (delta)
  3207. memcg->vmstats->state_pending[i] = 0;
  3208. /* Add CPU changes on this level since the last flush */
  3209. delta_cpu = 0;
  3210. v = READ_ONCE(statc->state[i]);
  3211. if (v != statc->state_prev[i]) {
  3212. delta_cpu = v - statc->state_prev[i];
  3213. delta += delta_cpu;
  3214. statc->state_prev[i] = v;
  3215. }
  3216. /* Aggregate counts on this level and propagate upwards */
  3217. if (delta_cpu)
  3218. memcg->vmstats->state_local[i] += delta_cpu;
  3219. if (delta) {
  3220. memcg->vmstats->state[i] += delta;
  3221. if (parent)
  3222. parent->vmstats->state_pending[i] += delta;
  3223. }
  3224. }
  3225. for (i = 0; i < NR_MEMCG_EVENTS; i++) {
  3226. delta = memcg->vmstats->events_pending[i];
  3227. if (delta)
  3228. memcg->vmstats->events_pending[i] = 0;
  3229. delta_cpu = 0;
  3230. v = READ_ONCE(statc->events[i]);
  3231. if (v != statc->events_prev[i]) {
  3232. delta_cpu = v - statc->events_prev[i];
  3233. delta += delta_cpu;
  3234. statc->events_prev[i] = v;
  3235. }
  3236. if (delta_cpu)
  3237. memcg->vmstats->events_local[i] += delta_cpu;
  3238. if (delta) {
  3239. memcg->vmstats->events[i] += delta;
  3240. if (parent)
  3241. parent->vmstats->events_pending[i] += delta;
  3242. }
  3243. }
  3244. for_each_node_state(nid, N_MEMORY) {
  3245. struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
  3246. struct lruvec_stats *lstats = pn->lruvec_stats;
  3247. struct lruvec_stats *plstats = NULL;
  3248. struct lruvec_stats_percpu *lstatc;
  3249. if (parent)
  3250. plstats = parent->nodeinfo[nid]->lruvec_stats;
  3251. lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
  3252. for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; i++) {
  3253. delta = lstats->state_pending[i];
  3254. if (delta)
  3255. lstats->state_pending[i] = 0;
  3256. delta_cpu = 0;
  3257. v = READ_ONCE(lstatc->state[i]);
  3258. if (v != lstatc->state_prev[i]) {
  3259. delta_cpu = v - lstatc->state_prev[i];
  3260. delta += delta_cpu;
  3261. lstatc->state_prev[i] = v;
  3262. }
  3263. if (delta_cpu)
  3264. lstats->state_local[i] += delta_cpu;
  3265. if (delta) {
  3266. lstats->state[i] += delta;
  3267. if (plstats)
  3268. plstats->state_pending[i] += delta;
  3269. }
  3270. }
  3271. }
  3272. WRITE_ONCE(statc->stats_updates, 0);
  3273. /* We are in a per-cpu loop here, only do the atomic write once */
  3274. if (atomic64_read(&memcg->vmstats->stats_updates))
  3275. atomic64_set(&memcg->vmstats->stats_updates, 0);
  3276. }
  3277. static void mem_cgroup_fork(struct task_struct *task)
  3278. {
  3279. /*
  3280. * Set the update flag to cause task->objcg to be initialized lazily
  3281. * on the first allocation. It can be done without any synchronization
  3282. * because it's always performed on the current task, so does
  3283. * current_objcg_update().
  3284. */
  3285. task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
  3286. }
  3287. static void mem_cgroup_exit(struct task_struct *task)
  3288. {
  3289. struct obj_cgroup *objcg = task->objcg;
  3290. objcg = (struct obj_cgroup *)
  3291. ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
  3292. obj_cgroup_put(objcg);
  3293. /*
  3294. * Some kernel allocations can happen after this point,
  3295. * but let's ignore them. It can be done without any synchronization
  3296. * because it's always performed on the current task, so does
  3297. * current_objcg_update().
  3298. */
  3299. task->objcg = NULL;
  3300. }
  3301. #ifdef CONFIG_LRU_GEN
  3302. static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
  3303. {
  3304. struct task_struct *task;
  3305. struct cgroup_subsys_state *css;
  3306. /* find the first leader if there is any */
  3307. cgroup_taskset_for_each_leader(task, css, tset)
  3308. break;
  3309. if (!task)
  3310. return;
  3311. task_lock(task);
  3312. if (task->mm && READ_ONCE(task->mm->owner) == task)
  3313. lru_gen_migrate_mm(task->mm);
  3314. task_unlock(task);
  3315. }
  3316. #else
  3317. static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
  3318. #endif /* CONFIG_LRU_GEN */
  3319. static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
  3320. {
  3321. struct task_struct *task;
  3322. struct cgroup_subsys_state *css;
  3323. cgroup_taskset_for_each(task, css, tset) {
  3324. /* atomically set the update bit */
  3325. set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
  3326. }
  3327. }
  3328. static void mem_cgroup_attach(struct cgroup_taskset *tset)
  3329. {
  3330. mem_cgroup_lru_gen_attach(tset);
  3331. mem_cgroup_kmem_attach(tset);
  3332. }
  3333. static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
  3334. {
  3335. if (value == PAGE_COUNTER_MAX)
  3336. seq_puts(m, "max\n");
  3337. else
  3338. seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
  3339. return 0;
  3340. }
  3341. static u64 memory_current_read(struct cgroup_subsys_state *css,
  3342. struct cftype *cft)
  3343. {
  3344. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3345. return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
  3346. }
  3347. #define OFP_PEAK_UNSET (((-1UL)))
  3348. static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
  3349. {
  3350. struct cgroup_of_peak *ofp = of_peak(sf->private);
  3351. u64 fd_peak = READ_ONCE(ofp->value), peak;
  3352. /* User wants global or local peak? */
  3353. if (fd_peak == OFP_PEAK_UNSET)
  3354. peak = pc->watermark;
  3355. else
  3356. peak = max(fd_peak, READ_ONCE(pc->local_watermark));
  3357. seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
  3358. return 0;
  3359. }
  3360. static int memory_peak_show(struct seq_file *sf, void *v)
  3361. {
  3362. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  3363. return peak_show(sf, v, &memcg->memory);
  3364. }
  3365. static int peak_open(struct kernfs_open_file *of)
  3366. {
  3367. struct cgroup_of_peak *ofp = of_peak(of);
  3368. ofp->value = OFP_PEAK_UNSET;
  3369. return 0;
  3370. }
  3371. static void peak_release(struct kernfs_open_file *of)
  3372. {
  3373. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3374. struct cgroup_of_peak *ofp = of_peak(of);
  3375. if (ofp->value == OFP_PEAK_UNSET) {
  3376. /* fast path (no writes on this fd) */
  3377. return;
  3378. }
  3379. spin_lock(&memcg->peaks_lock);
  3380. list_del(&ofp->list);
  3381. spin_unlock(&memcg->peaks_lock);
  3382. }
  3383. static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
  3384. loff_t off, struct page_counter *pc,
  3385. struct list_head *watchers)
  3386. {
  3387. unsigned long usage;
  3388. struct cgroup_of_peak *peer_ctx;
  3389. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3390. struct cgroup_of_peak *ofp = of_peak(of);
  3391. spin_lock(&memcg->peaks_lock);
  3392. usage = page_counter_read(pc);
  3393. WRITE_ONCE(pc->local_watermark, usage);
  3394. list_for_each_entry(peer_ctx, watchers, list)
  3395. if (usage > peer_ctx->value)
  3396. WRITE_ONCE(peer_ctx->value, usage);
  3397. /* initial write, register watcher */
  3398. if (ofp->value == -1)
  3399. list_add(&ofp->list, watchers);
  3400. WRITE_ONCE(ofp->value, usage);
  3401. spin_unlock(&memcg->peaks_lock);
  3402. return nbytes;
  3403. }
  3404. static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
  3405. size_t nbytes, loff_t off)
  3406. {
  3407. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3408. return peak_write(of, buf, nbytes, off, &memcg->memory,
  3409. &memcg->memory_peaks);
  3410. }
  3411. #undef OFP_PEAK_UNSET
  3412. static int memory_min_show(struct seq_file *m, void *v)
  3413. {
  3414. return seq_puts_memcg_tunable(m,
  3415. READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
  3416. }
  3417. static ssize_t memory_min_write(struct kernfs_open_file *of,
  3418. char *buf, size_t nbytes, loff_t off)
  3419. {
  3420. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3421. unsigned long min;
  3422. int err;
  3423. buf = strstrip(buf);
  3424. err = page_counter_memparse(buf, "max", &min);
  3425. if (err)
  3426. return err;
  3427. page_counter_set_min(&memcg->memory, min);
  3428. return nbytes;
  3429. }
  3430. static int memory_low_show(struct seq_file *m, void *v)
  3431. {
  3432. return seq_puts_memcg_tunable(m,
  3433. READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
  3434. }
  3435. static ssize_t memory_low_write(struct kernfs_open_file *of,
  3436. char *buf, size_t nbytes, loff_t off)
  3437. {
  3438. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3439. unsigned long low;
  3440. int err;
  3441. buf = strstrip(buf);
  3442. err = page_counter_memparse(buf, "max", &low);
  3443. if (err)
  3444. return err;
  3445. page_counter_set_low(&memcg->memory, low);
  3446. return nbytes;
  3447. }
  3448. static int memory_high_show(struct seq_file *m, void *v)
  3449. {
  3450. return seq_puts_memcg_tunable(m,
  3451. READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
  3452. }
  3453. static ssize_t memory_high_write(struct kernfs_open_file *of,
  3454. char *buf, size_t nbytes, loff_t off)
  3455. {
  3456. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3457. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  3458. bool drained = false;
  3459. unsigned long high;
  3460. int err;
  3461. buf = strstrip(buf);
  3462. err = page_counter_memparse(buf, "max", &high);
  3463. if (err)
  3464. return err;
  3465. page_counter_set_high(&memcg->memory, high);
  3466. for (;;) {
  3467. unsigned long nr_pages = page_counter_read(&memcg->memory);
  3468. unsigned long reclaimed;
  3469. if (nr_pages <= high)
  3470. break;
  3471. if (signal_pending(current))
  3472. break;
  3473. if (!drained) {
  3474. drain_all_stock(memcg);
  3475. drained = true;
  3476. continue;
  3477. }
  3478. reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
  3479. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
  3480. if (!reclaimed && !nr_retries--)
  3481. break;
  3482. }
  3483. memcg_wb_domain_size_changed(memcg);
  3484. return nbytes;
  3485. }
  3486. static int memory_max_show(struct seq_file *m, void *v)
  3487. {
  3488. return seq_puts_memcg_tunable(m,
  3489. READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
  3490. }
  3491. static ssize_t memory_max_write(struct kernfs_open_file *of,
  3492. char *buf, size_t nbytes, loff_t off)
  3493. {
  3494. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3495. unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
  3496. bool drained = false;
  3497. unsigned long max;
  3498. int err;
  3499. buf = strstrip(buf);
  3500. err = page_counter_memparse(buf, "max", &max);
  3501. if (err)
  3502. return err;
  3503. xchg(&memcg->memory.max, max);
  3504. for (;;) {
  3505. unsigned long nr_pages = page_counter_read(&memcg->memory);
  3506. if (nr_pages <= max)
  3507. break;
  3508. if (signal_pending(current))
  3509. break;
  3510. if (!drained) {
  3511. drain_all_stock(memcg);
  3512. drained = true;
  3513. continue;
  3514. }
  3515. if (nr_reclaims) {
  3516. if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
  3517. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
  3518. nr_reclaims--;
  3519. continue;
  3520. }
  3521. memcg_memory_event(memcg, MEMCG_OOM);
  3522. if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
  3523. break;
  3524. }
  3525. memcg_wb_domain_size_changed(memcg);
  3526. return nbytes;
  3527. }
  3528. /*
  3529. * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
  3530. * if any new events become available.
  3531. */
  3532. static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
  3533. {
  3534. seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
  3535. seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
  3536. seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
  3537. seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
  3538. seq_printf(m, "oom_kill %lu\n",
  3539. atomic_long_read(&events[MEMCG_OOM_KILL]));
  3540. seq_printf(m, "oom_group_kill %lu\n",
  3541. atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
  3542. }
  3543. static int memory_events_show(struct seq_file *m, void *v)
  3544. {
  3545. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3546. __memory_events_show(m, memcg->memory_events);
  3547. return 0;
  3548. }
  3549. static int memory_events_local_show(struct seq_file *m, void *v)
  3550. {
  3551. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3552. __memory_events_show(m, memcg->memory_events_local);
  3553. return 0;
  3554. }
  3555. int memory_stat_show(struct seq_file *m, void *v)
  3556. {
  3557. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3558. char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
  3559. struct seq_buf s;
  3560. if (!buf)
  3561. return -ENOMEM;
  3562. seq_buf_init(&s, buf, PAGE_SIZE);
  3563. memory_stat_format(memcg, &s);
  3564. seq_puts(m, buf);
  3565. kfree(buf);
  3566. return 0;
  3567. }
  3568. #ifdef CONFIG_NUMA
  3569. static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
  3570. int item)
  3571. {
  3572. return lruvec_page_state(lruvec, item) *
  3573. memcg_page_state_output_unit(item);
  3574. }
  3575. static int memory_numa_stat_show(struct seq_file *m, void *v)
  3576. {
  3577. int i;
  3578. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3579. mem_cgroup_flush_stats(memcg);
  3580. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  3581. int nid;
  3582. if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
  3583. continue;
  3584. seq_printf(m, "%s", memory_stats[i].name);
  3585. for_each_node_state(nid, N_MEMORY) {
  3586. u64 size;
  3587. struct lruvec *lruvec;
  3588. lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
  3589. size = lruvec_page_state_output(lruvec,
  3590. memory_stats[i].idx);
  3591. seq_printf(m, " N%d=%llu", nid, size);
  3592. }
  3593. seq_putc(m, '\n');
  3594. }
  3595. return 0;
  3596. }
  3597. #endif
  3598. static int memory_oom_group_show(struct seq_file *m, void *v)
  3599. {
  3600. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3601. seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
  3602. return 0;
  3603. }
  3604. static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
  3605. char *buf, size_t nbytes, loff_t off)
  3606. {
  3607. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3608. int ret, oom_group;
  3609. buf = strstrip(buf);
  3610. if (!buf)
  3611. return -EINVAL;
  3612. ret = kstrtoint(buf, 0, &oom_group);
  3613. if (ret)
  3614. return ret;
  3615. if (oom_group != 0 && oom_group != 1)
  3616. return -EINVAL;
  3617. WRITE_ONCE(memcg->oom_group, oom_group);
  3618. return nbytes;
  3619. }
  3620. enum {
  3621. MEMORY_RECLAIM_SWAPPINESS = 0,
  3622. MEMORY_RECLAIM_NULL,
  3623. };
  3624. static const match_table_t tokens = {
  3625. { MEMORY_RECLAIM_SWAPPINESS, "swappiness=%d"},
  3626. { MEMORY_RECLAIM_NULL, NULL },
  3627. };
  3628. static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
  3629. size_t nbytes, loff_t off)
  3630. {
  3631. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3632. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  3633. unsigned long nr_to_reclaim, nr_reclaimed = 0;
  3634. int swappiness = -1;
  3635. unsigned int reclaim_options;
  3636. char *old_buf, *start;
  3637. substring_t args[MAX_OPT_ARGS];
  3638. buf = strstrip(buf);
  3639. old_buf = buf;
  3640. nr_to_reclaim = memparse(buf, &buf) / PAGE_SIZE;
  3641. if (buf == old_buf)
  3642. return -EINVAL;
  3643. buf = strstrip(buf);
  3644. while ((start = strsep(&buf, " ")) != NULL) {
  3645. if (!strlen(start))
  3646. continue;
  3647. switch (match_token(start, tokens, args)) {
  3648. case MEMORY_RECLAIM_SWAPPINESS:
  3649. if (match_int(&args[0], &swappiness))
  3650. return -EINVAL;
  3651. if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
  3652. return -EINVAL;
  3653. break;
  3654. default:
  3655. return -EINVAL;
  3656. }
  3657. }
  3658. reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
  3659. while (nr_reclaimed < nr_to_reclaim) {
  3660. /* Will converge on zero, but reclaim enforces a minimum */
  3661. unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
  3662. unsigned long reclaimed;
  3663. if (signal_pending(current))
  3664. return -EINTR;
  3665. /*
  3666. * This is the final attempt, drain percpu lru caches in the
  3667. * hope of introducing more evictable pages for
  3668. * try_to_free_mem_cgroup_pages().
  3669. */
  3670. if (!nr_retries)
  3671. lru_add_drain_all();
  3672. reclaimed = try_to_free_mem_cgroup_pages(memcg,
  3673. batch_size, GFP_KERNEL,
  3674. reclaim_options,
  3675. swappiness == -1 ? NULL : &swappiness);
  3676. if (!reclaimed && !nr_retries--)
  3677. return -EAGAIN;
  3678. nr_reclaimed += reclaimed;
  3679. }
  3680. return nbytes;
  3681. }
  3682. static struct cftype memory_files[] = {
  3683. {
  3684. .name = "current",
  3685. .flags = CFTYPE_NOT_ON_ROOT,
  3686. .read_u64 = memory_current_read,
  3687. },
  3688. {
  3689. .name = "peak",
  3690. .flags = CFTYPE_NOT_ON_ROOT,
  3691. .open = peak_open,
  3692. .release = peak_release,
  3693. .seq_show = memory_peak_show,
  3694. .write = memory_peak_write,
  3695. },
  3696. {
  3697. .name = "min",
  3698. .flags = CFTYPE_NOT_ON_ROOT,
  3699. .seq_show = memory_min_show,
  3700. .write = memory_min_write,
  3701. },
  3702. {
  3703. .name = "low",
  3704. .flags = CFTYPE_NOT_ON_ROOT,
  3705. .seq_show = memory_low_show,
  3706. .write = memory_low_write,
  3707. },
  3708. {
  3709. .name = "high",
  3710. .flags = CFTYPE_NOT_ON_ROOT,
  3711. .seq_show = memory_high_show,
  3712. .write = memory_high_write,
  3713. },
  3714. {
  3715. .name = "max",
  3716. .flags = CFTYPE_NOT_ON_ROOT,
  3717. .seq_show = memory_max_show,
  3718. .write = memory_max_write,
  3719. },
  3720. {
  3721. .name = "events",
  3722. .flags = CFTYPE_NOT_ON_ROOT,
  3723. .file_offset = offsetof(struct mem_cgroup, events_file),
  3724. .seq_show = memory_events_show,
  3725. },
  3726. {
  3727. .name = "events.local",
  3728. .flags = CFTYPE_NOT_ON_ROOT,
  3729. .file_offset = offsetof(struct mem_cgroup, events_local_file),
  3730. .seq_show = memory_events_local_show,
  3731. },
  3732. {
  3733. .name = "stat",
  3734. .seq_show = memory_stat_show,
  3735. },
  3736. #ifdef CONFIG_NUMA
  3737. {
  3738. .name = "numa_stat",
  3739. .seq_show = memory_numa_stat_show,
  3740. },
  3741. #endif
  3742. {
  3743. .name = "oom.group",
  3744. .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
  3745. .seq_show = memory_oom_group_show,
  3746. .write = memory_oom_group_write,
  3747. },
  3748. {
  3749. .name = "reclaim",
  3750. .flags = CFTYPE_NS_DELEGATABLE,
  3751. .write = memory_reclaim,
  3752. },
  3753. { } /* terminate */
  3754. };
  3755. struct cgroup_subsys memory_cgrp_subsys = {
  3756. .css_alloc = mem_cgroup_css_alloc,
  3757. .css_online = mem_cgroup_css_online,
  3758. .css_offline = mem_cgroup_css_offline,
  3759. .css_released = mem_cgroup_css_released,
  3760. .css_free = mem_cgroup_css_free,
  3761. .css_reset = mem_cgroup_css_reset,
  3762. .css_rstat_flush = mem_cgroup_css_rstat_flush,
  3763. .attach = mem_cgroup_attach,
  3764. .fork = mem_cgroup_fork,
  3765. .exit = mem_cgroup_exit,
  3766. .dfl_cftypes = memory_files,
  3767. #ifdef CONFIG_MEMCG_V1
  3768. .can_attach = memcg1_can_attach,
  3769. .cancel_attach = memcg1_cancel_attach,
  3770. .post_attach = memcg1_move_task,
  3771. .legacy_cftypes = mem_cgroup_legacy_files,
  3772. #endif
  3773. .early_init = 0,
  3774. };
  3775. /**
  3776. * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
  3777. * @root: the top ancestor of the sub-tree being checked
  3778. * @memcg: the memory cgroup to check
  3779. *
  3780. * WARNING: This function is not stateless! It can only be used as part
  3781. * of a top-down tree iteration, not for isolated queries.
  3782. */
  3783. void mem_cgroup_calculate_protection(struct mem_cgroup *root,
  3784. struct mem_cgroup *memcg)
  3785. {
  3786. bool recursive_protection =
  3787. cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
  3788. if (mem_cgroup_disabled())
  3789. return;
  3790. if (!root)
  3791. root = root_mem_cgroup;
  3792. page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
  3793. }
  3794. static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
  3795. gfp_t gfp)
  3796. {
  3797. int ret;
  3798. ret = try_charge(memcg, gfp, folio_nr_pages(folio));
  3799. if (ret)
  3800. goto out;
  3801. mem_cgroup_commit_charge(folio, memcg);
  3802. out:
  3803. return ret;
  3804. }
  3805. int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
  3806. {
  3807. struct mem_cgroup *memcg;
  3808. int ret;
  3809. memcg = get_mem_cgroup_from_mm(mm);
  3810. ret = charge_memcg(folio, memcg, gfp);
  3811. css_put(&memcg->css);
  3812. return ret;
  3813. }
  3814. /**
  3815. * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
  3816. * @memcg: memcg to charge.
  3817. * @gfp: reclaim mode.
  3818. * @nr_pages: number of pages to charge.
  3819. *
  3820. * This function is called when allocating a huge page folio to determine if
  3821. * the memcg has the capacity for it. It does not commit the charge yet,
  3822. * as the hugetlb folio itself has not been obtained from the hugetlb pool.
  3823. *
  3824. * Once we have obtained the hugetlb folio, we can call
  3825. * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
  3826. * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
  3827. * of try_charge().
  3828. *
  3829. * Returns 0 on success. Otherwise, an error code is returned.
  3830. */
  3831. int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
  3832. long nr_pages)
  3833. {
  3834. /*
  3835. * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
  3836. * but do not attempt to commit charge later (or cancel on error) either.
  3837. */
  3838. if (mem_cgroup_disabled() || !memcg ||
  3839. !cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
  3840. !(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
  3841. return -EOPNOTSUPP;
  3842. if (try_charge(memcg, gfp, nr_pages))
  3843. return -ENOMEM;
  3844. return 0;
  3845. }
  3846. /**
  3847. * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
  3848. * @folio: folio to charge.
  3849. * @mm: mm context of the victim
  3850. * @gfp: reclaim mode
  3851. * @entry: swap entry for which the folio is allocated
  3852. *
  3853. * This function charges a folio allocated for swapin. Please call this before
  3854. * adding the folio to the swapcache.
  3855. *
  3856. * Returns 0 on success. Otherwise, an error code is returned.
  3857. */
  3858. int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
  3859. gfp_t gfp, swp_entry_t entry)
  3860. {
  3861. struct mem_cgroup *memcg;
  3862. unsigned short id;
  3863. int ret;
  3864. if (mem_cgroup_disabled())
  3865. return 0;
  3866. id = lookup_swap_cgroup_id(entry);
  3867. rcu_read_lock();
  3868. memcg = mem_cgroup_from_id(id);
  3869. if (!memcg || !css_tryget_online(&memcg->css))
  3870. memcg = get_mem_cgroup_from_mm(mm);
  3871. rcu_read_unlock();
  3872. ret = charge_memcg(folio, memcg, gfp);
  3873. css_put(&memcg->css);
  3874. return ret;
  3875. }
  3876. /*
  3877. * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
  3878. * @entry: the first swap entry for which the pages are charged
  3879. * @nr_pages: number of pages which will be uncharged
  3880. *
  3881. * Call this function after successfully adding the charged page to swapcache.
  3882. *
  3883. * Note: This function assumes the page for which swap slot is being uncharged
  3884. * is order 0 page.
  3885. */
  3886. void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
  3887. {
  3888. /*
  3889. * Cgroup1's unified memory+swap counter has been charged with the
  3890. * new swapcache page, finish the transfer by uncharging the swap
  3891. * slot. The swap slot would also get uncharged when it dies, but
  3892. * it can stick around indefinitely and we'd count the page twice
  3893. * the entire time.
  3894. *
  3895. * Cgroup2 has separate resource counters for memory and swap,
  3896. * so this is a non-issue here. Memory and swap charge lifetimes
  3897. * correspond 1:1 to page and swap slot lifetimes: we charge the
  3898. * page to memory here, and uncharge swap when the slot is freed.
  3899. */
  3900. if (!mem_cgroup_disabled() && do_memsw_account()) {
  3901. /*
  3902. * The swap entry might not get freed for a long time,
  3903. * let's not wait for it. The page already received a
  3904. * memory+swap charge, drop the swap entry duplicate.
  3905. */
  3906. mem_cgroup_uncharge_swap(entry, nr_pages);
  3907. }
  3908. }
  3909. struct uncharge_gather {
  3910. struct mem_cgroup *memcg;
  3911. unsigned long nr_memory;
  3912. unsigned long pgpgout;
  3913. unsigned long nr_kmem;
  3914. int nid;
  3915. };
  3916. static inline void uncharge_gather_clear(struct uncharge_gather *ug)
  3917. {
  3918. memset(ug, 0, sizeof(*ug));
  3919. }
  3920. static void uncharge_batch(const struct uncharge_gather *ug)
  3921. {
  3922. if (ug->nr_memory) {
  3923. page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
  3924. if (do_memsw_account())
  3925. page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
  3926. if (ug->nr_kmem) {
  3927. mod_memcg_state(ug->memcg, MEMCG_KMEM, -ug->nr_kmem);
  3928. memcg1_account_kmem(ug->memcg, -ug->nr_kmem);
  3929. }
  3930. memcg1_oom_recover(ug->memcg);
  3931. }
  3932. memcg1_uncharge_batch(ug->memcg, ug->pgpgout, ug->nr_memory, ug->nid);
  3933. /* drop reference from uncharge_folio */
  3934. css_put(&ug->memcg->css);
  3935. }
  3936. static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
  3937. {
  3938. long nr_pages;
  3939. struct mem_cgroup *memcg;
  3940. struct obj_cgroup *objcg;
  3941. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  3942. /*
  3943. * Nobody should be changing or seriously looking at
  3944. * folio memcg or objcg at this point, we have fully
  3945. * exclusive access to the folio.
  3946. */
  3947. if (folio_memcg_kmem(folio)) {
  3948. objcg = __folio_objcg(folio);
  3949. /*
  3950. * This get matches the put at the end of the function and
  3951. * kmem pages do not hold memcg references anymore.
  3952. */
  3953. memcg = get_mem_cgroup_from_objcg(objcg);
  3954. } else {
  3955. memcg = __folio_memcg(folio);
  3956. }
  3957. if (!memcg)
  3958. return;
  3959. if (ug->memcg != memcg) {
  3960. if (ug->memcg) {
  3961. uncharge_batch(ug);
  3962. uncharge_gather_clear(ug);
  3963. }
  3964. ug->memcg = memcg;
  3965. ug->nid = folio_nid(folio);
  3966. /* pairs with css_put in uncharge_batch */
  3967. css_get(&memcg->css);
  3968. }
  3969. nr_pages = folio_nr_pages(folio);
  3970. if (folio_memcg_kmem(folio)) {
  3971. ug->nr_memory += nr_pages;
  3972. ug->nr_kmem += nr_pages;
  3973. folio->memcg_data = 0;
  3974. obj_cgroup_put(objcg);
  3975. } else {
  3976. /* LRU pages aren't accounted at the root level */
  3977. if (!mem_cgroup_is_root(memcg))
  3978. ug->nr_memory += nr_pages;
  3979. ug->pgpgout++;
  3980. WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
  3981. folio->memcg_data = 0;
  3982. }
  3983. css_put(&memcg->css);
  3984. }
  3985. void __mem_cgroup_uncharge(struct folio *folio)
  3986. {
  3987. struct uncharge_gather ug;
  3988. /* Don't touch folio->lru of any random page, pre-check: */
  3989. if (!folio_memcg_charged(folio))
  3990. return;
  3991. uncharge_gather_clear(&ug);
  3992. uncharge_folio(folio, &ug);
  3993. uncharge_batch(&ug);
  3994. }
  3995. void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
  3996. {
  3997. struct uncharge_gather ug;
  3998. unsigned int i;
  3999. uncharge_gather_clear(&ug);
  4000. for (i = 0; i < folios->nr; i++)
  4001. uncharge_folio(folios->folios[i], &ug);
  4002. if (ug.memcg)
  4003. uncharge_batch(&ug);
  4004. }
  4005. /**
  4006. * mem_cgroup_replace_folio - Charge a folio's replacement.
  4007. * @old: Currently circulating folio.
  4008. * @new: Replacement folio.
  4009. *
  4010. * Charge @new as a replacement folio for @old. @old will
  4011. * be uncharged upon free.
  4012. *
  4013. * Both folios must be locked, @new->mapping must be set up.
  4014. */
  4015. void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
  4016. {
  4017. struct mem_cgroup *memcg;
  4018. long nr_pages = folio_nr_pages(new);
  4019. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  4020. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  4021. VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
  4022. VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
  4023. if (mem_cgroup_disabled())
  4024. return;
  4025. /* Page cache replacement: new folio already charged? */
  4026. if (folio_memcg_charged(new))
  4027. return;
  4028. memcg = folio_memcg(old);
  4029. VM_WARN_ON_ONCE_FOLIO(!memcg, old);
  4030. if (!memcg)
  4031. return;
  4032. /* Force-charge the new page. The old one will be freed soon */
  4033. if (!mem_cgroup_is_root(memcg)) {
  4034. page_counter_charge(&memcg->memory, nr_pages);
  4035. if (do_memsw_account())
  4036. page_counter_charge(&memcg->memsw, nr_pages);
  4037. }
  4038. css_get(&memcg->css);
  4039. commit_charge(new, memcg);
  4040. memcg1_commit_charge(new, memcg);
  4041. }
  4042. /**
  4043. * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
  4044. * @old: Currently circulating folio.
  4045. * @new: Replacement folio.
  4046. *
  4047. * Transfer the memcg data from the old folio to the new folio for migration.
  4048. * The old folio's data info will be cleared. Note that the memory counters
  4049. * will remain unchanged throughout the process.
  4050. *
  4051. * Both folios must be locked, @new->mapping must be set up.
  4052. */
  4053. void mem_cgroup_migrate(struct folio *old, struct folio *new)
  4054. {
  4055. struct mem_cgroup *memcg;
  4056. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  4057. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  4058. VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
  4059. VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
  4060. VM_BUG_ON_FOLIO(folio_test_lru(old), old);
  4061. if (mem_cgroup_disabled())
  4062. return;
  4063. memcg = folio_memcg(old);
  4064. /*
  4065. * Note that it is normal to see !memcg for a hugetlb folio.
  4066. * For e.g, itt could have been allocated when memory_hugetlb_accounting
  4067. * was not selected.
  4068. */
  4069. VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
  4070. if (!memcg)
  4071. return;
  4072. /* Transfer the charge and the css ref */
  4073. commit_charge(new, memcg);
  4074. /* Warning should never happen, so don't worry about refcount non-0 */
  4075. WARN_ON_ONCE(folio_unqueue_deferred_split(old));
  4076. old->memcg_data = 0;
  4077. }
  4078. DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
  4079. EXPORT_SYMBOL(memcg_sockets_enabled_key);
  4080. void mem_cgroup_sk_alloc(struct sock *sk)
  4081. {
  4082. struct mem_cgroup *memcg;
  4083. if (!mem_cgroup_sockets_enabled)
  4084. return;
  4085. /* Do not associate the sock with unrelated interrupted task's memcg. */
  4086. if (!in_task())
  4087. return;
  4088. rcu_read_lock();
  4089. memcg = mem_cgroup_from_task(current);
  4090. if (mem_cgroup_is_root(memcg))
  4091. goto out;
  4092. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
  4093. goto out;
  4094. if (css_tryget(&memcg->css))
  4095. sk->sk_memcg = memcg;
  4096. out:
  4097. rcu_read_unlock();
  4098. }
  4099. void mem_cgroup_sk_free(struct sock *sk)
  4100. {
  4101. if (sk->sk_memcg)
  4102. css_put(&sk->sk_memcg->css);
  4103. }
  4104. /**
  4105. * mem_cgroup_charge_skmem - charge socket memory
  4106. * @memcg: memcg to charge
  4107. * @nr_pages: number of pages to charge
  4108. * @gfp_mask: reclaim mode
  4109. *
  4110. * Charges @nr_pages to @memcg. Returns %true if the charge fit within
  4111. * @memcg's configured limit, %false if it doesn't.
  4112. */
  4113. bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
  4114. gfp_t gfp_mask)
  4115. {
  4116. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4117. return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
  4118. if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
  4119. mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
  4120. return true;
  4121. }
  4122. return false;
  4123. }
  4124. /**
  4125. * mem_cgroup_uncharge_skmem - uncharge socket memory
  4126. * @memcg: memcg to uncharge
  4127. * @nr_pages: number of pages to uncharge
  4128. */
  4129. void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
  4130. {
  4131. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  4132. memcg1_uncharge_skmem(memcg, nr_pages);
  4133. return;
  4134. }
  4135. mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
  4136. refill_stock(memcg, nr_pages);
  4137. }
  4138. static int __init cgroup_memory(char *s)
  4139. {
  4140. char *token;
  4141. while ((token = strsep(&s, ",")) != NULL) {
  4142. if (!*token)
  4143. continue;
  4144. if (!strcmp(token, "nosocket"))
  4145. cgroup_memory_nosocket = true;
  4146. if (!strcmp(token, "nokmem"))
  4147. cgroup_memory_nokmem = true;
  4148. if (!strcmp(token, "nobpf"))
  4149. cgroup_memory_nobpf = true;
  4150. }
  4151. return 1;
  4152. }
  4153. __setup("cgroup.memory=", cgroup_memory);
  4154. /*
  4155. * subsys_initcall() for memory controller.
  4156. *
  4157. * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
  4158. * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
  4159. * basically everything that doesn't depend on a specific mem_cgroup structure
  4160. * should be initialized from here.
  4161. */
  4162. static int __init mem_cgroup_init(void)
  4163. {
  4164. int cpu;
  4165. /*
  4166. * Currently s32 type (can refer to struct batched_lruvec_stat) is
  4167. * used for per-memcg-per-cpu caching of per-node statistics. In order
  4168. * to work fine, we should make sure that the overfill threshold can't
  4169. * exceed S32_MAX / PAGE_SIZE.
  4170. */
  4171. BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
  4172. cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
  4173. memcg_hotplug_cpu_dead);
  4174. for_each_possible_cpu(cpu)
  4175. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  4176. drain_local_stock);
  4177. return 0;
  4178. }
  4179. subsys_initcall(mem_cgroup_init);
  4180. #ifdef CONFIG_SWAP
  4181. static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
  4182. {
  4183. while (!refcount_inc_not_zero(&memcg->id.ref)) {
  4184. /*
  4185. * The root cgroup cannot be destroyed, so it's refcount must
  4186. * always be >= 1.
  4187. */
  4188. if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
  4189. VM_BUG_ON(1);
  4190. break;
  4191. }
  4192. memcg = parent_mem_cgroup(memcg);
  4193. if (!memcg)
  4194. memcg = root_mem_cgroup;
  4195. }
  4196. return memcg;
  4197. }
  4198. /**
  4199. * mem_cgroup_swapout - transfer a memsw charge to swap
  4200. * @folio: folio whose memsw charge to transfer
  4201. * @entry: swap entry to move the charge to
  4202. *
  4203. * Transfer the memsw charge of @folio to @entry.
  4204. */
  4205. void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
  4206. {
  4207. struct mem_cgroup *memcg, *swap_memcg;
  4208. unsigned int nr_entries;
  4209. unsigned short oldid;
  4210. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  4211. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  4212. if (mem_cgroup_disabled())
  4213. return;
  4214. if (!do_memsw_account())
  4215. return;
  4216. memcg = folio_memcg(folio);
  4217. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  4218. if (!memcg)
  4219. return;
  4220. /*
  4221. * In case the memcg owning these pages has been offlined and doesn't
  4222. * have an ID allocated to it anymore, charge the closest online
  4223. * ancestor for the swap instead and transfer the memory+swap charge.
  4224. */
  4225. swap_memcg = mem_cgroup_id_get_online(memcg);
  4226. nr_entries = folio_nr_pages(folio);
  4227. /* Get references for the tail pages, too */
  4228. if (nr_entries > 1)
  4229. mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
  4230. oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
  4231. nr_entries);
  4232. VM_BUG_ON_FOLIO(oldid, folio);
  4233. mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
  4234. folio_unqueue_deferred_split(folio);
  4235. folio->memcg_data = 0;
  4236. if (!mem_cgroup_is_root(memcg))
  4237. page_counter_uncharge(&memcg->memory, nr_entries);
  4238. if (memcg != swap_memcg) {
  4239. if (!mem_cgroup_is_root(swap_memcg))
  4240. page_counter_charge(&swap_memcg->memsw, nr_entries);
  4241. page_counter_uncharge(&memcg->memsw, nr_entries);
  4242. }
  4243. memcg1_swapout(folio, memcg);
  4244. css_put(&memcg->css);
  4245. }
  4246. /**
  4247. * __mem_cgroup_try_charge_swap - try charging swap space for a folio
  4248. * @folio: folio being added to swap
  4249. * @entry: swap entry to charge
  4250. *
  4251. * Try to charge @folio's memcg for the swap space at @entry.
  4252. *
  4253. * Returns 0 on success, -ENOMEM on failure.
  4254. */
  4255. int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
  4256. {
  4257. unsigned int nr_pages = folio_nr_pages(folio);
  4258. struct page_counter *counter;
  4259. struct mem_cgroup *memcg;
  4260. unsigned short oldid;
  4261. if (do_memsw_account())
  4262. return 0;
  4263. memcg = folio_memcg(folio);
  4264. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  4265. if (!memcg)
  4266. return 0;
  4267. if (!entry.val) {
  4268. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  4269. return 0;
  4270. }
  4271. memcg = mem_cgroup_id_get_online(memcg);
  4272. if (!mem_cgroup_is_root(memcg) &&
  4273. !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
  4274. memcg_memory_event(memcg, MEMCG_SWAP_MAX);
  4275. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  4276. mem_cgroup_id_put(memcg);
  4277. return -ENOMEM;
  4278. }
  4279. /* Get references for the tail pages, too */
  4280. if (nr_pages > 1)
  4281. mem_cgroup_id_get_many(memcg, nr_pages - 1);
  4282. oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
  4283. VM_BUG_ON_FOLIO(oldid, folio);
  4284. mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
  4285. return 0;
  4286. }
  4287. /**
  4288. * __mem_cgroup_uncharge_swap - uncharge swap space
  4289. * @entry: swap entry to uncharge
  4290. * @nr_pages: the amount of swap space to uncharge
  4291. */
  4292. void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
  4293. {
  4294. struct mem_cgroup *memcg;
  4295. unsigned short id;
  4296. id = swap_cgroup_record(entry, 0, nr_pages);
  4297. rcu_read_lock();
  4298. memcg = mem_cgroup_from_id(id);
  4299. if (memcg) {
  4300. if (!mem_cgroup_is_root(memcg)) {
  4301. if (do_memsw_account())
  4302. page_counter_uncharge(&memcg->memsw, nr_pages);
  4303. else
  4304. page_counter_uncharge(&memcg->swap, nr_pages);
  4305. }
  4306. mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
  4307. mem_cgroup_id_put_many(memcg, nr_pages);
  4308. }
  4309. rcu_read_unlock();
  4310. }
  4311. long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
  4312. {
  4313. long nr_swap_pages = get_nr_swap_pages();
  4314. if (mem_cgroup_disabled() || do_memsw_account())
  4315. return nr_swap_pages;
  4316. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
  4317. nr_swap_pages = min_t(long, nr_swap_pages,
  4318. READ_ONCE(memcg->swap.max) -
  4319. page_counter_read(&memcg->swap));
  4320. return nr_swap_pages;
  4321. }
  4322. bool mem_cgroup_swap_full(struct folio *folio)
  4323. {
  4324. struct mem_cgroup *memcg;
  4325. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  4326. if (vm_swap_full())
  4327. return true;
  4328. if (do_memsw_account())
  4329. return false;
  4330. memcg = folio_memcg(folio);
  4331. if (!memcg)
  4332. return false;
  4333. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  4334. unsigned long usage = page_counter_read(&memcg->swap);
  4335. if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
  4336. usage * 2 >= READ_ONCE(memcg->swap.max))
  4337. return true;
  4338. }
  4339. return false;
  4340. }
  4341. static int __init setup_swap_account(char *s)
  4342. {
  4343. bool res;
  4344. if (!kstrtobool(s, &res) && !res)
  4345. pr_warn_once("The swapaccount=0 commandline option is deprecated "
  4346. "in favor of configuring swap control via cgroupfs. "
  4347. "Please report your usecase to linux-mm@kvack.org if you "
  4348. "depend on this functionality.\n");
  4349. return 1;
  4350. }
  4351. __setup("swapaccount=", setup_swap_account);
  4352. static u64 swap_current_read(struct cgroup_subsys_state *css,
  4353. struct cftype *cft)
  4354. {
  4355. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4356. return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
  4357. }
  4358. static int swap_peak_show(struct seq_file *sf, void *v)
  4359. {
  4360. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  4361. return peak_show(sf, v, &memcg->swap);
  4362. }
  4363. static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
  4364. size_t nbytes, loff_t off)
  4365. {
  4366. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4367. return peak_write(of, buf, nbytes, off, &memcg->swap,
  4368. &memcg->swap_peaks);
  4369. }
  4370. static int swap_high_show(struct seq_file *m, void *v)
  4371. {
  4372. return seq_puts_memcg_tunable(m,
  4373. READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
  4374. }
  4375. static ssize_t swap_high_write(struct kernfs_open_file *of,
  4376. char *buf, size_t nbytes, loff_t off)
  4377. {
  4378. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4379. unsigned long high;
  4380. int err;
  4381. buf = strstrip(buf);
  4382. err = page_counter_memparse(buf, "max", &high);
  4383. if (err)
  4384. return err;
  4385. page_counter_set_high(&memcg->swap, high);
  4386. return nbytes;
  4387. }
  4388. static int swap_max_show(struct seq_file *m, void *v)
  4389. {
  4390. return seq_puts_memcg_tunable(m,
  4391. READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
  4392. }
  4393. static ssize_t swap_max_write(struct kernfs_open_file *of,
  4394. char *buf, size_t nbytes, loff_t off)
  4395. {
  4396. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4397. unsigned long max;
  4398. int err;
  4399. buf = strstrip(buf);
  4400. err = page_counter_memparse(buf, "max", &max);
  4401. if (err)
  4402. return err;
  4403. xchg(&memcg->swap.max, max);
  4404. return nbytes;
  4405. }
  4406. static int swap_events_show(struct seq_file *m, void *v)
  4407. {
  4408. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  4409. seq_printf(m, "high %lu\n",
  4410. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
  4411. seq_printf(m, "max %lu\n",
  4412. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
  4413. seq_printf(m, "fail %lu\n",
  4414. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
  4415. return 0;
  4416. }
  4417. static struct cftype swap_files[] = {
  4418. {
  4419. .name = "swap.current",
  4420. .flags = CFTYPE_NOT_ON_ROOT,
  4421. .read_u64 = swap_current_read,
  4422. },
  4423. {
  4424. .name = "swap.high",
  4425. .flags = CFTYPE_NOT_ON_ROOT,
  4426. .seq_show = swap_high_show,
  4427. .write = swap_high_write,
  4428. },
  4429. {
  4430. .name = "swap.max",
  4431. .flags = CFTYPE_NOT_ON_ROOT,
  4432. .seq_show = swap_max_show,
  4433. .write = swap_max_write,
  4434. },
  4435. {
  4436. .name = "swap.peak",
  4437. .flags = CFTYPE_NOT_ON_ROOT,
  4438. .open = peak_open,
  4439. .release = peak_release,
  4440. .seq_show = swap_peak_show,
  4441. .write = swap_peak_write,
  4442. },
  4443. {
  4444. .name = "swap.events",
  4445. .flags = CFTYPE_NOT_ON_ROOT,
  4446. .file_offset = offsetof(struct mem_cgroup, swap_events_file),
  4447. .seq_show = swap_events_show,
  4448. },
  4449. { } /* terminate */
  4450. };
  4451. #ifdef CONFIG_ZSWAP
  4452. /**
  4453. * obj_cgroup_may_zswap - check if this cgroup can zswap
  4454. * @objcg: the object cgroup
  4455. *
  4456. * Check if the hierarchical zswap limit has been reached.
  4457. *
  4458. * This doesn't check for specific headroom, and it is not atomic
  4459. * either. But with zswap, the size of the allocation is only known
  4460. * once compression has occurred, and this optimistic pre-check avoids
  4461. * spending cycles on compression when there is already no room left
  4462. * or zswap is disabled altogether somewhere in the hierarchy.
  4463. */
  4464. bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
  4465. {
  4466. struct mem_cgroup *memcg, *original_memcg;
  4467. bool ret = true;
  4468. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4469. return true;
  4470. original_memcg = get_mem_cgroup_from_objcg(objcg);
  4471. for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
  4472. memcg = parent_mem_cgroup(memcg)) {
  4473. unsigned long max = READ_ONCE(memcg->zswap_max);
  4474. unsigned long pages;
  4475. if (max == PAGE_COUNTER_MAX)
  4476. continue;
  4477. if (max == 0) {
  4478. ret = false;
  4479. break;
  4480. }
  4481. /*
  4482. * mem_cgroup_flush_stats() ignores small changes. Use
  4483. * do_flush_stats() directly to get accurate stats for charging.
  4484. */
  4485. do_flush_stats(memcg);
  4486. pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
  4487. if (pages < max)
  4488. continue;
  4489. ret = false;
  4490. break;
  4491. }
  4492. mem_cgroup_put(original_memcg);
  4493. return ret;
  4494. }
  4495. /**
  4496. * obj_cgroup_charge_zswap - charge compression backend memory
  4497. * @objcg: the object cgroup
  4498. * @size: size of compressed object
  4499. *
  4500. * This forces the charge after obj_cgroup_may_zswap() allowed
  4501. * compression and storage in zwap for this cgroup to go ahead.
  4502. */
  4503. void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
  4504. {
  4505. struct mem_cgroup *memcg;
  4506. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4507. return;
  4508. VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
  4509. /* PF_MEMALLOC context, charging must succeed */
  4510. if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
  4511. VM_WARN_ON_ONCE(1);
  4512. rcu_read_lock();
  4513. memcg = obj_cgroup_memcg(objcg);
  4514. mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
  4515. mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
  4516. rcu_read_unlock();
  4517. }
  4518. /**
  4519. * obj_cgroup_uncharge_zswap - uncharge compression backend memory
  4520. * @objcg: the object cgroup
  4521. * @size: size of compressed object
  4522. *
  4523. * Uncharges zswap memory on page in.
  4524. */
  4525. void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
  4526. {
  4527. struct mem_cgroup *memcg;
  4528. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4529. return;
  4530. obj_cgroup_uncharge(objcg, size);
  4531. rcu_read_lock();
  4532. memcg = obj_cgroup_memcg(objcg);
  4533. mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
  4534. mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
  4535. rcu_read_unlock();
  4536. }
  4537. bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
  4538. {
  4539. /* if zswap is disabled, do not block pages going to the swapping device */
  4540. if (!zswap_is_enabled())
  4541. return true;
  4542. for (; memcg; memcg = parent_mem_cgroup(memcg))
  4543. if (!READ_ONCE(memcg->zswap_writeback))
  4544. return false;
  4545. return true;
  4546. }
  4547. static u64 zswap_current_read(struct cgroup_subsys_state *css,
  4548. struct cftype *cft)
  4549. {
  4550. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4551. mem_cgroup_flush_stats(memcg);
  4552. return memcg_page_state(memcg, MEMCG_ZSWAP_B);
  4553. }
  4554. static int zswap_max_show(struct seq_file *m, void *v)
  4555. {
  4556. return seq_puts_memcg_tunable(m,
  4557. READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
  4558. }
  4559. static ssize_t zswap_max_write(struct kernfs_open_file *of,
  4560. char *buf, size_t nbytes, loff_t off)
  4561. {
  4562. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4563. unsigned long max;
  4564. int err;
  4565. buf = strstrip(buf);
  4566. err = page_counter_memparse(buf, "max", &max);
  4567. if (err)
  4568. return err;
  4569. xchg(&memcg->zswap_max, max);
  4570. return nbytes;
  4571. }
  4572. static int zswap_writeback_show(struct seq_file *m, void *v)
  4573. {
  4574. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  4575. seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
  4576. return 0;
  4577. }
  4578. static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
  4579. char *buf, size_t nbytes, loff_t off)
  4580. {
  4581. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4582. int zswap_writeback;
  4583. ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
  4584. if (parse_ret)
  4585. return parse_ret;
  4586. if (zswap_writeback != 0 && zswap_writeback != 1)
  4587. return -EINVAL;
  4588. WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
  4589. return nbytes;
  4590. }
  4591. static struct cftype zswap_files[] = {
  4592. {
  4593. .name = "zswap.current",
  4594. .flags = CFTYPE_NOT_ON_ROOT,
  4595. .read_u64 = zswap_current_read,
  4596. },
  4597. {
  4598. .name = "zswap.max",
  4599. .flags = CFTYPE_NOT_ON_ROOT,
  4600. .seq_show = zswap_max_show,
  4601. .write = zswap_max_write,
  4602. },
  4603. {
  4604. .name = "zswap.writeback",
  4605. .seq_show = zswap_writeback_show,
  4606. .write = zswap_writeback_write,
  4607. },
  4608. { } /* terminate */
  4609. };
  4610. #endif /* CONFIG_ZSWAP */
  4611. static int __init mem_cgroup_swap_init(void)
  4612. {
  4613. if (mem_cgroup_disabled())
  4614. return 0;
  4615. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
  4616. #ifdef CONFIG_MEMCG_V1
  4617. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
  4618. #endif
  4619. #ifdef CONFIG_ZSWAP
  4620. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
  4621. #endif
  4622. return 0;
  4623. }
  4624. subsys_initcall(mem_cgroup_swap_init);
  4625. #endif /* CONFIG_SWAP */