memcontrol.c 147 KB

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