memcontrol.c 145 KB

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