memcontrol.c 145 KB

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