blob: 109161c55bf01ead5642079635ed967eb3eeb4d6 [file] [log] [blame]
Thomas Gleixnerc942fdd2019-05-27 08:55:06 +02001// SPDX-License-Identifier: GPL-2.0-or-later
Balbir Singh8cdea7c2008-02-07 00:13:50 -08002/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
Pavel Emelianov78fb7462008-02-07 00:13:51 -08007 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080010 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
Glauber Costa7ae1e1d2012-12-18 14:21:56 -080014 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
Johannes Weiner1575e682015-04-14 15:44:51 -070018 * Native page reclaim
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
Alex Shi6168d0d2020-12-15 12:34:29 -080023 *
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
Balbir Singh8cdea7c2008-02-07 00:13:50 -080026 */
27
Johannes Weiner3e32cb22014-12-10 15:42:31 -080028#include <linux/page_counter.h>
Balbir Singh8cdea7c2008-02-07 00:13:50 -080029#include <linux/memcontrol.h>
30#include <linux/cgroup.h>
Christoph Hellwiga5201102019-08-28 16:19:53 +020031#include <linux/pagewalk.h>
Ingo Molnar6e84f312017-02-08 18:51:29 +010032#include <linux/sched/mm.h>
Hugh Dickins3a4f8a02017-02-24 14:59:36 -080033#include <linux/shmem_fs.h>
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -080034#include <linux/hugetlb.h>
KAMEZAWA Hiroyukid13d1442009-01-07 18:07:56 -080035#include <linux/pagemap.h>
Matthew Wilcox (Oracle)4882c8092024-02-27 17:42:39 +000036#include <linux/pagevec.h>
Chris Down1ff9e6e2019-03-05 15:48:09 -080037#include <linux/vm_event_item.h>
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -080038#include <linux/smp.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080039#include <linux/page-flags.h>
Balbir Singh66e17072008-02-07 00:13:56 -080040#include <linux/backing-dev.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080041#include <linux/bit_spinlock.h>
42#include <linux/rcupdate.h>
Balbir Singhe2224322009-04-02 16:57:39 -070043#include <linux/limits.h>
Paul Gortmakerb9e15ba2011-05-26 16:00:52 -040044#include <linux/export.h>
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -080045#include <linux/mutex.h>
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -070046#include <linux/rbtree.h>
Balbir Singhb6ac57d2008-04-29 01:00:19 -070047#include <linux/slab.h>
Balbir Singh66e17072008-02-07 00:13:56 -080048#include <linux/swap.h>
Daisuke Nishimura02491442010-03-10 15:22:17 -080049#include <linux/swapops.h>
Balbir Singh66e17072008-02-07 00:13:56 -080050#include <linux/spinlock.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080051#include <linux/eventfd.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050052#include <linux/poll.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080053#include <linux/sort.h>
Balbir Singh66e17072008-02-07 00:13:56 -080054#include <linux/fs.h>
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -080055#include <linux/seq_file.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070056#include <linux/vmpressure.h>
Christoph Hellwigdc90f082022-02-16 15:31:36 +110057#include <linux/memremap.h>
Christoph Lameterb69408e2008-10-18 20:26:14 -070058#include <linux/mm_inline.h>
Johannes Weiner5d1ea48b2014-12-10 15:44:55 -080059#include <linux/swap_cgroup.h>
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -080060#include <linux/cpu.h>
KAMEZAWA Hiroyuki158e0a22010-08-10 18:03:00 -070061#include <linux/oom.h>
Johannes Weiner0056f4e2013-10-31 16:34:14 -070062#include <linux/lockdep.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050063#include <linux/file.h>
Eric W. Biederman03248ad2022-02-09 12:20:45 -060064#include <linux/resume_user_mode.h>
Chris Down0e4b01d2019-09-23 15:34:55 -070065#include <linux/psi.h>
Johannes Weinerc8713d02019-07-11 20:55:59 -070066#include <linux/seq_buf.h>
Michal Hocko6a792692023-03-17 14:44:48 +010067#include <linux/sched/isolation.h>
Vlastimil Babka6011be52023-10-03 11:57:45 +020068#include <linux/kmemleak.h>
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -080069#include "internal.h"
Glauber Costad1a4c0b2011-12-11 21:47:04 +000070#include <net/sock.h>
Michal Hocko4bd2c1e2012-10-08 16:33:10 -070071#include <net/ip.h>
Qiang Huangf35c3a82013-11-12 15:08:22 -080072#include "slab.h"
NeilBrown014bb1d2022-05-09 18:20:47 -070073#include "swap.h"
Balbir Singh8cdea7c2008-02-07 00:13:50 -080074
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080075#include <linux/uaccess.h>
Balbir Singh8697d332008-02-07 00:13:59 -080076
KOSAKI Motohirocc8e9702010-08-09 17:19:57 -070077#include <trace/events/vmscan.h>
78
Tejun Heo073219e2014-02-08 10:36:58 -050079struct cgroup_subsys memory_cgrp_subsys __read_mostly;
80EXPORT_SYMBOL(memory_cgrp_subsys);
David Rientjes68ae5642012-12-12 13:51:57 -080081
Johannes Weiner7d828602016-01-14 15:20:56 -080082struct mem_cgroup *root_mem_cgroup __read_mostly;
83
Roman Gushchin37d59852020-10-17 16:13:50 -070084/* Active memory cgroup to use from an interrupt context */
85DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
Dan Schatzbergc74d40e2021-06-28 19:38:21 -070086EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
Roman Gushchin37d59852020-10-17 16:13:50 -070087
Johannes Weinerf7e1cb62016-01-14 15:21:29 -080088/* Socket memory accounting disabled? */
Roman Gushchin0f0cace2021-06-02 18:09:29 -070089static bool cgroup_memory_nosocket __ro_after_init;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -080090
Vladimir Davydov04823c82016-01-20 15:02:38 -080091/* Kernel memory accounting disabled? */
Muchun Song17c17362022-01-14 14:05:29 -080092static bool cgroup_memory_nokmem __ro_after_init;
Vladimir Davydov04823c82016-01-20 15:02:38 -080093
Yafang Shaob6c1a8a2023-02-10 15:47:31 +000094/* BPF memory accounting disabled? */
95static bool cgroup_memory_nobpf __ro_after_init;
96
Tejun Heo97b27822019-08-26 09:06:56 -070097#ifdef CONFIG_CGROUP_WRITEBACK
98static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
99#endif
100
Johannes Weiner7941d212016-01-14 15:21:23 -0800101/* Whether legacy memory+swap accounting is active */
102static bool do_memsw_account(void)
103{
Johannes Weinerb25806d2022-09-26 09:57:02 -0400104 return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
Johannes Weiner7941d212016-01-14 15:21:23 -0800105}
106
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700107#define THRESHOLDS_EVENTS_TARGET 128
108#define SOFTLIMIT_EVENTS_TARGET 1024
Johannes Weinere9f89742011-03-23 16:42:37 -0700109
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700110/*
111 * Cgroups above their limits are maintained in a RB-Tree, independent of
112 * their hierarchy representation
113 */
114
Mel Gormanef8f2322016-07-28 15:46:05 -0700115struct mem_cgroup_tree_per_node {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700116 struct rb_root rb_root;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700117 struct rb_node *rb_rightmost;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700118 spinlock_t lock;
119};
120
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700121struct mem_cgroup_tree {
122 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
123};
124
125static struct mem_cgroup_tree soft_limit_tree __read_mostly;
126
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -0700127/* for OOM */
128struct mem_cgroup_eventfd_list {
129 struct list_head list;
130 struct eventfd_ctx *eventfd;
131};
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800132
Tejun Heo79bd9812013-11-22 18:20:42 -0500133/*
134 * cgroup_event represents events which userspace want to receive.
135 */
Tejun Heo3bc942f2013-11-22 18:20:44 -0500136struct mem_cgroup_event {
Tejun Heo79bd9812013-11-22 18:20:42 -0500137 /*
Tejun Heo59b6f872013-11-22 18:20:43 -0500138 * memcg which the event belongs to.
Tejun Heo79bd9812013-11-22 18:20:42 -0500139 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500140 struct mem_cgroup *memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -0500141 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500142 * eventfd to signal userspace about the event.
143 */
144 struct eventfd_ctx *eventfd;
145 /*
146 * Each of these stored in a list by the cgroup.
147 */
148 struct list_head list;
149 /*
Tejun Heofba94802013-11-22 18:20:43 -0500150 * register_event() callback will be used to add new userspace
151 * waiter for changes related to this event. Use eventfd_signal()
152 * on eventfd to send notification to userspace.
153 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500154 int (*register_event)(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -0500155 struct eventfd_ctx *eventfd, const char *args);
Tejun Heofba94802013-11-22 18:20:43 -0500156 /*
157 * unregister_event() callback will be called when userspace closes
158 * the eventfd or on cgroup removing. This callback must be set,
159 * if you want provide notification functionality.
160 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500161 void (*unregister_event)(struct mem_cgroup *memcg,
Tejun Heofba94802013-11-22 18:20:43 -0500162 struct eventfd_ctx *eventfd);
163 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500164 * All fields below needed to unregister event when
165 * userspace closes eventfd.
166 */
167 poll_table pt;
168 wait_queue_head_t *wqh;
Ingo Molnarac6424b2017-06-20 12:06:13 +0200169 wait_queue_entry_t wait;
Tejun Heo79bd9812013-11-22 18:20:42 -0500170 struct work_struct remove;
171};
172
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700173static void mem_cgroup_threshold(struct mem_cgroup *memcg);
174static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800175
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800176/* Stuffs for move charges at task migration. */
177/*
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800178 * Types of charges to be moved.
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800179 */
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800180#define MOVE_ANON 0x1U
181#define MOVE_FILE 0x2U
182#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800183
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800184/* "mc" and its members are protected by cgroup_mutex */
185static struct move_charge_struct {
Daisuke Nishimurab1dd6932010-11-24 12:57:06 -0800186 spinlock_t lock; /* for from, to */
Tejun Heo264a0ae2016-04-21 19:09:02 -0400187 struct mm_struct *mm;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800188 struct mem_cgroup *from;
189 struct mem_cgroup *to;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800190 unsigned long flags;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800191 unsigned long precharge;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -0800192 unsigned long moved_charge;
Daisuke Nishimura483c30b2010-03-10 15:22:18 -0800193 unsigned long moved_swap;
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800194 struct task_struct *moving_task; /* a task moving charges */
195 wait_queue_head_t waitq; /* a waitq for other context */
196} mc = {
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -0700197 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800198 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
199};
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800200
Balbir Singh4e416952009-09-23 15:56:39 -0700201/*
Miaohe Linf4d005af2023-07-13 20:14:32 +0800202 * Maximum loops in mem_cgroup_soft_reclaim(), used for soft
Balbir Singh4e416952009-09-23 15:56:39 -0700203 * limit reclaim to prevent infinite loops, if they ever occur.
204 */
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700205#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700206#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
Balbir Singh4e416952009-09-23 15:56:39 -0700207
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800208/* for encoding cft->private value on file */
Glauber Costa86ae53e2012-12-18 14:21:45 -0800209enum res_type {
210 _MEM,
211 _MEMSWAP,
Glauber Costa510fc4e2012-12-18 14:21:47 -0800212 _KMEM,
Vladimir Davydovd55f90b2016-01-20 15:02:44 -0800213 _TCP,
Glauber Costa86ae53e2012-12-18 14:21:45 -0800214};
215
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700216#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
217#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800218#define MEMFILE_ATTR(val) ((val) & 0xffff)
219
Kirill Tkhaib05706f2018-08-17 15:47:33 -0700220/*
221 * Iteration constructs for visiting all cgroups (under a tree). If
222 * loops are exited prematurely (break), mem_cgroup_iter_break() must
223 * be used for reference counting.
224 */
225#define for_each_mem_cgroup_tree(iter, root) \
226 for (iter = mem_cgroup_iter(root, NULL, NULL); \
227 iter != NULL; \
228 iter = mem_cgroup_iter(root, iter, NULL))
229
230#define for_each_mem_cgroup(iter) \
231 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
232 iter != NULL; \
233 iter = mem_cgroup_iter(NULL, iter, NULL))
234
Vasily Averina4ebf1b2021-11-05 13:38:09 -0700235static inline bool task_is_dying(void)
Tetsuo Handa7775fac2019-03-05 15:46:47 -0800236{
237 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
238 (current->flags & PF_EXITING);
239}
240
Anton Vorontsov70ddf632013-04-29 15:08:31 -0700241/* Some nice accessors for the vmpressure. */
242struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
243{
244 if (!memcg)
245 memcg = root_mem_cgroup;
246 return &memcg->vmpressure;
247}
248
Hui Su96478752021-09-02 14:59:36 -0700249struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
Anton Vorontsov70ddf632013-04-29 15:08:31 -0700250{
Hui Su96478752021-09-02 14:59:36 -0700251 return container_of(vmpr, struct mem_cgroup, vmpressure);
Anton Vorontsov70ddf632013-04-29 15:08:31 -0700252}
253
Roman Gushchin1aacbd32023-10-19 15:53:42 -0700254#define CURRENT_OBJCG_UPDATE_BIT 0
255#define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
256
Kirill Tkhai84c07d12018-08-17 15:47:25 -0700257#ifdef CONFIG_MEMCG_KMEM
Roman Gushchin0764db92022-02-11 16:32:32 -0800258static DEFINE_SPINLOCK(objcg_lock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700259
Roman Gushchin4d5c8ae2021-06-02 18:09:30 -0700260bool mem_cgroup_kmem_disabled(void)
261{
262 return cgroup_memory_nokmem;
263}
264
Muchun Songf1286fa2021-04-29 22:56:55 -0700265static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
266 unsigned int nr_pages);
Roman Gushchinc1a660d2021-02-24 12:03:58 -0800267
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700268static void obj_cgroup_release(struct percpu_ref *ref)
269{
270 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700271 unsigned int nr_bytes;
272 unsigned int nr_pages;
273 unsigned long flags;
274
275 /*
276 * At this point all allocated objects are freed, and
277 * objcg->nr_charged_bytes can't have an arbitrary byte value.
278 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
279 *
280 * The following sequence can lead to it:
281 * 1) CPU0: objcg == stock->cached_objcg
282 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
283 * PAGE_SIZE bytes are charged
284 * 3) CPU1: a process from another memcg is allocating something,
285 * the stock if flushed,
286 * objcg->nr_charged_bytes = PAGE_SIZE - 92
287 * 5) CPU0: we do release this object,
288 * 92 bytes are added to stock->nr_bytes
289 * 6) CPU0: stock is flushed,
290 * 92 bytes are added to objcg->nr_charged_bytes
291 *
292 * In the result, nr_charged_bytes == PAGE_SIZE.
293 * This page will be uncharged in obj_cgroup_release().
294 */
295 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
296 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
297 nr_pages = nr_bytes >> PAGE_SHIFT;
298
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700299 if (nr_pages)
Muchun Songf1286fa2021-04-29 22:56:55 -0700300 obj_cgroup_uncharge_pages(objcg, nr_pages);
Muchun Song271dd6b2021-06-28 19:38:06 -0700301
Roman Gushchin0764db92022-02-11 16:32:32 -0800302 spin_lock_irqsave(&objcg_lock, flags);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700303 list_del(&objcg->list);
Roman Gushchin0764db92022-02-11 16:32:32 -0800304 spin_unlock_irqrestore(&objcg_lock, flags);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700305
306 percpu_ref_exit(ref);
307 kfree_rcu(objcg, rcu);
308}
309
310static struct obj_cgroup *obj_cgroup_alloc(void)
311{
312 struct obj_cgroup *objcg;
313 int ret;
314
315 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
316 if (!objcg)
317 return NULL;
318
319 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
320 GFP_KERNEL);
321 if (ret) {
322 kfree(objcg);
323 return NULL;
324 }
325 INIT_LIST_HEAD(&objcg->list);
326 return objcg;
327}
328
329static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
330 struct mem_cgroup *parent)
331{
332 struct obj_cgroup *objcg, *iter;
333
334 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
335
Roman Gushchin0764db92022-02-11 16:32:32 -0800336 spin_lock_irq(&objcg_lock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700337
Muchun Song98383542021-06-28 19:38:03 -0700338 /* 1) Ready to reparent active objcg. */
339 list_add(&objcg->list, &memcg->objcg_list);
340 /* 2) Reparent active objcg and already reparented objcgs to parent. */
341 list_for_each_entry(iter, &memcg->objcg_list, list)
342 WRITE_ONCE(iter->memcg, parent);
343 /* 3) Move already reparented objcgs to the parent's list */
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700344 list_splice(&memcg->objcg_list, &parent->objcg_list);
345
Roman Gushchin0764db92022-02-11 16:32:32 -0800346 spin_unlock_irq(&objcg_lock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700347
348 percpu_ref_kill(&objcg->refcnt);
349}
350
Glauber Costa55007d82012-12-18 14:22:38 -0800351/*
Glauber Costad7f25f82012-12-18 14:22:40 -0800352 * A lot of the calls to the cache allocation functions are expected to be
Vlastimil Babka9f9796b42024-03-26 11:37:38 +0100353 * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
Glauber Costad7f25f82012-12-18 14:22:40 -0800354 * conditional to this static branch, we'll have to allow modules that does
355 * kmem_cache_alloc and the such to see this symbol as well
356 */
Roman Gushchinf7a449f2023-02-13 11:29:22 -0800357DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
358EXPORT_SYMBOL(memcg_kmem_online_key);
Yafang Shaob6c1a8a2023-02-10 15:47:31 +0000359
360DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
361EXPORT_SYMBOL(memcg_bpf_enabled_key);
Yang Shi0a432dcb2019-09-23 15:38:12 -0700362#endif
Tejun Heo17cc4df2017-02-22 15:41:36 -0800363
Tejun Heoad7fa852015-05-27 20:00:02 -0400364/**
Matthew Wilcox (Oracle)75376c62023-01-16 19:25:07 +0000365 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
366 * @folio: folio of interest
Tejun Heoad7fa852015-05-27 20:00:02 -0400367 *
368 * If memcg is bound to the default hierarchy, css of the memcg associated
Matthew Wilcox (Oracle)75376c62023-01-16 19:25:07 +0000369 * with @folio is returned. The returned css remains associated with @folio
Tejun Heoad7fa852015-05-27 20:00:02 -0400370 * until it is released.
371 *
372 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
373 * is returned.
Tejun Heoad7fa852015-05-27 20:00:02 -0400374 */
Matthew Wilcox (Oracle)75376c62023-01-16 19:25:07 +0000375struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
Tejun Heoad7fa852015-05-27 20:00:02 -0400376{
Matthew Wilcox (Oracle)75376c62023-01-16 19:25:07 +0000377 struct mem_cgroup *memcg = folio_memcg(folio);
Tejun Heoad7fa852015-05-27 20:00:02 -0400378
Tejun Heo9e10a132015-09-18 11:56:28 -0400379 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heoad7fa852015-05-27 20:00:02 -0400380 memcg = root_mem_cgroup;
381
Tejun Heoad7fa852015-05-27 20:00:02 -0400382 return &memcg->css;
383}
384
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700385/**
386 * page_cgroup_ino - return inode number of the memcg a page is charged to
387 * @page: the page
388 *
389 * Look up the closest online ancestor of the memory cgroup @page is charged to
390 * and return its inode number or 0 if @page is not charged to any cgroup. It
391 * is safe to call this function without holding a reference to @page.
392 *
393 * Note, this function is inherently racy, because there is nothing to prevent
394 * the cgroup inode from getting torn down and potentially reallocated a moment
395 * after page_cgroup_ino() returns, so it only should be used by callers that
396 * do not care (such as procfs interfaces).
397 */
398ino_t page_cgroup_ino(struct page *page)
399{
400 struct mem_cgroup *memcg;
401 unsigned long ino = 0;
402
403 rcu_read_lock();
Yosry Ahmedec342602023-04-12 00:34:51 +0000404 /* page_folio() is racy here, but the entire function is racy anyway */
405 memcg = folio_memcg_check(page_folio(page));
Roman Gushchin286e04b2020-08-06 23:20:52 -0700406
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700407 while (memcg && !(memcg->css.flags & CSS_ONLINE))
408 memcg = parent_mem_cgroup(memcg);
409 if (memcg)
410 ino = cgroup_ino(memcg->css.cgroup);
411 rcu_read_unlock();
412 return ino;
413}
414
Mel Gormanef8f2322016-07-28 15:46:05 -0700415static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
416 struct mem_cgroup_tree_per_node *mctz,
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800417 unsigned long new_usage_in_excess)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700418{
419 struct rb_node **p = &mctz->rb_root.rb_node;
420 struct rb_node *parent = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -0700421 struct mem_cgroup_per_node *mz_node;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700422 bool rightmost = true;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700423
424 if (mz->on_tree)
425 return;
426
427 mz->usage_in_excess = new_usage_in_excess;
428 if (!mz->usage_in_excess)
429 return;
430 while (*p) {
431 parent = *p;
Mel Gormanef8f2322016-07-28 15:46:05 -0700432 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700433 tree_node);
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700434 if (mz->usage_in_excess < mz_node->usage_in_excess) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700435 p = &(*p)->rb_left;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700436 rightmost = false;
Miaohe Lin378876b02020-12-14 19:06:28 -0800437 } else {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700438 p = &(*p)->rb_right;
Miaohe Lin378876b02020-12-14 19:06:28 -0800439 }
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700440 }
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700441
442 if (rightmost)
443 mctz->rb_rightmost = &mz->tree_node;
444
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700445 rb_link_node(&mz->tree_node, parent, p);
446 rb_insert_color(&mz->tree_node, &mctz->rb_root);
447 mz->on_tree = true;
448}
449
Mel Gormanef8f2322016-07-28 15:46:05 -0700450static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
451 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700452{
453 if (!mz->on_tree)
454 return;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700455
456 if (&mz->tree_node == mctz->rb_rightmost)
457 mctz->rb_rightmost = rb_prev(&mz->tree_node);
458
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700459 rb_erase(&mz->tree_node, &mctz->rb_root);
460 mz->on_tree = false;
461}
462
Mel Gormanef8f2322016-07-28 15:46:05 -0700463static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
464 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700465{
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700466 unsigned long flags;
467
468 spin_lock_irqsave(&mctz->lock, flags);
Johannes Weinercf2c8122014-06-06 14:38:21 -0700469 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700470 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700471}
472
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800473static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
474{
475 unsigned long nr_pages = page_counter_read(&memcg->memory);
Jason Low4db0c3c2015-04-15 16:14:08 -0700476 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800477 unsigned long excess = 0;
478
479 if (nr_pages > soft_limit)
480 excess = nr_pages - soft_limit;
481
482 return excess;
483}
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700484
Matthew Wilcox (Oracle)658b69c2021-04-29 14:51:26 -0400485static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700486{
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800487 unsigned long excess;
Mel Gormanef8f2322016-07-28 15:46:05 -0700488 struct mem_cgroup_per_node *mz;
489 struct mem_cgroup_tree_per_node *mctz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700490
Yu Zhaoe4dde562022-12-21 21:19:04 -0700491 if (lru_gen_enabled()) {
T.J. Alumbaugh36c7b4d2023-01-18 00:18:24 +0000492 if (soft_limit_excess(memcg))
T.J. Alumbaugh5c7e7a02023-05-22 11:20:56 +0000493 lru_gen_soft_reclaim(memcg, nid);
Yu Zhaoe4dde562022-12-21 21:19:04 -0700494 return;
495 }
496
Matthew Wilcox (Oracle)2ab082b2021-06-25 08:57:02 -0400497 mctz = soft_limit_tree.rb_tree_per_node[nid];
Laurent Dufourbfc72282017-03-09 16:17:06 -0800498 if (!mctz)
499 return;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700500 /*
501 * Necessary to update all ancestors when hierarchy is used.
502 * because their event counter is not touched.
503 */
504 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
Matthew Wilcox (Oracle)658b69c2021-04-29 14:51:26 -0400505 mz = memcg->nodeinfo[nid];
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800506 excess = soft_limit_excess(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700507 /*
508 * We have to update the tree if mz is on RB-tree or
509 * mem is over its softlimit.
510 */
511 if (excess || mz->on_tree) {
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700512 unsigned long flags;
513
514 spin_lock_irqsave(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700515 /* if on-tree, remove it */
516 if (mz->on_tree)
Johannes Weinercf2c8122014-06-06 14:38:21 -0700517 __mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700518 /*
519 * Insert again. mz->usage_in_excess will be updated.
520 * If excess is 0, no tree ops.
521 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700522 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700523 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700524 }
525 }
526}
527
528static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
529{
Mel Gormanef8f2322016-07-28 15:46:05 -0700530 struct mem_cgroup_tree_per_node *mctz;
531 struct mem_cgroup_per_node *mz;
532 int nid;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700533
Jianyu Zhane2318752014-06-06 14:38:20 -0700534 for_each_node(nid) {
Johannes Weinera3747b52021-04-29 22:56:14 -0700535 mz = memcg->nodeinfo[nid];
Matthew Wilcox (Oracle)2ab082b2021-06-25 08:57:02 -0400536 mctz = soft_limit_tree.rb_tree_per_node[nid];
Laurent Dufourbfc72282017-03-09 16:17:06 -0800537 if (mctz)
538 mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700539 }
540}
541
Mel Gormanef8f2322016-07-28 15:46:05 -0700542static struct mem_cgroup_per_node *
543__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700544{
Mel Gormanef8f2322016-07-28 15:46:05 -0700545 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700546
547retry:
548 mz = NULL;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700549 if (!mctz->rb_rightmost)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700550 goto done; /* Nothing to reclaim from */
551
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700552 mz = rb_entry(mctz->rb_rightmost,
553 struct mem_cgroup_per_node, tree_node);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700554 /*
555 * Remove the node now but someone else can add it back,
556 * we will to add it back at the end of reclaim to its correct
557 * position in the tree.
558 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700559 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800560 if (!soft_limit_excess(mz->memcg) ||
Shakeel Butt8965aa22020-04-01 21:07:10 -0700561 !css_tryget(&mz->memcg->css))
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700562 goto retry;
563done:
564 return mz;
565}
566
Mel Gormanef8f2322016-07-28 15:46:05 -0700567static struct mem_cgroup_per_node *
568mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700569{
Mel Gormanef8f2322016-07-28 15:46:05 -0700570 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700571
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700572 spin_lock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700573 mz = __mem_cgroup_largest_soft_limit_node(mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700574 spin_unlock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700575 return mz;
576}
577
Shakeel Buttff48c712024-05-01 10:26:13 -0700578/* Subset of node_stat_item for memcg stats */
579static const unsigned int memcg_node_stat_items[] = {
580 NR_INACTIVE_ANON,
581 NR_ACTIVE_ANON,
582 NR_INACTIVE_FILE,
583 NR_ACTIVE_FILE,
584 NR_UNEVICTABLE,
585 NR_SLAB_RECLAIMABLE_B,
586 NR_SLAB_UNRECLAIMABLE_B,
587 WORKINGSET_REFAULT_ANON,
588 WORKINGSET_REFAULT_FILE,
589 WORKINGSET_ACTIVATE_ANON,
590 WORKINGSET_ACTIVATE_FILE,
591 WORKINGSET_RESTORE_ANON,
592 WORKINGSET_RESTORE_FILE,
593 WORKINGSET_NODERECLAIM,
594 NR_ANON_MAPPED,
595 NR_FILE_MAPPED,
596 NR_FILE_PAGES,
597 NR_FILE_DIRTY,
598 NR_WRITEBACK,
599 NR_SHMEM,
600 NR_SHMEM_THPS,
601 NR_FILE_THPS,
602 NR_ANON_THPS,
603 NR_KERNEL_STACK_KB,
604 NR_PAGETABLE,
605 NR_SECONDARY_PAGETABLE,
606#ifdef CONFIG_SWAP
607 NR_SWAPCACHE,
608#endif
609};
610
611static const unsigned int memcg_stat_items[] = {
612 MEMCG_SWAP,
613 MEMCG_SOCK,
614 MEMCG_PERCPU_B,
615 MEMCG_VMALLOC,
616 MEMCG_KMEM,
617 MEMCG_ZSWAP_B,
618 MEMCG_ZSWAPPED,
619};
620
621#define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
622#define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
623 ARRAY_SIZE(memcg_stat_items))
624static int8_t mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
625
626static void init_memcg_stats(void)
627{
628 int8_t i, j = 0;
629
630 BUILD_BUG_ON(MEMCG_NR_STAT >= S8_MAX);
631
632 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i)
633 mem_cgroup_stats_index[memcg_node_stat_items[i]] = ++j;
634
635 for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i)
636 mem_cgroup_stats_index[memcg_stat_items[i]] = ++j;
637}
638
639static inline int memcg_stats_index(int idx)
640{
641 return mem_cgroup_stats_index[idx] - 1;
642}
643
Shakeel Butt70a64b72024-05-01 10:26:11 -0700644struct lruvec_stats_percpu {
645 /* Local (CPU and cgroup) state */
Shakeel Buttff48c712024-05-01 10:26:13 -0700646 long state[NR_MEMCG_NODE_STAT_ITEMS];
Shakeel Butt70a64b72024-05-01 10:26:11 -0700647
648 /* Delta calculation for lockless upward propagation */
Shakeel Buttff48c712024-05-01 10:26:13 -0700649 long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
Shakeel Butt70a64b72024-05-01 10:26:11 -0700650};
651
652struct lruvec_stats {
653 /* Aggregated (CPU and subtree) state */
Shakeel Buttff48c712024-05-01 10:26:13 -0700654 long state[NR_MEMCG_NODE_STAT_ITEMS];
Shakeel Butt70a64b72024-05-01 10:26:11 -0700655
656 /* Non-hierarchical (CPU aggregated) state */
Shakeel Buttff48c712024-05-01 10:26:13 -0700657 long state_local[NR_MEMCG_NODE_STAT_ITEMS];
Shakeel Butt70a64b72024-05-01 10:26:11 -0700658
659 /* Pending child counts during tree propagation */
Shakeel Buttff48c712024-05-01 10:26:13 -0700660 long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
Shakeel Butt70a64b72024-05-01 10:26:11 -0700661};
662
663unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
664{
665 struct mem_cgroup_per_node *pn;
666 long x;
Shakeel Buttff48c712024-05-01 10:26:13 -0700667 int i;
Shakeel Butt70a64b72024-05-01 10:26:11 -0700668
669 if (mem_cgroup_disabled())
670 return node_page_state(lruvec_pgdat(lruvec), idx);
671
Shakeel Buttff48c712024-05-01 10:26:13 -0700672 i = memcg_stats_index(idx);
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700673 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Shakeel Buttff48c712024-05-01 10:26:13 -0700674 return 0;
675
Shakeel Butt70a64b72024-05-01 10:26:11 -0700676 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Shakeel Buttff48c712024-05-01 10:26:13 -0700677 x = READ_ONCE(pn->lruvec_stats->state[i]);
Shakeel Butt70a64b72024-05-01 10:26:11 -0700678#ifdef CONFIG_SMP
679 if (x < 0)
680 x = 0;
681#endif
682 return x;
683}
684
685unsigned long lruvec_page_state_local(struct lruvec *lruvec,
686 enum node_stat_item idx)
687{
688 struct mem_cgroup_per_node *pn;
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700689 long x;
Shakeel Buttff48c712024-05-01 10:26:13 -0700690 int i;
Shakeel Butt70a64b72024-05-01 10:26:11 -0700691
692 if (mem_cgroup_disabled())
693 return node_page_state(lruvec_pgdat(lruvec), idx);
694
Shakeel Buttff48c712024-05-01 10:26:13 -0700695 i = memcg_stats_index(idx);
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700696 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Shakeel Buttff48c712024-05-01 10:26:13 -0700697 return 0;
698
Shakeel Butt70a64b72024-05-01 10:26:11 -0700699 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Shakeel Buttff48c712024-05-01 10:26:13 -0700700 x = READ_ONCE(pn->lruvec_stats->state_local[i]);
Shakeel Butt70a64b72024-05-01 10:26:11 -0700701#ifdef CONFIG_SMP
702 if (x < 0)
703 x = 0;
704#endif
705 return x;
706}
707
Shakeel Buttd396def2022-09-07 04:35:36 +0000708/* Subset of vm_event_item to report for memcg event stats */
709static const unsigned int memcg_vm_event_stat[] = {
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000710 PGPGIN,
711 PGPGOUT,
Shakeel Buttd396def2022-09-07 04:35:36 +0000712 PGSCAN_KSWAPD,
713 PGSCAN_DIRECT,
Johannes Weiner57e9cc52022-10-26 14:01:33 -0400714 PGSCAN_KHUGEPAGED,
Shakeel Buttd396def2022-09-07 04:35:36 +0000715 PGSTEAL_KSWAPD,
716 PGSTEAL_DIRECT,
Johannes Weiner57e9cc52022-10-26 14:01:33 -0400717 PGSTEAL_KHUGEPAGED,
Shakeel Buttd396def2022-09-07 04:35:36 +0000718 PGFAULT,
719 PGMAJFAULT,
720 PGREFILL,
721 PGACTIVATE,
722 PGDEACTIVATE,
723 PGLAZYFREE,
724 PGLAZYFREED,
725#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
726 ZSWPIN,
727 ZSWPOUT,
Yosry Ahmede0bf1dc2023-11-29 03:21:50 +0000728 ZSWPWB,
Shakeel Buttd396def2022-09-07 04:35:36 +0000729#endif
730#ifdef CONFIG_TRANSPARENT_HUGEPAGE
731 THP_FAULT_ALLOC,
732 THP_COLLAPSE_ALLOC,
Xin Hao811244a2023-09-14 00:49:37 +0800733 THP_SWPOUT,
734 THP_SWPOUT_FALLBACK,
Shakeel Buttd396def2022-09-07 04:35:36 +0000735#endif
736};
737
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000738#define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
Shakeel Butt59142d82024-05-01 10:26:10 -0700739static int8_t mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000740
741static void init_memcg_events(void)
742{
Shakeel Butt59142d82024-05-01 10:26:10 -0700743 int8_t i;
744
745 BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= S8_MAX);
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000746
747 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
748 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
749}
750
751static inline int memcg_events_index(enum vm_event_item idx)
752{
753 return mem_cgroup_events_index[idx] - 1;
754}
755
Shakeel Butt410f8e82022-09-07 04:35:35 +0000756struct memcg_vmstats_percpu {
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000757 /* Stats updates since the last flush */
758 unsigned int stats_updates;
759
760 /* Cached pointers for fast iteration in memcg_rstat_updated() */
761 struct memcg_vmstats_percpu *parent;
762 struct memcg_vmstats *vmstats;
763
764 /* The above should fit a single cacheline for memcg_rstat_updated() */
765
Shakeel Butt410f8e82022-09-07 04:35:35 +0000766 /* Local (CPU and cgroup) page state & events */
Shakeel Buttff48c712024-05-01 10:26:13 -0700767 long state[MEMCG_VMSTAT_SIZE];
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000768 unsigned long events[NR_MEMCG_EVENTS];
Shakeel Butt410f8e82022-09-07 04:35:35 +0000769
770 /* Delta calculation for lockless upward propagation */
Shakeel Buttff48c712024-05-01 10:26:13 -0700771 long state_prev[MEMCG_VMSTAT_SIZE];
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000772 unsigned long events_prev[NR_MEMCG_EVENTS];
Shakeel Butt410f8e82022-09-07 04:35:35 +0000773
774 /* Cgroup1: threshold notifications & softlimit tree updates */
775 unsigned long nr_page_events;
776 unsigned long targets[MEM_CGROUP_NTARGETS];
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000777} ____cacheline_aligned;
Shakeel Butt410f8e82022-09-07 04:35:35 +0000778
779struct memcg_vmstats {
780 /* Aggregated (CPU and subtree) page state & events */
Shakeel Buttff48c712024-05-01 10:26:13 -0700781 long state[MEMCG_VMSTAT_SIZE];
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000782 unsigned long events[NR_MEMCG_EVENTS];
Shakeel Butt410f8e82022-09-07 04:35:35 +0000783
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +0000784 /* Non-hierarchical (CPU aggregated) page state & events */
Shakeel Buttff48c712024-05-01 10:26:13 -0700785 long state_local[MEMCG_VMSTAT_SIZE];
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +0000786 unsigned long events_local[NR_MEMCG_EVENTS];
787
Shakeel Butt410f8e82022-09-07 04:35:35 +0000788 /* Pending child counts during tree propagation */
Shakeel Buttff48c712024-05-01 10:26:13 -0700789 long state_pending[MEMCG_VMSTAT_SIZE];
Shakeel Butt8278f1c2022-09-07 04:35:37 +0000790 unsigned long events_pending[NR_MEMCG_EVENTS];
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000791
792 /* Stats updates since the last flush */
793 atomic64_t stats_updates;
Shakeel Butt410f8e82022-09-07 04:35:35 +0000794};
795
Glauber Costaa8964b92012-12-18 14:22:09 -0800796/*
797 * memcg and lruvec stats flushing
798 *
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700799 * Many codepaths leading to stats update or read are performance sensitive and
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800800 * adding stats flushing in such codepaths is not desirable. So, to optimize the
Balbir Singhf64c3f52009-09-23 15:56:37 -0700801 * flushing the kernel does:
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700802 *
Balbir Singhf64c3f52009-09-23 15:56:37 -0700803 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
Glauber Costa45cf7eb2013-02-22 16:34:49 -0800804 * rstat update tree grow unbounded.
Johannes Weiner54f72fe2013-07-08 15:59:49 -0700805 *
Balbir Singhf64c3f52009-09-23 15:56:37 -0700806 * 2) Flush the stats synchronously on reader side only when there are more than
807 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700808 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
Wu Fengguangd3242362009-12-16 12:19:59 +0100809 * only for 2 seconds due to (1).
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700810 */
Wu Fengguangd3242362009-12-16 12:19:59 +0100811static void flush_memcg_stats_dwork(struct work_struct *w);
812static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
Yosry Ahmed508bed82023-11-29 03:21:49 +0000813static u64 flush_last_time;
Johannes Weiner97a6c372011-03-23 16:42:27 -0700814
Balbir Singhf64c3f52009-09-23 15:56:37 -0700815#define FLUSH_TIME (2UL*HZ)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700816
Balbir Singhf64c3f52009-09-23 15:56:37 -0700817/*
818 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
Shakeel Butt11192d92021-11-05 13:37:31 -0700819 * not rely on this as part of an acquired spinlock_t lock. These functions are
820 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
821 * is sufficient.
822 */
823static void memcg_stats_lock(void)
824{
825 preempt_disable_nested();
826 VM_WARN_ON_IRQS_ENABLED();
827}
828
829static void __memcg_stats_lock(void)
830{
831 preempt_disable_nested();
832}
833
834static void memcg_stats_unlock(void)
835{
836 preempt_enable_nested();
837}
838
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000839
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000840static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000841{
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000842 return atomic64_read(&vmstats->stats_updates) >
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000843 MEMCG_CHARGE_BATCH * num_online_cpus();
844}
845
Shakeel Butt9b301612022-04-21 16:35:40 -0700846static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
847{
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000848 struct memcg_vmstats_percpu *statc;
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000849 int cpu = smp_processor_id();
Breno Leitao78ec6f92024-04-24 05:59:39 -0700850 unsigned int stats_updates;
Shakeel Butt11192d92021-11-05 13:37:31 -0700851
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -0700852 if (!val)
853 return;
854
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000855 cgroup_rstat_updated(memcg->css.cgroup, cpu);
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000856 statc = this_cpu_ptr(memcg->vmstats_percpu);
857 for (; statc; statc = statc->parent) {
Breno Leitao78ec6f92024-04-24 05:59:39 -0700858 stats_updates = READ_ONCE(statc->stats_updates) + abs(val);
859 WRITE_ONCE(statc->stats_updates, stats_updates);
860 if (stats_updates < MEMCG_CHARGE_BATCH)
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000861 continue;
862
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -0700863 /*
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000864 * If @memcg is already flush-able, increasing stats_updates is
865 * redundant. Avoid the overhead of the atomic update.
Thomas Gleixnere575d402022-08-25 18:41:28 +0200866 */
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000867 if (!memcg_vmstats_needs_flush(statc->vmstats))
Breno Leitao78ec6f92024-04-24 05:59:39 -0700868 atomic64_add(stats_updates,
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000869 &statc->vmstats->stats_updates);
Breno Leitao78ec6f92024-04-24 05:59:39 -0700870 WRITE_ONCE(statc->stats_updates, 0);
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -0700871 }
Thomas Gleixnere575d402022-08-25 18:41:28 +0200872}
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -0700873
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000874static void do_flush_stats(struct mem_cgroup *memcg)
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -0700875{
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000876 if (mem_cgroup_is_root(memcg))
877 WRITE_ONCE(flush_last_time, jiffies_64);
878
879 cgroup_rstat_flush(memcg->css.cgroup);
880}
881
882/*
883 * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
884 * @memcg: root of the subtree to flush
885 *
886 * Flushing is serialized by the underlying global rstat lock. There is also a
887 * minimum amount of work to be done even if there are no stat updates to flush.
888 * Hence, we only flush the stats if the updates delta exceeds a threshold. This
889 * avoids unnecessary work and contention on the underlying lock.
890 */
891void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
892{
893 if (mem_cgroup_disabled())
Shakeel Butt5b3be692022-01-14 14:05:39 -0800894 return;
Shakeel Butt11192d92021-11-05 13:37:31 -0700895
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000896 if (!memcg)
897 memcg = root_mem_cgroup;
Shakeel Butt5b3be692022-01-14 14:05:39 -0800898
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000899 if (memcg_vmstats_needs_flush(memcg->vmstats))
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000900 do_flush_stats(memcg);
Jiebin Sun873f64b2022-07-23 00:49:49 +0800901}
902
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000903void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
Shakeel Butt11192d92021-11-05 13:37:31 -0700904{
Yosry Ahmed508bed82023-11-29 03:21:49 +0000905 /* Only flush if the periodic flusher is one full cycle late */
906 if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000907 mem_cgroup_flush_stats(memcg);
Shakeel Buttfd25a9e2021-11-05 13:37:34 -0700908}
909
Shakeel Butt11192d92021-11-05 13:37:31 -0700910static void flush_memcg_stats_dwork(struct work_struct *w)
911{
Shakeel Butt9b301612022-04-21 16:35:40 -0700912 /*
Yosry Ahmed9cee7e82024-01-24 10:00:22 +0000913 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
Yosry Ahmed8d59d222023-11-29 03:21:51 +0000914 * in latency-sensitive paths is as cheap as possible.
Shakeel Buttfd25a9e2021-11-05 13:37:34 -0700915 */
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +0000916 do_flush_stats(root_mem_cgroup);
Shakeel Butt11192d92021-11-05 13:37:31 -0700917 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
918}
919
Shakeel Butt410f8e82022-09-07 04:35:35 +0000920unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
921{
Shakeel Buttff48c712024-05-01 10:26:13 -0700922 long x;
923 int i = memcg_stats_index(idx);
924
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700925 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Shakeel Buttff48c712024-05-01 10:26:13 -0700926 return 0;
927
928 x = READ_ONCE(memcg->vmstats->state[i]);
Shakeel Butt410f8e82022-09-07 04:35:35 +0000929#ifdef CONFIG_SMP
930 if (x < 0)
931 x = 0;
932#endif
933 return x;
934}
935
Yosry Ahmed7bd5bc32023-09-22 17:57:40 +0000936static int memcg_page_state_unit(int item);
937
938/*
939 * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
940 * up non-zero sub-page updates to 1 page as zero page updates are ignored.
941 */
942static int memcg_state_val_in_pages(int idx, int val)
943{
944 int unit = memcg_page_state_unit(idx);
945
946 if (!val || unit == PAGE_SIZE)
947 return val;
948 else
949 return max(val * unit / PAGE_SIZE, 1UL);
950}
951
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700952/**
953 * __mod_memcg_state - update cgroup memory statistics
954 * @memcg: the memory cgroup
955 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
956 * @val: delta to add to the counter, can be negative
957 */
Shakeel Butta94032b2024-05-01 10:26:17 -0700958void __mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
959 int val)
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700960{
Shakeel Buttff48c712024-05-01 10:26:13 -0700961 int i = memcg_stats_index(idx);
962
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700963 if (mem_cgroup_disabled())
964 return;
965
966 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700967 return;
968
Shakeel Buttff48c712024-05-01 10:26:13 -0700969 __this_cpu_add(memcg->vmstats_percpu->state[i], val);
Yosry Ahmed7bd5bc32023-09-22 17:57:40 +0000970 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700971}
972
Johannes Weiner2d146aa2021-04-29 22:56:26 -0700973/* idx can be of type enum memcg_stat_item or node_stat_item. */
Johannes Weinera18e6e62021-04-29 22:56:17 -0700974static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
975{
Shakeel Buttff48c712024-05-01 10:26:13 -0700976 long x;
977 int i = memcg_stats_index(idx);
Johannes Weinera18e6e62021-04-29 22:56:17 -0700978
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700979 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Shakeel Buttff48c712024-05-01 10:26:13 -0700980 return 0;
981
982 x = READ_ONCE(memcg->vmstats->state_local[i]);
Johannes Weinera18e6e62021-04-29 22:56:17 -0700983#ifdef CONFIG_SMP
984 if (x < 0)
985 x = 0;
986#endif
987 return x;
988}
989
Shakeel Butt91882c12024-04-20 16:25:05 -0700990static void __mod_memcg_lruvec_state(struct lruvec *lruvec,
991 enum node_stat_item idx,
992 int val)
Roman Gushchineedc4e52020-08-06 23:20:32 -0700993{
994 struct mem_cgroup_per_node *pn;
995 struct mem_cgroup *memcg;
Shakeel Buttff48c712024-05-01 10:26:13 -0700996 int i = memcg_stats_index(idx);
997
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -0700998 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Shakeel Buttff48c712024-05-01 10:26:13 -0700999 return;
Roman Gushchineedc4e52020-08-06 23:20:32 -07001000
1001 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1002 memcg = pn->memcg;
1003
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001004 /*
Muhammad Muzammilbe16dd762023-10-23 17:44:05 +05001005 * The caller from rmap relies on disabled preemption because they never
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001006 * update their counter from in-interrupt context. For these two
1007 * counters we check that the update is never performed from an
1008 * interrupt context while other caller need to have disabled interrupt.
1009 */
1010 __memcg_stats_lock();
Thomas Gleixnere575d402022-08-25 18:41:28 +02001011 if (IS_ENABLED(CONFIG_DEBUG_VM)) {
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001012 switch (idx) {
1013 case NR_ANON_MAPPED:
1014 case NR_FILE_MAPPED:
1015 case NR_ANON_THPS:
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001016 WARN_ON_ONCE(!in_task());
1017 break;
1018 default:
Thomas Gleixnere575d402022-08-25 18:41:28 +02001019 VM_WARN_ON_IRQS_ENABLED();
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001020 }
1021 }
1022
Roman Gushchineedc4e52020-08-06 23:20:32 -07001023 /* Update memcg */
Shakeel Buttff48c712024-05-01 10:26:13 -07001024 __this_cpu_add(memcg->vmstats_percpu->state[i], val);
Roman Gushchineedc4e52020-08-06 23:20:32 -07001025
1026 /* Update lruvec */
Shakeel Buttff48c712024-05-01 10:26:13 -07001027 __this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
Shakeel Butt11192d92021-11-05 13:37:31 -07001028
Yosry Ahmed7bd5bc32023-09-22 17:57:40 +00001029 memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001030 memcg_stats_unlock();
Roman Gushchineedc4e52020-08-06 23:20:32 -07001031}
1032
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001033/**
1034 * __mod_lruvec_state - update lruvec memory statistics
1035 * @lruvec: the lruvec
1036 * @idx: the stat item
1037 * @val: delta to add to the counter, can be negative
1038 *
1039 * The lruvec is the intersection of the NUMA node and a cgroup. This
1040 * function updates the all three counters that are affected by a
1041 * change of state at this level: per-node, per-cgroup, per-lruvec.
1042 */
1043void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
1044 int val)
1045{
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001046 /* Update node */
Roman Gushchineedc4e52020-08-06 23:20:32 -07001047 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001048
Roman Gushchineedc4e52020-08-06 23:20:32 -07001049 /* Update memcg and lruvec */
1050 if (!mem_cgroup_disabled())
1051 __mod_memcg_lruvec_state(lruvec, idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001052}
1053
Matthew Wilcox (Oracle)c7011232023-12-28 08:57:48 +00001054void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
Shakeel Buttc47d5032020-12-14 19:07:14 -08001055 int val)
1056{
Muchun Songb4e0b682021-04-29 22:56:52 -07001057 struct mem_cgroup *memcg;
Matthew Wilcox (Oracle)c7011232023-12-28 08:57:48 +00001058 pg_data_t *pgdat = folio_pgdat(folio);
Shakeel Buttc47d5032020-12-14 19:07:14 -08001059 struct lruvec *lruvec;
1060
Muchun Songb4e0b682021-04-29 22:56:52 -07001061 rcu_read_lock();
Matthew Wilcox (Oracle)c7011232023-12-28 08:57:48 +00001062 memcg = folio_memcg(folio);
Shakeel Buttc47d5032020-12-14 19:07:14 -08001063 /* Untracked pages have no memcg, no lruvec. Update only the node */
Linus Torvaldsd635a69d2020-12-15 13:22:29 -08001064 if (!memcg) {
Muchun Songb4e0b682021-04-29 22:56:52 -07001065 rcu_read_unlock();
Shakeel Buttc47d5032020-12-14 19:07:14 -08001066 __mod_node_page_state(pgdat, idx, val);
1067 return;
1068 }
1069
Linus Torvaldsd635a69d2020-12-15 13:22:29 -08001070 lruvec = mem_cgroup_lruvec(memcg, pgdat);
Shakeel Buttc47d5032020-12-14 19:07:14 -08001071 __mod_lruvec_state(lruvec, idx, val);
Muchun Songb4e0b682021-04-29 22:56:52 -07001072 rcu_read_unlock();
Shakeel Buttc47d5032020-12-14 19:07:14 -08001073}
Matthew Wilcox (Oracle)c7011232023-12-28 08:57:48 +00001074EXPORT_SYMBOL(__lruvec_stat_mod_folio);
Shakeel Buttc47d5032020-12-14 19:07:14 -08001075
Muchun Songda3ceef2020-12-14 19:07:04 -08001076void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
Roman Gushchinec9f0232019-08-13 15:37:41 -07001077{
Roman Gushchin4f103c62020-04-01 21:06:36 -07001078 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
Roman Gushchinec9f0232019-08-13 15:37:41 -07001079 struct mem_cgroup *memcg;
1080 struct lruvec *lruvec;
1081
1082 rcu_read_lock();
Roman Gushchinfc4db902022-06-10 11:03:10 -07001083 memcg = mem_cgroup_from_slab_obj(p);
Roman Gushchinec9f0232019-08-13 15:37:41 -07001084
Muchun Song8faeb1f2020-11-21 22:17:12 -08001085 /*
1086 * Untracked pages have no memcg, no lruvec. Update only the
1087 * node. If we reparent the slab objects to the root memcg,
1088 * when we free the slab object, we need to update the per-memcg
1089 * vmstats to keep it correct for the root memcg.
1090 */
1091 if (!memcg) {
Roman Gushchinec9f0232019-08-13 15:37:41 -07001092 __mod_node_page_state(pgdat, idx, val);
1093 } else {
Johannes Weiner867e5e12019-11-30 17:55:34 -08001094 lruvec = mem_cgroup_lruvec(memcg, pgdat);
Roman Gushchinec9f0232019-08-13 15:37:41 -07001095 __mod_lruvec_state(lruvec, idx, val);
1096 }
1097 rcu_read_unlock();
1098}
1099
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001100/**
1101 * __count_memcg_events - account VM events in a cgroup
1102 * @memcg: the memory cgroup
1103 * @idx: the event item
Ingo Molnarf0953a12021-05-06 18:06:47 -07001104 * @count: the number of events that occurred
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001105 */
1106void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
1107 unsigned long count)
1108{
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001109 int i = memcg_events_index(idx);
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001110
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001111 if (mem_cgroup_disabled())
1112 return;
1113
1114 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, idx))
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001115 return;
1116
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001117 memcg_stats_lock();
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001118 __this_cpu_add(memcg->vmstats_percpu->events[i], count);
Shakeel Butt5b3be692022-01-14 14:05:39 -08001119 memcg_rstat_updated(memcg, count);
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07001120 memcg_stats_unlock();
Johannes Weinerdb9adbc2019-05-14 15:47:09 -07001121}
1122
Johannes Weiner42a30032019-05-14 15:47:12 -07001123static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
Johannes Weinere9f89742011-03-23 16:42:37 -07001124{
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001125 int i = memcg_events_index(event);
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001126
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001127 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, event))
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001128 return 0;
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001129
1130 return READ_ONCE(memcg->vmstats->events[i]);
Johannes Weinere9f89742011-03-23 16:42:37 -07001131}
1132
Johannes Weiner42a30032019-05-14 15:47:12 -07001133static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
1134{
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001135 int i = memcg_events_index(event);
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001136
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001137 if (WARN_ONCE(i < 0, "%s: missing stat item %d\n", __func__, event))
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001138 return 0;
Johannes Weiner815744d2019-06-13 15:55:46 -07001139
Shakeel Buttacb5fe2f2024-05-01 10:26:16 -07001140 return READ_ONCE(memcg->vmstats->events_local[i]);
Johannes Weiner42a30032019-05-14 15:47:12 -07001141}
1142
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001143static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
Johannes Weiner3fba69a2020-06-03 16:01:31 -07001144 int nr_pages)
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -08001145{
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -08001146 /* pagein of a big page is an event. So, ignore page size */
1147 if (nr_pages > 0)
Johannes Weinerc9019e92018-01-31 16:16:37 -08001148 __count_memcg_events(memcg, PGPGIN, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -08001149 else {
Johannes Weinerc9019e92018-01-31 16:16:37 -08001150 __count_memcg_events(memcg, PGPGOUT, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -08001151 nr_pages = -nr_pages; /* for event */
1152 }
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -08001153
Chris Down871789d2019-05-14 15:46:57 -07001154 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08001155}
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -08001156
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001157static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1158 enum mem_cgroup_events_target target)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -08001159{
Johannes Weiner7a159cc2011-03-23 16:42:38 -07001160 unsigned long val, next;
1161
Chris Down871789d2019-05-14 15:46:57 -07001162 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
1163 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
Johannes Weiner7a159cc2011-03-23 16:42:38 -07001164 /* from time_after() in jiffies.h */
Michal Hocko6a1a8b82017-07-10 15:48:53 -07001165 if ((long)(next - val) < 0) {
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001166 switch (target) {
1167 case MEM_CGROUP_TARGET_THRESH:
1168 next = val + THRESHOLDS_EVENTS_TARGET;
1169 break;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -07001170 case MEM_CGROUP_TARGET_SOFTLIMIT:
1171 next = val + SOFTLIMIT_EVENTS_TARGET;
1172 break;
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001173 default:
1174 break;
1175 }
Chris Down871789d2019-05-14 15:46:57 -07001176 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001177 return true;
Johannes Weiner7a159cc2011-03-23 16:42:38 -07001178 }
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001179 return false;
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -08001180}
1181
1182/*
1183 * Check events in order.
1184 *
1185 */
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04001186static void memcg_check_events(struct mem_cgroup *memcg, int nid)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -08001187{
Sebastian Andrzej Siewior2343e882022-03-22 14:40:38 -07001188 if (IS_ENABLED(CONFIG_PREEMPT_RT))
1189 return;
1190
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -08001191 /* threshold event is triggered in finer grain than soft limit */
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001192 if (unlikely(mem_cgroup_event_ratelimit(memcg,
1193 MEM_CGROUP_TARGET_THRESH))) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -07001194 bool do_softlimit;
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001195
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -07001196 do_softlimit = mem_cgroup_event_ratelimit(memcg,
1197 MEM_CGROUP_TARGET_SOFTLIMIT);
Johannes Weinerf53d7ce32012-01-12 17:18:23 -08001198 mem_cgroup_threshold(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -07001199 if (unlikely(do_softlimit))
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04001200 mem_cgroup_update_tree(memcg, nid);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001201 }
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -08001202}
1203
Balbir Singhcf475ad2008-04-29 01:00:16 -07001204struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
Pavel Emelianov78fb7462008-02-07 00:13:51 -08001205{
Balbir Singh31a78f22008-09-28 23:09:31 +01001206 /*
1207 * mm_update_next_owner() may clear mm->owner to NULL
1208 * if it races with swapoff, page migration, etc.
1209 * So this can be called with p == NULL.
1210 */
1211 if (unlikely(!p))
1212 return NULL;
1213
Tejun Heo073219e2014-02-08 10:36:58 -05001214 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
Pavel Emelianov78fb7462008-02-07 00:13:51 -08001215}
Michal Hocko33398cf2015-09-08 15:01:02 -07001216EXPORT_SYMBOL(mem_cgroup_from_task);
Pavel Emelianov78fb7462008-02-07 00:13:51 -08001217
Dan Schatzberg04f94e32021-06-28 19:38:18 -07001218static __always_inline struct mem_cgroup *active_memcg(void)
1219{
Vasily Averin55a68c82021-09-02 14:55:49 -07001220 if (!in_task())
Dan Schatzberg04f94e32021-06-28 19:38:18 -07001221 return this_cpu_read(int_active_memcg);
1222 else
1223 return current->active_memcg;
1224}
1225
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001226/**
1227 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1228 * @mm: mm from which memcg should be extracted. It can be NULL.
1229 *
Dan Schatzberg04f94e32021-06-28 19:38:18 -07001230 * Obtain a reference on mm->memcg and returns it if successful. If mm
1231 * is NULL, then the memcg is chosen as follows:
1232 * 1) The active memcg, if set.
1233 * 2) current->mm->memcg, if available
1234 * 3) root memcg
1235 * If mem_cgroup is disabled, NULL is returned.
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001236 */
1237struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001238{
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001239 struct mem_cgroup *memcg;
1240
1241 if (mem_cgroup_disabled())
1242 return NULL;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001243
Muchun Song2884b6b2021-06-28 19:37:50 -07001244 /*
1245 * Page cache insertions can happen without an
1246 * actual mm context, e.g. during disk probing
1247 * on boot, loopback IO, acct() writes etc.
1248 *
1249 * No need to css_get on root memcg as the reference
1250 * counting is disabled on the root level in the
1251 * cgroup core. See CSS_NO_REF.
1252 */
Dan Schatzberg04f94e32021-06-28 19:38:18 -07001253 if (unlikely(!mm)) {
1254 memcg = active_memcg();
1255 if (unlikely(memcg)) {
1256 /* remote memcg must hold a ref */
1257 css_get(&memcg->css);
1258 return memcg;
1259 }
1260 mm = current->mm;
1261 if (unlikely(!mm))
1262 return root_mem_cgroup;
1263 }
Muchun Song2884b6b2021-06-28 19:37:50 -07001264
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001265 rcu_read_lock();
1266 do {
Muchun Song2884b6b2021-06-28 19:37:50 -07001267 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1268 if (unlikely(!memcg))
Johannes Weinerdf381972014-04-07 15:37:43 -07001269 memcg = root_mem_cgroup;
Roman Gushchin00d484f2019-11-15 17:34:43 -08001270 } while (!css_tryget(&memcg->css));
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001271 rcu_read_unlock();
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001272 return memcg;
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001273}
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001274EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1275
Shakeel Buttf745c6f2018-08-17 15:46:44 -07001276/**
Nhat Pham4b569382023-10-06 11:46:26 -07001277 * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
1278 */
1279struct mem_cgroup *get_mem_cgroup_from_current(void)
1280{
1281 struct mem_cgroup *memcg;
1282
1283 if (mem_cgroup_disabled())
1284 return NULL;
1285
1286again:
1287 rcu_read_lock();
1288 memcg = mem_cgroup_from_task(current);
1289 if (!css_tryget(&memcg->css)) {
1290 rcu_read_unlock();
1291 goto again;
1292 }
1293 rcu_read_unlock();
1294 return memcg;
1295}
1296
1297/**
Johannes Weiner56600482012-01-12 17:17:59 -08001298 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1299 * @root: hierarchy root
1300 * @prev: previously returned memcg, NULL on first invocation
1301 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1302 *
1303 * Returns references to children of the hierarchy below @root, or
1304 * @root itself, or %NULL after a full round-trip.
1305 *
1306 * Caller must pass the return value in @prev on subsequent
1307 * invocations for reference counting, or use mem_cgroup_iter_break()
1308 * to cancel a hierarchy walk before the round-trip is complete.
1309 *
Miaohe Lin05bdc522020-10-13 16:52:45 -07001310 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1311 * in the hierarchy among all concurrent reclaimers operating on the
1312 * same node.
Johannes Weiner56600482012-01-12 17:17:59 -08001313 */
Andrew Morton694fbc02013-09-24 15:27:37 -07001314struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
Johannes Weiner56600482012-01-12 17:17:59 -08001315 struct mem_cgroup *prev,
Andrew Morton694fbc02013-09-24 15:27:37 -07001316 struct mem_cgroup_reclaim_cookie *reclaim)
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07001317{
Kees Cook3f649ab2020-06-03 13:09:38 -07001318 struct mem_cgroup_reclaim_iter *iter;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001319 struct cgroup_subsys_state *css = NULL;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001320 struct mem_cgroup *memcg = NULL;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001321 struct mem_cgroup *pos = NULL;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001322
Andrew Morton694fbc02013-09-24 15:27:37 -07001323 if (mem_cgroup_disabled())
1324 return NULL;
Johannes Weiner56600482012-01-12 17:17:59 -08001325
KAMEZAWA Hiroyuki711d3d22010-10-27 15:33:42 -07001326 if (!root)
1327 root = root_mem_cgroup;
1328
Michal Hocko542f85f2013-04-29 15:07:15 -07001329 rcu_read_lock();
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001330
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001331 if (reclaim) {
Mel Gormanef8f2322016-07-28 15:46:05 -07001332 struct mem_cgroup_per_node *mz;
Johannes Weiner527a5ec2012-01-12 17:17:55 -08001333
Johannes Weinera3747b52021-04-29 22:56:14 -07001334 mz = root->nodeinfo[reclaim->pgdat->node_id];
Yafang Shao9da83f32019-11-30 17:50:03 -08001335 iter = &mz->iter;
Michal Hocko5f578162013-04-29 15:07:17 -07001336
Wei Yanga9320aa2022-04-28 23:15:59 -07001337 /*
1338 * On start, join the current reclaim iteration cycle.
1339 * Exit when a concurrent walker completes it.
1340 */
1341 if (!prev)
1342 reclaim->generation = iter->generation;
1343 else if (reclaim->generation != iter->generation)
Michal Hocko542f85f2013-04-29 15:07:15 -07001344 goto out_unlock;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001345
Vladimir Davydov6df38682015-12-29 14:54:10 -08001346 while (1) {
Jason Low4db0c3c2015-04-15 16:14:08 -07001347 pos = READ_ONCE(iter->position);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001348 if (!pos || css_tryget(&pos->css))
1349 break;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001350 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001351 * css reference reached zero, so iter->position will
1352 * be cleared by ->css_released. However, we should not
1353 * rely on this happening soon, because ->css_released
1354 * is called from a work queue, and by busy-waiting we
1355 * might block it. So we clear iter->position right
1356 * away.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001357 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001358 (void)cmpxchg(&iter->position, pos, NULL);
1359 }
Wei Yang89d83302022-04-28 23:15:58 -07001360 } else if (prev) {
1361 pos = prev;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001362 }
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001363
1364 if (pos)
1365 css = &pos->css;
1366
1367 for (;;) {
1368 css = css_next_descendant_pre(css, &root->css);
1369 if (!css) {
1370 /*
1371 * Reclaimers share the hierarchy walk, and a
1372 * new one might jump in right at the end of
1373 * the hierarchy - make sure they see at least
1374 * one group and restart from the beginning.
1375 */
1376 if (!prev)
1377 continue;
1378 break;
1379 }
1380
1381 /*
1382 * Verify the css and acquire a reference. The root
1383 * is provided by the caller, so we know it's alive
1384 * and kicking, and don't take an extra reference.
1385 */
Wei Yang41555da2022-04-28 23:15:58 -07001386 if (css == &root->css || css_tryget(css)) {
1387 memcg = mem_cgroup_from_css(css);
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001388 break;
Wei Yang41555da2022-04-28 23:15:58 -07001389 }
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001390 }
1391
1392 if (reclaim) {
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001393 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001394 * The position could have already been updated by a competing
1395 * thread, so check that the value hasn't changed since we read
1396 * it to avoid reclaiming from the same cgroup twice.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001397 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001398 (void)cmpxchg(&iter->position, pos, memcg);
1399
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001400 if (pos)
1401 css_put(&pos->css);
1402
1403 if (!memcg)
1404 iter->generation++;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001405 }
1406
Michal Hocko542f85f2013-04-29 15:07:15 -07001407out_unlock:
1408 rcu_read_unlock();
Michal Hockoc40046f2013-04-29 15:07:14 -07001409 if (prev && prev != root)
1410 css_put(&prev->css);
1411
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001412 return memcg;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001413}
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001414
Johannes Weiner56600482012-01-12 17:17:59 -08001415/**
1416 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1417 * @root: hierarchy root
1418 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1419 */
1420void mem_cgroup_iter_break(struct mem_cgroup *root,
1421 struct mem_cgroup *prev)
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001422{
1423 if (!root)
1424 root = root_mem_cgroup;
1425 if (prev && prev != root)
1426 css_put(&prev->css);
1427}
1428
Miles Chen54a83d62019-08-13 15:37:28 -07001429static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1430 struct mem_cgroup *dead_memcg)
Vladimir Davydov6df38682015-12-29 14:54:10 -08001431{
Vladimir Davydov6df38682015-12-29 14:54:10 -08001432 struct mem_cgroup_reclaim_iter *iter;
Mel Gormanef8f2322016-07-28 15:46:05 -07001433 struct mem_cgroup_per_node *mz;
1434 int nid;
Vladimir Davydov6df38682015-12-29 14:54:10 -08001435
Miles Chen54a83d62019-08-13 15:37:28 -07001436 for_each_node(nid) {
Johannes Weinera3747b52021-04-29 22:56:14 -07001437 mz = from->nodeinfo[nid];
Yafang Shao9da83f32019-11-30 17:50:03 -08001438 iter = &mz->iter;
1439 cmpxchg(&iter->position, dead_memcg, NULL);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001440 }
1441}
1442
Miles Chen54a83d62019-08-13 15:37:28 -07001443static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1444{
1445 struct mem_cgroup *memcg = dead_memcg;
1446 struct mem_cgroup *last;
1447
1448 do {
1449 __invalidate_reclaim_iterators(memcg, dead_memcg);
1450 last = memcg;
1451 } while ((memcg = parent_mem_cgroup(memcg)));
1452
1453 /*
xupandab8dd3ee2022-08-15 06:51:04 +00001454 * When cgroup1 non-hierarchy mode is used,
Miles Chen54a83d62019-08-13 15:37:28 -07001455 * parent_mem_cgroup() does not walk all the way up to the
1456 * cgroup root (root_mem_cgroup). So we have to handle
1457 * dead_memcg from cgroup root separately.
1458 */
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05301459 if (!mem_cgroup_is_root(last))
Miles Chen54a83d62019-08-13 15:37:28 -07001460 __invalidate_reclaim_iterators(root_mem_cgroup,
1461 dead_memcg);
1462}
1463
Johannes Weiner925b7672012-01-12 17:18:15 -08001464/**
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001465 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1466 * @memcg: hierarchy root
1467 * @fn: function to call for each task
1468 * @arg: argument passed to @fn
1469 *
1470 * This function iterates over tasks attached to @memcg or to any of its
1471 * descendants and calls @fn for each task. If @fn returns a non-zero
ZhangPeng025b7792023-06-16 14:30:30 +08001472 * value, the function breaks the iteration loop. Otherwise, it will iterate
1473 * over all tasks and return 0.
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001474 *
1475 * This function must not be called for the root memory cgroup.
1476 */
ZhangPeng025b7792023-06-16 14:30:30 +08001477void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1478 int (*fn)(struct task_struct *, void *), void *arg)
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001479{
1480 struct mem_cgroup *iter;
1481 int ret = 0;
1482
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05301483 BUG_ON(mem_cgroup_is_root(memcg));
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001484
1485 for_each_mem_cgroup_tree(iter, memcg) {
1486 struct css_task_iter it;
1487 struct task_struct *task;
1488
Tetsuo Handaf168a9a2019-07-11 21:00:20 -07001489 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001490 while (!ret && (task = css_task_iter_next(&it)))
1491 ret = fn(task, arg);
1492 css_task_iter_end(&it);
1493 if (ret) {
1494 mem_cgroup_iter_break(memcg, iter);
1495 break;
1496 }
1497 }
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001498}
1499
Alex Shi6168d0d2020-12-15 12:34:29 -08001500#ifdef CONFIG_DEBUG_VM
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001501void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
Alex Shi6168d0d2020-12-15 12:34:29 -08001502{
1503 struct mem_cgroup *memcg;
1504
1505 if (mem_cgroup_disabled())
1506 return;
1507
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001508 memcg = folio_memcg(folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001509
1510 if (!memcg)
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05301511 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001512 else
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001513 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001514}
1515#endif
1516
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001517/**
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001518 * folio_lruvec_lock - Lock the lruvec for a folio.
1519 * @folio: Pointer to the folio.
Alex Shi6168d0d2020-12-15 12:34:29 -08001520 *
Alex Shid7e3aba2021-02-24 12:03:47 -08001521 * These functions are safe to use under any of the following conditions:
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001522 * - folio locked
1523 * - folio_test_lru false
1524 * - folio_memcg_lock()
1525 * - folio frozen (refcount of 0)
1526 *
1527 * Return: The lruvec this folio is on with its lock held.
Alex Shi6168d0d2020-12-15 12:34:29 -08001528 */
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001529struct lruvec *folio_lruvec_lock(struct folio *folio)
Alex Shi6168d0d2020-12-15 12:34:29 -08001530{
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001531 struct lruvec *lruvec = folio_lruvec(folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001532
Alex Shi6168d0d2020-12-15 12:34:29 -08001533 spin_lock(&lruvec->lru_lock);
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001534 lruvec_memcg_debug(lruvec, folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001535
1536 return lruvec;
1537}
1538
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001539/**
1540 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1541 * @folio: Pointer to the folio.
1542 *
1543 * These functions are safe to use under any of the following conditions:
1544 * - folio locked
1545 * - folio_test_lru false
1546 * - folio_memcg_lock()
1547 * - folio frozen (refcount of 0)
1548 *
1549 * Return: The lruvec this folio is on with its lock held and interrupts
1550 * disabled.
1551 */
1552struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
Alex Shi6168d0d2020-12-15 12:34:29 -08001553{
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001554 struct lruvec *lruvec = folio_lruvec(folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001555
Alex Shi6168d0d2020-12-15 12:34:29 -08001556 spin_lock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001557 lruvec_memcg_debug(lruvec, folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001558
1559 return lruvec;
1560}
1561
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001562/**
1563 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1564 * @folio: Pointer to the folio.
1565 * @flags: Pointer to irqsave flags.
1566 *
1567 * These functions are safe to use under any of the following conditions:
1568 * - folio locked
1569 * - folio_test_lru false
1570 * - folio_memcg_lock()
1571 * - folio frozen (refcount of 0)
1572 *
1573 * Return: The lruvec this folio is on with its lock held and interrupts
1574 * disabled.
1575 */
1576struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1577 unsigned long *flags)
Alex Shi6168d0d2020-12-15 12:34:29 -08001578{
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001579 struct lruvec *lruvec = folio_lruvec(folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001580
Alex Shi6168d0d2020-12-15 12:34:29 -08001581 spin_lock_irqsave(&lruvec->lru_lock, *flags);
Matthew Wilcox (Oracle)e809c3f2021-06-28 21:59:47 -04001582 lruvec_memcg_debug(lruvec, folio);
Alex Shi6168d0d2020-12-15 12:34:29 -08001583
1584 return lruvec;
1585}
1586
1587/**
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001588 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1589 * @lruvec: mem_cgroup per zone lru vector
1590 * @lru: index of lru list the page is sitting on
Michal Hockob4536f0c82017-01-10 16:58:04 -08001591 * @zid: zone id of the accounted pages
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001592 * @nr_pages: positive when adding or negative when removing
Johannes Weiner925b7672012-01-12 17:18:15 -08001593 *
Hugh Dickinsca707232016-05-19 17:12:35 -07001594 * This function must be called under lru_lock, just before a page is added
Hugh Dickins07ca7602022-02-14 18:29:54 -08001595 * to or just after a page is removed from an lru list.
Johannes Weiner925b7672012-01-12 17:18:15 -08001596 */
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001597void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001598 int zid, int nr_pages)
Johannes Weiner925b7672012-01-12 17:18:15 -08001599{
Mel Gormanef8f2322016-07-28 15:46:05 -07001600 struct mem_cgroup_per_node *mz;
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001601 unsigned long *lru_size;
Hugh Dickinsca707232016-05-19 17:12:35 -07001602 long size;
Johannes Weiner925b7672012-01-12 17:18:15 -08001603
1604 if (mem_cgroup_disabled())
1605 return;
1606
Mel Gormanef8f2322016-07-28 15:46:05 -07001607 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Michal Hockob4536f0c82017-01-10 16:58:04 -08001608 lru_size = &mz->lru_zone_size[zid][lru];
Hugh Dickinsca707232016-05-19 17:12:35 -07001609
1610 if (nr_pages < 0)
1611 *lru_size += nr_pages;
1612
1613 size = *lru_size;
Michal Hockob4536f0c82017-01-10 16:58:04 -08001614 if (WARN_ONCE(size < 0,
1615 "%s(%p, %d, %d): lru_size %ld\n",
1616 __func__, lruvec, lru, nr_pages, size)) {
Hugh Dickinsca707232016-05-19 17:12:35 -07001617 VM_BUG_ON(1);
1618 *lru_size = 0;
1619 }
1620
1621 if (nr_pages > 0)
1622 *lru_size += nr_pages;
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -08001623}
KAMEZAWA Hiroyuki544122e2009-01-07 18:08:34 -08001624
Johannes Weiner19942822011-02-01 15:52:43 -08001625/**
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001626 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
Wanpeng Lidad75572012-06-20 12:53:01 -07001627 * @memcg: the memory cgroup
Johannes Weiner19942822011-02-01 15:52:43 -08001628 *
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001629 * Returns the maximum amount of memory @mem can be charged with, in
Johannes Weiner7ec99d62011-03-23 16:42:36 -07001630 * pages.
Johannes Weiner19942822011-02-01 15:52:43 -08001631 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001632static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
Johannes Weiner19942822011-02-01 15:52:43 -08001633{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001634 unsigned long margin = 0;
1635 unsigned long count;
1636 unsigned long limit;
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001637
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001638 count = page_counter_read(&memcg->memory);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001639 limit = READ_ONCE(memcg->memory.max);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001640 if (count < limit)
1641 margin = limit - count;
1642
Johannes Weiner7941d212016-01-14 15:21:23 -08001643 if (do_memsw_account()) {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001644 count = page_counter_read(&memcg->memsw);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001645 limit = READ_ONCE(memcg->memsw.max);
Kaixu Xia1c4448e2020-06-01 21:49:36 -07001646 if (count < limit)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001647 margin = min(margin, limit - count);
Li RongQingcbedbac2016-05-27 14:27:43 -07001648 else
1649 margin = 0;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001650 }
1651
1652 return margin;
Johannes Weiner19942822011-02-01 15:52:43 -08001653}
1654
KAMEZAWA Hiroyuki619d0942012-03-21 16:34:23 -07001655/*
Qiang Huangbdcbb652014-06-04 16:08:21 -07001656 * A routine for checking "mem" is under move_account() or not.
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001657 *
Qiang Huangbdcbb652014-06-04 16:08:21 -07001658 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1659 * moving cgroups. This is for waiting at high-memory pressure
1660 * caused by "move".
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001661 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001662static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001663{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001664 struct mem_cgroup *from;
1665 struct mem_cgroup *to;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001666 bool ret = false;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001667 /*
1668 * Unlike task_move routines, we access mc.to, mc.from not under
1669 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1670 */
1671 spin_lock(&mc.lock);
1672 from = mc.from;
1673 to = mc.to;
1674 if (!from)
1675 goto unlock;
Michal Hocko3e920412011-07-26 16:08:29 -07001676
Johannes Weiner2314b422014-12-10 15:44:33 -08001677 ret = mem_cgroup_is_descendant(from, memcg) ||
1678 mem_cgroup_is_descendant(to, memcg);
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001679unlock:
1680 spin_unlock(&mc.lock);
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001681 return ret;
1682}
1683
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001684static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001685{
1686 if (mc.moving_task && current != mc.moving_task) {
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001687 if (mem_cgroup_under_move(memcg)) {
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001688 DEFINE_WAIT(wait);
1689 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1690 /* moving charge context might have finished. */
1691 if (mc.moving_task)
1692 schedule();
1693 finish_wait(&mc.waitq, &wait);
1694 return true;
1695 }
1696 }
1697 return false;
1698}
1699
Muchun Song5f9a4f42020-10-13 16:52:59 -07001700struct memory_stat {
1701 const char *name;
Muchun Song5f9a4f42020-10-13 16:52:59 -07001702 unsigned int idx;
1703};
1704
Muchun Song57b28472021-02-24 12:03:31 -08001705static const struct memory_stat memory_stats[] = {
Muchun Songfff66b72021-02-24 12:03:43 -08001706 { "anon", NR_ANON_MAPPED },
1707 { "file", NR_FILE_PAGES },
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07001708 { "kernel", MEMCG_KMEM },
Muchun Songfff66b72021-02-24 12:03:43 -08001709 { "kernel_stack", NR_KERNEL_STACK_KB },
1710 { "pagetables", NR_PAGETABLE },
Yosry Ahmedebc97a52022-08-23 00:46:36 +00001711 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
Muchun Songfff66b72021-02-24 12:03:43 -08001712 { "percpu", MEMCG_PERCPU_B },
1713 { "sock", MEMCG_SOCK },
Shakeel Butt4e5aa1f2022-01-14 14:05:45 -08001714 { "vmalloc", MEMCG_VMALLOC },
Muchun Songfff66b72021-02-24 12:03:43 -08001715 { "shmem", NR_SHMEM },
Johannes Weinerf4840cc2022-05-19 14:08:53 -07001716#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1717 { "zswap", MEMCG_ZSWAP_B },
1718 { "zswapped", MEMCG_ZSWAPPED },
1719#endif
Muchun Songfff66b72021-02-24 12:03:43 -08001720 { "file_mapped", NR_FILE_MAPPED },
1721 { "file_dirty", NR_FILE_DIRTY },
1722 { "file_writeback", NR_WRITEBACK },
Shakeel Buttb6038942021-02-24 12:03:55 -08001723#ifdef CONFIG_SWAP
1724 { "swapcached", NR_SWAPCACHE },
1725#endif
Muchun Song5f9a4f42020-10-13 16:52:59 -07001726#ifdef CONFIG_TRANSPARENT_HUGEPAGE
Muchun Songfff66b72021-02-24 12:03:43 -08001727 { "anon_thp", NR_ANON_THPS },
1728 { "file_thp", NR_FILE_THPS },
1729 { "shmem_thp", NR_SHMEM_THPS },
Muchun Song5f9a4f42020-10-13 16:52:59 -07001730#endif
Muchun Songfff66b72021-02-24 12:03:43 -08001731 { "inactive_anon", NR_INACTIVE_ANON },
1732 { "active_anon", NR_ACTIVE_ANON },
1733 { "inactive_file", NR_INACTIVE_FILE },
1734 { "active_file", NR_ACTIVE_FILE },
1735 { "unevictable", NR_UNEVICTABLE },
1736 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1737 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
Muchun Song5f9a4f42020-10-13 16:52:59 -07001738
1739 /* The memory events */
Muchun Songfff66b72021-02-24 12:03:43 -08001740 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1741 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1742 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1743 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1744 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1745 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1746 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
Muchun Song5f9a4f42020-10-13 16:52:59 -07001747};
1748
Yosry Ahmedff841a02023-09-22 17:57:39 +00001749/* The actual unit of the state item, not the same as the output unit */
Muchun Songfff66b72021-02-24 12:03:43 -08001750static int memcg_page_state_unit(int item)
1751{
1752 switch (item) {
1753 case MEMCG_PERCPU_B:
Johannes Weinerf4840cc2022-05-19 14:08:53 -07001754 case MEMCG_ZSWAP_B:
Muchun Songfff66b72021-02-24 12:03:43 -08001755 case NR_SLAB_RECLAIMABLE_B:
1756 case NR_SLAB_UNRECLAIMABLE_B:
Muchun Songfff66b72021-02-24 12:03:43 -08001757 return 1;
1758 case NR_KERNEL_STACK_KB:
1759 return SZ_1K;
1760 default:
1761 return PAGE_SIZE;
1762 }
1763}
1764
Yosry Ahmedff841a02023-09-22 17:57:39 +00001765/* Translate stat items to the correct unit for memory.stat output */
1766static int memcg_page_state_output_unit(int item)
1767{
1768 /*
1769 * Workingset state is actually in pages, but we export it to userspace
1770 * as a scalar count of events, so special case it here.
1771 */
1772 switch (item) {
1773 case WORKINGSET_REFAULT_ANON:
1774 case WORKINGSET_REFAULT_FILE:
1775 case WORKINGSET_ACTIVATE_ANON:
1776 case WORKINGSET_ACTIVATE_FILE:
1777 case WORKINGSET_RESTORE_ANON:
1778 case WORKINGSET_RESTORE_FILE:
1779 case WORKINGSET_NODERECLAIM:
1780 return 1;
1781 default:
1782 return memcg_page_state_unit(item);
1783 }
1784}
1785
Muchun Songfff66b72021-02-24 12:03:43 -08001786static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1787 int item)
1788{
Yosry Ahmedff841a02023-09-22 17:57:39 +00001789 return memcg_page_state(memcg, item) *
1790 memcg_page_state_output_unit(item);
1791}
1792
1793static inline unsigned long memcg_page_state_local_output(
1794 struct mem_cgroup *memcg, int item)
1795{
1796 return memcg_page_state_local(memcg, item) *
1797 memcg_page_state_output_unit(item);
Muchun Songfff66b72021-02-24 12:03:43 -08001798}
1799
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00001800static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
Johannes Weinerc8713d02019-07-11 20:55:59 -07001801{
Johannes Weinerc8713d02019-07-11 20:55:59 -07001802 int i;
Johannes Weiner71cd3112017-05-03 14:55:13 -07001803
Johannes Weinerc8713d02019-07-11 20:55:59 -07001804 /*
1805 * Provide statistics on the state of the memory subsystem as
1806 * well as cumulative event counters that show past behavior.
1807 *
1808 * This list is ordered following a combination of these gradients:
1809 * 1) generic big picture -> specifics and details
1810 * 2) reflecting userspace activity -> reflecting kernel heuristics
1811 *
1812 * Current memory state:
1813 */
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00001814 mem_cgroup_flush_stats(memcg);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001815
Muchun Song5f9a4f42020-10-13 16:52:59 -07001816 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1817 u64 size;
Johannes Weinerc8713d02019-07-11 20:55:59 -07001818
Muchun Songfff66b72021-02-24 12:03:43 -08001819 size = memcg_page_state_output(memcg, memory_stats[i].idx);
Yosry Ahmed5b423602023-04-28 13:24:05 +00001820 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001821
Muchun Song5f9a4f42020-10-13 16:52:59 -07001822 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
Muchun Songfff66b72021-02-24 12:03:43 -08001823 size += memcg_page_state_output(memcg,
1824 NR_SLAB_RECLAIMABLE_B);
Yosry Ahmed5b423602023-04-28 13:24:05 +00001825 seq_buf_printf(s, "slab %llu\n", size);
Muchun Song5f9a4f42020-10-13 16:52:59 -07001826 }
1827 }
Johannes Weinerc8713d02019-07-11 20:55:59 -07001828
1829 /* Accumulated memory events */
Yosry Ahmed5b423602023-04-28 13:24:05 +00001830 seq_buf_printf(s, "pgscan %lu\n",
Johannes Weinerc8713d02019-07-11 20:55:59 -07001831 memcg_events(memcg, PGSCAN_KSWAPD) +
Johannes Weiner57e9cc52022-10-26 14:01:33 -04001832 memcg_events(memcg, PGSCAN_DIRECT) +
1833 memcg_events(memcg, PGSCAN_KHUGEPAGED));
Yosry Ahmed5b423602023-04-28 13:24:05 +00001834 seq_buf_printf(s, "pgsteal %lu\n",
Johannes Weinerc8713d02019-07-11 20:55:59 -07001835 memcg_events(memcg, PGSTEAL_KSWAPD) +
Johannes Weiner57e9cc52022-10-26 14:01:33 -04001836 memcg_events(memcg, PGSTEAL_DIRECT) +
1837 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001838
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001839 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1840 if (memcg_vm_event_stat[i] == PGPGIN ||
1841 memcg_vm_event_stat[i] == PGPGOUT)
1842 continue;
1843
Yosry Ahmed5b423602023-04-28 13:24:05 +00001844 seq_buf_printf(s, "%s %lu\n",
Qi Zheng673520f2022-06-04 16:22:09 +08001845 vm_event_name(memcg_vm_event_stat[i]),
1846 memcg_events(memcg, memcg_vm_event_stat[i]));
Shakeel Butt8278f1c2022-09-07 04:35:37 +00001847 }
Johannes Weinerc8713d02019-07-11 20:55:59 -07001848
1849 /* The above should easily fit into one page */
Yosry Ahmed5b423602023-04-28 13:24:05 +00001850 WARN_ON_ONCE(seq_buf_has_overflowed(s));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001851}
Johannes Weiner71cd3112017-05-03 14:55:13 -07001852
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00001853static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s);
1854
1855static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1856{
1857 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1858 memcg_stat_format(memcg, s);
1859 else
1860 memcg1_stat_format(memcg, s);
1861 WARN_ON_ONCE(seq_buf_has_overflowed(s));
1862}
1863
Balbir Singhe2224322009-04-02 16:57:39 -07001864/**
yuzhoujianf0c867d2018-12-28 00:36:10 -08001865 * mem_cgroup_print_oom_context: Print OOM information relevant to
1866 * memory controller.
Balbir Singhe2224322009-04-02 16:57:39 -07001867 * @memcg: The memory cgroup that went over limit
1868 * @p: Task that is going to be killed
1869 *
1870 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1871 * enabled
1872 */
yuzhoujianf0c867d2018-12-28 00:36:10 -08001873void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1874{
1875 rcu_read_lock();
1876
1877 if (memcg) {
1878 pr_cont(",oom_memcg=");
1879 pr_cont_cgroup_path(memcg->css.cgroup);
1880 } else
1881 pr_cont(",global_oom");
1882 if (p) {
1883 pr_cont(",task_memcg=");
1884 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1885 }
1886 rcu_read_unlock();
1887}
1888
1889/**
1890 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1891 * memory controller.
1892 * @memcg: The memory cgroup that went over limit
1893 */
1894void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
Balbir Singhe2224322009-04-02 16:57:39 -07001895{
Tetsuo Handa68aaee12022-07-22 19:45:39 +09001896 /* Use static buffer, for the caller is holding oom_lock. */
1897 static char buf[PAGE_SIZE];
Yosry Ahmed5b423602023-04-28 13:24:05 +00001898 struct seq_buf s;
Tetsuo Handa68aaee12022-07-22 19:45:39 +09001899
1900 lockdep_assert_held(&oom_lock);
Balbir Singhe2224322009-04-02 16:57:39 -07001901
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001902 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1903 K((u64)page_counter_read(&memcg->memory)),
Chris Down15b42562020-04-01 21:07:20 -07001904 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001905 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1906 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1907 K((u64)page_counter_read(&memcg->swap)),
Chris Down32d087c2020-04-01 21:07:30 -07001908 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001909 else {
1910 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1911 K((u64)page_counter_read(&memcg->memsw)),
1912 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1913 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1914 K((u64)page_counter_read(&memcg->kmem)),
1915 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
Sha Zhengju58cf1882013-02-22 16:32:05 -08001916 }
Johannes Weinerc8713d02019-07-11 20:55:59 -07001917
1918 pr_info("Memory cgroup stats for ");
1919 pr_cont_cgroup_path(memcg->css.cgroup);
1920 pr_cont(":");
Yosry Ahmed5b423602023-04-28 13:24:05 +00001921 seq_buf_init(&s, buf, sizeof(buf));
1922 memory_stat_format(memcg, &s);
1923 seq_buf_do_printk(&s, KERN_INFO);
Balbir Singhe2224322009-04-02 16:57:39 -07001924}
1925
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07001926/*
David Rientjesa63d83f2010-08-09 17:19:46 -07001927 * Return the memory (and swap, if configured) limit for a memcg.
1928 */
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001929unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
David Rientjesa63d83f2010-08-09 17:19:46 -07001930{
Waiman Long8d387a52020-10-13 16:52:52 -07001931 unsigned long max = READ_ONCE(memcg->memory.max);
David Rientjesa63d83f2010-08-09 17:19:46 -07001932
Johannes Weinerb94c4e92022-09-26 09:57:03 -04001933 if (do_memsw_account()) {
Waiman Long8d387a52020-10-13 16:52:52 -07001934 if (mem_cgroup_swappiness(memcg)) {
1935 /* Calculate swap excess capacity from memsw limit */
1936 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001937
Waiman Long8d387a52020-10-13 16:52:52 -07001938 max += min(swap, (unsigned long)total_swap_pages);
1939 }
Johannes Weinerb94c4e92022-09-26 09:57:03 -04001940 } else {
1941 if (mem_cgroup_swappiness(memcg))
1942 max += min(READ_ONCE(memcg->swap.max),
1943 (unsigned long)total_swap_pages);
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001944 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001945 return max;
David Rientjesa63d83f2010-08-09 17:19:46 -07001946}
1947
Chris Down9783aa92019-10-06 17:58:32 -07001948unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1949{
1950 return page_counter_read(&memcg->memory);
1951}
1952
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07001953static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
David Rientjes19965462012-12-11 16:00:26 -08001954 int order)
David Rientjes9cbb78b2012-07-31 16:43:44 -07001955{
David Rientjes6e0fc462015-09-08 15:00:36 -07001956 struct oom_control oc = {
1957 .zonelist = NULL,
1958 .nodemask = NULL,
Vladimir Davydov2a966b72016-07-26 15:22:33 -07001959 .memcg = memcg,
David Rientjes6e0fc462015-09-08 15:00:36 -07001960 .gfp_mask = gfp_mask,
1961 .order = order,
David Rientjes6e0fc462015-09-08 15:00:36 -07001962 };
Yafang Shao1378b372020-08-06 23:22:08 -07001963 bool ret = true;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001964
Tetsuo Handa7775fac2019-03-05 15:46:47 -08001965 if (mutex_lock_killable(&oom_lock))
1966 return true;
Yafang Shao1378b372020-08-06 23:22:08 -07001967
1968 if (mem_cgroup_margin(memcg) >= (1 << order))
1969 goto unlock;
1970
Tetsuo Handa7775fac2019-03-05 15:46:47 -08001971 /*
1972 * A few threads which were not waiting at mutex_lock_killable() can
1973 * fail to bail out. Therefore, check again after holding oom_lock.
1974 */
Vasily Averina4ebf1b2021-11-05 13:38:09 -07001975 ret = task_is_dying() || out_of_memory(&oc);
Yafang Shao1378b372020-08-06 23:22:08 -07001976
1977unlock:
Johannes Weinerdc564012015-06-24 16:57:19 -07001978 mutex_unlock(&oom_lock);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001979 return ret;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001980}
1981
Andrew Morton0608f432013-09-24 15:27:41 -07001982static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
Mel Gormanef8f2322016-07-28 15:46:05 -07001983 pg_data_t *pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001984 gfp_t gfp_mask,
1985 unsigned long *total_scanned)
Balbir Singh6d61ef42009-01-07 18:08:06 -08001986{
Andrew Morton0608f432013-09-24 15:27:41 -07001987 struct mem_cgroup *victim = NULL;
1988 int total = 0;
1989 int loop = 0;
1990 unsigned long excess;
1991 unsigned long nr_scanned;
1992 struct mem_cgroup_reclaim_cookie reclaim = {
Mel Gormanef8f2322016-07-28 15:46:05 -07001993 .pgdat = pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001994 };
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001995
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001996 excess = soft_limit_excess(root_memcg);
Balbir Singh6d61ef42009-01-07 18:08:06 -08001997
Andrew Morton0608f432013-09-24 15:27:41 -07001998 while (1) {
1999 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2000 if (!victim) {
2001 loop++;
2002 if (loop >= 2) {
2003 /*
2004 * If we have not been able to reclaim
2005 * anything, it might because there are
2006 * no reclaimable pages under this hierarchy
2007 */
2008 if (!total)
2009 break;
2010 /*
2011 * We want to do more targeted reclaim.
2012 * excess >> 2 is not to excessive so as to
2013 * reclaim too much, nor too less that we keep
2014 * coming back to reclaim from this cgroup
2015 */
2016 if (total >= (excess >> 2) ||
2017 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2018 break;
2019 }
2020 continue;
2021 }
Mel Gormana9dd0a82016-07-28 15:46:02 -07002022 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
Mel Gormanef8f2322016-07-28 15:46:05 -07002023 pgdat, &nr_scanned);
Andrew Morton0608f432013-09-24 15:27:41 -07002024 *total_scanned += nr_scanned;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002025 if (!soft_limit_excess(root_memcg))
Andrew Morton0608f432013-09-24 15:27:41 -07002026 break;
Balbir Singh6d61ef42009-01-07 18:08:06 -08002027 }
Andrew Morton0608f432013-09-24 15:27:41 -07002028 mem_cgroup_iter_break(root_memcg, victim);
2029 return total;
Balbir Singh6d61ef42009-01-07 18:08:06 -08002030}
2031
Johannes Weiner0056f4e2013-10-31 16:34:14 -07002032#ifdef CONFIG_LOCKDEP
2033static struct lockdep_map memcg_oom_lock_dep_map = {
2034 .name = "memcg_oom_lock",
2035};
2036#endif
2037
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002038static DEFINE_SPINLOCK(memcg_oom_lock);
2039
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002040/*
2041 * Check OOM-Killer is already running under our hierarchy.
2042 * If someone is running, return false.
2043 */
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002044static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002045{
Michal Hocko79dfdac2011-07-26 16:08:23 -07002046 struct mem_cgroup *iter, *failed = NULL;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08002047
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002048 spin_lock(&memcg_oom_lock);
2049
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08002050 for_each_mem_cgroup_tree(iter, memcg) {
Johannes Weiner23751be2011-08-25 15:59:16 -07002051 if (iter->oom_lock) {
Michal Hocko79dfdac2011-07-26 16:08:23 -07002052 /*
2053 * this subtree of our hierarchy is already locked
2054 * so we cannot give a lock.
2055 */
Michal Hocko79dfdac2011-07-26 16:08:23 -07002056 failed = iter;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08002057 mem_cgroup_iter_break(memcg, iter);
2058 break;
Johannes Weiner23751be2011-08-25 15:59:16 -07002059 } else
2060 iter->oom_lock = true;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07002061 }
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002062
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002063 if (failed) {
2064 /*
2065 * OK, we failed to lock the whole subtree so we have
2066 * to clean up what we set up to the failing subtree
2067 */
2068 for_each_mem_cgroup_tree(iter, memcg) {
2069 if (iter == failed) {
2070 mem_cgroup_iter_break(memcg, iter);
2071 break;
2072 }
2073 iter->oom_lock = false;
Michal Hocko79dfdac2011-07-26 16:08:23 -07002074 }
Johannes Weiner0056f4e2013-10-31 16:34:14 -07002075 } else
2076 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002077
2078 spin_unlock(&memcg_oom_lock);
2079
2080 return !failed;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08002081}
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07002082
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002083static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07002084{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07002085 struct mem_cgroup *iter;
2086
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002087 spin_lock(&memcg_oom_lock);
Qian Cai5facae42019-09-19 12:09:40 -04002088 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002089 for_each_mem_cgroup_tree(iter, memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07002090 iter->oom_lock = false;
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002091 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07002092}
2093
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002094static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07002095{
2096 struct mem_cgroup *iter;
2097
Tejun Heoc2b42d32015-06-24 16:58:23 -07002098 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002099 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07002100 iter->under_oom++;
2101 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07002102}
2103
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002104static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07002105{
2106 struct mem_cgroup *iter;
2107
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002108 /*
Ingo Molnarf0953a12021-05-06 18:06:47 -07002109 * Be careful about under_oom underflows because a child memcg
Miaohe Lin7a52d4d82020-10-13 16:53:05 -07002110 * could have been added after mem_cgroup_mark_under_oom.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002111 */
Tejun Heoc2b42d32015-06-24 16:58:23 -07002112 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002113 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07002114 if (iter->under_oom > 0)
2115 iter->under_oom--;
2116 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07002117}
2118
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002119static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2120
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002121struct oom_wait_info {
Hugh Dickinsd79154b2012-03-21 16:34:18 -07002122 struct mem_cgroup *memcg;
Ingo Molnarac6424b2017-06-20 12:06:13 +02002123 wait_queue_entry_t wait;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002124};
2125
Ingo Molnarac6424b2017-06-20 12:06:13 +02002126static int memcg_oom_wake_function(wait_queue_entry_t *wait,
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002127 unsigned mode, int sync, void *arg)
2128{
Hugh Dickinsd79154b2012-03-21 16:34:18 -07002129 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2130 struct mem_cgroup *oom_wait_memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002131 struct oom_wait_info *oom_wait_info;
2132
2133 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07002134 oom_wait_memcg = oom_wait_info->memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002135
Johannes Weiner2314b422014-12-10 15:44:33 -08002136 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
2137 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002138 return 0;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07002139 return autoremove_wake_function(wait, mode, sync, arg);
2140}
2141
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002142static void memcg_oom_recover(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07002143{
Tejun Heoc2b42d32015-06-24 16:58:23 -07002144 /*
2145 * For the following lockless ->under_oom test, the only required
2146 * guarantee is that it must see the state asserted by an OOM when
2147 * this function is called as a result of userland actions
2148 * triggered by the notification of the OOM. This is trivially
2149 * achieved by invoking mem_cgroup_mark_under_oom() before
2150 * triggering notification.
2151 */
2152 if (memcg && memcg->under_oom)
Tejun Heof4b90b702015-06-24 16:58:21 -07002153 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07002154}
2155
Shakeel Buttbecdf892022-03-22 14:40:19 -07002156/*
2157 * Returns true if successfully killed one or more processes. Though in some
2158 * corner cases it can return true even without killing any process.
2159 */
2160static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002161{
Shakeel Buttbecdf892022-03-22 14:40:19 -07002162 bool locked, ret;
Michal Hocko7056d3a2018-12-28 00:39:57 -08002163
Michal Hocko29ef6802018-08-17 15:47:11 -07002164 if (order > PAGE_ALLOC_COSTLY_ORDER)
Shakeel Buttbecdf892022-03-22 14:40:19 -07002165 return false;
Michal Hocko29ef6802018-08-17 15:47:11 -07002166
Roman Gushchin7a1adfd2018-10-26 15:09:48 -07002167 memcg_memory_event(memcg, MEMCG_OOM);
2168
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002169 /*
Johannes Weiner494264202013-10-16 13:46:59 -07002170 * We are in the middle of the charge context here, so we
2171 * don't want to block when potentially sitting on a callstack
2172 * that holds all kinds of filesystem and mm locks.
2173 *
Michal Hocko29ef6802018-08-17 15:47:11 -07002174 * cgroup1 allows disabling the OOM killer and waiting for outside
2175 * handling until the charge can succeed; remember the context and put
2176 * the task to sleep at the end of the page fault when all locks are
2177 * released.
Johannes Weiner494264202013-10-16 13:46:59 -07002178 *
Michal Hocko29ef6802018-08-17 15:47:11 -07002179 * On the other hand, in-kernel OOM killer allows for an async victim
2180 * memory reclaim (oom_reaper) and that means that we are not solely
2181 * relying on the oom victim to make a forward progress and we can
2182 * invoke the oom killer here.
2183 *
2184 * Please note that mem_cgroup_out_of_memory might fail to find a
2185 * victim and then we have to bail out from the charge path.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002186 */
Yue Zhao17c56de2023-03-06 23:41:37 +08002187 if (READ_ONCE(memcg->oom_kill_disable)) {
Shakeel Buttbecdf892022-03-22 14:40:19 -07002188 if (current->in_user_fault) {
2189 css_get(&memcg->css);
2190 current->memcg_in_oom = memcg;
Shakeel Buttbecdf892022-03-22 14:40:19 -07002191 }
2192 return false;
Michal Hocko29ef6802018-08-17 15:47:11 -07002193 }
2194
Michal Hocko7056d3a2018-12-28 00:39:57 -08002195 mem_cgroup_mark_under_oom(memcg);
Michal Hocko29ef6802018-08-17 15:47:11 -07002196
Michal Hocko7056d3a2018-12-28 00:39:57 -08002197 locked = mem_cgroup_oom_trylock(memcg);
2198
2199 if (locked)
2200 mem_cgroup_oom_notify(memcg);
2201
2202 mem_cgroup_unmark_under_oom(memcg);
Shakeel Buttbecdf892022-03-22 14:40:19 -07002203 ret = mem_cgroup_out_of_memory(memcg, mask, order);
Michal Hocko7056d3a2018-12-28 00:39:57 -08002204
2205 if (locked)
2206 mem_cgroup_oom_unlock(memcg);
2207
2208 return ret;
Johannes Weiner494264202013-10-16 13:46:59 -07002209}
2210
2211/**
2212 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2213 * @handle: actually kill/wait or just clean up the OOM state
2214 *
2215 * This has to be called at the end of a page fault if the memcg OOM
2216 * handler was enabled.
2217 *
2218 * Memcg supports userspace OOM handling where failed allocations must
2219 * sleep on a waitqueue until the userspace task resolves the
2220 * situation. Sleeping directly in the charge context with all kinds
2221 * of locks held is not a good idea, instead we remember an OOM state
2222 * in the task and mem_cgroup_oom_synchronize() has to be called at
2223 * the end of the page fault to complete the OOM handling.
2224 *
2225 * Returns %true if an ongoing memcg OOM situation was detected and
2226 * completed, %false otherwise.
2227 */
2228bool mem_cgroup_oom_synchronize(bool handle)
2229{
Tejun Heo626ebc42015-11-05 18:46:09 -08002230 struct mem_cgroup *memcg = current->memcg_in_oom;
Johannes Weiner494264202013-10-16 13:46:59 -07002231 struct oom_wait_info owait;
2232 bool locked;
2233
2234 /* OOM is global, do not handle */
2235 if (!memcg)
2236 return false;
2237
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07002238 if (!handle)
Johannes Weiner494264202013-10-16 13:46:59 -07002239 goto cleanup;
2240
2241 owait.memcg = memcg;
2242 owait.wait.flags = 0;
2243 owait.wait.func = memcg_oom_wake_function;
2244 owait.wait.private = current;
Ingo Molnar2055da92017-06-20 12:06:46 +02002245 INIT_LIST_HEAD(&owait.wait.entry);
Johannes Weiner494264202013-10-16 13:46:59 -07002246
2247 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002248 mem_cgroup_mark_under_oom(memcg);
2249
2250 locked = mem_cgroup_oom_trylock(memcg);
2251
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07002252 if (locked)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002253 mem_cgroup_oom_notify(memcg);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002254
Haifeng Xu857f2132023-04-19 03:07:38 +00002255 schedule();
2256 mem_cgroup_unmark_under_oom(memcg);
2257 finish_wait(&memcg_oom_waitq, &owait.wait);
Johannes Weiner494264202013-10-16 13:46:59 -07002258
Haifeng Xu18b1d182023-04-19 03:07:39 +00002259 if (locked)
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07002260 mem_cgroup_oom_unlock(memcg);
Johannes Weiner494264202013-10-16 13:46:59 -07002261cleanup:
Tejun Heo626ebc42015-11-05 18:46:09 -08002262 current->memcg_in_oom = NULL;
Johannes Weiner3812c8c2013-09-12 15:13:44 -07002263 css_put(&memcg->css);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002264 return true;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07002265}
2266
Johannes Weinerd7365e72014-10-29 14:50:48 -07002267/**
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002268 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2269 * @victim: task to be killed by the OOM killer
2270 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2271 *
2272 * Returns a pointer to a memory cgroup, which has to be cleaned up
2273 * by killing all belonging OOM-killable tasks.
2274 *
2275 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2276 */
2277struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2278 struct mem_cgroup *oom_domain)
2279{
2280 struct mem_cgroup *oom_group = NULL;
2281 struct mem_cgroup *memcg;
2282
2283 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2284 return NULL;
2285
2286 if (!oom_domain)
2287 oom_domain = root_mem_cgroup;
2288
2289 rcu_read_lock();
2290
2291 memcg = mem_cgroup_from_task(victim);
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05302292 if (mem_cgroup_is_root(memcg))
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002293 goto out;
2294
2295 /*
Roman Gushchin48fe2672020-04-01 21:07:39 -07002296 * If the victim task has been asynchronously moved to a different
2297 * memory cgroup, we might end up killing tasks outside oom_domain.
2298 * In this case it's better to ignore memory.group.oom.
2299 */
2300 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2301 goto out;
2302
2303 /*
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002304 * Traverse the memory cgroup hierarchy from the victim task's
2305 * cgroup up to the OOMing cgroup (or root) to find the
2306 * highest-level memory cgroup with oom.group set.
2307 */
2308 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
Yue Zhaoeaf7b662023-03-06 23:41:35 +08002309 if (READ_ONCE(memcg->oom_group))
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002310 oom_group = memcg;
2311
2312 if (memcg == oom_domain)
2313 break;
2314 }
2315
2316 if (oom_group)
2317 css_get(&oom_group->css);
2318out:
2319 rcu_read_unlock();
2320
2321 return oom_group;
2322}
2323
2324void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2325{
2326 pr_info("Tasks in ");
2327 pr_cont_cgroup_path(memcg->css.cgroup);
2328 pr_cont(" are going to be killed due to memory.oom.group set\n");
2329}
2330
2331/**
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002332 * folio_memcg_lock - Bind a folio to its memcg.
2333 * @folio: The folio.
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07002334 *
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002335 * This function prevents unlocked LRU folios from being moved to
Johannes Weiner739f79f2017-08-18 15:15:48 -07002336 * another cgroup.
2337 *
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002338 * It ensures lifetime of the bound memcg. The caller is responsible
2339 * for the lifetime of the folio.
Balbir Singhd69b0422009-06-17 16:26:34 -07002340 */
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002341void folio_memcg_lock(struct folio *folio)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002342{
2343 struct mem_cgroup *memcg;
Johannes Weiner6de22612015-02-11 15:25:01 -08002344 unsigned long flags;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002345
Johannes Weiner6de22612015-02-11 15:25:01 -08002346 /*
2347 * The RCU lock is held throughout the transaction. The fast
2348 * path can get away without acquiring the memcg->move_lock
2349 * because page moving starts with an RCU grace period.
Johannes Weiner739f79f2017-08-18 15:15:48 -07002350 */
Johannes Weinerd7365e72014-10-29 14:50:48 -07002351 rcu_read_lock();
2352
2353 if (mem_cgroup_disabled())
Johannes Weiner1c824a62021-04-29 22:55:32 -07002354 return;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002355again:
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002356 memcg = folio_memcg(folio);
Johannes Weiner29833312014-12-10 15:44:02 -08002357 if (unlikely(!memcg))
Johannes Weiner1c824a62021-04-29 22:55:32 -07002358 return;
Johannes Weinerd7365e72014-10-29 14:50:48 -07002359
Alex Shi20ad50d2020-12-15 12:33:51 -08002360#ifdef CONFIG_PROVE_LOCKING
2361 local_irq_save(flags);
2362 might_lock(&memcg->move_lock);
2363 local_irq_restore(flags);
2364#endif
2365
Qiang Huangbdcbb652014-06-04 16:08:21 -07002366 if (atomic_read(&memcg->moving_account) <= 0)
Johannes Weiner1c824a62021-04-29 22:55:32 -07002367 return;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002368
Johannes Weiner6de22612015-02-11 15:25:01 -08002369 spin_lock_irqsave(&memcg->move_lock, flags);
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002370 if (memcg != folio_memcg(folio)) {
Johannes Weiner6de22612015-02-11 15:25:01 -08002371 spin_unlock_irqrestore(&memcg->move_lock, flags);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002372 goto again;
2373 }
Johannes Weiner6de22612015-02-11 15:25:01 -08002374
2375 /*
Johannes Weiner1c824a62021-04-29 22:55:32 -07002376 * When charge migration first begins, we can have multiple
2377 * critical sections holding the fast-path RCU lock and one
2378 * holding the slowpath move_lock. Track the task who has the
Kefeng Wang6c77b602023-06-14 22:36:12 +08002379 * move_lock for folio_memcg_unlock().
Johannes Weiner6de22612015-02-11 15:25:01 -08002380 */
2381 memcg->move_lock_task = current;
2382 memcg->move_lock_flags = flags;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002383}
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002384
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002385static void __folio_memcg_unlock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002386{
Johannes Weiner6de22612015-02-11 15:25:01 -08002387 if (memcg && memcg->move_lock_task == current) {
2388 unsigned long flags = memcg->move_lock_flags;
2389
2390 memcg->move_lock_task = NULL;
2391 memcg->move_lock_flags = 0;
2392
2393 spin_unlock_irqrestore(&memcg->move_lock, flags);
2394 }
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002395
Johannes Weinerd7365e72014-10-29 14:50:48 -07002396 rcu_read_unlock();
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002397}
Johannes Weiner739f79f2017-08-18 15:15:48 -07002398
2399/**
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002400 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2401 * @folio: The folio.
2402 *
2403 * This releases the binding created by folio_memcg_lock(). This does
2404 * not change the accounting of this folio to its memcg, but it does
2405 * permit others to change it.
Johannes Weiner739f79f2017-08-18 15:15:48 -07002406 */
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002407void folio_memcg_unlock(struct folio *folio)
2408{
2409 __folio_memcg_unlock(folio_memcg(folio));
2410}
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04002411
Michal Hockofead2b82022-03-22 14:40:35 -07002412struct memcg_stock_pcp {
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002413 local_lock_t stock_lock;
Michal Hockofead2b82022-03-22 14:40:35 -07002414 struct mem_cgroup *cached; /* this never be root cgroup */
2415 unsigned int nr_pages;
2416
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002417#ifdef CONFIG_MEMCG_KMEM
2418 struct obj_cgroup *cached_objcg;
Waiman Long68ac5b3c2021-06-28 19:37:23 -07002419 struct pglist_data *cached_pgdat;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002420 unsigned int nr_bytes;
Waiman Long68ac5b3c2021-06-28 19:37:23 -07002421 int nr_slab_reclaimable_b;
2422 int nr_slab_unreclaimable_b;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002423#endif
2424
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002425 struct work_struct work;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002426 unsigned long flags;
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -07002427#define FLUSHING_CACHED_CHARGE 0
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002428};
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002429static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2430 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2431};
Michal Hocko9f50fad2011-08-09 11:56:26 +02002432static DEFINE_MUTEX(percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002433
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002434#ifdef CONFIG_MEMCG_KMEM
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002435static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002436static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2437 struct mem_cgroup *root_memcg);
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07002438static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002439
2440#else
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002441static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002442{
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002443 return NULL;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002444}
2445static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2446 struct mem_cgroup *root_memcg)
2447{
2448 return false;
2449}
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07002450static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2451{
2452}
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002453#endif
2454
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002455/**
2456 * consume_stock: Try to consume stocked charge on this cpu.
2457 * @memcg: memcg to consume from.
2458 * @nr_pages: how many pages to charge.
2459 *
2460 * The charges will only happen if @memcg matches the current cpu's memcg
2461 * stock, and at least @nr_pages are available in that stock. Failure to
2462 * service an allocation will refill the stock.
2463 *
2464 * returns true if successful, false otherwise.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002465 */
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002466static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002467{
2468 struct memcg_stock_pcp *stock;
Breno Leitao1872b3b2024-05-01 02:54:20 -07002469 unsigned int stock_pages;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002470 unsigned long flags;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002471 bool ret = false;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002472
Johannes Weinera983b5e2018-01-31 16:16:45 -08002473 if (nr_pages > MEMCG_CHARGE_BATCH)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002474 return ret;
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002475
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002476 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002477
2478 stock = this_cpu_ptr(&memcg_stock);
Breno Leitao1872b3b2024-05-01 02:54:20 -07002479 stock_pages = READ_ONCE(stock->nr_pages);
2480 if (memcg == READ_ONCE(stock->cached) && stock_pages >= nr_pages) {
2481 WRITE_ONCE(stock->nr_pages, stock_pages - nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002482 ret = true;
2483 }
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002484
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002485 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002486
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002487 return ret;
2488}
2489
2490/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002491 * Returns stocks cached in percpu and reset cached information.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002492 */
2493static void drain_stock(struct memcg_stock_pcp *stock)
2494{
Breno Leitao1872b3b2024-05-01 02:54:20 -07002495 unsigned int stock_pages = READ_ONCE(stock->nr_pages);
Roman Gushchinf785a8f2023-05-02 09:08:39 -07002496 struct mem_cgroup *old = READ_ONCE(stock->cached);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002497
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002498 if (!old)
2499 return;
2500
Breno Leitao1872b3b2024-05-01 02:54:20 -07002501 if (stock_pages) {
2502 page_counter_uncharge(&old->memory, stock_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002503 if (do_memsw_account())
Breno Leitao1872b3b2024-05-01 02:54:20 -07002504 page_counter_uncharge(&old->memsw, stock_pages);
2505
2506 WRITE_ONCE(stock->nr_pages, 0);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002507 }
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002508
2509 css_put(&old->css);
Roman Gushchinf785a8f2023-05-02 09:08:39 -07002510 WRITE_ONCE(stock->cached, NULL);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002511}
2512
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002513static void drain_local_stock(struct work_struct *dummy)
2514{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002515 struct memcg_stock_pcp *stock;
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002516 struct obj_cgroup *old = NULL;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002517 unsigned long flags;
2518
Michal Hocko72f01842017-10-03 16:14:53 -07002519 /*
Michal Hocko5c49cf92021-09-02 14:56:02 -07002520 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2521 * drain_stock races is that we always operate on local CPU stock
2522 * here with IRQ disabled
Michal Hocko72f01842017-10-03 16:14:53 -07002523 */
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002524 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002525
2526 stock = this_cpu_ptr(&memcg_stock);
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002527 old = drain_obj_stock(stock);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002528 drain_stock(stock);
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002529 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002530
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002531 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
Yosry Ahmed91b71e782024-03-16 01:58:03 +00002532 obj_cgroup_put(old);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002533}
2534
2535/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002536 * Cache charges(val) to local per_cpu area.
Greg Thelen320cc512010-03-15 15:27:28 +01002537 * This will be consumed by consume_stock() function, later.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002538 */
Johannes Weineraf9a3b62022-03-22 14:40:44 -07002539static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002540{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002541 struct memcg_stock_pcp *stock;
Breno Leitao1872b3b2024-05-01 02:54:20 -07002542 unsigned int stock_pages;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002543
2544 stock = this_cpu_ptr(&memcg_stock);
Roman Gushchinf785a8f2023-05-02 09:08:39 -07002545 if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002546 drain_stock(stock);
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002547 css_get(&memcg->css);
Roman Gushchinf785a8f2023-05-02 09:08:39 -07002548 WRITE_ONCE(stock->cached, memcg);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002549 }
Breno Leitao1872b3b2024-05-01 02:54:20 -07002550 stock_pages = READ_ONCE(stock->nr_pages) + nr_pages;
2551 WRITE_ONCE(stock->nr_pages, stock_pages);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002552
Breno Leitao1872b3b2024-05-01 02:54:20 -07002553 if (stock_pages > MEMCG_CHARGE_BATCH)
Roman Gushchin475d0482017-09-08 16:13:09 -07002554 drain_stock(stock);
Johannes Weineraf9a3b62022-03-22 14:40:44 -07002555}
Roman Gushchin475d0482017-09-08 16:13:09 -07002556
Johannes Weineraf9a3b62022-03-22 14:40:44 -07002557static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2558{
2559 unsigned long flags;
2560
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002561 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Johannes Weineraf9a3b62022-03-22 14:40:44 -07002562 __refill_stock(memcg, nr_pages);
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07002563 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002564}
2565
2566/*
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002567 * Drains all per-CPU charge caches for given root_memcg resp. subtree
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002568 * of the hierarchy under it.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002569 */
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002570static void drain_all_stock(struct mem_cgroup *root_memcg)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002571{
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002572 int cpu, curcpu;
Michal Hockod38144b2011-07-26 16:08:28 -07002573
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002574 /* If someone's already draining, avoid adding running more workers. */
2575 if (!mutex_trylock(&percpu_charge_mutex))
2576 return;
Michal Hocko72f01842017-10-03 16:14:53 -07002577 /*
2578 * Notify other cpus that system-wide "drain" is running
2579 * We do not care about races with the cpu hotplug because cpu down
2580 * as well as workers from this path always operate on the local
2581 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2582 */
Sebastian Andrzej Siewior0790ed62022-03-22 14:40:50 -07002583 migrate_disable();
2584 curcpu = smp_processor_id();
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002585 for_each_online_cpu(cpu) {
2586 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002587 struct mem_cgroup *memcg;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002588 bool flush = false;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002589
Roman Gushchine1a366b2019-09-23 15:34:58 -07002590 rcu_read_lock();
Roman Gushchinf785a8f2023-05-02 09:08:39 -07002591 memcg = READ_ONCE(stock->cached);
Breno Leitao1872b3b2024-05-01 02:54:20 -07002592 if (memcg && READ_ONCE(stock->nr_pages) &&
Roman Gushchine1a366b2019-09-23 15:34:58 -07002593 mem_cgroup_is_descendant(memcg, root_memcg))
2594 flush = true;
Miaohe Lin27fb0952021-09-02 14:55:59 -07002595 else if (obj_stock_flush_required(stock, root_memcg))
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002596 flush = true;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002597 rcu_read_unlock();
2598
2599 if (flush &&
2600 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
Michal Hockod1a05b62011-07-26 16:08:27 -07002601 if (cpu == curcpu)
2602 drain_local_stock(&stock->work);
Michal Hocko6a792692023-03-17 14:44:48 +01002603 else if (!cpu_is_isolated(cpu))
Michal Hockod1a05b62011-07-26 16:08:27 -07002604 schedule_work_on(cpu, &stock->work);
2605 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002606 }
Sebastian Andrzej Siewior0790ed62022-03-22 14:40:50 -07002607 migrate_enable();
Michal Hocko9f50fad2011-08-09 11:56:26 +02002608 mutex_unlock(&percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002609}
2610
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002611static int memcg_hotplug_cpu_dead(unsigned int cpu)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002612{
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002613 struct memcg_stock_pcp *stock;
2614
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002615 stock = &per_cpu(memcg_stock, cpu);
2616 drain_stock(stock);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002617
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002618 return 0;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002619}
2620
Chris Downb3ff9292020-08-06 23:21:54 -07002621static unsigned long reclaim_high(struct mem_cgroup *memcg,
2622 unsigned int nr_pages,
2623 gfp_t gfp_mask)
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002624{
Chris Downb3ff9292020-08-06 23:21:54 -07002625 unsigned long nr_reclaimed = 0;
2626
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002627 do {
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002628 unsigned long pflags;
2629
Jakub Kicinskid1663a92020-06-01 21:49:49 -07002630 if (page_counter_read(&memcg->memory) <=
2631 READ_ONCE(memcg->memory.high))
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002632 continue;
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002633
Johannes Weinere27be242018-04-10 16:29:45 -07002634 memcg_memory_event(memcg, MEMCG_HIGH);
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002635
2636 psi_memstall_enter(&pflags);
Chris Downb3ff9292020-08-06 23:21:54 -07002637 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
Yosry Ahmed73b73ba2022-07-14 06:49:18 +00002638 gfp_mask,
Michal Hocko55ab8342022-12-16 10:46:33 +01002639 MEMCG_RECLAIM_MAY_SWAP);
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002640 psi_memstall_leave(&pflags);
Chris Down4bf17302020-04-06 20:03:30 -07002641 } while ((memcg = parent_mem_cgroup(memcg)) &&
2642 !mem_cgroup_is_root(memcg));
Chris Downb3ff9292020-08-06 23:21:54 -07002643
2644 return nr_reclaimed;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002645}
2646
2647static void high_work_func(struct work_struct *work)
2648{
2649 struct mem_cgroup *memcg;
2650
2651 memcg = container_of(work, struct mem_cgroup, high_work);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002652 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002653}
2654
Tejun Heob23afb92015-11-05 18:46:11 -08002655/*
Chris Down0e4b01d2019-09-23 15:34:55 -07002656 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2657 * enough to still cause a significant slowdown in most cases, while still
2658 * allowing diagnostics and tracing to proceed without becoming stuck.
2659 */
2660#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2661
2662/*
2663 * When calculating the delay, we use these either side of the exponentiation to
2664 * maintain precision and scale to a reasonable number of jiffies (see the table
2665 * below.
2666 *
2667 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2668 * overage ratio to a delay.
Randy Dunlapac5ddd02020-08-11 18:33:02 -07002669 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
Chris Down0e4b01d2019-09-23 15:34:55 -07002670 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2671 * to produce a reasonable delay curve.
2672 *
2673 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2674 * reasonable delay curve compared to precision-adjusted overage, not
2675 * penalising heavily at first, but still making sure that growth beyond the
2676 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2677 * example, with a high of 100 megabytes:
2678 *
2679 * +-------+------------------------+
2680 * | usage | time to allocate in ms |
2681 * +-------+------------------------+
2682 * | 100M | 0 |
2683 * | 101M | 6 |
2684 * | 102M | 25 |
2685 * | 103M | 57 |
2686 * | 104M | 102 |
2687 * | 105M | 159 |
2688 * | 106M | 230 |
2689 * | 107M | 313 |
2690 * | 108M | 409 |
2691 * | 109M | 518 |
2692 * | 110M | 639 |
2693 * | 111M | 774 |
2694 * | 112M | 921 |
2695 * | 113M | 1081 |
2696 * | 114M | 1254 |
2697 * | 115M | 1439 |
2698 * | 116M | 1638 |
2699 * | 117M | 1849 |
2700 * | 118M | 2000 |
2701 * | 119M | 2000 |
2702 * | 120M | 2000 |
2703 * +-------+------------------------+
2704 */
2705 #define MEMCG_DELAY_PRECISION_SHIFT 20
2706 #define MEMCG_DELAY_SCALING_SHIFT 14
2707
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002708static u64 calculate_overage(unsigned long usage, unsigned long high)
2709{
2710 u64 overage;
2711
2712 if (usage <= high)
2713 return 0;
2714
2715 /*
2716 * Prevent division by 0 in overage calculation by acting as if
2717 * it was a threshold of 1 page
2718 */
2719 high = max(high, 1UL);
2720
2721 overage = usage - high;
2722 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2723 return div64_u64(overage, high);
2724}
2725
2726static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2727{
2728 u64 overage, max_overage = 0;
2729
2730 do {
2731 overage = calculate_overage(page_counter_read(&memcg->memory),
Jakub Kicinskid1663a92020-06-01 21:49:49 -07002732 READ_ONCE(memcg->memory.high));
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002733 max_overage = max(overage, max_overage);
2734 } while ((memcg = parent_mem_cgroup(memcg)) &&
2735 !mem_cgroup_is_root(memcg));
2736
2737 return max_overage;
2738}
2739
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002740static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2741{
2742 u64 overage, max_overage = 0;
2743
2744 do {
2745 overage = calculate_overage(page_counter_read(&memcg->swap),
2746 READ_ONCE(memcg->swap.high));
2747 if (overage)
2748 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2749 max_overage = max(overage, max_overage);
2750 } while ((memcg = parent_mem_cgroup(memcg)) &&
2751 !mem_cgroup_is_root(memcg));
2752
2753 return max_overage;
2754}
2755
Chris Down0e4b01d2019-09-23 15:34:55 -07002756/*
Chris Downe26733e2020-03-21 18:22:23 -07002757 * Get the number of jiffies that we should penalise a mischievous cgroup which
2758 * is exceeding its memory.high by checking both it and its ancestors.
Tejun Heob23afb92015-11-05 18:46:11 -08002759 */
Chris Downe26733e2020-03-21 18:22:23 -07002760static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002761 unsigned int nr_pages,
2762 u64 max_overage)
Tejun Heob23afb92015-11-05 18:46:11 -08002763{
Chris Downe26733e2020-03-21 18:22:23 -07002764 unsigned long penalty_jiffies;
Chris Downe26733e2020-03-21 18:22:23 -07002765
2766 if (!max_overage)
2767 return 0;
Chris Down0e4b01d2019-09-23 15:34:55 -07002768
2769 /*
Chris Down0e4b01d2019-09-23 15:34:55 -07002770 * We use overage compared to memory.high to calculate the number of
2771 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2772 * fairly lenient on small overages, and increasingly harsh when the
2773 * memcg in question makes it clear that it has no intention of stopping
2774 * its crazy behaviour, so we exponentially increase the delay based on
2775 * overage amount.
2776 */
Chris Downe26733e2020-03-21 18:22:23 -07002777 penalty_jiffies = max_overage * max_overage * HZ;
2778 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2779 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
Chris Down0e4b01d2019-09-23 15:34:55 -07002780
2781 /*
2782 * Factor in the task's own contribution to the overage, such that four
2783 * N-sized allocations are throttled approximately the same as one
2784 * 4N-sized allocation.
2785 *
2786 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2787 * larger the current charge patch is than that.
2788 */
Jakub Kicinskiff144e62020-06-01 21:49:45 -07002789 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
Chris Downe26733e2020-03-21 18:22:23 -07002790}
2791
2792/*
Johannes Weiner63fd3272024-01-11 08:29:02 -05002793 * Reclaims memory over the high limit. Called directly from
2794 * try_charge() (context permitting), as well as from the userland
2795 * return path where reclaim is always able to block.
Chris Downe26733e2020-03-21 18:22:23 -07002796 */
Johannes Weiner9ea9cb02023-09-14 11:21:39 -04002797void mem_cgroup_handle_over_high(gfp_t gfp_mask)
Chris Downe26733e2020-03-21 18:22:23 -07002798{
2799 unsigned long penalty_jiffies;
2800 unsigned long pflags;
Chris Downb3ff9292020-08-06 23:21:54 -07002801 unsigned long nr_reclaimed;
Chris Downe26733e2020-03-21 18:22:23 -07002802 unsigned int nr_pages = current->memcg_nr_pages_over_high;
Chris Downd977aa92020-08-06 23:21:58 -07002803 int nr_retries = MAX_RECLAIM_RETRIES;
Chris Downe26733e2020-03-21 18:22:23 -07002804 struct mem_cgroup *memcg;
Chris Downb3ff9292020-08-06 23:21:54 -07002805 bool in_retry = false;
Chris Downe26733e2020-03-21 18:22:23 -07002806
2807 if (likely(!nr_pages))
2808 return;
2809
2810 memcg = get_mem_cgroup_from_mm(current->mm);
Chris Downe26733e2020-03-21 18:22:23 -07002811 current->memcg_nr_pages_over_high = 0;
2812
Chris Downb3ff9292020-08-06 23:21:54 -07002813retry_reclaim:
2814 /*
Johannes Weiner63fd3272024-01-11 08:29:02 -05002815 * Bail if the task is already exiting. Unlike memory.max,
2816 * memory.high enforcement isn't as strict, and there is no
2817 * OOM killer involved, which means the excess could already
2818 * be much bigger (and still growing) than it could for
2819 * memory.max; the dying task could get stuck in fruitless
2820 * reclaim for a long time, which isn't desirable.
2821 */
2822 if (task_is_dying())
2823 goto out;
2824
2825 /*
Chris Downb3ff9292020-08-06 23:21:54 -07002826 * The allocating task should reclaim at least the batch size, but for
2827 * subsequent retries we only want to do what's necessary to prevent oom
2828 * or breaching resource isolation.
2829 *
2830 * This is distinct from memory.max or page allocator behaviour because
2831 * memory.high is currently batched, whereas memory.max and the page
2832 * allocator run every time an allocation is made.
2833 */
2834 nr_reclaimed = reclaim_high(memcg,
2835 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
Johannes Weiner9ea9cb02023-09-14 11:21:39 -04002836 gfp_mask);
Chris Downb3ff9292020-08-06 23:21:54 -07002837
Chris Downe26733e2020-03-21 18:22:23 -07002838 /*
2839 * memory.high is breached and reclaim is unable to keep up. Throttle
2840 * allocators proactively to slow down excessive growth.
2841 */
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002842 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2843 mem_find_max_overage(memcg));
Chris Down0e4b01d2019-09-23 15:34:55 -07002844
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002845 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2846 swap_find_max_overage(memcg));
2847
Chris Down0e4b01d2019-09-23 15:34:55 -07002848 /*
Jakub Kicinskiff144e62020-06-01 21:49:45 -07002849 * Clamp the max delay per usermode return so as to still keep the
2850 * application moving forwards and also permit diagnostics, albeit
2851 * extremely slowly.
2852 */
2853 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2854
2855 /*
Chris Down0e4b01d2019-09-23 15:34:55 -07002856 * Don't sleep if the amount of jiffies this memcg owes us is so low
2857 * that it's not even worth doing, in an attempt to be nice to those who
2858 * go only a small amount over their memory.high value and maybe haven't
2859 * been aggressively reclaimed enough yet.
2860 */
2861 if (penalty_jiffies <= HZ / 100)
2862 goto out;
2863
2864 /*
Chris Downb3ff9292020-08-06 23:21:54 -07002865 * If reclaim is making forward progress but we're still over
2866 * memory.high, we want to encourage that rather than doing allocator
2867 * throttling.
2868 */
2869 if (nr_reclaimed || nr_retries--) {
2870 in_retry = true;
2871 goto retry_reclaim;
2872 }
2873
2874 /*
Johannes Weiner63fd3272024-01-11 08:29:02 -05002875 * Reclaim didn't manage to push usage below the limit, slow
2876 * this allocating task down.
2877 *
Chris Down0e4b01d2019-09-23 15:34:55 -07002878 * If we exit early, we're guaranteed to die (since
2879 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2880 * need to account for any ill-begotten jiffies to pay them off later.
2881 */
2882 psi_memstall_enter(&pflags);
2883 schedule_timeout_killable(penalty_jiffies);
2884 psi_memstall_leave(&pflags);
2885
2886out:
2887 css_put(&memcg->css);
Tejun Heob23afb92015-11-05 18:46:11 -08002888}
2889
Muchun Songc5c8b162021-06-28 19:37:44 -07002890static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2891 unsigned int nr_pages)
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002892{
Johannes Weinera983b5e2018-01-31 16:16:45 -08002893 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
Chris Downd977aa92020-08-06 23:21:58 -07002894 int nr_retries = MAX_RECLAIM_RETRIES;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002895 struct mem_cgroup *mem_over_limit;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002896 struct page_counter *counter;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002897 unsigned long nr_reclaimed;
Vasily Averina4ebf1b2021-11-05 13:38:09 -07002898 bool passed_oom = false;
Yosry Ahmed73b73ba2022-07-14 06:49:18 +00002899 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002900 bool drained = false;
Roman Gushchind6e103a2022-07-01 20:35:21 -07002901 bool raised_max_event = false;
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002902 unsigned long pflags;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08002903
Johannes Weiner6539cc02014-08-06 16:05:42 -07002904retry:
Michal Hockob6b6cc72014-04-07 15:37:44 -07002905 if (consume_stock(memcg, nr_pages))
Tejun Heo10d53c72015-11-05 18:46:17 -08002906 return 0;
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002907
Johannes Weiner7941d212016-01-14 15:21:23 -08002908 if (!do_memsw_account() ||
Johannes Weiner6071ca52015-11-05 18:50:26 -08002909 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2910 if (page_counter_try_charge(&memcg->memory, batch, &counter))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002911 goto done_restock;
Johannes Weiner7941d212016-01-14 15:21:23 -08002912 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002913 page_counter_uncharge(&memcg->memsw, batch);
2914 mem_over_limit = mem_cgroup_from_counter(counter, memory);
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002915 } else {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002916 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
Yosry Ahmed73b73ba2022-07-14 06:49:18 +00002917 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002918 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002919
Johannes Weiner6539cc02014-08-06 16:05:42 -07002920 if (batch > nr_pages) {
2921 batch = nr_pages;
2922 goto retry;
2923 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002924
Johannes Weiner06b078fc02014-08-06 16:05:44 -07002925 /*
Johannes Weiner89a28482016-10-27 17:46:56 -07002926 * Prevent unbounded recursion when reclaim operations need to
2927 * allocate memory. This might exceed the limits temporarily,
2928 * but we prefer facilitating memory reclaim and getting back
2929 * under the limit over triggering OOM kills in these cases.
2930 */
2931 if (unlikely(current->flags & PF_MEMALLOC))
2932 goto force;
2933
Johannes Weiner06b078fc02014-08-06 16:05:44 -07002934 if (unlikely(task_in_memcg_oom(current)))
2935 goto nomem;
2936
Mel Gormand0164ad2015-11-06 16:28:21 -08002937 if (!gfpflags_allow_blocking(gfp_mask))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002938 goto nomem;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07002939
Johannes Weinere27be242018-04-10 16:29:45 -07002940 memcg_memory_event(mem_over_limit, MEMCG_MAX);
Roman Gushchind6e103a2022-07-01 20:35:21 -07002941 raised_max_event = true;
Johannes Weiner241994ed2015-02-11 15:26:06 -08002942
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002943 psi_memstall_enter(&pflags);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002944 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
Michal Hocko55ab8342022-12-16 10:46:33 +01002945 gfp_mask, reclaim_options);
Johannes Weinere22c6ed2020-08-06 23:22:15 -07002946 psi_memstall_leave(&pflags);
Johannes Weiner6539cc02014-08-06 16:05:42 -07002947
Johannes Weiner61e02c72014-08-06 16:08:16 -07002948 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
Johannes Weiner6539cc02014-08-06 16:05:42 -07002949 goto retry;
Johannes Weiner28c34c22014-08-06 16:05:47 -07002950
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002951 if (!drained) {
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002952 drain_all_stock(mem_over_limit);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002953 drained = true;
2954 goto retry;
2955 }
2956
Johannes Weiner28c34c22014-08-06 16:05:47 -07002957 if (gfp_mask & __GFP_NORETRY)
2958 goto nomem;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002959 /*
2960 * Even though the limit is exceeded at this point, reclaim
2961 * may have been able to free some pages. Retry the charge
2962 * before killing the task.
2963 *
2964 * Only for regular pages, though: huge pages are rather
2965 * unlikely to succeed so close to the limit, and we fall back
2966 * to regular pages anyway in case of failure.
2967 */
Johannes Weiner61e02c72014-08-06 16:08:16 -07002968 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002969 goto retry;
2970 /*
2971 * At task move, charge accounts can be doubly counted. So, it's
2972 * better to wait until the end of task_move if something is going on.
2973 */
2974 if (mem_cgroup_wait_acct_move(mem_over_limit))
2975 goto retry;
2976
Johannes Weiner9b130612014-08-06 16:05:51 -07002977 if (nr_retries--)
2978 goto retry;
2979
Shakeel Butt38d38492019-07-11 20:55:48 -07002980 if (gfp_mask & __GFP_RETRY_MAYFAIL)
Michal Hocko29ef6802018-08-17 15:47:11 -07002981 goto nomem;
2982
Vasily Averina4ebf1b2021-11-05 13:38:09 -07002983 /* Avoid endless loop for tasks bypassed by the oom killer */
2984 if (passed_oom && task_is_dying())
2985 goto nomem;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002986
Michal Hocko29ef6802018-08-17 15:47:11 -07002987 /*
2988 * keep retrying as long as the memcg oom killer is able to make
2989 * a forward progress or bypass the charge if the oom killer
2990 * couldn't make any progress.
2991 */
Shakeel Buttbecdf892022-03-22 14:40:19 -07002992 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2993 get_order(nr_pages * PAGE_SIZE))) {
Vasily Averina4ebf1b2021-11-05 13:38:09 -07002994 passed_oom = true;
Chris Downd977aa92020-08-06 23:21:58 -07002995 nr_retries = MAX_RECLAIM_RETRIES;
Michal Hocko29ef6802018-08-17 15:47:11 -07002996 goto retry;
Michal Hocko29ef6802018-08-17 15:47:11 -07002997 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002998nomem:
Shakeel Butt1461e8c2022-03-22 14:40:22 -07002999 /*
3000 * Memcg doesn't have a dedicated reserve for atomic
3001 * allocations. But like the global atomic pool, we need to
3002 * put the burden of reclaim on regular allocation requests
3003 * and let these go through as privileged allocations.
3004 */
3005 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
Johannes Weiner3168ecb2013-10-31 16:34:13 -07003006 return -ENOMEM;
Tejun Heo10d53c72015-11-05 18:46:17 -08003007force:
3008 /*
Roman Gushchind6e103a2022-07-01 20:35:21 -07003009 * If the allocation has to be enforced, don't forget to raise
3010 * a MEMCG_MAX event.
3011 */
3012 if (!raised_max_event)
3013 memcg_memory_event(mem_over_limit, MEMCG_MAX);
3014
3015 /*
Tejun Heo10d53c72015-11-05 18:46:17 -08003016 * The allocation either can't fail or will lead to more memory
3017 * being freed very soon. Allow memory usage go over the limit
3018 * temporarily by force charging it.
3019 */
3020 page_counter_charge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08003021 if (do_memsw_account())
Tejun Heo10d53c72015-11-05 18:46:17 -08003022 page_counter_charge(&memcg->memsw, nr_pages);
Tejun Heo10d53c72015-11-05 18:46:17 -08003023
3024 return 0;
Johannes Weiner6539cc02014-08-06 16:05:42 -07003025
3026done_restock:
3027 if (batch > nr_pages)
3028 refill_stock(memcg, batch - nr_pages);
Tejun Heob23afb92015-11-05 18:46:11 -08003029
Johannes Weiner241994ed2015-02-11 15:26:06 -08003030 /*
Tejun Heob23afb92015-11-05 18:46:11 -08003031 * If the hierarchy is above the normal consumption range, schedule
3032 * reclaim on returning to userland. We can perform reclaim here
Mel Gorman71baba42015-11-06 16:28:28 -08003033 * if __GFP_RECLAIM but let's always punt for simplicity and so that
Tejun Heob23afb92015-11-05 18:46:11 -08003034 * GFP_KERNEL can consistently be used during reclaim. @memcg is
3035 * not recorded as it most likely matches current's and won't
3036 * change in the meantime. As high limit is checked again before
3037 * reclaim, the cost of mismatch is negligible.
Johannes Weiner241994ed2015-02-11 15:26:06 -08003038 */
3039 do {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07003040 bool mem_high, swap_high;
3041
3042 mem_high = page_counter_read(&memcg->memory) >
3043 READ_ONCE(memcg->memory.high);
3044 swap_high = page_counter_read(&memcg->swap) >
3045 READ_ONCE(memcg->swap.high);
3046
3047 /* Don't bother a random interrupted task */
Shakeel Butt086f6942022-03-22 14:40:07 -07003048 if (!in_task()) {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07003049 if (mem_high) {
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08003050 schedule_work(&memcg->high_work);
3051 break;
3052 }
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07003053 continue;
3054 }
3055
3056 if (mem_high || swap_high) {
3057 /*
3058 * The allocating tasks in this cgroup will need to do
3059 * reclaim or be throttled to prevent further growth
3060 * of the memory or swap footprints.
3061 *
3062 * Target some best-effort fairness between the tasks,
3063 * and distribute reclaim work and delay penalties
3064 * based on how much each task is actually allocating.
3065 */
Vladimir Davydov9516a182015-12-11 13:40:24 -08003066 current->memcg_nr_pages_over_high += batch;
Tejun Heob23afb92015-11-05 18:46:11 -08003067 set_notify_resume(current);
3068 break;
3069 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08003070 } while ((memcg = parent_mem_cgroup(memcg)));
Tejun Heo10d53c72015-11-05 18:46:17 -08003071
Johannes Weiner63fd3272024-01-11 08:29:02 -05003072 /*
3073 * Reclaim is set up above to be called from the userland
3074 * return path. But also attempt synchronous reclaim to avoid
3075 * excessive overrun while the task is still inside the
3076 * kernel. If this is successful, the return path will see it
3077 * when it rechecks the overage and simply bail out.
3078 */
Shakeel Buttc9afe312022-03-22 14:40:28 -07003079 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
3080 !(current->flags & PF_MEMALLOC) &&
Johannes Weiner63fd3272024-01-11 08:29:02 -05003081 gfpflags_allow_blocking(gfp_mask))
Johannes Weiner9ea9cb02023-09-14 11:21:39 -04003082 mem_cgroup_handle_over_high(gfp_mask);
Tejun Heo10d53c72015-11-05 18:46:17 -08003083 return 0;
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08003084}
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08003085
Muchun Songc5c8b162021-06-28 19:37:44 -07003086static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
3087 unsigned int nr_pages)
3088{
3089 if (mem_cgroup_is_root(memcg))
3090 return 0;
3091
3092 return try_charge_memcg(memcg, gfp_mask, nr_pages);
3093}
3094
Nhat Pham4b569382023-10-06 11:46:26 -07003095/**
3096 * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
3097 * @memcg: memcg previously charged.
3098 * @nr_pages: number of pages previously charged.
3099 */
3100void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
Daisuke Nishimuraa3032a22009-12-15 16:47:10 -08003101{
Johannes Weinerce00a962014-09-05 08:43:57 -04003102 if (mem_cgroup_is_root(memcg))
3103 return;
3104
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003105 page_counter_uncharge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08003106 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003107 page_counter_uncharge(&memcg->memsw, nr_pages);
KAMEZAWA Hiroyukid01dd172012-05-29 15:07:03 -07003108}
3109
Matthew Wilcox (Oracle)118f2872021-04-29 14:07:12 -04003110static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003111{
Matthew Wilcox (Oracle)118f2872021-04-29 14:07:12 -04003112 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003113 /*
Alex Shia5eb0112020-12-14 19:06:42 -08003114 * Any of the following ensures page's memcg stability:
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003115 *
Johannes Weinera0b5b412020-06-03 16:02:27 -07003116 * - the page lock
3117 * - LRU isolation
Kefeng Wang6c77b602023-06-14 22:36:12 +08003118 * - folio_memcg_lock()
Johannes Weinera0b5b412020-06-03 16:02:27 -07003119 * - exclusive reference
Yu Zhao018ee472022-09-18 02:00:04 -06003120 * - mem_cgroup_trylock_pages()
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003121 */
Matthew Wilcox (Oracle)118f2872021-04-29 14:07:12 -04003122 folio->memcg_data = (unsigned long)memcg;
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08003123}
3124
Nhat Pham4b569382023-10-06 11:46:26 -07003125/**
3126 * mem_cgroup_commit_charge - commit a previously successful try_charge().
3127 * @folio: folio to commit the charge to.
3128 * @memcg: memcg previously charged.
3129 */
3130void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
3131{
3132 css_get(&memcg->css);
3133 commit_charge(folio, memcg);
3134
3135 local_irq_disable();
3136 mem_cgroup_charge_statistics(memcg, folio_nr_pages(folio));
3137 memcg_check_events(memcg, folio_nid(folio));
3138 local_irq_enable();
3139}
3140
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003141#ifdef CONFIG_MEMCG_KMEM
Waiman Long41eb5df2021-06-28 19:37:34 -07003142
Shakeel Butt91882c12024-04-20 16:25:05 -07003143static inline void __mod_objcg_mlstate(struct obj_cgroup *objcg,
3144 struct pglist_data *pgdat,
3145 enum node_stat_item idx, int nr)
Waiman Longa7ebf562021-12-10 14:47:05 -08003146{
3147 struct mem_cgroup *memcg;
3148 struct lruvec *lruvec;
3149
3150 rcu_read_lock();
3151 memcg = obj_cgroup_memcg(objcg);
3152 lruvec = mem_cgroup_lruvec(memcg, pgdat);
Shakeel Butt91882c12024-04-20 16:25:05 -07003153 __mod_memcg_lruvec_state(lruvec, idx, nr);
Waiman Longa7ebf562021-12-10 14:47:05 -08003154 rcu_read_unlock();
3155}
3156
Roman Gushchinfc4db902022-06-10 11:03:10 -07003157static __always_inline
3158struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
Roman Gushchin8380ce42020-03-28 19:17:25 -07003159{
Roman Gushchin8380ce42020-03-28 19:17:25 -07003160 /*
Roman Gushchin98556092020-08-06 23:21:10 -07003161 * Slab objects are accounted individually, not per-page.
3162 * Memcg membership data for each individual object is saved in
Suren Baghdasaryan21c690a2024-03-21 09:36:28 -07003163 * slab->obj_exts.
Roman Gushchin8380ce42020-03-28 19:17:25 -07003164 */
Vlastimil Babka4b5f8d9a2021-11-02 22:42:04 +01003165 if (folio_test_slab(folio)) {
Suren Baghdasaryan21c690a2024-03-21 09:36:28 -07003166 struct slabobj_ext *obj_exts;
Vlastimil Babka4b5f8d9a2021-11-02 22:42:04 +01003167 struct slab *slab;
Roman Gushchin98556092020-08-06 23:21:10 -07003168 unsigned int off;
3169
Vlastimil Babka4b5f8d9a2021-11-02 22:42:04 +01003170 slab = folio_slab(folio);
Suren Baghdasaryan21c690a2024-03-21 09:36:28 -07003171 obj_exts = slab_obj_exts(slab);
3172 if (!obj_exts)
Vlastimil Babka4b5f8d9a2021-11-02 22:42:04 +01003173 return NULL;
3174
3175 off = obj_to_index(slab->slab_cache, slab, p);
Suren Baghdasaryan21c690a2024-03-21 09:36:28 -07003176 if (obj_exts[off].objcg)
3177 return obj_cgroup_memcg(obj_exts[off].objcg);
Roman Gushchin10befea2020-08-06 23:21:27 -07003178
3179 return NULL;
Roman Gushchin98556092020-08-06 23:21:10 -07003180 }
Roman Gushchin8380ce42020-03-28 19:17:25 -07003181
Roman Gushchinbcfe06b2020-12-01 13:58:27 -08003182 /*
Matthew Wilcoxbecacb02022-12-30 15:08:42 +08003183 * folio_memcg_check() is used here, because in theory we can encounter
Vlastimil Babka4b5f8d9a2021-11-02 22:42:04 +01003184 * a folio where the slab flag has been cleared already, but
Suren Baghdasaryan21c690a2024-03-21 09:36:28 -07003185 * slab->obj_exts has not been freed yet
Matthew Wilcoxbecacb02022-12-30 15:08:42 +08003186 * folio_memcg_check() will guarantee that a proper memory
Roman Gushchinbcfe06b2020-12-01 13:58:27 -08003187 * cgroup pointer or NULL will be returned.
3188 */
Matthew Wilcoxbecacb02022-12-30 15:08:42 +08003189 return folio_memcg_check(folio);
Roman Gushchin8380ce42020-03-28 19:17:25 -07003190}
3191
Roman Gushchinfc4db902022-06-10 11:03:10 -07003192/*
3193 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3194 *
3195 * A passed kernel object can be a slab object, vmalloc object or a generic
3196 * kernel page, so different mechanisms for getting the memory cgroup pointer
3197 * should be used.
3198 *
3199 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
3200 * can not know for sure how the kernel object is implemented.
3201 * mem_cgroup_from_obj() can be safely used in such cases.
3202 *
3203 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3204 * cgroup_mutex, etc.
3205 */
3206struct mem_cgroup *mem_cgroup_from_obj(void *p)
3207{
3208 struct folio *folio;
3209
3210 if (mem_cgroup_disabled())
3211 return NULL;
3212
3213 if (unlikely(is_vmalloc_addr(p)))
3214 folio = page_folio(vmalloc_to_page(p));
3215 else
3216 folio = virt_to_folio(p);
3217
3218 return mem_cgroup_from_obj_folio(folio, p);
3219}
3220
3221/*
3222 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3223 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3224 * allocated using vmalloc().
3225 *
3226 * A passed kernel object must be a slab object or a generic kernel page.
3227 *
3228 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3229 * cgroup_mutex, etc.
3230 */
3231struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3232{
3233 if (mem_cgroup_disabled())
3234 return NULL;
3235
3236 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3237}
3238
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003239static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3240{
3241 struct obj_cgroup *objcg = NULL;
3242
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05303243 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003244 objcg = rcu_dereference(memcg->objcg);
Roman Gushchin7d0715d2023-10-19 15:53:41 -07003245 if (likely(objcg && obj_cgroup_tryget(objcg)))
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003246 break;
3247 objcg = NULL;
3248 }
3249 return objcg;
3250}
3251
Roman Gushchin1aacbd32023-10-19 15:53:42 -07003252static struct obj_cgroup *current_objcg_update(void)
3253{
3254 struct mem_cgroup *memcg;
3255 struct obj_cgroup *old, *objcg = NULL;
3256
3257 do {
3258 /* Atomically drop the update bit. */
3259 old = xchg(&current->objcg, NULL);
3260 if (old) {
3261 old = (struct obj_cgroup *)
3262 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
Yosry Ahmed91b71e782024-03-16 01:58:03 +00003263 obj_cgroup_put(old);
Roman Gushchin1aacbd32023-10-19 15:53:42 -07003264
3265 old = NULL;
3266 }
3267
3268 /* If new objcg is NULL, no reason for the second atomic update. */
3269 if (!current->mm || (current->flags & PF_KTHREAD))
3270 return NULL;
3271
3272 /*
3273 * Release the objcg pointer from the previous iteration,
3274 * if try_cmpxcg() below fails.
3275 */
3276 if (unlikely(objcg)) {
3277 obj_cgroup_put(objcg);
3278 objcg = NULL;
3279 }
3280
3281 /*
3282 * Obtain the new objcg pointer. The current task can be
3283 * asynchronously moved to another memcg and the previous
3284 * memcg can be offlined. So let's get the memcg pointer
3285 * and try get a reference to objcg under a rcu read lock.
3286 */
3287
3288 rcu_read_lock();
3289 memcg = mem_cgroup_from_task(current);
3290 objcg = __get_obj_cgroup_from_memcg(memcg);
3291 rcu_read_unlock();
3292
3293 /*
3294 * Try set up a new objcg pointer atomically. If it
3295 * fails, it means the update flag was set concurrently, so
3296 * the whole procedure should be repeated.
3297 */
3298 } while (!try_cmpxchg(&current->objcg, &old, objcg));
3299
3300 return objcg;
3301}
3302
Roman Gushchine86828e2023-10-19 15:53:44 -07003303__always_inline struct obj_cgroup *current_obj_cgroup(void)
3304{
3305 struct mem_cgroup *memcg;
3306 struct obj_cgroup *objcg;
3307
3308 if (in_task()) {
3309 memcg = current->active_memcg;
3310 if (unlikely(memcg))
3311 goto from_memcg;
3312
3313 objcg = READ_ONCE(current->objcg);
3314 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
3315 objcg = current_objcg_update();
3316 /*
3317 * Objcg reference is kept by the task, so it's safe
3318 * to use the objcg by the current task.
3319 */
3320 return objcg;
3321 }
3322
3323 memcg = this_cpu_read(int_active_memcg);
3324 if (unlikely(memcg))
3325 goto from_memcg;
3326
3327 return NULL;
3328
3329from_memcg:
Roman Gushchin5f794892023-11-15 18:51:09 -08003330 objcg = NULL;
Roman Gushchine86828e2023-10-19 15:53:44 -07003331 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
3332 /*
3333 * Memcg pointer is protected by scope (see set_active_memcg())
3334 * and is pinning the corresponding objcg, so objcg can't go
3335 * away and can be used within the scope without any additional
3336 * protection.
3337 */
3338 objcg = rcu_dereference_check(memcg->objcg, 1);
3339 if (likely(objcg))
3340 break;
Roman Gushchine86828e2023-10-19 15:53:44 -07003341 }
3342
3343 return objcg;
3344}
3345
Matthew Wilcox (Oracle)074e3e22023-07-15 05:23:41 +01003346struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003347{
3348 struct obj_cgroup *objcg;
3349
Roman Gushchinf7a449f2023-02-13 11:29:22 -08003350 if (!memcg_kmem_online())
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003351 return NULL;
3352
Matthew Wilcox (Oracle)074e3e22023-07-15 05:23:41 +01003353 if (folio_memcg_kmem(folio)) {
3354 objcg = __folio_objcg(folio);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003355 obj_cgroup_get(objcg);
3356 } else {
3357 struct mem_cgroup *memcg;
3358
3359 rcu_read_lock();
Matthew Wilcox (Oracle)074e3e22023-07-15 05:23:41 +01003360 memcg = __folio_memcg(folio);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07003361 if (memcg)
3362 objcg = __get_obj_cgroup_from_memcg(memcg);
3363 else
3364 objcg = NULL;
3365 rcu_read_unlock();
3366 }
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003367 return objcg;
3368}
3369
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07003370static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3371{
3372 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3373 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3374 if (nr_pages > 0)
3375 page_counter_charge(&memcg->kmem, nr_pages);
3376 else
3377 page_counter_uncharge(&memcg->kmem, -nr_pages);
3378 }
3379}
3380
3381
Muchun Songf1286fa2021-04-29 22:56:55 -07003382/*
3383 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3384 * @objcg: object cgroup to uncharge
3385 * @nr_pages: number of pages to uncharge
3386 */
Muchun Songe74d2252021-04-29 22:56:42 -07003387static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3388 unsigned int nr_pages)
3389{
3390 struct mem_cgroup *memcg;
3391
3392 memcg = get_mem_cgroup_from_objcg(objcg);
Muchun Songf1286fa2021-04-29 22:56:55 -07003393
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07003394 memcg_account_kmem(memcg, -nr_pages);
Muchun Songf1286fa2021-04-29 22:56:55 -07003395 refill_stock(memcg, nr_pages);
3396
Muchun Songe74d2252021-04-29 22:56:42 -07003397 css_put(&memcg->css);
3398}
3399
Muchun Songf1286fa2021-04-29 22:56:55 -07003400/*
3401 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3402 * @objcg: object cgroup to charge
Vladimir Davydov45264772016-07-26 15:24:21 -07003403 * @gfp: reclaim mode
Roman Gushchin92d0510c2020-04-01 21:06:49 -07003404 * @nr_pages: number of pages to charge
Vladimir Davydov45264772016-07-26 15:24:21 -07003405 *
3406 * Returns 0 on success, an error code on failure.
3407 */
Muchun Songf1286fa2021-04-29 22:56:55 -07003408static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3409 unsigned int nr_pages)
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003410{
Muchun Songf1286fa2021-04-29 22:56:55 -07003411 struct mem_cgroup *memcg;
Johannes Weiner6071ca52015-11-05 18:50:26 -08003412 int ret;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003413
Muchun Songf1286fa2021-04-29 22:56:55 -07003414 memcg = get_mem_cgroup_from_objcg(objcg);
3415
Muchun Songc5c8b162021-06-28 19:37:44 -07003416 ret = try_charge_memcg(memcg, gfp, nr_pages);
Johannes Weiner52c29b02016-01-20 15:02:35 -08003417 if (ret)
Muchun Songf1286fa2021-04-29 22:56:55 -07003418 goto out;
Johannes Weiner52c29b02016-01-20 15:02:35 -08003419
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07003420 memcg_account_kmem(memcg, nr_pages);
Muchun Songf1286fa2021-04-29 22:56:55 -07003421out:
3422 css_put(&memcg->css);
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003423
Muchun Songf1286fa2021-04-29 22:56:55 -07003424 return ret;
Roman Gushchin4b13f642020-04-01 21:06:56 -07003425}
3426
3427/**
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003428 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
Vladimir Davydov45264772016-07-26 15:24:21 -07003429 * @page: page to charge
3430 * @gfp: reclaim mode
3431 * @order: allocation order
3432 *
3433 * Returns 0 on success, an error code on failure.
3434 */
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003435int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003436{
Muchun Songb4e0b682021-04-29 22:56:52 -07003437 struct obj_cgroup *objcg;
Vladimir Davydovfcff7d72016-03-17 14:17:29 -07003438 int ret = 0;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003439
Roman Gushchine86828e2023-10-19 15:53:44 -07003440 objcg = current_obj_cgroup();
Muchun Songb4e0b682021-04-29 22:56:52 -07003441 if (objcg) {
3442 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
Roman Gushchin4d96ba32019-07-11 20:56:31 -07003443 if (!ret) {
Roman Gushchine86828e2023-10-19 15:53:44 -07003444 obj_cgroup_get(objcg);
Muchun Songb4e0b682021-04-29 22:56:52 -07003445 page->memcg_data = (unsigned long)objcg |
Roman Gushchin18b2db32020-12-01 13:58:30 -08003446 MEMCG_DATA_KMEM;
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07003447 return 0;
Roman Gushchin4d96ba32019-07-11 20:56:31 -07003448 }
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003449 }
Vladimir Davydovd05e83a2015-11-05 18:48:59 -08003450 return ret;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003451}
Roman Gushchin49a18ea2019-07-11 20:56:13 -07003452
3453/**
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003454 * __memcg_kmem_uncharge_page: uncharge a kmem page
Vladimir Davydov45264772016-07-26 15:24:21 -07003455 * @page: page to uncharge
3456 * @order: allocation order
3457 */
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003458void __memcg_kmem_uncharge_page(struct page *page, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003459{
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003460 struct folio *folio = page_folio(page);
Muchun Songb4e0b682021-04-29 22:56:52 -07003461 struct obj_cgroup *objcg;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003462 unsigned int nr_pages = 1 << order;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003463
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003464 if (!folio_memcg_kmem(folio))
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003465 return;
3466
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003467 objcg = __folio_objcg(folio);
Muchun Songb4e0b682021-04-29 22:56:52 -07003468 obj_cgroup_uncharge_pages(objcg, nr_pages);
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003469 folio->memcg_data = 0;
Muchun Songb4e0b682021-04-29 22:56:52 -07003470 obj_cgroup_put(objcg);
Vladimir Davydov60d3fd32015-02-12 14:59:10 -08003471}
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003472
Shakeel Butt91882c12024-04-20 16:25:05 -07003473static void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003474 enum node_stat_item idx, int nr)
3475{
Michal Hockofead2b82022-03-22 14:40:35 -07003476 struct memcg_stock_pcp *stock;
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003477 struct obj_cgroup *old = NULL;
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003478 unsigned long flags;
3479 int *bytes;
3480
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003481 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Michal Hockofead2b82022-03-22 14:40:35 -07003482 stock = this_cpu_ptr(&memcg_stock);
3483
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003484 /*
3485 * Save vmstat data in stock and skip vmstat array update unless
3486 * accumulating over a page of vmstat data or when pgdat or idx
3487 * changes.
3488 */
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003489 if (READ_ONCE(stock->cached_objcg) != objcg) {
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003490 old = drain_obj_stock(stock);
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003491 obj_cgroup_get(objcg);
3492 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3493 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003494 WRITE_ONCE(stock->cached_objcg, objcg);
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003495 stock->cached_pgdat = pgdat;
3496 } else if (stock->cached_pgdat != pgdat) {
3497 /* Flush the existing cached vmstat data */
Waiman Long7fa0dac2021-08-13 16:54:41 -07003498 struct pglist_data *oldpg = stock->cached_pgdat;
3499
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003500 if (stock->nr_slab_reclaimable_b) {
Shakeel Butt91882c12024-04-20 16:25:05 -07003501 __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003502 stock->nr_slab_reclaimable_b);
3503 stock->nr_slab_reclaimable_b = 0;
3504 }
3505 if (stock->nr_slab_unreclaimable_b) {
Shakeel Butt91882c12024-04-20 16:25:05 -07003506 __mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003507 stock->nr_slab_unreclaimable_b);
3508 stock->nr_slab_unreclaimable_b = 0;
3509 }
3510 stock->cached_pgdat = pgdat;
3511 }
3512
3513 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3514 : &stock->nr_slab_unreclaimable_b;
3515 /*
3516 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3517 * cached locally at least once before pushing it out.
3518 */
3519 if (!*bytes) {
3520 *bytes = nr;
3521 nr = 0;
3522 } else {
3523 *bytes += nr;
3524 if (abs(*bytes) > PAGE_SIZE) {
3525 nr = *bytes;
3526 *bytes = 0;
3527 } else {
3528 nr = 0;
3529 }
3530 }
3531 if (nr)
Shakeel Butt91882c12024-04-20 16:25:05 -07003532 __mod_objcg_mlstate(objcg, pgdat, idx, nr);
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003533
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003534 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
Yosry Ahmed91b71e782024-03-16 01:58:03 +00003535 obj_cgroup_put(old);
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003536}
3537
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003538static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3539{
Michal Hockofead2b82022-03-22 14:40:35 -07003540 struct memcg_stock_pcp *stock;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003541 unsigned long flags;
3542 bool ret = false;
3543
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003544 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Michal Hockofead2b82022-03-22 14:40:35 -07003545
3546 stock = this_cpu_ptr(&memcg_stock);
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003547 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003548 stock->nr_bytes -= nr_bytes;
3549 ret = true;
3550 }
3551
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003552 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003553
3554 return ret;
3555}
3556
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003557static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003558{
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003559 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003560
3561 if (!old)
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003562 return NULL;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003563
3564 if (stock->nr_bytes) {
3565 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3566 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3567
Johannes Weineraf9a3b62022-03-22 14:40:44 -07003568 if (nr_pages) {
3569 struct mem_cgroup *memcg;
3570
3571 memcg = get_mem_cgroup_from_objcg(old);
3572
3573 memcg_account_kmem(memcg, -nr_pages);
3574 __refill_stock(memcg, nr_pages);
3575
3576 css_put(&memcg->css);
3577 }
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003578
3579 /*
3580 * The leftover is flushed to the centralized per-memcg value.
3581 * On the next attempt to refill obj stock it will be moved
3582 * to a per-cpu stock (probably, on an other CPU), see
3583 * refill_obj_stock().
3584 *
3585 * How often it's flushed is a trade-off between the memory
3586 * limit enforcement accuracy and potential CPU contention,
3587 * so it might be changed in the future.
3588 */
3589 atomic_add(nr_bytes, &old->nr_charged_bytes);
3590 stock->nr_bytes = 0;
3591 }
3592
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003593 /*
3594 * Flush the vmstat data in current stock
3595 */
3596 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3597 if (stock->nr_slab_reclaimable_b) {
Shakeel Butt91882c12024-04-20 16:25:05 -07003598 __mod_objcg_mlstate(old, stock->cached_pgdat,
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003599 NR_SLAB_RECLAIMABLE_B,
3600 stock->nr_slab_reclaimable_b);
3601 stock->nr_slab_reclaimable_b = 0;
3602 }
3603 if (stock->nr_slab_unreclaimable_b) {
Shakeel Butt91882c12024-04-20 16:25:05 -07003604 __mod_objcg_mlstate(old, stock->cached_pgdat,
Waiman Long68ac5b3c2021-06-28 19:37:23 -07003605 NR_SLAB_UNRECLAIMABLE_B,
3606 stock->nr_slab_unreclaimable_b);
3607 stock->nr_slab_unreclaimable_b = 0;
3608 }
3609 stock->cached_pgdat = NULL;
3610 }
3611
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003612 WRITE_ONCE(stock->cached_objcg, NULL);
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003613 /*
3614 * The `old' objects needs to be released by the caller via
3615 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3616 */
3617 return old;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003618}
3619
3620static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3621 struct mem_cgroup *root_memcg)
3622{
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003623 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003624 struct mem_cgroup *memcg;
3625
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003626 if (objcg) {
3627 memcg = obj_cgroup_memcg(objcg);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003628 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3629 return true;
3630 }
3631
3632 return false;
3633}
3634
Waiman Long5387c9042021-06-28 19:37:27 -07003635static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3636 bool allow_uncharge)
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003637{
Michal Hockofead2b82022-03-22 14:40:35 -07003638 struct memcg_stock_pcp *stock;
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003639 struct obj_cgroup *old = NULL;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003640 unsigned long flags;
Waiman Long5387c9042021-06-28 19:37:27 -07003641 unsigned int nr_pages = 0;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003642
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003643 local_lock_irqsave(&memcg_stock.stock_lock, flags);
Michal Hockofead2b82022-03-22 14:40:35 -07003644
3645 stock = this_cpu_ptr(&memcg_stock);
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003646 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003647 old = drain_obj_stock(stock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003648 obj_cgroup_get(objcg);
Roman Gushchin3b8abb32023-05-02 09:08:38 -07003649 WRITE_ONCE(stock->cached_objcg, objcg);
Waiman Long5387c9042021-06-28 19:37:27 -07003650 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3651 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3652 allow_uncharge = true; /* Allow uncharge when objcg changes */
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003653 }
3654 stock->nr_bytes += nr_bytes;
3655
Waiman Long5387c9042021-06-28 19:37:27 -07003656 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3657 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3658 stock->nr_bytes &= (PAGE_SIZE - 1);
3659 }
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003660
Sebastian Andrzej Siewior56751142022-03-22 14:40:47 -07003661 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
Yosry Ahmed91b71e782024-03-16 01:58:03 +00003662 obj_cgroup_put(old);
Waiman Long5387c9042021-06-28 19:37:27 -07003663
3664 if (nr_pages)
3665 obj_cgroup_uncharge_pages(objcg, nr_pages);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003666}
3667
3668int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3669{
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003670 unsigned int nr_pages, nr_bytes;
3671 int ret;
3672
3673 if (consume_obj_stock(objcg, size))
3674 return 0;
3675
3676 /*
Waiman Long5387c9042021-06-28 19:37:27 -07003677 * In theory, objcg->nr_charged_bytes can have enough
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003678 * pre-charged bytes to satisfy the allocation. However,
Waiman Long5387c9042021-06-28 19:37:27 -07003679 * flushing objcg->nr_charged_bytes requires two atomic
3680 * operations, and objcg->nr_charged_bytes can't be big.
3681 * The shared objcg->nr_charged_bytes can also become a
3682 * performance bottleneck if all tasks of the same memcg are
3683 * trying to update it. So it's better to ignore it and try
3684 * grab some new pages. The stock's nr_bytes will be flushed to
3685 * objcg->nr_charged_bytes later on when objcg changes.
3686 *
3687 * The stock's nr_bytes may contain enough pre-charged bytes
3688 * to allow one less page from being charged, but we can't rely
3689 * on the pre-charged bytes not being changed outside of
3690 * consume_obj_stock() or refill_obj_stock(). So ignore those
3691 * pre-charged bytes as well when charging pages. To avoid a
3692 * page uncharge right after a page charge, we set the
3693 * allow_uncharge flag to false when calling refill_obj_stock()
3694 * to temporarily allow the pre-charged bytes to exceed the page
3695 * size limit. The maximum reachable value of the pre-charged
3696 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3697 * race.
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003698 */
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003699 nr_pages = size >> PAGE_SHIFT;
3700 nr_bytes = size & (PAGE_SIZE - 1);
3701
3702 if (nr_bytes)
3703 nr_pages += 1;
3704
Muchun Songe74d2252021-04-29 22:56:42 -07003705 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003706 if (!ret && nr_bytes)
Waiman Long5387c9042021-06-28 19:37:27 -07003707 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003708
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003709 return ret;
3710}
3711
3712void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3713{
Waiman Long5387c9042021-06-28 19:37:27 -07003714 refill_obj_stock(objcg, size, true);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003715}
3716
Vlastimil Babkae6100a42024-03-26 11:37:39 +01003717static inline size_t obj_full_size(struct kmem_cache *s)
3718{
3719 /*
3720 * For each accounted object there is an extra space which is used
3721 * to store obj_cgroup membership. Charge it too.
3722 */
3723 return s->size + sizeof(struct obj_cgroup *);
3724}
3725
3726bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3727 gfp_t flags, size_t size, void **p)
3728{
3729 struct obj_cgroup *objcg;
3730 struct slab *slab;
3731 unsigned long off;
3732 size_t i;
3733
3734 /*
3735 * The obtained objcg pointer is safe to use within the current scope,
3736 * defined by current task or set_active_memcg() pair.
3737 * obj_cgroup_get() is used to get a permanent reference.
3738 */
3739 objcg = current_obj_cgroup();
3740 if (!objcg)
3741 return true;
3742
3743 /*
3744 * slab_alloc_node() avoids the NULL check, so we might be called with a
3745 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3746 * the whole requested size.
3747 * return success as there's nothing to free back
3748 */
3749 if (unlikely(*p == NULL))
3750 return true;
3751
3752 flags &= gfp_allowed_mask;
3753
3754 if (lru) {
3755 int ret;
3756 struct mem_cgroup *memcg;
3757
3758 memcg = get_mem_cgroup_from_objcg(objcg);
3759 ret = memcg_list_lru_alloc(memcg, lru, flags);
3760 css_put(&memcg->css);
3761
3762 if (ret)
3763 return false;
3764 }
3765
3766 if (obj_cgroup_charge(objcg, flags, size * obj_full_size(s)))
3767 return false;
3768
3769 for (i = 0; i < size; i++) {
3770 slab = virt_to_slab(p[i]);
3771
3772 if (!slab_obj_exts(slab) &&
3773 alloc_slab_obj_exts(slab, s, flags, false)) {
3774 obj_cgroup_uncharge(objcg, obj_full_size(s));
3775 continue;
3776 }
3777
3778 off = obj_to_index(s, slab, p[i]);
3779 obj_cgroup_get(objcg);
3780 slab_obj_exts(slab)[off].objcg = objcg;
3781 mod_objcg_state(objcg, slab_pgdat(slab),
3782 cache_vmstat_idx(s), obj_full_size(s));
3783 }
3784
3785 return true;
3786}
3787
3788void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3789 void **p, int objects, struct slabobj_ext *obj_exts)
3790{
3791 for (int i = 0; i < objects; i++) {
3792 struct obj_cgroup *objcg;
3793 unsigned int off;
3794
3795 off = obj_to_index(s, slab, p[i]);
3796 objcg = obj_exts[off].objcg;
3797 if (!objcg)
3798 continue;
3799
3800 obj_exts[off].objcg = NULL;
3801 obj_cgroup_uncharge(objcg, obj_full_size(s));
3802 mod_objcg_state(objcg, slab_pgdat(slab), cache_vmstat_idx(s),
3803 -obj_full_size(s));
3804 obj_cgroup_put(objcg);
3805 }
3806}
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003807#endif /* CONFIG_MEMCG_KMEM */
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003808
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003809/*
Kefeng Wangffc3c8a2024-05-24 09:49:50 +08003810 * Because folio_memcg(head) is not set on tails, set it now.
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003811 */
Zi Yanb8791382024-02-26 15:55:31 -05003812void split_page_memcg(struct page *head, int old_order, int new_order)
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003813{
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003814 struct folio *folio = page_folio(head);
3815 struct mem_cgroup *memcg = folio_memcg(folio);
KAMEZAWA Hiroyukie94c8a92012-01-12 17:18:20 -08003816 int i;
Zi Yanb8791382024-02-26 15:55:31 -05003817 unsigned int old_nr = 1 << old_order;
3818 unsigned int new_nr = 1 << new_order;
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003819
Zhou Guanghuibe6c8982021-03-12 21:08:30 -08003820 if (mem_cgroup_disabled() || !memcg)
KAMEZAWA Hiroyuki3d37c4a2011-01-25 15:07:28 -08003821 return;
David Rientjesb070e652013-05-07 16:18:09 -07003822
Zi Yanb8791382024-02-26 15:55:31 -05003823 for (i = new_nr; i < old_nr; i += new_nr)
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003824 folio_page(folio, i)->memcg_data = folio->memcg_data;
Muchun Songb4e0b682021-04-29 22:56:52 -07003825
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04003826 if (folio_memcg_kmem(folio))
Zi Yanb8791382024-02-26 15:55:31 -05003827 obj_cgroup_get_many(__folio_objcg(folio), old_nr / new_nr - 1);
Muchun Songb4e0b682021-04-29 22:56:52 -07003828 else
Zi Yanb8791382024-02-26 15:55:31 -05003829 css_get_many(&memcg->css, old_nr / new_nr - 1);
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003830}
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003831
Johannes Weinere55b9f92022-09-26 09:57:04 -04003832#ifdef CONFIG_SWAP
Daisuke Nishimura02491442010-03-10 15:22:17 -08003833/**
3834 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3835 * @entry: swap entry to be moved
3836 * @from: mem_cgroup which the entry is moved from
3837 * @to: mem_cgroup which the entry is moved to
3838 *
3839 * It succeeds only when the swap_cgroup's record for this entry is the same
3840 * as the mem_cgroup's id of @from.
3841 *
3842 * Returns 0 on success, -EINVAL on failure.
3843 *
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003844 * The caller must have charged to @to, IOW, called page_counter_charge() about
Daisuke Nishimura02491442010-03-10 15:22:17 -08003845 * both res and memsw, and called css_get().
3846 */
3847static int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003848 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003849{
3850 unsigned short old_id, new_id;
3851
Li Zefan34c00c32013-09-23 16:56:01 +08003852 old_id = mem_cgroup_id(from);
3853 new_id = mem_cgroup_id(to);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003854
3855 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
Johannes Weinerc9019e92018-01-31 16:16:37 -08003856 mod_memcg_state(from, MEMCG_SWAP, -1);
3857 mod_memcg_state(to, MEMCG_SWAP, 1);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003858 return 0;
3859 }
3860 return -EINVAL;
3861}
3862#else
3863static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003864 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003865{
3866 return -EINVAL;
3867}
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003868#endif
3869
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003870static DEFINE_MUTEX(memcg_max_mutex);
Daisuke Nishimuraf212ad72011-03-23 16:42:25 -07003871
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003872static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3873 unsigned long max, bool memsw)
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003874{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003875 bool enlarge = false;
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003876 bool drained = false;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003877 int ret;
Yu Zhaoc054a782018-01-31 16:20:02 -08003878 bool limits_invariant;
3879 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07003880
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003881 do {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003882 if (signal_pending(current)) {
3883 ret = -EINTR;
3884 break;
3885 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003886
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003887 mutex_lock(&memcg_max_mutex);
Yu Zhaoc054a782018-01-31 16:20:02 -08003888 /*
3889 * Make sure that the new limit (memsw or memory limit) doesn't
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003890 * break our basic invariant rule memory.max <= memsw.max.
Yu Zhaoc054a782018-01-31 16:20:02 -08003891 */
Chris Down15b42562020-04-01 21:07:20 -07003892 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003893 max <= memcg->memsw.max;
Yu Zhaoc054a782018-01-31 16:20:02 -08003894 if (!limits_invariant) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003895 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003896 ret = -EINVAL;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003897 break;
3898 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003899 if (max > counter->max)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003900 enlarge = true;
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003901 ret = page_counter_set_max(counter, max);
3902 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003903
3904 if (!ret)
3905 break;
3906
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003907 if (!drained) {
3908 drain_all_stock(memcg);
3909 drained = true;
3910 continue;
3911 }
3912
Yosry Ahmed73b73ba2022-07-14 06:49:18 +00003913 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
Michal Hocko55ab8342022-12-16 10:46:33 +01003914 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
Andrey Ryabinin1ab5c052018-01-31 16:20:37 -08003915 ret = -EBUSY;
3916 break;
3917 }
3918 } while (true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003919
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07003920 if (!ret && enlarge)
3921 memcg_oom_recover(memcg);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003922
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003923 return ret;
3924}
3925
Mel Gormanef8f2322016-07-28 15:46:05 -07003926unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
Andrew Morton0608f432013-09-24 15:27:41 -07003927 gfp_t gfp_mask,
3928 unsigned long *total_scanned)
3929{
3930 unsigned long nr_reclaimed = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003931 struct mem_cgroup_per_node *mz, *next_mz = NULL;
Andrew Morton0608f432013-09-24 15:27:41 -07003932 unsigned long reclaimed;
3933 int loop = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003934 struct mem_cgroup_tree_per_node *mctz;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003935 unsigned long excess;
Andrew Morton0608f432013-09-24 15:27:41 -07003936
Yu Zhaoe4dde562022-12-21 21:19:04 -07003937 if (lru_gen_enabled())
3938 return 0;
3939
Andrew Morton0608f432013-09-24 15:27:41 -07003940 if (order > 0)
3941 return 0;
3942
Matthew Wilcox (Oracle)2ab082b2021-06-25 08:57:02 -04003943 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
Michal Hockod6507ff2016-08-02 14:02:37 -07003944
3945 /*
3946 * Do not even bother to check the largest node if the root
3947 * is empty. Do it lockless to prevent lock bouncing. Races
3948 * are acceptable as soft limit is best effort anyway.
3949 */
Laurent Dufourbfc72282017-03-09 16:17:06 -08003950 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
Michal Hockod6507ff2016-08-02 14:02:37 -07003951 return 0;
3952
Andrew Morton0608f432013-09-24 15:27:41 -07003953 /*
3954 * This loop can run a while, specially if mem_cgroup's continuously
3955 * keep exceeding their soft limit and putting the system under
3956 * pressure
3957 */
3958 do {
3959 if (next_mz)
3960 mz = next_mz;
3961 else
3962 mz = mem_cgroup_largest_soft_limit_node(mctz);
3963 if (!mz)
3964 break;
3965
Mel Gormanef8f2322016-07-28 15:46:05 -07003966 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
Miaohe Lind8f65332022-04-28 23:15:58 -07003967 gfp_mask, total_scanned);
Andrew Morton0608f432013-09-24 15:27:41 -07003968 nr_reclaimed += reclaimed;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003969 spin_lock_irq(&mctz->lock);
Andrew Morton0608f432013-09-24 15:27:41 -07003970
3971 /*
3972 * If we failed to reclaim anything from this memory cgroup
3973 * it is time to move on to the next cgroup
3974 */
3975 next_mz = NULL;
Vladimir Davydovbc2f2e72014-12-10 15:43:40 -08003976 if (!reclaimed)
3977 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3978
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003979 excess = soft_limit_excess(mz->memcg);
Andrew Morton0608f432013-09-24 15:27:41 -07003980 /*
3981 * One school of thought says that we should not add
3982 * back the node to the tree if reclaim returns 0.
3983 * But our reclaim could return 0, simply because due
3984 * to priority we are exposing a smaller subset of
3985 * memory to reclaim from. Consider this as a longer
3986 * term TODO.
3987 */
3988 /* If excess == 0, no tree ops */
Johannes Weinercf2c8122014-06-06 14:38:21 -07003989 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003990 spin_unlock_irq(&mctz->lock);
Andrew Morton0608f432013-09-24 15:27:41 -07003991 css_put(&mz->memcg->css);
3992 loop++;
3993 /*
3994 * Could not reclaim anything and there are no more
3995 * mem cgroups to try or we seem to be looping without
3996 * reclaiming anything.
3997 */
3998 if (!nr_reclaimed &&
3999 (next_mz == NULL ||
4000 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4001 break;
4002 } while (!nr_reclaimed);
4003 if (next_mz)
4004 css_put(&next_mz->memcg->css);
4005 return nr_reclaimed;
4006}
4007
Tejun Heoea280e72014-05-16 13:22:48 -04004008/*
Greg Thelen51038172016-05-20 16:58:18 -07004009 * Reclaims as many pages from the given memcg as possible.
Michal Hockoc26251f2012-10-26 13:37:28 +02004010 *
4011 * Caller is responsible for holding css reference for memcg.
4012 */
4013static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4014{
Chris Downd977aa92020-08-06 23:21:58 -07004015 int nr_retries = MAX_RECLAIM_RETRIES;
Michal Hockoc26251f2012-10-26 13:37:28 +02004016
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004017 /* we call try-to-free pages for make this cgroup empty */
4018 lru_add_drain_all();
Junaid Shahidd12c60f2018-06-07 17:07:31 -07004019
4020 drain_all_stock(memcg);
4021
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08004022 /* try to free all pages in this cgroup */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004023 while (nr_retries && page_counter_read(&memcg->memory)) {
Michal Hockoc26251f2012-10-26 13:37:28 +02004024 if (signal_pending(current))
4025 return -EINTR;
4026
Yosry Ahmed73b73ba2022-07-14 06:49:18 +00004027 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
Michal Hocko55ab8342022-12-16 10:46:33 +01004028 MEMCG_RECLAIM_MAY_SWAP))
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08004029 nr_retries--;
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08004030 }
Michal Hockoab5196c2012-10-26 13:37:32 +02004031
4032 return 0;
KAMEZAWA Hiroyukicc847582008-02-07 00:14:16 -08004033}
4034
Tejun Heo6770c642014-05-13 12:16:21 -04004035static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
4036 char *buf, size_t nbytes,
4037 loff_t off)
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004038{
Tejun Heo6770c642014-05-13 12:16:21 -04004039 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Michal Hockoc26251f2012-10-26 13:37:28 +02004040
Michal Hockod8423012012-10-26 13:37:29 +02004041 if (mem_cgroup_is_root(memcg))
4042 return -EINVAL;
Tejun Heo6770c642014-05-13 12:16:21 -04004043 return mem_cgroup_force_empty(memcg) ?: nbytes;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004044}
4045
Tejun Heo182446d2013-08-08 20:11:24 -04004046static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
4047 struct cftype *cft)
Balbir Singh18f59ea2009-01-07 18:08:07 -08004048{
Roman Gushchinbef86202020-12-14 19:06:49 -08004049 return 1;
Balbir Singh18f59ea2009-01-07 18:08:07 -08004050}
4051
Tejun Heo182446d2013-08-08 20:11:24 -04004052static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
4053 struct cftype *cft, u64 val)
Balbir Singh18f59ea2009-01-07 18:08:07 -08004054{
Roman Gushchinbef86202020-12-14 19:06:49 -08004055 if (val == 1)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08004056 return 0;
Glauber Costa567fb432012-07-31 16:43:07 -07004057
Roman Gushchinbef86202020-12-14 19:06:49 -08004058 pr_warn_once("Non-hierarchical mode is deprecated. "
4059 "Please report your usecase to linux-mm@kvack.org if you "
4060 "depend on this functionality.\n");
Glauber Costa567fb432012-07-31 16:43:07 -07004061
Roman Gushchinbef86202020-12-14 19:06:49 -08004062 return -EINVAL;
Balbir Singh18f59ea2009-01-07 18:08:07 -08004063}
4064
Andrew Morton6f646152015-11-06 16:28:58 -08004065static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
Johannes Weinerce00a962014-09-05 08:43:57 -04004066{
Johannes Weiner42a30032019-05-14 15:47:12 -07004067 unsigned long val;
Johannes Weinerce00a962014-09-05 08:43:57 -04004068
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004069 if (mem_cgroup_is_root(memcg)) {
Yosry Ahmeda2174e92023-03-30 19:17:56 +00004070 /*
Yosry Ahmedf82a7a82023-04-21 17:40:18 +00004071 * Approximate root's usage from global state. This isn't
4072 * perfect, but the root usage was always an approximation.
Yosry Ahmeda2174e92023-03-30 19:17:56 +00004073 */
Yosry Ahmedf82a7a82023-04-21 17:40:18 +00004074 val = global_node_page_state(NR_FILE_PAGES) +
4075 global_node_page_state(NR_ANON_MAPPED);
Johannes Weiner42a30032019-05-14 15:47:12 -07004076 if (swap)
Yosry Ahmedf82a7a82023-04-21 17:40:18 +00004077 val += total_swap_pages - get_nr_swap_pages();
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004078 } else {
Johannes Weinerce00a962014-09-05 08:43:57 -04004079 if (!swap)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004080 val = page_counter_read(&memcg->memory);
Johannes Weinerce00a962014-09-05 08:43:57 -04004081 else
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004082 val = page_counter_read(&memcg->memsw);
Johannes Weinerce00a962014-09-05 08:43:57 -04004083 }
Michal Hockoc12176d2015-11-05 18:50:29 -08004084 return val;
Johannes Weinerce00a962014-09-05 08:43:57 -04004085}
4086
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004087enum {
4088 RES_USAGE,
4089 RES_LIMIT,
4090 RES_MAX_USAGE,
4091 RES_FAILCNT,
4092 RES_SOFT_LIMIT,
4093};
Johannes Weinerce00a962014-09-05 08:43:57 -04004094
Tejun Heo791badb2013-12-05 12:28:02 -05004095static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
Johannes Weiner05b84302014-08-06 16:05:59 -07004096 struct cftype *cft)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004097{
Tejun Heo182446d2013-08-08 20:11:24 -04004098 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004099 struct page_counter *counter;
Tejun Heoaf36f902012-04-01 12:09:55 -07004100
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004101 switch (MEMFILE_TYPE(cft->private)) {
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004102 case _MEM:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004103 counter = &memcg->memory;
Glauber Costa510fc4e2012-12-18 14:21:47 -08004104 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004105 case _MEMSWAP:
4106 counter = &memcg->memsw;
4107 break;
4108 case _KMEM:
4109 counter = &memcg->kmem;
4110 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004111 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08004112 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004113 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004114 default:
4115 BUG();
4116 }
4117
4118 switch (MEMFILE_ATTR(cft->private)) {
4119 case RES_USAGE:
4120 if (counter == &memcg->memory)
Michal Hockoc12176d2015-11-05 18:50:29 -08004121 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004122 if (counter == &memcg->memsw)
Michal Hockoc12176d2015-11-05 18:50:29 -08004123 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004124 return (u64)page_counter_read(counter) * PAGE_SIZE;
4125 case RES_LIMIT:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004126 return (u64)counter->max * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004127 case RES_MAX_USAGE:
4128 return (u64)counter->watermark * PAGE_SIZE;
4129 case RES_FAILCNT:
4130 return counter->failcnt;
4131 case RES_SOFT_LIMIT:
Yue Zhao2178e202023-03-06 23:41:38 +08004132 return (u64)READ_ONCE(memcg->soft_limit) * PAGE_SIZE;
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004133 default:
4134 BUG();
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004135 }
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004136}
Glauber Costa510fc4e2012-12-18 14:21:47 -08004137
Florian Schmidt6b0ba2a2023-04-04 10:58:59 +00004138/*
4139 * This function doesn't do anything useful. Its only job is to provide a read
4140 * handler for a file so that cgroup_file_mode() will add read permissions.
4141 */
4142static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
4143 __always_unused void *v)
4144{
4145 return -EINVAL;
4146}
4147
Kirill Tkhai84c07d12018-08-17 15:47:25 -07004148#ifdef CONFIG_MEMCG_KMEM
Johannes Weiner567e9ab2016-01-20 15:02:24 -08004149static int memcg_online_kmem(struct mem_cgroup *memcg)
Vladimir Davydovd6441632014-01-23 15:53:09 -08004150{
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004151 struct obj_cgroup *objcg;
Vladimir Davydovd6441632014-01-23 15:53:09 -08004152
Xiang Yang9c94bef2022-06-25 14:18:44 +08004153 if (mem_cgroup_kmem_disabled())
Vladimir Davydovb313aee2016-03-17 14:18:27 -07004154 return 0;
4155
Muchun Songda0efe32022-03-22 14:41:15 -07004156 if (unlikely(mem_cgroup_is_root(memcg)))
4157 return 0;
Vladimir Davydovd6441632014-01-23 15:53:09 -08004158
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004159 objcg = obj_cgroup_alloc();
Muchun Songf9c69d62022-03-22 14:41:28 -07004160 if (!objcg)
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004161 return -ENOMEM;
Muchun Songf9c69d62022-03-22 14:41:28 -07004162
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004163 objcg->memcg = memcg;
4164 rcu_assign_pointer(memcg->objcg, objcg);
Roman Gushchin675d6c92023-10-19 15:53:43 -07004165 obj_cgroup_get(objcg);
4166 memcg->orig_objcg = objcg;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004167
Roman Gushchinf7a449f2023-02-13 11:29:22 -08004168 static_branch_enable(&memcg_kmem_online_key);
Roman Gushchind648bcc2020-08-06 23:20:28 -07004169
Muchun Songf9c69d62022-03-22 14:41:28 -07004170 memcg->kmemcg_id = memcg->id.id;
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08004171
4172 return 0;
Vladimir Davydovd6441632014-01-23 15:53:09 -08004173}
4174
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004175static void memcg_offline_kmem(struct mem_cgroup *memcg)
4176{
Muchun Song64268862021-11-05 13:37:53 -07004177 struct mem_cgroup *parent;
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004178
Xiang Yang9c94bef2022-06-25 14:18:44 +08004179 if (mem_cgroup_kmem_disabled())
Muchun Songda0efe32022-03-22 14:41:15 -07004180 return;
4181
4182 if (unlikely(mem_cgroup_is_root(memcg)))
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004183 return;
Roman Gushchin98556092020-08-06 23:21:10 -07004184
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004185 parent = parent_mem_cgroup(memcg);
4186 if (!parent)
4187 parent = root_mem_cgroup;
4188
Roman Gushchinbf4f0592020-08-06 23:20:49 -07004189 memcg_reparent_objcgs(memcg, parent);
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07004190
Muchun Song5abc1e32022-03-22 14:41:19 -07004191 /*
Muchun Song64268862021-11-05 13:37:53 -07004192 * After we have finished memcg_reparent_objcgs(), all list_lrus
4193 * corresponding to this cgroup are guaranteed to remain empty.
4194 * The ordering is imposed by list_lru_node->lock taken by
Muchun Song1f391eb2022-03-22 14:41:22 -07004195 * memcg_reparent_list_lrus().
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004196 */
Muchun Song1f391eb2022-03-22 14:41:22 -07004197 memcg_reparent_list_lrus(memcg, parent);
Johannes Weiner8e0a8912016-01-20 15:02:26 -08004198}
Vladimir Davydovd6441632014-01-23 15:53:09 -08004199#else
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08004200static int memcg_online_kmem(struct mem_cgroup *memcg)
Johannes Weiner127424c2016-01-20 15:02:32 -08004201{
4202 return 0;
4203}
4204static void memcg_offline_kmem(struct mem_cgroup *memcg)
4205{
4206}
Kirill Tkhai84c07d12018-08-17 15:47:25 -07004207#endif /* CONFIG_MEMCG_KMEM */
Johannes Weiner127424c2016-01-20 15:02:32 -08004208
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004209static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004210{
4211 int ret;
4212
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004213 mutex_lock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004214
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004215 ret = page_counter_set_max(&memcg->tcpmem, max);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004216 if (ret)
4217 goto out;
4218
Johannes Weiner0db15292016-01-20 15:02:50 -08004219 if (!memcg->tcpmem_active) {
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004220 /*
4221 * The active flag needs to be written after the static_key
4222 * update. This is what guarantees that the socket activation
Johannes Weiner2d758072016-10-07 17:00:58 -07004223 * function is the last one to run. See mem_cgroup_sk_alloc()
4224 * for details, and note that we don't mark any socket as
4225 * belonging to this memcg until that flag is up.
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004226 *
4227 * We need to do this, because static_keys will span multiple
4228 * sites, but we can't control their order. If we mark a socket
4229 * as accounted, but the accounting functions are not patched in
4230 * yet, we'll lose accounting.
4231 *
Johannes Weiner2d758072016-10-07 17:00:58 -07004232 * We never race with the readers in mem_cgroup_sk_alloc(),
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004233 * because when this value change, the code to process it is not
4234 * patched in yet.
4235 */
4236 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weiner0db15292016-01-20 15:02:50 -08004237 memcg->tcpmem_active = true;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004238 }
4239out:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004240 mutex_unlock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004241 return ret;
4242}
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004243
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07004244/*
4245 * The user of this function is...
4246 * RES_LIMIT.
4247 */
Tejun Heo451af5042014-05-13 12:16:21 -04004248static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
4249 char *buf, size_t nbytes, loff_t off)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004250{
Tejun Heo451af5042014-05-13 12:16:21 -04004251 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004252 unsigned long nr_pages;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07004253 int ret;
4254
Tejun Heo451af5042014-05-13 12:16:21 -04004255 buf = strstrip(buf);
Johannes Weiner650c5e52015-02-11 15:26:03 -08004256 ret = page_counter_memparse(buf, "-1", &nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004257 if (ret)
4258 return ret;
Tejun Heoaf36f902012-04-01 12:09:55 -07004259
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004260 switch (MEMFILE_ATTR(of_cft(of)->private)) {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07004261 case RES_LIMIT:
Balbir Singh4b3bde42009-09-23 15:56:32 -07004262 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4263 ret = -EINVAL;
4264 break;
4265 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004266 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4267 case _MEM:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004268 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004269 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004270 case _MEMSWAP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004271 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004272 break;
Michal Hocko45976482023-09-21 09:38:29 +02004273 case _KMEM:
4274 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
4275 "Writing any value to this file has no effect. "
4276 "Please report your usecase to linux-mm@kvack.org if you "
4277 "depend on this functionality.\n");
4278 ret = 0;
4279 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004280 case _TCP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004281 ret = memcg_update_tcp_max(memcg, nr_pages);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004282 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004283 }
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07004284 break;
Balbir Singh296c81d2009-09-23 15:56:36 -07004285 case RES_SOFT_LIMIT:
Sebastian Andrzej Siewior2343e882022-03-22 14:40:38 -07004286 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4287 ret = -EOPNOTSUPP;
4288 } else {
Yue Zhao2178e202023-03-06 23:41:38 +08004289 WRITE_ONCE(memcg->soft_limit, nr_pages);
Sebastian Andrzej Siewior2343e882022-03-22 14:40:38 -07004290 ret = 0;
4291 }
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07004292 break;
4293 }
Tejun Heo451af5042014-05-13 12:16:21 -04004294 return ret ?: nbytes;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004295}
4296
Tejun Heo6770c642014-05-13 12:16:21 -04004297static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
4298 size_t nbytes, loff_t off)
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07004299{
Tejun Heo6770c642014-05-13 12:16:21 -04004300 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004301 struct page_counter *counter;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07004302
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004303 switch (MEMFILE_TYPE(of_cft(of)->private)) {
4304 case _MEM:
4305 counter = &memcg->memory;
4306 break;
4307 case _MEMSWAP:
4308 counter = &memcg->memsw;
4309 break;
4310 case _KMEM:
4311 counter = &memcg->kmem;
4312 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004313 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08004314 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004315 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004316 default:
4317 BUG();
4318 }
Tejun Heoaf36f902012-04-01 12:09:55 -07004319
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004320 switch (MEMFILE_ATTR(of_cft(of)->private)) {
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07004321 case RES_MAX_USAGE:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004322 page_counter_reset_watermark(counter);
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07004323 break;
4324 case RES_FAILCNT:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004325 counter->failcnt = 0;
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07004326 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004327 default:
4328 BUG();
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07004329 }
Balbir Singhf64c3f52009-09-23 15:56:37 -07004330
Tejun Heo6770c642014-05-13 12:16:21 -04004331 return nbytes;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07004332}
4333
Tejun Heo182446d2013-08-08 20:11:24 -04004334static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004335 struct cftype *cft)
4336{
Tejun Heo182446d2013-08-08 20:11:24 -04004337 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004338}
4339
Daisuke Nishimura02491442010-03-10 15:22:17 -08004340#ifdef CONFIG_MMU
Tejun Heo182446d2013-08-08 20:11:24 -04004341static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004342 struct cftype *cft, u64 val)
4343{
Tejun Heo182446d2013-08-08 20:11:24 -04004344 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004345
Johannes Weinerda34a842022-12-07 14:00:39 +01004346 pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
4347 "Please report your usecase to linux-mm@kvack.org if you "
4348 "depend on this functionality.\n");
4349
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08004350 if (val & ~MOVE_MASK)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004351 return -EINVAL;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004352
Glauber Costaee5e8472013-02-22 16:34:50 -08004353 /*
4354 * No kind of locking is needed in here, because ->can_attach() will
4355 * check this value once in the beginning of the process, and then carry
4356 * on with stale data. This means that changes to this value will only
4357 * affect task migrations starting after the change.
4358 */
4359 memcg->move_charge_at_immigrate = val;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004360 return 0;
4361}
Daisuke Nishimura02491442010-03-10 15:22:17 -08004362#else
Tejun Heo182446d2013-08-08 20:11:24 -04004363static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura02491442010-03-10 15:22:17 -08004364 struct cftype *cft, u64 val)
4365{
4366 return -ENOSYS;
4367}
4368#endif
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004369
Ying Han406eb0c2011-05-26 16:25:37 -07004370#ifdef CONFIG_NUMA
Johannes Weiner113b7df2019-05-13 17:18:11 -07004371
4372#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
4373#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
4374#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
4375
4376static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004377 int nid, unsigned int lru_mask, bool tree)
Johannes Weiner113b7df2019-05-13 17:18:11 -07004378{
Johannes Weiner867e5e12019-11-30 17:55:34 -08004379 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
Johannes Weiner113b7df2019-05-13 17:18:11 -07004380 unsigned long nr = 0;
4381 enum lru_list lru;
4382
4383 VM_BUG_ON((unsigned)nid >= nr_node_ids);
4384
4385 for_each_lru(lru) {
4386 if (!(BIT(lru) & lru_mask))
4387 continue;
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004388 if (tree)
4389 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
4390 else
4391 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07004392 }
4393 return nr;
4394}
4395
4396static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004397 unsigned int lru_mask,
4398 bool tree)
Johannes Weiner113b7df2019-05-13 17:18:11 -07004399{
4400 unsigned long nr = 0;
4401 enum lru_list lru;
4402
4403 for_each_lru(lru) {
4404 if (!(BIT(lru) & lru_mask))
4405 continue;
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004406 if (tree)
4407 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4408 else
4409 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07004410 }
4411 return nr;
4412}
4413
Tejun Heo2da8ca82013-12-05 12:28:04 -05004414static int memcg_numa_stat_show(struct seq_file *m, void *v)
Ying Han406eb0c2011-05-26 16:25:37 -07004415{
Greg Thelen25485de2013-11-12 15:07:40 -08004416 struct numa_stat {
4417 const char *name;
4418 unsigned int lru_mask;
4419 };
4420
4421 static const struct numa_stat stats[] = {
4422 { "total", LRU_ALL },
4423 { "file", LRU_ALL_FILE },
4424 { "anon", LRU_ALL_ANON },
4425 { "unevictable", BIT(LRU_UNEVICTABLE) },
4426 };
4427 const struct numa_stat *stat;
Ying Han406eb0c2011-05-26 16:25:37 -07004428 int nid;
Chris Downaa9694b2019-03-05 15:45:52 -08004429 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Ying Han406eb0c2011-05-26 16:25:37 -07004430
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00004431 mem_cgroup_flush_stats(memcg);
Johannes Weiner2d146aa2021-04-29 22:56:26 -07004432
Greg Thelen25485de2013-11-12 15:07:40 -08004433 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004434 seq_printf(m, "%s=%lu", stat->name,
4435 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4436 false));
4437 for_each_node_state(nid, N_MEMORY)
4438 seq_printf(m, " N%d=%lu", nid,
4439 mem_cgroup_node_nr_lru_pages(memcg, nid,
4440 stat->lru_mask, false));
Greg Thelen25485de2013-11-12 15:07:40 -08004441 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07004442 }
Ying Han406eb0c2011-05-26 16:25:37 -07004443
Ying Han071aee12013-11-12 15:07:41 -08004444 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
Ying Han406eb0c2011-05-26 16:25:37 -07004445
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004446 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4447 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4448 true));
4449 for_each_node_state(nid, N_MEMORY)
4450 seq_printf(m, " N%d=%lu", nid,
4451 mem_cgroup_node_nr_lru_pages(memcg, nid,
4452 stat->lru_mask, true));
Ying Han071aee12013-11-12 15:07:41 -08004453 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07004454 }
Ying Han406eb0c2011-05-26 16:25:37 -07004455
Ying Han406eb0c2011-05-26 16:25:37 -07004456 return 0;
4457}
4458#endif /* CONFIG_NUMA */
4459
Johannes Weinerc8713d02019-07-11 20:55:59 -07004460static const unsigned int memcg1_stats[] = {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07004461 NR_FILE_PAGES,
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07004462 NR_ANON_MAPPED,
Johannes Weiner468c3982020-06-03 16:02:01 -07004463#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4464 NR_ANON_THPS,
4465#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004466 NR_SHMEM,
4467 NR_FILE_MAPPED,
4468 NR_FILE_DIRTY,
4469 NR_WRITEBACK,
Yang Shie09b0b62022-08-16 11:58:01 -07004470 WORKINGSET_REFAULT_ANON,
4471 WORKINGSET_REFAULT_FILE,
Liu Shixin72a14e82023-09-15 18:58:44 +08004472#ifdef CONFIG_SWAP
Johannes Weinerc8713d02019-07-11 20:55:59 -07004473 MEMCG_SWAP,
Liu Shixin72a14e82023-09-15 18:58:44 +08004474 NR_SWAPCACHE,
4475#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004476};
4477
4478static const char *const memcg1_stat_names[] = {
4479 "cache",
4480 "rss",
Johannes Weiner468c3982020-06-03 16:02:01 -07004481#ifdef CONFIG_TRANSPARENT_HUGEPAGE
Johannes Weinerc8713d02019-07-11 20:55:59 -07004482 "rss_huge",
Johannes Weiner468c3982020-06-03 16:02:01 -07004483#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004484 "shmem",
4485 "mapped_file",
4486 "dirty",
4487 "writeback",
Yang Shie09b0b62022-08-16 11:58:01 -07004488 "workingset_refault_anon",
4489 "workingset_refault_file",
Liu Shixin72a14e82023-09-15 18:58:44 +08004490#ifdef CONFIG_SWAP
Johannes Weinerc8713d02019-07-11 20:55:59 -07004491 "swap",
Liu Shixin72a14e82023-09-15 18:58:44 +08004492 "swapcached",
4493#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004494};
4495
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004496/* Universal VM events cgroup1 shows, original sort order */
Greg Thelen8dd53fd2018-06-07 17:07:23 -07004497static const unsigned int memcg1_events[] = {
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004498 PGPGIN,
4499 PGPGOUT,
4500 PGFAULT,
4501 PGMAJFAULT,
4502};
4503
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004504static void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004505{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004506 unsigned long memory, memsw;
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004507 struct mem_cgroup *mi;
4508 unsigned int i;
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004509
Johannes Weiner71cd3112017-05-03 14:55:13 -07004510 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
Rickard Strandqvist70bc0682014-12-12 16:56:41 -08004511
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00004512 mem_cgroup_flush_stats(memcg);
Johannes Weiner2d146aa2021-04-29 22:56:26 -07004513
Johannes Weiner71cd3112017-05-03 14:55:13 -07004514 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
Johannes Weiner468c3982020-06-03 16:02:01 -07004515 unsigned long nr;
4516
Yosry Ahmedff841a02023-09-22 17:57:39 +00004517 nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
4518 seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07004519 }
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08004520
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004521 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004522 seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
4523 memcg_events_local(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004524
4525 for (i = 0; i < NR_LRU_LISTS; i++)
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004526 seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
4527 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
4528 PAGE_SIZE);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004529
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07004530 /* Hierarchical information */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004531 memory = memsw = PAGE_COUNTER_MAX;
4532 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
Chris Down15b42562020-04-01 21:07:20 -07004533 memory = min(memory, READ_ONCE(mi->memory.max));
4534 memsw = min(memsw, READ_ONCE(mi->memsw.max));
KAMEZAWA Hiroyukifee7b542009-01-07 18:08:26 -08004535 }
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004536 seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
4537 (u64)memory * PAGE_SIZE);
Liu Shixin840ea532023-09-15 18:58:45 +08004538 seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
4539 (u64)memsw * PAGE_SIZE);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004540
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004541 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
zhongjiang-ali7de2e9f2020-11-01 17:07:30 -08004542 unsigned long nr;
4543
Yosry Ahmedff841a02023-09-22 17:57:39 +00004544 nr = memcg_page_state_output(memcg, memcg1_stats[i]);
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004545 seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
Yosry Ahmedff841a02023-09-22 17:57:39 +00004546 (u64)nr);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004547 }
4548
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004549 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004550 seq_buf_printf(s, "total_%s %llu\n",
4551 vm_event_name(memcg1_events[i]),
4552 (u64)memcg_events(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004553
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004554 for (i = 0; i < NR_LRU_LISTS; i++)
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004555 seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
4556 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4557 PAGE_SIZE);
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07004558
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004559#ifdef CONFIG_DEBUG_VM
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004560 {
Mel Gormanef8f2322016-07-28 15:46:05 -07004561 pg_data_t *pgdat;
4562 struct mem_cgroup_per_node *mz;
Johannes Weiner1431d4d2020-06-03 16:02:53 -07004563 unsigned long anon_cost = 0;
4564 unsigned long file_cost = 0;
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004565
Mel Gormanef8f2322016-07-28 15:46:05 -07004566 for_each_online_pgdat(pgdat) {
Johannes Weinera3747b52021-04-29 22:56:14 -07004567 mz = memcg->nodeinfo[pgdat->node_id];
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004568
Johannes Weiner1431d4d2020-06-03 16:02:53 -07004569 anon_cost += mz->lruvec.anon_cost;
4570 file_cost += mz->lruvec.file_cost;
Mel Gormanef8f2322016-07-28 15:46:05 -07004571 }
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00004572 seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
4573 seq_buf_printf(s, "file_cost %lu\n", file_cost);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004574 }
4575#endif
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004576}
4577
Tejun Heo182446d2013-08-08 20:11:24 -04004578static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4579 struct cftype *cft)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004580{
Tejun Heo182446d2013-08-08 20:11:24 -04004581 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004582
KAMEZAWA Hiroyuki1f4c0252011-07-26 16:08:21 -07004583 return mem_cgroup_swappiness(memcg);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004584}
4585
Tejun Heo182446d2013-08-08 20:11:24 -04004586static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4587 struct cftype *cft, u64 val)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004588{
Tejun Heo182446d2013-08-08 20:11:24 -04004589 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Li Zefan068b38c2009-01-15 13:51:26 -08004590
Baolin Wang37bc3cb2021-09-02 14:55:53 -07004591 if (val > 200)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004592 return -EINVAL;
4593
Shakeel Butta4792032021-04-29 22:56:05 -07004594 if (!mem_cgroup_is_root(memcg))
Yue Zhao82b3aa22023-03-06 23:41:36 +08004595 WRITE_ONCE(memcg->swappiness, val);
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004596 else
Yue Zhao82b3aa22023-03-06 23:41:36 +08004597 WRITE_ONCE(vm_swappiness, val);
Li Zefan068b38c2009-01-15 13:51:26 -08004598
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004599 return 0;
4600}
4601
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004602static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4603{
4604 struct mem_cgroup_threshold_ary *t;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004605 unsigned long usage;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004606 int i;
4607
4608 rcu_read_lock();
4609 if (!swap)
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004610 t = rcu_dereference(memcg->thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004611 else
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004612 t = rcu_dereference(memcg->memsw_thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004613
4614 if (!t)
4615 goto unlock;
4616
Johannes Weinerce00a962014-09-05 08:43:57 -04004617 usage = mem_cgroup_usage(memcg, swap);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004618
4619 /*
Sha Zhengju748dad32012-05-29 15:06:57 -07004620 * current_threshold points to threshold just below or equal to usage.
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004621 * If it's not true, a threshold was crossed after last
4622 * call of __mem_cgroup_threshold().
4623 */
Phil Carmody5407a562010-05-26 14:42:42 -07004624 i = t->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004625
4626 /*
4627 * Iterate backward over array of thresholds starting from
4628 * current_threshold and check if a threshold is crossed.
4629 * If none of thresholds below usage is crossed, we read
4630 * only one element of the array here.
4631 */
4632 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
Christian Brauner36521172023-11-22 13:48:23 +01004633 eventfd_signal(t->entries[i].eventfd);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004634
4635 /* i = current_threshold + 1 */
4636 i++;
4637
4638 /*
4639 * Iterate forward over array of thresholds starting from
4640 * current_threshold+1 and check if a threshold is crossed.
4641 * If none of thresholds above usage is crossed, we read
4642 * only one element of the array here.
4643 */
4644 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
Christian Brauner36521172023-11-22 13:48:23 +01004645 eventfd_signal(t->entries[i].eventfd);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004646
4647 /* Update current_threshold */
Phil Carmody5407a562010-05-26 14:42:42 -07004648 t->current_threshold = i - 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004649unlock:
4650 rcu_read_unlock();
4651}
4652
4653static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4654{
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004655 while (memcg) {
4656 __mem_cgroup_threshold(memcg, false);
Johannes Weiner7941d212016-01-14 15:21:23 -08004657 if (do_memsw_account())
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004658 __mem_cgroup_threshold(memcg, true);
4659
4660 memcg = parent_mem_cgroup(memcg);
4661 }
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004662}
4663
4664static int compare_thresholds(const void *a, const void *b)
4665{
4666 const struct mem_cgroup_threshold *_a = a;
4667 const struct mem_cgroup_threshold *_b = b;
4668
Greg Thelen2bff24a2013-09-11 14:23:08 -07004669 if (_a->threshold > _b->threshold)
4670 return 1;
4671
4672 if (_a->threshold < _b->threshold)
4673 return -1;
4674
4675 return 0;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004676}
4677
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004678static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004679{
4680 struct mem_cgroup_eventfd_list *ev;
4681
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004682 spin_lock(&memcg_oom_lock);
4683
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004684 list_for_each_entry(ev, &memcg->oom_notify, list)
Christian Brauner36521172023-11-22 13:48:23 +01004685 eventfd_signal(ev->eventfd);
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004686
4687 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004688 return 0;
4689}
4690
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004691static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004692{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004693 struct mem_cgroup *iter;
4694
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004695 for_each_mem_cgroup_tree(iter, memcg)
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004696 mem_cgroup_oom_notify_cb(iter);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004697}
4698
Tejun Heo59b6f872013-11-22 18:20:43 -05004699static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004700 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004701{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004702 struct mem_cgroup_thresholds *thresholds;
4703 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004704 unsigned long threshold;
4705 unsigned long usage;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004706 int i, size, ret;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004707
Johannes Weiner650c5e52015-02-11 15:26:03 -08004708 ret = page_counter_memparse(args, "-1", &threshold);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004709 if (ret)
4710 return ret;
4711
4712 mutex_lock(&memcg->thresholds_lock);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004713
Johannes Weiner05b84302014-08-06 16:05:59 -07004714 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004715 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004716 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004717 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004718 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004719 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004720 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004721 BUG();
4722
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004723 /* Check if a threshold crossed before adding a new one */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004724 if (thresholds->primary)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004725 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4726
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004727 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004728
4729 /* Allocate memory for new array of thresholds */
Gustavo A. R. Silva67b80462019-03-05 15:44:05 -08004730 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004731 if (!new) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004732 ret = -ENOMEM;
4733 goto unlock;
4734 }
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004735 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004736
4737 /* Copy thresholds (if any) to new array */
Gustavo A. R. Silvae90342e2020-10-13 16:52:36 -07004738 if (thresholds->primary)
4739 memcpy(new->entries, thresholds->primary->entries,
4740 flex_array_size(new, entries, size - 1));
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004741
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004742 /* Add new threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004743 new->entries[size - 1].eventfd = eventfd;
4744 new->entries[size - 1].threshold = threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004745
4746 /* Sort thresholds. Registering of new threshold isn't time-critical */
Gustavo A. R. Silva61e604e62020-10-13 16:52:39 -07004747 sort(new->entries, size, sizeof(*new->entries),
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004748 compare_thresholds, NULL);
4749
4750 /* Find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004751 new->current_threshold = -1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004752 for (i = 0; i < size; i++) {
Sha Zhengju748dad32012-05-29 15:06:57 -07004753 if (new->entries[i].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004754 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004755 * new->current_threshold will not be used until
4756 * rcu_assign_pointer(), so it's safe to increment
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004757 * it here.
4758 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004759 ++new->current_threshold;
Sha Zhengju748dad32012-05-29 15:06:57 -07004760 } else
4761 break;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004762 }
4763
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004764 /* Free old spare buffer and save old primary buffer as spare */
4765 kfree(thresholds->spare);
4766 thresholds->spare = thresholds->primary;
4767
4768 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004769
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004770 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004771 synchronize_rcu();
4772
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004773unlock:
4774 mutex_unlock(&memcg->thresholds_lock);
4775
4776 return ret;
4777}
4778
Tejun Heo59b6f872013-11-22 18:20:43 -05004779static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004780 struct eventfd_ctx *eventfd, const char *args)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004781{
Tejun Heo59b6f872013-11-22 18:20:43 -05004782 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004783}
4784
Tejun Heo59b6f872013-11-22 18:20:43 -05004785static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004786 struct eventfd_ctx *eventfd, const char *args)
4787{
Tejun Heo59b6f872013-11-22 18:20:43 -05004788 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004789}
4790
Tejun Heo59b6f872013-11-22 18:20:43 -05004791static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004792 struct eventfd_ctx *eventfd, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004793{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004794 struct mem_cgroup_thresholds *thresholds;
4795 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004796 unsigned long usage;
Chunguang Xu7d366652020-03-21 18:22:10 -07004797 int i, j, size, entries;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004798
4799 mutex_lock(&memcg->thresholds_lock);
Johannes Weiner05b84302014-08-06 16:05:59 -07004800
4801 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004802 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004803 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004804 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004805 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004806 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004807 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004808 BUG();
4809
Anton Vorontsov371528c2012-02-24 05:14:46 +04004810 if (!thresholds->primary)
4811 goto unlock;
4812
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004813 /* Check if a threshold crossed before removing */
4814 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4815
4816 /* Calculate new number of threshold */
Chunguang Xu7d366652020-03-21 18:22:10 -07004817 size = entries = 0;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004818 for (i = 0; i < thresholds->primary->size; i++) {
4819 if (thresholds->primary->entries[i].eventfd != eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004820 size++;
Chunguang Xu7d366652020-03-21 18:22:10 -07004821 else
4822 entries++;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004823 }
4824
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004825 new = thresholds->spare;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004826
Chunguang Xu7d366652020-03-21 18:22:10 -07004827 /* If no items related to eventfd have been cleared, nothing to do */
4828 if (!entries)
4829 goto unlock;
4830
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004831 /* Set thresholds array to NULL if we don't have thresholds */
4832 if (!size) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004833 kfree(new);
4834 new = NULL;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004835 goto swap_buffers;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004836 }
4837
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004838 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004839
4840 /* Copy thresholds and find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004841 new->current_threshold = -1;
4842 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4843 if (thresholds->primary->entries[i].eventfd == eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004844 continue;
4845
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004846 new->entries[j] = thresholds->primary->entries[i];
Sha Zhengju748dad32012-05-29 15:06:57 -07004847 if (new->entries[j].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004848 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004849 * new->current_threshold will not be used
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004850 * until rcu_assign_pointer(), so it's safe to increment
4851 * it here.
4852 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004853 ++new->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004854 }
4855 j++;
4856 }
4857
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004858swap_buffers:
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004859 /* Swap primary and spare array */
4860 thresholds->spare = thresholds->primary;
Sha Zhengju8c757762012-05-10 13:01:45 -07004861
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004862 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004863
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004864 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004865 synchronize_rcu();
Martijn Coenen6611d8d2016-01-15 16:57:49 -08004866
4867 /* If all events are unregistered, free the spare array */
4868 if (!new) {
4869 kfree(thresholds->spare);
4870 thresholds->spare = NULL;
4871 }
Anton Vorontsov371528c2012-02-24 05:14:46 +04004872unlock:
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004873 mutex_unlock(&memcg->thresholds_lock);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004874}
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004875
Tejun Heo59b6f872013-11-22 18:20:43 -05004876static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004877 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004878{
Tejun Heo59b6f872013-11-22 18:20:43 -05004879 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004880}
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004881
Tejun Heo59b6f872013-11-22 18:20:43 -05004882static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004883 struct eventfd_ctx *eventfd)
4884{
Tejun Heo59b6f872013-11-22 18:20:43 -05004885 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004886}
4887
Tejun Heo59b6f872013-11-22 18:20:43 -05004888static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004889 struct eventfd_ctx *eventfd, const char *args)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004890{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004891 struct mem_cgroup_eventfd_list *event;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004892
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004893 event = kmalloc(sizeof(*event), GFP_KERNEL);
4894 if (!event)
4895 return -ENOMEM;
4896
Michal Hocko1af8efe2011-07-26 16:08:24 -07004897 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004898
4899 event->eventfd = eventfd;
4900 list_add(&event->list, &memcg->oom_notify);
4901
4902 /* already in OOM ? */
Tejun Heoc2b42d32015-06-24 16:58:23 -07004903 if (memcg->under_oom)
Christian Brauner36521172023-11-22 13:48:23 +01004904 eventfd_signal(eventfd);
Michal Hocko1af8efe2011-07-26 16:08:24 -07004905 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004906
4907 return 0;
4908}
4909
Tejun Heo59b6f872013-11-22 18:20:43 -05004910static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004911 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004912{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004913 struct mem_cgroup_eventfd_list *ev, *tmp;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004914
Michal Hocko1af8efe2011-07-26 16:08:24 -07004915 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004916
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004917 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004918 if (ev->eventfd == eventfd) {
4919 list_del(&ev->list);
4920 kfree(ev);
4921 }
4922 }
4923
Michal Hocko1af8efe2011-07-26 16:08:24 -07004924 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004925}
4926
Tejun Heo2da8ca82013-12-05 12:28:04 -05004927static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004928{
Chris Downaa9694b2019-03-05 15:45:52 -08004929 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004930
Yue Zhao17c56de2023-03-06 23:41:37 +08004931 seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
Tejun Heoc2b42d32015-06-24 16:58:23 -07004932 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
Roman Gushchinfe6bdfc2018-06-14 15:28:05 -07004933 seq_printf(sf, "oom_kill %lu\n",
4934 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004935 return 0;
4936}
4937
Tejun Heo182446d2013-08-08 20:11:24 -04004938static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004939 struct cftype *cft, u64 val)
4940{
Tejun Heo182446d2013-08-08 20:11:24 -04004941 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004942
4943 /* cannot set to root cgroup and only 0 and 1 are allowed */
Shakeel Butta4792032021-04-29 22:56:05 -07004944 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004945 return -EINVAL;
4946
Yue Zhao17c56de2023-03-06 23:41:37 +08004947 WRITE_ONCE(memcg->oom_kill_disable, val);
KAMEZAWA Hiroyuki4d845eb2010-06-29 15:05:18 -07004948 if (!val)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004949 memcg_oom_recover(memcg);
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004950
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004951 return 0;
4952}
4953
Tejun Heo52ebea72015-05-22 17:13:37 -04004954#ifdef CONFIG_CGROUP_WRITEBACK
4955
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004956#include <trace/events/writeback.h>
4957
Tejun Heo841710a2015-05-22 18:23:33 -04004958static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4959{
4960 return wb_domain_init(&memcg->cgwb_domain, gfp);
4961}
4962
4963static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4964{
4965 wb_domain_exit(&memcg->cgwb_domain);
4966}
4967
Tejun Heo2529bb32015-05-22 18:23:34 -04004968static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4969{
4970 wb_domain_size_changed(&memcg->cgwb_domain);
4971}
4972
Tejun Heo841710a2015-05-22 18:23:33 -04004973struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4974{
4975 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4976
4977 if (!memcg->css.parent)
4978 return NULL;
4979
4980 return &memcg->cgwb_domain;
4981}
4982
Tejun Heoc2aa7232015-05-22 18:23:35 -04004983/**
4984 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4985 * @wb: bdi_writeback in question
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004986 * @pfilepages: out parameter for number of file pages
4987 * @pheadroom: out parameter for number of allocatable pages according to memcg
Tejun Heoc2aa7232015-05-22 18:23:35 -04004988 * @pdirty: out parameter for number of dirty pages
4989 * @pwriteback: out parameter for number of pages under writeback
4990 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004991 * Determine the numbers of file, headroom, dirty, and writeback pages in
4992 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4993 * is a bit more involved.
Tejun Heoc2aa7232015-05-22 18:23:35 -04004994 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004995 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4996 * headroom is calculated as the lowest headroom of itself and the
4997 * ancestors. Note that this doesn't consider the actual amount of
4998 * available memory in the system. The caller should further cap
4999 * *@pheadroom accordingly.
Tejun Heoc2aa7232015-05-22 18:23:35 -04005000 */
Tejun Heoc5edf9c2015-09-29 13:04:26 -04005001void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
5002 unsigned long *pheadroom, unsigned long *pdirty,
5003 unsigned long *pwriteback)
Tejun Heoc2aa7232015-05-22 18:23:35 -04005004{
5005 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
5006 struct mem_cgroup *parent;
Tejun Heoc2aa7232015-05-22 18:23:35 -04005007
Shakeel Buttd9b3ce82024-01-18 18:42:35 +00005008 mem_cgroup_flush_stats_ratelimited(memcg);
Tejun Heoc2aa7232015-05-22 18:23:35 -04005009
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005010 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
5011 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
5012 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
5013 memcg_page_state(memcg, NR_ACTIVE_FILE);
5014
Tejun Heoc5edf9c2015-09-29 13:04:26 -04005015 *pheadroom = PAGE_COUNTER_MAX;
Tejun Heoc2aa7232015-05-22 18:23:35 -04005016 while ((parent = parent_mem_cgroup(memcg))) {
Chris Down15b42562020-04-01 21:07:20 -07005017 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
Jakub Kicinskid1663a92020-06-01 21:49:49 -07005018 READ_ONCE(memcg->memory.high));
Tejun Heoc2aa7232015-05-22 18:23:35 -04005019 unsigned long used = page_counter_read(&memcg->memory);
5020
Tejun Heoc5edf9c2015-09-29 13:04:26 -04005021 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
Tejun Heoc2aa7232015-05-22 18:23:35 -04005022 memcg = parent;
5023 }
Tejun Heoc2aa7232015-05-22 18:23:35 -04005024}
5025
Tejun Heo97b27822019-08-26 09:06:56 -07005026/*
5027 * Foreign dirty flushing
5028 *
5029 * There's an inherent mismatch between memcg and writeback. The former
Ingo Molnarf0953a12021-05-06 18:06:47 -07005030 * tracks ownership per-page while the latter per-inode. This was a
Tejun Heo97b27822019-08-26 09:06:56 -07005031 * deliberate design decision because honoring per-page ownership in the
5032 * writeback path is complicated, may lead to higher CPU and IO overheads
5033 * and deemed unnecessary given that write-sharing an inode across
5034 * different cgroups isn't a common use-case.
5035 *
5036 * Combined with inode majority-writer ownership switching, this works well
5037 * enough in most cases but there are some pathological cases. For
5038 * example, let's say there are two cgroups A and B which keep writing to
5039 * different but confined parts of the same inode. B owns the inode and
5040 * A's memory is limited far below B's. A's dirty ratio can rise enough to
5041 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
5042 * triggering background writeback. A will be slowed down without a way to
5043 * make writeback of the dirty pages happen.
5044 *
Ingo Molnarf0953a12021-05-06 18:06:47 -07005045 * Conditions like the above can lead to a cgroup getting repeatedly and
Tejun Heo97b27822019-08-26 09:06:56 -07005046 * severely throttled after making some progress after each
Ingo Molnarf0953a12021-05-06 18:06:47 -07005047 * dirty_expire_interval while the underlying IO device is almost
Tejun Heo97b27822019-08-26 09:06:56 -07005048 * completely idle.
5049 *
5050 * Solving this problem completely requires matching the ownership tracking
5051 * granularities between memcg and writeback in either direction. However,
5052 * the more egregious behaviors can be avoided by simply remembering the
5053 * most recent foreign dirtying events and initiating remote flushes on
5054 * them when local writeback isn't enough to keep the memory clean enough.
5055 *
5056 * The following two functions implement such mechanism. When a foreign
5057 * page - a page whose memcg and writeback ownerships don't match - is
5058 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
5059 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
5060 * decides that the memcg needs to sleep due to high dirty ratio, it calls
5061 * mem_cgroup_flush_foreign() which queues writeback on the recorded
5062 * foreign bdi_writebacks which haven't expired. Both the numbers of
5063 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
5064 * limited to MEMCG_CGWB_FRN_CNT.
5065 *
5066 * The mechanism only remembers IDs and doesn't hold any object references.
5067 * As being wrong occasionally doesn't matter, updates and accesses to the
5068 * records are lockless and racy.
5069 */
Matthew Wilcox (Oracle)9d8053f2021-05-04 11:43:01 -04005070void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
Tejun Heo97b27822019-08-26 09:06:56 -07005071 struct bdi_writeback *wb)
5072{
Matthew Wilcox (Oracle)9d8053f2021-05-04 11:43:01 -04005073 struct mem_cgroup *memcg = folio_memcg(folio);
Tejun Heo97b27822019-08-26 09:06:56 -07005074 struct memcg_cgwb_frn *frn;
5075 u64 now = get_jiffies_64();
5076 u64 oldest_at = now;
5077 int oldest = -1;
5078 int i;
5079
Matthew Wilcox (Oracle)9d8053f2021-05-04 11:43:01 -04005080 trace_track_foreign_dirty(folio, wb);
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07005081
Tejun Heo97b27822019-08-26 09:06:56 -07005082 /*
5083 * Pick the slot to use. If there is already a slot for @wb, keep
5084 * using it. If not replace the oldest one which isn't being
5085 * written out.
5086 */
5087 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
5088 frn = &memcg->cgwb_frn[i];
5089 if (frn->bdi_id == wb->bdi->id &&
5090 frn->memcg_id == wb->memcg_css->id)
5091 break;
5092 if (time_before64(frn->at, oldest_at) &&
5093 atomic_read(&frn->done.cnt) == 1) {
5094 oldest = i;
5095 oldest_at = frn->at;
5096 }
5097 }
5098
5099 if (i < MEMCG_CGWB_FRN_CNT) {
5100 /*
5101 * Re-using an existing one. Update timestamp lazily to
5102 * avoid making the cacheline hot. We want them to be
5103 * reasonably up-to-date and significantly shorter than
5104 * dirty_expire_interval as that's what expires the record.
5105 * Use the shorter of 1s and dirty_expire_interval / 8.
5106 */
5107 unsigned long update_intv =
5108 min_t(unsigned long, HZ,
5109 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
5110
5111 if (time_before64(frn->at, now - update_intv))
5112 frn->at = now;
5113 } else if (oldest >= 0) {
5114 /* replace the oldest free one */
5115 frn = &memcg->cgwb_frn[oldest];
5116 frn->bdi_id = wb->bdi->id;
5117 frn->memcg_id = wb->memcg_css->id;
5118 frn->at = now;
5119 }
5120}
5121
5122/* issue foreign writeback flushes for recorded foreign dirtying events */
5123void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
5124{
5125 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
5126 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
5127 u64 now = jiffies_64;
5128 int i;
5129
5130 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
5131 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
5132
5133 /*
5134 * If the record is older than dirty_expire_interval,
5135 * writeback on it has already started. No need to kick it
5136 * off again. Also, don't start a new one if there's
5137 * already one in flight.
5138 */
5139 if (time_after64(frn->at, now - intv) &&
5140 atomic_read(&frn->done.cnt) == 1) {
5141 frn->at = 0;
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07005142 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
Shakeel Butt7490a2d2021-09-02 14:53:27 -07005143 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
Tejun Heo97b27822019-08-26 09:06:56 -07005144 WB_REASON_FOREIGN_FLUSH,
5145 &frn->done);
5146 }
5147 }
5148}
5149
Tejun Heo841710a2015-05-22 18:23:33 -04005150#else /* CONFIG_CGROUP_WRITEBACK */
5151
5152static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
5153{
5154 return 0;
5155}
5156
5157static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
5158{
5159}
5160
Tejun Heo2529bb32015-05-22 18:23:34 -04005161static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
5162{
5163}
5164
Tejun Heo52ebea72015-05-22 17:13:37 -04005165#endif /* CONFIG_CGROUP_WRITEBACK */
5166
Tejun Heo79bd9812013-11-22 18:20:42 -05005167/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05005168 * DO NOT USE IN NEW FILES.
5169 *
5170 * "cgroup.event_control" implementation.
5171 *
5172 * This is way over-engineered. It tries to support fully configurable
5173 * events for each user. Such level of flexibility is completely
5174 * unnecessary especially in the light of the planned unified hierarchy.
5175 *
5176 * Please deprecate this and replace with something simpler if at all
5177 * possible.
5178 */
5179
5180/*
Tejun Heo79bd9812013-11-22 18:20:42 -05005181 * Unregister event and free resources.
5182 *
5183 * Gets called from workqueue.
5184 */
Tejun Heo3bc942f2013-11-22 18:20:44 -05005185static void memcg_event_remove(struct work_struct *work)
Tejun Heo79bd9812013-11-22 18:20:42 -05005186{
Tejun Heo3bc942f2013-11-22 18:20:44 -05005187 struct mem_cgroup_event *event =
5188 container_of(work, struct mem_cgroup_event, remove);
Tejun Heo59b6f872013-11-22 18:20:43 -05005189 struct mem_cgroup *memcg = event->memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05005190
5191 remove_wait_queue(event->wqh, &event->wait);
5192
Tejun Heo59b6f872013-11-22 18:20:43 -05005193 event->unregister_event(memcg, event->eventfd);
Tejun Heo79bd9812013-11-22 18:20:42 -05005194
5195 /* Notify userspace the event is going away. */
Christian Brauner36521172023-11-22 13:48:23 +01005196 eventfd_signal(event->eventfd);
Tejun Heo79bd9812013-11-22 18:20:42 -05005197
5198 eventfd_ctx_put(event->eventfd);
5199 kfree(event);
Tejun Heo59b6f872013-11-22 18:20:43 -05005200 css_put(&memcg->css);
Tejun Heo79bd9812013-11-22 18:20:42 -05005201}
5202
5203/*
Linus Torvaldsa9a08842018-02-11 14:34:03 -08005204 * Gets called on EPOLLHUP on eventfd when user closes it.
Tejun Heo79bd9812013-11-22 18:20:42 -05005205 *
5206 * Called with wqh->lock held and interrupts disabled.
5207 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02005208static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
Tejun Heo3bc942f2013-11-22 18:20:44 -05005209 int sync, void *key)
Tejun Heo79bd9812013-11-22 18:20:42 -05005210{
Tejun Heo3bc942f2013-11-22 18:20:44 -05005211 struct mem_cgroup_event *event =
5212 container_of(wait, struct mem_cgroup_event, wait);
Tejun Heo59b6f872013-11-22 18:20:43 -05005213 struct mem_cgroup *memcg = event->memcg;
Al Viro3ad6f932017-07-03 20:14:56 -04005214 __poll_t flags = key_to_poll(key);
Tejun Heo79bd9812013-11-22 18:20:42 -05005215
Linus Torvaldsa9a08842018-02-11 14:34:03 -08005216 if (flags & EPOLLHUP) {
Tejun Heo79bd9812013-11-22 18:20:42 -05005217 /*
5218 * If the event has been detached at cgroup removal, we
5219 * can simply return knowing the other side will cleanup
5220 * for us.
5221 *
5222 * We can't race against event freeing since the other
5223 * side will require wqh->lock via remove_wait_queue(),
5224 * which we hold.
5225 */
Tejun Heofba94802013-11-22 18:20:43 -05005226 spin_lock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05005227 if (!list_empty(&event->list)) {
5228 list_del_init(&event->list);
5229 /*
5230 * We are in atomic context, but cgroup_event_remove()
5231 * may sleep, so we have to call it in workqueue.
5232 */
5233 schedule_work(&event->remove);
5234 }
Tejun Heofba94802013-11-22 18:20:43 -05005235 spin_unlock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05005236 }
5237
5238 return 0;
5239}
5240
Tejun Heo3bc942f2013-11-22 18:20:44 -05005241static void memcg_event_ptable_queue_proc(struct file *file,
Tejun Heo79bd9812013-11-22 18:20:42 -05005242 wait_queue_head_t *wqh, poll_table *pt)
5243{
Tejun Heo3bc942f2013-11-22 18:20:44 -05005244 struct mem_cgroup_event *event =
5245 container_of(pt, struct mem_cgroup_event, pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05005246
5247 event->wqh = wqh;
5248 add_wait_queue(wqh, &event->wait);
5249}
5250
5251/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05005252 * DO NOT USE IN NEW FILES.
5253 *
Tejun Heo79bd9812013-11-22 18:20:42 -05005254 * Parse input and register new cgroup event handler.
5255 *
5256 * Input must be in format '<event_fd> <control_fd> <args>'.
5257 * Interpretation of args is defined by control file implementation.
5258 */
Tejun Heo451af5042014-05-13 12:16:21 -04005259static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
5260 char *buf, size_t nbytes, loff_t off)
Tejun Heo79bd9812013-11-22 18:20:42 -05005261{
Tejun Heo451af5042014-05-13 12:16:21 -04005262 struct cgroup_subsys_state *css = of_css(of);
Tejun Heofba94802013-11-22 18:20:43 -05005263 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05005264 struct mem_cgroup_event *event;
Tejun Heo79bd9812013-11-22 18:20:42 -05005265 struct cgroup_subsys_state *cfile_css;
5266 unsigned int efd, cfd;
5267 struct fd efile;
5268 struct fd cfile;
Tejun Heo4a7ba452022-12-07 16:53:15 -10005269 struct dentry *cdentry;
Tejun Heofba94802013-11-22 18:20:43 -05005270 const char *name;
Tejun Heo79bd9812013-11-22 18:20:42 -05005271 char *endp;
5272 int ret;
5273
Sebastian Andrzej Siewior2343e882022-03-22 14:40:38 -07005274 if (IS_ENABLED(CONFIG_PREEMPT_RT))
5275 return -EOPNOTSUPP;
5276
Tejun Heo451af5042014-05-13 12:16:21 -04005277 buf = strstrip(buf);
5278
5279 efd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05005280 if (*endp != ' ')
5281 return -EINVAL;
Tejun Heo451af5042014-05-13 12:16:21 -04005282 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05005283
Tejun Heo451af5042014-05-13 12:16:21 -04005284 cfd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05005285 if ((*endp != ' ') && (*endp != '\0'))
5286 return -EINVAL;
Tejun Heo451af5042014-05-13 12:16:21 -04005287 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05005288
5289 event = kzalloc(sizeof(*event), GFP_KERNEL);
5290 if (!event)
5291 return -ENOMEM;
5292
Tejun Heo59b6f872013-11-22 18:20:43 -05005293 event->memcg = memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05005294 INIT_LIST_HEAD(&event->list);
Tejun Heo3bc942f2013-11-22 18:20:44 -05005295 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
5296 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
5297 INIT_WORK(&event->remove, memcg_event_remove);
Tejun Heo79bd9812013-11-22 18:20:42 -05005298
5299 efile = fdget(efd);
5300 if (!efile.file) {
5301 ret = -EBADF;
5302 goto out_kfree;
5303 }
5304
5305 event->eventfd = eventfd_ctx_fileget(efile.file);
5306 if (IS_ERR(event->eventfd)) {
5307 ret = PTR_ERR(event->eventfd);
5308 goto out_put_efile;
5309 }
5310
5311 cfile = fdget(cfd);
5312 if (!cfile.file) {
5313 ret = -EBADF;
5314 goto out_put_eventfd;
5315 }
5316
5317 /* the process need read permission on control file */
5318 /* AV: shouldn't we check that it's been opened for read instead? */
Christian Brauner02f92b32021-01-21 14:19:22 +01005319 ret = file_permission(cfile.file, MAY_READ);
Tejun Heo79bd9812013-11-22 18:20:42 -05005320 if (ret < 0)
5321 goto out_put_cfile;
5322
Tejun Heo79bd9812013-11-22 18:20:42 -05005323 /*
Tejun Heo4a7ba452022-12-07 16:53:15 -10005324 * The control file must be a regular cgroup1 file. As a regular cgroup
5325 * file can't be renamed, it's safe to access its name afterwards.
5326 */
5327 cdentry = cfile.file->f_path.dentry;
5328 if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
5329 ret = -EINVAL;
5330 goto out_put_cfile;
5331 }
5332
5333 /*
Tejun Heofba94802013-11-22 18:20:43 -05005334 * Determine the event callbacks and set them in @event. This used
5335 * to be done via struct cftype but cgroup core no longer knows
5336 * about these events. The following is crude but the whole thing
5337 * is for compatibility anyway.
Tejun Heo3bc942f2013-11-22 18:20:44 -05005338 *
5339 * DO NOT ADD NEW FILES.
Tejun Heofba94802013-11-22 18:20:43 -05005340 */
Tejun Heo4a7ba452022-12-07 16:53:15 -10005341 name = cdentry->d_name.name;
Tejun Heofba94802013-11-22 18:20:43 -05005342
5343 if (!strcmp(name, "memory.usage_in_bytes")) {
5344 event->register_event = mem_cgroup_usage_register_event;
5345 event->unregister_event = mem_cgroup_usage_unregister_event;
5346 } else if (!strcmp(name, "memory.oom_control")) {
5347 event->register_event = mem_cgroup_oom_register_event;
5348 event->unregister_event = mem_cgroup_oom_unregister_event;
5349 } else if (!strcmp(name, "memory.pressure_level")) {
5350 event->register_event = vmpressure_register_event;
5351 event->unregister_event = vmpressure_unregister_event;
5352 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
Tejun Heo347c4a82013-11-22 18:20:43 -05005353 event->register_event = memsw_cgroup_usage_register_event;
5354 event->unregister_event = memsw_cgroup_usage_unregister_event;
Tejun Heofba94802013-11-22 18:20:43 -05005355 } else {
5356 ret = -EINVAL;
5357 goto out_put_cfile;
5358 }
5359
5360 /*
Tejun Heob5557c42013-11-22 18:20:42 -05005361 * Verify @cfile should belong to @css. Also, remaining events are
5362 * automatically removed on cgroup destruction but the removal is
5363 * asynchronous, so take an extra ref on @css.
Tejun Heo79bd9812013-11-22 18:20:42 -05005364 */
Tejun Heo4a7ba452022-12-07 16:53:15 -10005365 cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
Tejun Heoec903c02014-05-13 12:11:01 -04005366 &memory_cgrp_subsys);
Tejun Heo79bd9812013-11-22 18:20:42 -05005367 ret = -EINVAL;
Tejun Heo5a17f542014-02-11 11:52:47 -05005368 if (IS_ERR(cfile_css))
Tejun Heo79bd9812013-11-22 18:20:42 -05005369 goto out_put_cfile;
Tejun Heo5a17f542014-02-11 11:52:47 -05005370 if (cfile_css != css) {
5371 css_put(cfile_css);
5372 goto out_put_cfile;
5373 }
Tejun Heo79bd9812013-11-22 18:20:42 -05005374
Tejun Heo451af5042014-05-13 12:16:21 -04005375 ret = event->register_event(memcg, event->eventfd, buf);
Tejun Heo79bd9812013-11-22 18:20:42 -05005376 if (ret)
5377 goto out_put_css;
5378
Christoph Hellwig9965ed172018-03-05 07:26:05 -08005379 vfs_poll(efile.file, &event->pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05005380
Shakeel Butt4ba95152021-09-02 14:56:05 -07005381 spin_lock_irq(&memcg->event_list_lock);
Tejun Heofba94802013-11-22 18:20:43 -05005382 list_add(&event->list, &memcg->event_list);
Shakeel Butt4ba95152021-09-02 14:56:05 -07005383 spin_unlock_irq(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05005384
5385 fdput(cfile);
5386 fdput(efile);
5387
Tejun Heo451af5042014-05-13 12:16:21 -04005388 return nbytes;
Tejun Heo79bd9812013-11-22 18:20:42 -05005389
5390out_put_css:
Tejun Heob5557c42013-11-22 18:20:42 -05005391 css_put(css);
Tejun Heo79bd9812013-11-22 18:20:42 -05005392out_put_cfile:
5393 fdput(cfile);
5394out_put_eventfd:
5395 eventfd_ctx_put(event->eventfd);
5396out_put_efile:
5397 fdput(efile);
5398out_kfree:
5399 kfree(event);
5400
5401 return ret;
5402}
5403
Vlastimil Babkabc3dcb82023-10-02 16:33:43 +02005404#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
Muchun Songc29b5b32022-01-14 14:04:01 -08005405static int mem_cgroup_slab_show(struct seq_file *m, void *p)
5406{
5407 /*
5408 * Deprecated.
Yang Yangdf4ae282022-06-10 02:44:52 +00005409 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
Muchun Songc29b5b32022-01-14 14:04:01 -08005410 */
5411 return 0;
5412}
5413#endif
5414
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00005415static int memory_stat_show(struct seq_file *m, void *v);
5416
Johannes Weiner241994ed2015-02-11 15:26:06 -08005417static struct cftype mem_cgroup_legacy_files[] = {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005418 {
Balbir Singh0eea1032008-02-07 00:13:57 -08005419 .name = "usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005420 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05005421 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005422 },
5423 {
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07005424 .name = "max_usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005425 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04005426 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005427 .read_u64 = mem_cgroup_read_u64,
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07005428 },
5429 {
Balbir Singh0eea1032008-02-07 00:13:57 -08005430 .name = "limit_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005431 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
Tejun Heo451af5042014-05-13 12:16:21 -04005432 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05005433 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005434 },
5435 {
Balbir Singh296c81d2009-09-23 15:56:36 -07005436 .name = "soft_limit_in_bytes",
5437 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
Tejun Heo451af5042014-05-13 12:16:21 -04005438 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05005439 .read_u64 = mem_cgroup_read_u64,
Balbir Singh296c81d2009-09-23 15:56:36 -07005440 },
5441 {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005442 .name = "failcnt",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005443 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04005444 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005445 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005446 },
Balbir Singh8697d332008-02-07 00:13:59 -08005447 {
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08005448 .name = "stat",
Yosry Ahmeddddb44f2023-04-28 13:24:06 +00005449 .seq_show = memory_stat_show,
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08005450 },
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08005451 {
5452 .name = "force_empty",
Tejun Heo6770c642014-05-13 12:16:21 -04005453 .write = mem_cgroup_force_empty_write,
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08005454 },
Balbir Singh18f59ea2009-01-07 18:08:07 -08005455 {
5456 .name = "use_hierarchy",
5457 .write_u64 = mem_cgroup_hierarchy_write,
5458 .read_u64 = mem_cgroup_hierarchy_read,
5459 },
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005460 {
Tejun Heo3bc942f2013-11-22 18:20:44 -05005461 .name = "cgroup.event_control", /* XXX: for compat */
Tejun Heo451af5042014-05-13 12:16:21 -04005462 .write = memcg_write_event_control,
Tejun Heo7dbdb192015-09-18 17:54:23 -04005463 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
Tejun Heo79bd9812013-11-22 18:20:42 -05005464 },
5465 {
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005466 .name = "swappiness",
5467 .read_u64 = mem_cgroup_swappiness_read,
5468 .write_u64 = mem_cgroup_swappiness_write,
5469 },
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005470 {
5471 .name = "move_charge_at_immigrate",
5472 .read_u64 = mem_cgroup_move_charge_read,
5473 .write_u64 = mem_cgroup_move_charge_write,
5474 },
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07005475 {
5476 .name = "oom_control",
Tejun Heo2da8ca82013-12-05 12:28:04 -05005477 .seq_show = mem_cgroup_oom_control_read,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07005478 .write_u64 = mem_cgroup_oom_control_write,
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07005479 },
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005480 {
5481 .name = "pressure_level",
Florian Schmidt6b0ba2a2023-04-04 10:58:59 +00005482 .seq_show = mem_cgroup_dummy_seq_show,
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005483 },
Ying Han406eb0c2011-05-26 16:25:37 -07005484#ifdef CONFIG_NUMA
5485 {
5486 .name = "numa_stat",
Tejun Heo2da8ca82013-12-05 12:28:04 -05005487 .seq_show = memcg_numa_stat_show,
Ying Han406eb0c2011-05-26 16:25:37 -07005488 },
5489#endif
Glauber Costa510fc4e2012-12-18 14:21:47 -08005490 {
Michal Hocko45976482023-09-21 09:38:29 +02005491 .name = "kmem.limit_in_bytes",
5492 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5493 .write = mem_cgroup_write,
5494 .read_u64 = mem_cgroup_read_u64,
5495 },
5496 {
Glauber Costa510fc4e2012-12-18 14:21:47 -08005497 .name = "kmem.usage_in_bytes",
5498 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05005499 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005500 },
5501 {
5502 .name = "kmem.failcnt",
5503 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04005504 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005505 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005506 },
5507 {
5508 .name = "kmem.max_usage_in_bytes",
5509 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04005510 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005511 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005512 },
Vlastimil Babkabc3dcb82023-10-02 16:33:43 +02005513#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_SLUB_DEBUG)
Glauber Costa749c5412012-12-18 14:23:01 -08005514 {
5515 .name = "kmem.slabinfo",
Muchun Songc29b5b32022-01-14 14:04:01 -08005516 .seq_show = mem_cgroup_slab_show,
Glauber Costa749c5412012-12-18 14:23:01 -08005517 },
5518#endif
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08005519 {
5520 .name = "kmem.tcp.limit_in_bytes",
5521 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5522 .write = mem_cgroup_write,
5523 .read_u64 = mem_cgroup_read_u64,
5524 },
5525 {
5526 .name = "kmem.tcp.usage_in_bytes",
5527 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5528 .read_u64 = mem_cgroup_read_u64,
5529 },
5530 {
5531 .name = "kmem.tcp.failcnt",
5532 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5533 .write = mem_cgroup_reset,
5534 .read_u64 = mem_cgroup_read_u64,
5535 },
5536 {
5537 .name = "kmem.tcp.max_usage_in_bytes",
5538 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5539 .write = mem_cgroup_reset,
5540 .read_u64 = mem_cgroup_read_u64,
5541 },
Tejun Heo6bc10342012-04-01 12:09:55 -07005542 { }, /* terminate */
Tejun Heoaf36f902012-04-01 12:09:55 -07005543};
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005544
Johannes Weiner73f576c2016-07-20 15:44:57 -07005545/*
5546 * Private memory cgroup IDR
5547 *
5548 * Swap-out records and page cache shadow entries need to store memcg
5549 * references in constrained space, so we maintain an ID space that is
5550 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5551 * memory-controlled cgroups to 64k.
5552 *
Ethon Paulb8f29352020-06-04 16:49:28 -07005553 * However, there usually are many references to the offline CSS after
Johannes Weiner73f576c2016-07-20 15:44:57 -07005554 * the cgroup has been destroyed, such as page cache or reclaimable
5555 * slab objects, that don't need to hang on to the ID. We want to keep
5556 * those dead CSS from occupying IDs, or we might quickly exhaust the
5557 * relatively small ID space and prevent the creation of new cgroups
5558 * even when there are much fewer than 64k cgroups - possibly none.
5559 *
5560 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5561 * be freed and recycled when it's no longer needed, which is usually
5562 * when the CSS is offlined.
5563 *
5564 * The only exception to that are records of swapped out tmpfs/shmem
5565 * pages that need to be attributed to live ancestors on swapin. But
5566 * those references are manageable from userspace.
5567 */
5568
Miaohe Lin60b1e242023-07-08 10:33:04 +08005569#define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
Johannes Weiner73f576c2016-07-20 15:44:57 -07005570static DEFINE_IDR(mem_cgroup_idr);
5571
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005572static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5573{
5574 if (memcg->id.id > 0) {
5575 idr_remove(&mem_cgroup_idr, memcg->id.id);
5576 memcg->id.id = 0;
5577 }
5578}
5579
Vincenzo Frascinoc1514c02020-04-01 21:07:13 -07005580static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5581 unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07005582{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005583 refcount_add(n, &memcg->id.ref);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005584}
5585
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005586static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07005587{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005588 if (refcount_sub_and_test(n, &memcg->id.ref)) {
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005589 mem_cgroup_id_remove(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005590
5591 /* Memcg ID pins CSS */
5592 css_put(&memcg->css);
5593 }
5594}
5595
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005596static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5597{
5598 mem_cgroup_id_put_many(memcg, 1);
5599}
5600
Johannes Weiner73f576c2016-07-20 15:44:57 -07005601/**
5602 * mem_cgroup_from_id - look up a memcg from a memcg id
5603 * @id: the memcg id to look up
5604 *
5605 * Caller must hold rcu_read_lock().
5606 */
5607struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5608{
5609 WARN_ON_ONCE(!rcu_read_lock_held());
5610 return idr_find(&mem_cgroup_idr, id);
5611}
5612
Roman Gushchinc15187a2022-05-31 20:22:22 -07005613#ifdef CONFIG_SHRINKER_DEBUG
5614struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5615{
5616 struct cgroup *cgrp;
5617 struct cgroup_subsys_state *css;
5618 struct mem_cgroup *memcg;
5619
5620 cgrp = cgroup_get_from_id(ino);
Michal Koutnýfa7e4392022-08-26 18:52:37 +02005621 if (IS_ERR(cgrp))
Tejun Heoc0f2df492022-08-28 17:54:15 -10005622 return ERR_CAST(cgrp);
Roman Gushchinc15187a2022-05-31 20:22:22 -07005623
5624 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5625 if (css)
5626 memcg = container_of(css, struct mem_cgroup, css);
5627 else
5628 memcg = ERR_PTR(-ENOENT);
5629
5630 cgroup_put(cgrp);
5631
5632 return memcg;
5633}
5634#endif
5635
Xiu Jianfenga8248bb2024-05-07 13:23:24 +00005636static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005637{
5638 struct mem_cgroup_per_node *pn;
Wei Yang8c9bb392022-03-22 14:47:06 -07005639
5640 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005641 if (!pn)
Xiu Jianfenga8248bb2024-05-07 13:23:24 +00005642 return false;
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005643
Roman Gushchinaab61032024-05-01 10:26:12 -07005644 pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
5645 GFP_KERNEL_ACCOUNT, node);
Shakeel Butt70a64b72024-05-01 10:26:11 -07005646 if (!pn->lruvec_stats)
5647 goto fail;
5648
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07005649 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5650 GFP_KERNEL_ACCOUNT);
Shakeel Butt70a64b72024-05-01 10:26:11 -07005651 if (!pn->lruvec_stats_percpu)
5652 goto fail;
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005653
Mel Gormanef8f2322016-07-28 15:46:05 -07005654 lruvec_init(&pn->lruvec);
Mel Gormanef8f2322016-07-28 15:46:05 -07005655 pn->memcg = memcg;
5656
Johannes Weiner54f72fe2013-07-08 15:59:49 -07005657 memcg->nodeinfo[node] = pn;
Xiu Jianfenga8248bb2024-05-07 13:23:24 +00005658 return true;
Shakeel Butt70a64b72024-05-01 10:26:11 -07005659fail:
5660 kfree(pn->lruvec_stats);
5661 kfree(pn);
Xiu Jianfenga8248bb2024-05-07 13:23:24 +00005662 return false;
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005663}
5664
Mel Gormanef8f2322016-07-28 15:46:05 -07005665static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005666{
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005667 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5668
Michal Hocko4eaf4312018-04-10 16:29:52 -07005669 if (!pn)
5670 return;
5671
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07005672 free_percpu(pn->lruvec_stats_percpu);
Shakeel Butt70a64b72024-05-01 10:26:11 -07005673 kfree(pn->lruvec_stats);
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005674 kfree(pn);
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005675}
5676
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005677static void __mem_cgroup_free(struct mem_cgroup *memcg)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005678{
5679 int node;
5680
Yosry Ahmed91b71e782024-03-16 01:58:03 +00005681 obj_cgroup_put(memcg->orig_objcg);
Roman Gushchin675d6c92023-10-19 15:53:43 -07005682
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005683 for_each_node(node)
Mel Gormanef8f2322016-07-28 15:46:05 -07005684 free_mem_cgroup_per_node_info(memcg, node);
Shakeel Butt410f8e82022-09-07 04:35:35 +00005685 kfree(memcg->vmstats);
Chris Down871789d2019-05-14 15:46:57 -07005686 free_percpu(memcg->vmstats_percpu);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005687 kfree(memcg);
5688}
5689
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005690static void mem_cgroup_free(struct mem_cgroup *memcg)
5691{
Yu Zhaoec1c86b2022-09-18 02:00:02 -06005692 lru_gen_exit_memcg(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005693 memcg_wb_domain_exit(memcg);
5694 __mem_cgroup_free(memcg);
5695}
5696
Yosry Ahmed9cee7e82024-01-24 10:00:22 +00005697static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005698{
Yosry Ahmed9cee7e82024-01-24 10:00:22 +00005699 struct memcg_vmstats_percpu *statc, *pstatc;
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005700 struct mem_cgroup *memcg;
Yosry Ahmed9cee7e82024-01-24 10:00:22 +00005701 int node, cpu;
Tejun Heo97b27822019-08-26 09:06:56 -07005702 int __maybe_unused i;
Yafang Shao11d67612020-05-07 18:35:43 -07005703 long error = -ENOMEM;
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005704
Wang Weiyang06b2c3b2022-01-14 14:05:42 -08005705 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005706 if (!memcg)
Yafang Shao11d67612020-05-07 18:35:43 -07005707 return ERR_PTR(error);
Dan Carpentere7bbcdf2010-03-23 13:35:12 -07005708
Johannes Weiner73f576c2016-07-20 15:44:57 -07005709 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
Muchun Songbe740502022-03-22 14:41:31 -07005710 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
Yafang Shao11d67612020-05-07 18:35:43 -07005711 if (memcg->id.id < 0) {
5712 error = memcg->id.id;
Johannes Weiner73f576c2016-07-20 15:44:57 -07005713 goto fail;
Yafang Shao11d67612020-05-07 18:35:43 -07005714 }
Johannes Weiner73f576c2016-07-20 15:44:57 -07005715
Roman Gushchinaab61032024-05-01 10:26:12 -07005716 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
5717 GFP_KERNEL_ACCOUNT);
Shakeel Butt410f8e82022-09-07 04:35:35 +00005718 if (!memcg->vmstats)
5719 goto fail;
5720
Roman Gushchin3e38e0a2020-08-11 18:30:25 -07005721 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5722 GFP_KERNEL_ACCOUNT);
Chris Down871789d2019-05-14 15:46:57 -07005723 if (!memcg->vmstats_percpu)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005724 goto fail;
Pavel Emelianov78fb7462008-02-07 00:13:51 -08005725
Yosry Ahmed9cee7e82024-01-24 10:00:22 +00005726 for_each_possible_cpu(cpu) {
5727 if (parent)
5728 pstatc = per_cpu_ptr(parent->vmstats_percpu, cpu);
5729 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5730 statc->parent = parent ? pstatc : NULL;
5731 statc->vmstats = memcg->vmstats;
5732 }
5733
Bob Liu3ed28fa2012-01-12 17:19:04 -08005734 for_each_node(node)
Xiu Jianfenga8248bb2024-05-07 13:23:24 +00005735 if (!alloc_mem_cgroup_per_node_info(memcg, node))
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005736 goto fail;
Balbir Singhf64c3f52009-09-23 15:56:37 -07005737
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005738 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5739 goto fail;
Balbir Singh28dbc4b2009-01-07 18:08:05 -08005740
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005741 INIT_WORK(&memcg->high_work, high_work_func);
Glauber Costad142e3e2013-02-22 16:34:52 -08005742 INIT_LIST_HEAD(&memcg->oom_notify);
Glauber Costad142e3e2013-02-22 16:34:52 -08005743 mutex_init(&memcg->thresholds_lock);
5744 spin_lock_init(&memcg->move_lock);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005745 vmpressure_init(&memcg->vmpressure);
Tejun Heofba94802013-11-22 18:20:43 -05005746 INIT_LIST_HEAD(&memcg->event_list);
5747 spin_lock_init(&memcg->event_list_lock);
Johannes Weinerd886f4e2016-01-20 15:02:47 -08005748 memcg->socket_pressure = jiffies;
Kirill Tkhai84c07d12018-08-17 15:47:25 -07005749#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005750 memcg->kmemcg_id = -1;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07005751 INIT_LIST_HEAD(&memcg->objcg_list);
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005752#endif
Tejun Heo52ebea72015-05-22 17:13:37 -04005753#ifdef CONFIG_CGROUP_WRITEBACK
5754 INIT_LIST_HEAD(&memcg->cgwb_list);
Tejun Heo97b27822019-08-26 09:06:56 -07005755 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5756 memcg->cgwb_frn[i].done =
5757 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
Tejun Heo52ebea72015-05-22 17:13:37 -04005758#endif
Yang Shi87eaceb2019-09-23 15:38:15 -07005759#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5760 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5761 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5762 memcg->deferred_split_queue.split_queue_len = 0;
5763#endif
Yu Zhaoec1c86b2022-09-18 02:00:02 -06005764 lru_gen_init_memcg(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005765 return memcg;
5766fail:
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005767 mem_cgroup_id_remove(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005768 __mem_cgroup_free(memcg);
Yafang Shao11d67612020-05-07 18:35:43 -07005769 return ERR_PTR(error);
Glauber Costad142e3e2013-02-22 16:34:52 -08005770}
5771
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005772static struct cgroup_subsys_state * __ref
5773mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
Glauber Costad142e3e2013-02-22 16:34:52 -08005774{
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005775 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
Roman Gushchinb87d8ce2020-10-17 16:13:40 -07005776 struct mem_cgroup *memcg, *old_memcg;
Glauber Costad142e3e2013-02-22 16:34:52 -08005777
Roman Gushchinb87d8ce2020-10-17 16:13:40 -07005778 old_memcg = set_active_memcg(parent);
Yosry Ahmed9cee7e82024-01-24 10:00:22 +00005779 memcg = mem_cgroup_alloc(parent);
Roman Gushchinb87d8ce2020-10-17 16:13:40 -07005780 set_active_memcg(old_memcg);
Yafang Shao11d67612020-05-07 18:35:43 -07005781 if (IS_ERR(memcg))
5782 return ERR_CAST(memcg);
Li Zefan4219b2d2013-09-23 16:56:29 +08005783
Jakub Kicinskid1663a92020-06-01 21:49:49 -07005784 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
Yue Zhao2178e202023-03-06 23:41:38 +08005785 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07005786#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5787 memcg->zswap_max = PAGE_COUNTER_MAX;
Nhat Pham501a06f2023-12-07 11:24:06 -08005788 WRITE_ONCE(memcg->zswap_writeback,
5789 !parent || READ_ONCE(parent->zswap_writeback));
Johannes Weinerf4840cc2022-05-19 14:08:53 -07005790#endif
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07005791 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005792 if (parent) {
Yue Zhao82b3aa22023-03-06 23:41:36 +08005793 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
Yue Zhao17c56de2023-03-06 23:41:37 +08005794 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
Roman Gushchinbef86202020-12-14 19:06:49 -08005795
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005796 page_counter_init(&memcg->memory, &parent->memory);
Vladimir Davydov37e84352016-01-20 15:02:56 -08005797 page_counter_init(&memcg->swap, &parent->swap);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005798 page_counter_init(&memcg->kmem, &parent->kmem);
Johannes Weiner0db15292016-01-20 15:02:50 -08005799 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
Balbir Singh18f59ea2009-01-07 18:08:07 -08005800 } else {
Shakeel Buttff48c712024-05-01 10:26:13 -07005801 init_memcg_stats();
Shakeel Butt8278f1c2022-09-07 04:35:37 +00005802 init_memcg_events();
Roman Gushchinbef86202020-12-14 19:06:49 -08005803 page_counter_init(&memcg->memory, NULL);
5804 page_counter_init(&memcg->swap, NULL);
5805 page_counter_init(&memcg->kmem, NULL);
5806 page_counter_init(&memcg->tcpmem, NULL);
Vladimir Davydovd6441632014-01-23 15:53:09 -08005807
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005808 root_mem_cgroup = memcg;
5809 return &memcg->css;
5810 }
5811
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005812 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005813 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005814
Yafang Shaob6c1a8a2023-02-10 15:47:31 +00005815#if defined(CONFIG_MEMCG_KMEM)
5816 if (!cgroup_memory_nobpf)
5817 static_branch_inc(&memcg_bpf_enabled_key);
5818#endif
5819
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005820 return &memcg->css;
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005821}
5822
Johannes Weiner73f576c2016-07-20 15:44:57 -07005823static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005824{
Vladimir Davydov58fa2a52016-10-07 16:57:29 -07005825 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5826
Muchun Songda0efe32022-03-22 14:41:15 -07005827 if (memcg_online_kmem(memcg))
5828 goto remove_id;
5829
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005830 /*
Yang Shie4262c42021-05-04 18:36:23 -07005831 * A memcg must be visible for expand_shrinker_info()
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005832 * by the time the maps are allocated. So, we allocate maps
5833 * here, when for_each_mem_cgroup() can't skip it.
5834 */
Muchun Songda0efe32022-03-22 14:41:15 -07005835 if (alloc_shrinker_info(memcg))
5836 goto offline_kmem;
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005837
T.J. Mercier13ef7422024-01-26 21:19:25 +00005838 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
Shakeel Buttaa48e472021-09-02 14:55:04 -07005839 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
Miaohe Lin396faf82023-06-03 15:21:16 +08005840 FLUSH_TIME);
Yu Zhaoe4dde562022-12-21 21:19:04 -07005841 lru_gen_online_memcg(memcg);
Johannes Weiner6f0df8e2023-08-23 15:54:30 -07005842
5843 /* Online state pins memcg ID, memcg ID pins CSS */
5844 refcount_set(&memcg->id.ref, 1);
5845 css_get(css);
5846
5847 /*
5848 * Ensure mem_cgroup_from_id() works once we're fully online.
5849 *
5850 * We could do this earlier and require callers to filter with
5851 * css_tryget_online(). But right now there are no users that
5852 * need earlier access, and the workingset code relies on the
5853 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
5854 * publish it here at the end of onlining. This matches the
5855 * regular ID destruction during offlining.
5856 */
5857 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5858
Johannes Weiner2f7dd7a2014-10-02 16:16:57 -07005859 return 0;
Muchun Songda0efe32022-03-22 14:41:15 -07005860offline_kmem:
5861 memcg_offline_kmem(memcg);
5862remove_id:
5863 mem_cgroup_id_remove(memcg);
5864 return -ENOMEM;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005865}
5866
Tejun Heoeb954192013-08-08 20:11:23 -04005867static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005868{
Tejun Heoeb954192013-08-08 20:11:23 -04005869 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05005870 struct mem_cgroup_event *event, *tmp;
Tejun Heo79bd9812013-11-22 18:20:42 -05005871
5872 /*
5873 * Unregister events and notify userspace.
5874 * Notify userspace about cgroup removing only after rmdir of cgroup
5875 * directory to avoid race between userspace and kernelspace.
5876 */
Shakeel Butt4ba95152021-09-02 14:56:05 -07005877 spin_lock_irq(&memcg->event_list_lock);
Tejun Heofba94802013-11-22 18:20:43 -05005878 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
Tejun Heo79bd9812013-11-22 18:20:42 -05005879 list_del_init(&event->list);
5880 schedule_work(&event->remove);
5881 }
Shakeel Butt4ba95152021-09-02 14:56:05 -07005882 spin_unlock_irq(&memcg->event_list_lock);
KAMEZAWA Hiroyukiec64f512009-04-02 16:57:26 -07005883
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005884 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005885 page_counter_set_low(&memcg->memory, 0);
Roman Gushchin63677c742017-09-06 16:21:47 -07005886
Domenico Cerasuoloa65b0e72023-11-30 11:40:20 -08005887 zswap_memcg_offline_cleanup(memcg);
5888
Johannes Weiner567e9ab2016-01-20 15:02:24 -08005889 memcg_offline_kmem(memcg);
Yang Shia1780152021-05-04 18:36:42 -07005890 reparent_shrinker_deferred(memcg);
Tejun Heo52ebea72015-05-22 17:13:37 -04005891 wb_memcg_offline(memcg);
Yu Zhaoe4dde562022-12-21 21:19:04 -07005892 lru_gen_offline_memcg(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005893
Roman Gushchin591edfb2018-10-26 15:03:23 -07005894 drain_all_stock(memcg);
5895
Johannes Weiner73f576c2016-07-20 15:44:57 -07005896 mem_cgroup_id_put(memcg);
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005897}
5898
Vladimir Davydov6df38682015-12-29 14:54:10 -08005899static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5900{
5901 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5902
5903 invalidate_reclaim_iterators(memcg);
Yu Zhaoe4dde562022-12-21 21:19:04 -07005904 lru_gen_release_memcg(memcg);
Vladimir Davydov6df38682015-12-29 14:54:10 -08005905}
5906
Tejun Heoeb954192013-08-08 20:11:23 -04005907static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005908{
Tejun Heoeb954192013-08-08 20:11:23 -04005909 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo97b27822019-08-26 09:06:56 -07005910 int __maybe_unused i;
Daisuke Nishimurac268e992009-01-15 13:51:13 -08005911
Tejun Heo97b27822019-08-26 09:06:56 -07005912#ifdef CONFIG_CGROUP_WRITEBACK
5913 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5914 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5915#endif
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005916 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005917 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005918
Johannes Weiner0db15292016-01-20 15:02:50 -08005919 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08005920 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005921
Yafang Shaob6c1a8a2023-02-10 15:47:31 +00005922#if defined(CONFIG_MEMCG_KMEM)
5923 if (!cgroup_memory_nobpf)
5924 static_branch_dec(&memcg_bpf_enabled_key);
5925#endif
5926
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005927 vmpressure_cleanup(&memcg->vmpressure);
5928 cancel_work_sync(&memcg->high_work);
5929 mem_cgroup_remove_from_trees(memcg);
Yang Shie4262c42021-05-04 18:36:23 -07005930 free_shrinker_info(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005931 mem_cgroup_free(memcg);
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005932}
5933
Tejun Heo1ced953b2014-07-08 18:02:57 -04005934/**
5935 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5936 * @css: the target css
5937 *
5938 * Reset the states of the mem_cgroup associated with @css. This is
5939 * invoked when the userland requests disabling on the default hierarchy
5940 * but the memcg is pinned through dependency. The memcg should stop
5941 * applying policies and should revert to the vanilla state as it may be
5942 * made visible again.
5943 *
5944 * The current implementation only resets the essential configurations.
5945 * This needs to be expanded to cover all the visible parts.
5946 */
5947static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5948{
5949 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5950
Roman Gushchinbbec2e12018-06-07 17:06:18 -07005951 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5952 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07005953 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5954 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005955 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005956 page_counter_set_low(&memcg->memory, 0);
Jakub Kicinskid1663a92020-06-01 21:49:49 -07005957 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
Yue Zhao2178e202023-03-06 23:41:38 +08005958 WRITE_ONCE(memcg->soft_limit, PAGE_COUNTER_MAX);
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07005959 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
Tejun Heo2529bb32015-05-22 18:23:34 -04005960 memcg_wb_domain_size_changed(memcg);
Tejun Heo1ced953b2014-07-08 18:02:57 -04005961}
5962
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005963static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5964{
5965 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5966 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5967 struct memcg_vmstats_percpu *statc;
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00005968 long delta, delta_cpu, v;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07005969 int i, nid;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005970
5971 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5972
Shakeel Buttff48c712024-05-01 10:26:13 -07005973 for (i = 0; i < MEMCG_VMSTAT_SIZE; i++) {
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005974 /*
5975 * Collect the aggregated propagation counts of groups
5976 * below us. We're in a per-cpu loop here and this is
5977 * a global counter, so the first cycle will get them.
5978 */
Shakeel Butt410f8e82022-09-07 04:35:35 +00005979 delta = memcg->vmstats->state_pending[i];
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005980 if (delta)
Shakeel Butt410f8e82022-09-07 04:35:35 +00005981 memcg->vmstats->state_pending[i] = 0;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005982
5983 /* Add CPU changes on this level since the last flush */
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00005984 delta_cpu = 0;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005985 v = READ_ONCE(statc->state[i]);
5986 if (v != statc->state_prev[i]) {
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00005987 delta_cpu = v - statc->state_prev[i];
5988 delta += delta_cpu;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005989 statc->state_prev[i] = v;
5990 }
5991
Johannes Weiner2d146aa2021-04-29 22:56:26 -07005992 /* Aggregate counts on this level and propagate upwards */
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00005993 if (delta_cpu)
5994 memcg->vmstats->state_local[i] += delta_cpu;
5995
5996 if (delta) {
5997 memcg->vmstats->state[i] += delta;
5998 if (parent)
5999 parent->vmstats->state_pending[i] += delta;
6000 }
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006001 }
6002
Shakeel Butt8278f1c2022-09-07 04:35:37 +00006003 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
Shakeel Butt410f8e82022-09-07 04:35:35 +00006004 delta = memcg->vmstats->events_pending[i];
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006005 if (delta)
Shakeel Butt410f8e82022-09-07 04:35:35 +00006006 memcg->vmstats->events_pending[i] = 0;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006007
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006008 delta_cpu = 0;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006009 v = READ_ONCE(statc->events[i]);
6010 if (v != statc->events_prev[i]) {
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006011 delta_cpu = v - statc->events_prev[i];
6012 delta += delta_cpu;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006013 statc->events_prev[i] = v;
6014 }
6015
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006016 if (delta_cpu)
6017 memcg->vmstats->events_local[i] += delta_cpu;
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006018
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006019 if (delta) {
6020 memcg->vmstats->events[i] += delta;
6021 if (parent)
6022 parent->vmstats->events_pending[i] += delta;
6023 }
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006024 }
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006025
6026 for_each_node_state(nid, N_MEMORY) {
6027 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
Shakeel Butt70a64b72024-05-01 10:26:11 -07006028 struct lruvec_stats *lstats = pn->lruvec_stats;
6029 struct lruvec_stats *plstats = NULL;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006030 struct lruvec_stats_percpu *lstatc;
6031
6032 if (parent)
Shakeel Butt70a64b72024-05-01 10:26:11 -07006033 plstats = parent->nodeinfo[nid]->lruvec_stats;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006034
6035 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
6036
Shakeel Buttff48c712024-05-01 10:26:13 -07006037 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; i++) {
Shakeel Butt70a64b72024-05-01 10:26:11 -07006038 delta = lstats->state_pending[i];
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006039 if (delta)
Shakeel Butt70a64b72024-05-01 10:26:11 -07006040 lstats->state_pending[i] = 0;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006041
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006042 delta_cpu = 0;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006043 v = READ_ONCE(lstatc->state[i]);
6044 if (v != lstatc->state_prev[i]) {
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006045 delta_cpu = v - lstatc->state_prev[i];
6046 delta += delta_cpu;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006047 lstatc->state_prev[i] = v;
6048 }
6049
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006050 if (delta_cpu)
Shakeel Butt70a64b72024-05-01 10:26:11 -07006051 lstats->state_local[i] += delta_cpu;
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006052
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006053 if (delta) {
Shakeel Butt70a64b72024-05-01 10:26:11 -07006054 lstats->state[i] += delta;
6055 if (plstats)
6056 plstats->state_pending[i] += delta;
Yosry Ahmedf82e6bf2023-07-26 15:32:23 +00006057 }
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07006058 }
6059 }
Breno Leitao78ec6f92024-04-24 05:59:39 -07006060 WRITE_ONCE(statc->stats_updates, 0);
Yosry Ahmed8d59d222023-11-29 03:21:51 +00006061 /* We are in a per-cpu loop here, only do the atomic write once */
6062 if (atomic64_read(&memcg->vmstats->stats_updates))
6063 atomic64_set(&memcg->vmstats->stats_updates, 0);
Johannes Weiner2d146aa2021-04-29 22:56:26 -07006064}
6065
Daisuke Nishimura02491442010-03-10 15:22:17 -08006066#ifdef CONFIG_MMU
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006067/* Handlers for move charge at task migration. */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006068static int mem_cgroup_do_precharge(unsigned long count)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006069{
Johannes Weiner05b84302014-08-06 16:05:59 -07006070 int ret;
Johannes Weiner9476db92014-08-06 16:05:55 -07006071
Mel Gormand0164ad2015-11-06 16:28:21 -08006072 /* Try a single bulk charge without reclaim first, kswapd may wake */
6073 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
Johannes Weiner9476db92014-08-06 16:05:55 -07006074 if (!ret) {
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006075 mc.precharge += count;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006076 return ret;
6077 }
Johannes Weiner9476db92014-08-06 16:05:55 -07006078
David Rientjes36745342017-01-24 15:18:10 -08006079 /* Try charges one by one with reclaim, but do not retry */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006080 while (count--) {
David Rientjes36745342017-01-24 15:18:10 -08006081 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08006082 if (ret)
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08006083 return ret;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006084 mc.precharge++;
Johannes Weiner9476db92014-08-06 16:05:55 -07006085 cond_resched();
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006086 }
Johannes Weiner9476db92014-08-06 16:05:55 -07006087 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006088}
6089
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006090union mc_target {
Matthew Wilcox (Oracle)b46777d2024-01-11 18:12:17 +00006091 struct folio *folio;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006092 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006093};
6094
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006095enum mc_target_type {
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006096 MC_TARGET_NONE = 0,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006097 MC_TARGET_PAGE,
Daisuke Nishimura02491442010-03-10 15:22:17 -08006098 MC_TARGET_SWAP,
Jérôme Glissec733a822017-09-08 16:11:54 -07006099 MC_TARGET_DEVICE,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006100};
6101
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006102static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6103 unsigned long addr, pte_t ptent)
6104{
Christoph Hellwig25b29952019-06-13 22:50:49 +02006105 struct page *page = vm_normal_page(vma, addr, ptent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006106
Miaohe Lin58f341f2023-07-17 19:36:44 +08006107 if (!page)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006108 return NULL;
6109 if (PageAnon(page)) {
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006110 if (!(mc.flags & MOVE_ANON))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006111 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006112 } else {
6113 if (!(mc.flags & MOVE_FILE))
6114 return NULL;
6115 }
Miaohe Lin58f341f2023-07-17 19:36:44 +08006116 get_page(page);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006117
6118 return page;
6119}
6120
Jérôme Glissec733a822017-09-08 16:11:54 -07006121#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006122static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07006123 pte_t ptent, swp_entry_t *entry)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006124{
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006125 struct page *page = NULL;
6126 swp_entry_t ent = pte_to_swp_entry(ptent);
6127
Ralph Campbell9a137152020-10-13 16:53:13 -07006128 if (!(mc.flags & MOVE_ANON))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006129 return NULL;
Jérôme Glissec733a822017-09-08 16:11:54 -07006130
6131 /*
Christoph Hellwig27674ef2022-02-16 15:31:36 +11006132 * Handle device private pages that are not accessible by the CPU, but
6133 * stored as special swap entries in the page table.
Jérôme Glissec733a822017-09-08 16:11:54 -07006134 */
6135 if (is_device_private_entry(ent)) {
Alistair Poppleaf5cdaf2021-06-30 18:54:06 -07006136 page = pfn_swap_entry_to_page(ent);
Christoph Hellwig27674ef2022-02-16 15:31:36 +11006137 if (!get_page_unless_zero(page))
Jérôme Glissec733a822017-09-08 16:11:54 -07006138 return NULL;
6139 return page;
6140 }
6141
Ralph Campbell9a137152020-10-13 16:53:13 -07006142 if (non_swap_entry(ent))
6143 return NULL;
6144
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07006145 /*
Matthew Wilcox (Oracle)cb691e22022-09-02 20:46:34 +01006146 * Because swap_cache_get_folio() updates some statistics counter,
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07006147 * we call find_get_page() with swapper_space directly.
6148 */
Kairui Song7aad25b2024-05-22 01:58:53 +08006149 page = find_get_page(swap_address_space(ent), swap_cache_index(ent));
Johannes Weiner2d1c4982020-06-03 16:02:14 -07006150 entry->val = ent.val;
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006151
6152 return page;
6153}
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07006154#else
6155static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07006156 pte_t ptent, swp_entry_t *entry)
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07006157{
6158 return NULL;
6159}
6160#endif
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006161
Daisuke Nishimura87946a72010-05-26 14:42:39 -07006162static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
Peter Xu48384b02021-11-05 13:37:28 -07006163 unsigned long addr, pte_t ptent)
Daisuke Nishimura87946a72010-05-26 14:42:39 -07006164{
Matthew Wilcox (Oracle)524984f2022-10-19 19:33:31 +01006165 unsigned long index;
6166 struct folio *folio;
6167
Daisuke Nishimura87946a72010-05-26 14:42:39 -07006168 if (!vma->vm_file) /* anonymous vma */
6169 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006170 if (!(mc.flags & MOVE_FILE))
Daisuke Nishimura87946a72010-05-26 14:42:39 -07006171 return NULL;
6172
Matthew Wilcox (Oracle)524984f2022-10-19 19:33:31 +01006173 /* folio is moved even if it's not RSS of this task(page-faulted). */
Hugh Dickinsaa3b1892011-08-03 16:21:24 -07006174 /* shmem/tmpfs may report page out on swap: account for that too. */
Matthew Wilcox (Oracle)524984f2022-10-19 19:33:31 +01006175 index = linear_page_index(vma, addr);
6176 folio = filemap_get_incore_folio(vma->vm_file->f_mapping, index);
Christoph Hellwig66dabbb2023-03-07 15:34:10 +01006177 if (IS_ERR(folio))
Matthew Wilcox (Oracle)524984f2022-10-19 19:33:31 +01006178 return NULL;
6179 return folio_file_page(folio, index);
Daisuke Nishimura87946a72010-05-26 14:42:39 -07006180}
6181
Chen Gangb1b0dea2015-04-14 15:47:35 -07006182/**
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006183 * mem_cgroup_move_account - move account of the folio
6184 * @folio: The folio.
Li RongQing25843c22016-07-26 15:26:56 -07006185 * @compound: charge the page as compound or small page
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006186 * @from: mem_cgroup which the folio is moved from.
6187 * @to: mem_cgroup which the folio is moved to. @from != @to.
Chen Gangb1b0dea2015-04-14 15:47:35 -07006188 *
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006189 * The folio must be locked and not on the LRU.
Chen Gangb1b0dea2015-04-14 15:47:35 -07006190 *
6191 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
6192 * from old cgroup.
6193 */
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006194static int mem_cgroup_move_account(struct folio *folio,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006195 bool compound,
Chen Gangb1b0dea2015-04-14 15:47:35 -07006196 struct mem_cgroup *from,
6197 struct mem_cgroup *to)
6198{
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07006199 struct lruvec *from_vec, *to_vec;
6200 struct pglist_data *pgdat;
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006201 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04006202 int nid, ret;
Chen Gangb1b0dea2015-04-14 15:47:35 -07006203
6204 VM_BUG_ON(from == to);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006205 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006206 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
Matthew Wilcox (Oracle)9c325212021-11-16 21:17:14 -05006207 VM_BUG_ON(compound && !folio_test_large(folio));
Chen Gangb1b0dea2015-04-14 15:47:35 -07006208
Chen Gangb1b0dea2015-04-14 15:47:35 -07006209 ret = -EINVAL;
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006210 if (folio_memcg(folio) != from)
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006211 goto out;
Chen Gangb1b0dea2015-04-14 15:47:35 -07006212
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006213 pgdat = folio_pgdat(folio);
Johannes Weiner867e5e12019-11-30 17:55:34 -08006214 from_vec = mem_cgroup_lruvec(from, pgdat);
6215 to_vec = mem_cgroup_lruvec(to, pgdat);
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07006216
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006217 folio_memcg_lock(folio);
Chen Gangb1b0dea2015-04-14 15:47:35 -07006218
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006219 if (folio_test_anon(folio)) {
6220 if (folio_mapped(folio)) {
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07006221 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
6222 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
Matthew Wilcox (Oracle)61992772023-08-16 16:11:59 +01006223 if (folio_test_pmd_mappable(folio)) {
Muchun Song69473e52021-02-24 12:03:23 -08006224 __mod_lruvec_state(from_vec, NR_ANON_THPS,
6225 -nr_pages);
6226 __mod_lruvec_state(to_vec, NR_ANON_THPS,
6227 nr_pages);
Johannes Weiner468c3982020-06-03 16:02:01 -07006228 }
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07006229 }
6230 } else {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07006231 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
6232 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
6233
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006234 if (folio_test_swapbacked(folio)) {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07006235 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
6236 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
6237 }
6238
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006239 if (folio_mapped(folio)) {
Johannes Weiner49e50d22020-06-03 16:01:47 -07006240 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
6241 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
6242 }
Chen Gangb1b0dea2015-04-14 15:47:35 -07006243
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006244 if (folio_test_dirty(folio)) {
6245 struct address_space *mapping = folio_mapping(folio);
Greg Thelenc4843a72015-05-22 17:13:16 -04006246
Christoph Hellwigf56753a2020-09-24 08:51:40 +02006247 if (mapping_can_writeback(mapping)) {
Johannes Weiner49e50d22020-06-03 16:01:47 -07006248 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
6249 -nr_pages);
6250 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
6251 nr_pages);
6252 }
Greg Thelenc4843a72015-05-22 17:13:16 -04006253 }
6254 }
6255
Hugh Dickinsc449deb2022-12-04 17:01:03 -08006256#ifdef CONFIG_SWAP
6257 if (folio_test_swapcache(folio)) {
6258 __mod_lruvec_state(from_vec, NR_SWAPCACHE, -nr_pages);
6259 __mod_lruvec_state(to_vec, NR_SWAPCACHE, nr_pages);
6260 }
6261#endif
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006262 if (folio_test_writeback(folio)) {
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07006263 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
6264 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07006265 }
6266
6267 /*
Johannes Weinerabb242f2020-06-03 16:01:28 -07006268 * All state has been migrated, let's switch to the new memcg.
6269 *
Roman Gushchinbcfe06b2020-12-01 13:58:27 -08006270 * It is safe to change page's memcg here because the page
Johannes Weinerabb242f2020-06-03 16:01:28 -07006271 * is referenced, charged, isolated, and locked: we can't race
6272 * with (un)charging, migration, LRU putback, or anything else
Roman Gushchinbcfe06b2020-12-01 13:58:27 -08006273 * that would rely on a stable page's memory cgroup.
Johannes Weinerabb242f2020-06-03 16:01:28 -07006274 *
Kefeng Wang6c77b602023-06-14 22:36:12 +08006275 * Note that folio_memcg_lock is a memcg lock, not a page lock,
Roman Gushchinbcfe06b2020-12-01 13:58:27 -08006276 * to save space. As soon as we switch page's memory cgroup to a
Johannes Weinerabb242f2020-06-03 16:01:28 -07006277 * new memcg that isn't locked, the above state can change
6278 * concurrently again. Make sure we're truly done with it.
Chen Gangb1b0dea2015-04-14 15:47:35 -07006279 */
Johannes Weinerabb242f2020-06-03 16:01:28 -07006280 smp_mb();
Chen Gangb1b0dea2015-04-14 15:47:35 -07006281
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07006282 css_get(&to->css);
6283 css_put(&from->css);
6284
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006285 folio->memcg_data = (unsigned long)to;
Yang Shi87eaceb2019-09-23 15:38:15 -07006286
Matthew Wilcox (Oracle)f70ad442021-06-28 17:26:00 -04006287 __folio_memcg_unlock(from);
Chen Gangb1b0dea2015-04-14 15:47:35 -07006288
6289 ret = 0;
Matthew Wilcox (Oracle)fcce4672021-03-01 16:34:06 -05006290 nid = folio_nid(folio);
Chen Gangb1b0dea2015-04-14 15:47:35 -07006291
6292 local_irq_disable();
Matthew Wilcox (Oracle)6e0110c2021-04-29 13:40:11 -04006293 mem_cgroup_charge_statistics(to, nr_pages);
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04006294 memcg_check_events(to, nid);
Matthew Wilcox (Oracle)6e0110c2021-04-29 13:40:11 -04006295 mem_cgroup_charge_statistics(from, -nr_pages);
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04006296 memcg_check_events(from, nid);
Chen Gangb1b0dea2015-04-14 15:47:35 -07006297 local_irq_enable();
Chen Gangb1b0dea2015-04-14 15:47:35 -07006298out:
6299 return ret;
6300}
6301
Li RongQing7cf78062016-05-27 14:27:46 -07006302/**
6303 * get_mctgt_type - get target type of moving charge
6304 * @vma: the vma the pte to be checked belongs
6305 * @addr: the address corresponding to the pte to be checked
6306 * @ptent: the pte to be checked
6307 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6308 *
Matthew Wilcox (Oracle)853f62a2023-08-18 21:06:28 +01006309 * Context: Called with pte lock held.
6310 * Return:
6311 * * MC_TARGET_NONE - If the pte is not a target for move charge.
6312 * * MC_TARGET_PAGE - If the page corresponding to this pte is a target for
Matthew Wilcox (Oracle)b46777d2024-01-11 18:12:17 +00006313 * move charge. If @target is not NULL, the folio is stored in target->folio
Matthew Wilcox (Oracle)853f62a2023-08-18 21:06:28 +01006314 * with extra refcnt taken (Caller should release it).
6315 * * MC_TARGET_SWAP - If the swap entry corresponding to this pte is a
6316 * target for charge migration. If @target is not NULL, the entry is
6317 * stored in target->ent.
6318 * * MC_TARGET_DEVICE - Like MC_TARGET_PAGE but page is device memory and
6319 * thus not on the lru. For now such page is charged like a regular page
6320 * would be as it is just special memory taking the place of a regular page.
6321 * See Documentations/vm/hmm.txt and include/linux/hmm.h
Li RongQing7cf78062016-05-27 14:27:46 -07006322 */
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006323static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006324 unsigned long addr, pte_t ptent, union mc_target *target)
6325{
Daisuke Nishimura02491442010-03-10 15:22:17 -08006326 struct page *page = NULL;
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006327 struct folio *folio;
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006328 enum mc_target_type ret = MC_TARGET_NONE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006329 swp_entry_t ent = { .val = 0 };
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006330
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006331 if (pte_present(ptent))
6332 page = mc_handle_present_pte(vma, addr, ptent);
Peter Xu5c041f52022-05-12 20:22:52 -07006333 else if (pte_none_mostly(ptent))
6334 /*
6335 * PTE markers should be treated as a none pte here, separated
6336 * from other swap handling below.
6337 */
6338 page = mc_handle_file_pte(vma, addr, ptent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006339 else if (is_swap_pte(ptent))
Li RongQing48406ef2016-07-26 15:22:14 -07006340 page = mc_handle_swap_pte(vma, ptent, &ent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006341
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006342 if (page)
6343 folio = page_folio(page);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006344 if (target && page) {
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006345 if (!folio_trylock(folio)) {
6346 folio_put(folio);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006347 return ret;
6348 }
6349 /*
6350 * page_mapped() must be stable during the move. This
6351 * pte is locked, so if it's present, the page cannot
6352 * become unmapped. If it isn't, we have only partial
6353 * control over the mapped state: the page lock will
6354 * prevent new faults against pagecache and swapcache,
6355 * so an unmapped page cannot become mapped. However,
6356 * if the page is already mapped elsewhere, it can
6357 * unmap, and there is nothing we can do about it.
6358 * Alas, skip moving the page in this case.
6359 */
6360 if (!pte_present(ptent) && page_mapped(page)) {
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006361 folio_unlock(folio);
6362 folio_put(folio);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006363 return ret;
6364 }
6365 }
6366
Daisuke Nishimura90254a62010-05-26 14:42:38 -07006367 if (!page && !ent.val)
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006368 return ret;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006369 if (page) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08006370 /*
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006371 * Do only loose check w/o serialization.
Johannes Weiner1306a852014-12-10 15:44:52 -08006372 * mem_cgroup_move_account() checks the page is valid or
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006373 * not under LRU exclusion.
Daisuke Nishimura02491442010-03-10 15:22:17 -08006374 */
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006375 if (folio_memcg(folio) == mc.from) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08006376 ret = MC_TARGET_PAGE;
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006377 if (folio_is_device_private(folio) ||
6378 folio_is_device_coherent(folio))
Jérôme Glissec733a822017-09-08 16:11:54 -07006379 ret = MC_TARGET_DEVICE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006380 if (target)
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006381 target->folio = folio;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006382 }
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006383 if (!ret || !target) {
6384 if (target)
Matthew Wilcox (Oracle)b67fa6e2024-01-11 18:12:18 +00006385 folio_unlock(folio);
6386 folio_put(folio);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006387 }
Daisuke Nishimura02491442010-03-10 15:22:17 -08006388 }
Huang Ying3e14a572017-09-06 16:22:37 -07006389 /*
6390 * There is a swap entry and a page doesn't exist or isn't charged.
6391 * But we cannot move a tail-page in a THP.
6392 */
6393 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
Li Zefan34c00c32013-09-23 16:56:01 +08006394 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
KAMEZAWA Hiroyuki7f0f1542010-05-11 14:06:58 -07006395 ret = MC_TARGET_SWAP;
6396 if (target)
6397 target->ent = ent;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006398 }
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006399 return ret;
6400}
6401
Naoya Horiguchi12724852012-03-21 16:34:28 -07006402#ifdef CONFIG_TRANSPARENT_HUGEPAGE
6403/*
Huang Yingd6810d732017-09-06 16:22:45 -07006404 * We don't consider PMD mapped swapping or file mapped pages because THP does
6405 * not support them for now.
Naoya Horiguchi12724852012-03-21 16:34:28 -07006406 * Caller should make sure that pmd_trans_huge(pmd) is true.
6407 */
6408static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6409 unsigned long addr, pmd_t pmd, union mc_target *target)
6410{
6411 struct page *page = NULL;
Matthew Wilcox (Oracle)f6c75902024-01-11 18:12:19 +00006412 struct folio *folio;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006413 enum mc_target_type ret = MC_TARGET_NONE;
6414
Zi Yan84c3fc42017-09-08 16:11:01 -07006415 if (unlikely(is_swap_pmd(pmd))) {
6416 VM_BUG_ON(thp_migration_supported() &&
6417 !is_pmd_migration_entry(pmd));
6418 return ret;
6419 }
Naoya Horiguchi12724852012-03-21 16:34:28 -07006420 page = pmd_page(pmd);
Sasha Levin309381fea2014-01-23 15:52:54 -08006421 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
Matthew Wilcox (Oracle)f6c75902024-01-11 18:12:19 +00006422 folio = page_folio(page);
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006423 if (!(mc.flags & MOVE_ANON))
Naoya Horiguchi12724852012-03-21 16:34:28 -07006424 return ret;
Matthew Wilcox (Oracle)f6c75902024-01-11 18:12:19 +00006425 if (folio_memcg(folio) == mc.from) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07006426 ret = MC_TARGET_PAGE;
6427 if (target) {
Matthew Wilcox (Oracle)f6c75902024-01-11 18:12:19 +00006428 folio_get(folio);
6429 if (!folio_trylock(folio)) {
6430 folio_put(folio);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006431 return MC_TARGET_NONE;
6432 }
Matthew Wilcox (Oracle)f6c75902024-01-11 18:12:19 +00006433 target->folio = folio;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006434 }
6435 }
6436 return ret;
6437}
6438#else
6439static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6440 unsigned long addr, pmd_t pmd, union mc_target *target)
6441{
6442 return MC_TARGET_NONE;
6443}
6444#endif
6445
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006446static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6447 unsigned long addr, unsigned long end,
6448 struct mm_walk *walk)
6449{
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08006450 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006451 pte_t *pte;
6452 spinlock_t *ptl;
6453
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08006454 ptl = pmd_trans_huge_lock(pmd, vma);
6455 if (ptl) {
Jérôme Glissec733a822017-09-08 16:11:54 -07006456 /*
6457 * Note their can not be MC_TARGET_DEVICE for now as we do not
Christoph Hellwig25b29952019-06-13 22:50:49 +02006458 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
6459 * this might change.
Jérôme Glissec733a822017-09-08 16:11:54 -07006460 */
Naoya Horiguchi12724852012-03-21 16:34:28 -07006461 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6462 mc.precharge += HPAGE_PMD_NR;
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08006463 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07006464 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006465 }
Dave Hansen03319322011-03-22 16:32:56 -07006466
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006467 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
Hugh Dickins04dee9e2023-06-08 18:29:22 -07006468 if (!pte)
6469 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006470 for (; addr != end; pte++, addr += PAGE_SIZE)
Ryan Robertsc33c7942023-06-12 16:15:45 +01006471 if (get_mctgt_type(vma, addr, ptep_get(pte), NULL))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006472 mc.precharge++; /* increment precharge temporarily */
6473 pte_unmap_unlock(pte - 1, ptl);
6474 cond_resched();
6475
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006476 return 0;
6477}
6478
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006479static const struct mm_walk_ops precharge_walk_ops = {
6480 .pmd_entry = mem_cgroup_count_precharge_pte_range,
Suren Baghdasaryan49b06382023-08-04 08:27:19 -07006481 .walk_lock = PGWALK_RDLOCK,
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006482};
6483
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006484static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6485{
6486 unsigned long precharge;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006487
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006488 mmap_read_lock(mm);
Liam R. Howlettba0aff82022-09-06 19:49:01 +00006489 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006490 mmap_read_unlock(mm);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006491
6492 precharge = mc.precharge;
6493 mc.precharge = 0;
6494
6495 return precharge;
6496}
6497
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006498static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6499{
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006500 unsigned long precharge = mem_cgroup_count_precharge(mm);
6501
6502 VM_BUG_ON(mc.moving_task);
6503 mc.moving_task = current;
6504 return mem_cgroup_do_precharge(precharge);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006505}
6506
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006507/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6508static void __mem_cgroup_clear_mc(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006509{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07006510 struct mem_cgroup *from = mc.from;
6511 struct mem_cgroup *to = mc.to;
6512
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006513 /* we must uncharge all the leftover precharges from mc.to */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006514 if (mc.precharge) {
Nhat Pham4b569382023-10-06 11:46:26 -07006515 mem_cgroup_cancel_charge(mc.to, mc.precharge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006516 mc.precharge = 0;
6517 }
6518 /*
6519 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6520 * we must uncharge here.
6521 */
6522 if (mc.moved_charge) {
Nhat Pham4b569382023-10-06 11:46:26 -07006523 mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006524 mc.moved_charge = 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006525 }
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006526 /* we must fixup refcnts and charges */
6527 if (mc.moved_swap) {
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006528 /* uncharge swap account from the old cgroup */
Johannes Weinerce00a962014-09-05 08:43:57 -04006529 if (!mem_cgroup_is_root(mc.from))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08006530 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006531
Vladimir Davydov615d66c2016-08-11 15:33:03 -07006532 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6533
Johannes Weiner05b84302014-08-06 16:05:59 -07006534 /*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08006535 * we charged both to->memory and to->memsw, so we
6536 * should uncharge to->memory.
Johannes Weiner05b84302014-08-06 16:05:59 -07006537 */
Johannes Weinerce00a962014-09-05 08:43:57 -04006538 if (!mem_cgroup_is_root(mc.to))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08006539 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006540
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006541 mc.moved_swap = 0;
6542 }
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006543 memcg_oom_recover(from);
6544 memcg_oom_recover(to);
6545 wake_up_all(&mc.waitq);
6546}
6547
6548static void mem_cgroup_clear_mc(void)
6549{
Tejun Heo264a0ae2016-04-21 19:09:02 -04006550 struct mm_struct *mm = mc.mm;
6551
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006552 /*
6553 * we must clear moving_task before waking up waiters at the end of
6554 * task migration.
6555 */
6556 mc.moving_task = NULL;
6557 __mem_cgroup_clear_mc();
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07006558 spin_lock(&mc.lock);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006559 mc.from = NULL;
6560 mc.to = NULL;
Tejun Heo264a0ae2016-04-21 19:09:02 -04006561 mc.mm = NULL;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07006562 spin_unlock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04006563
6564 mmput(mm);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006565}
6566
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006567static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006568{
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006569 struct cgroup_subsys_state *css;
Ross Zwislereed67d72015-12-23 14:53:27 -07006570 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
Tejun Heo9f2115f2015-09-08 15:01:10 -07006571 struct mem_cgroup *from;
Tejun Heo4530edd2015-09-11 15:00:19 -04006572 struct task_struct *leader, *p;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006573 struct mm_struct *mm;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006574 unsigned long move_flags;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006575 int ret = 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006576
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006577 /* charge immigration isn't supported on the default hierarchy */
6578 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo9f2115f2015-09-08 15:01:10 -07006579 return 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006580
Tejun Heo4530edd2015-09-11 15:00:19 -04006581 /*
6582 * Multi-process migrations only happen on the default hierarchy
6583 * where charge immigration is not used. Perform charge
6584 * immigration if @tset contains a leader and whine if there are
6585 * multiple.
6586 */
6587 p = NULL;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006588 cgroup_taskset_for_each_leader(leader, css, tset) {
Tejun Heo4530edd2015-09-11 15:00:19 -04006589 WARN_ON_ONCE(p);
6590 p = leader;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006591 memcg = mem_cgroup_from_css(css);
Tejun Heo4530edd2015-09-11 15:00:19 -04006592 }
6593 if (!p)
6594 return 0;
6595
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006596 /*
Ingo Molnarf0953a12021-05-06 18:06:47 -07006597 * We are now committed to this value whatever it is. Changes in this
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006598 * tunable will only affect upcoming migrations, not the current one.
6599 * So we need to save it, and keep it going.
6600 */
6601 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6602 if (!move_flags)
6603 return 0;
6604
Tejun Heo9f2115f2015-09-08 15:01:10 -07006605 from = mem_cgroup_from_task(p);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006606
Tejun Heo9f2115f2015-09-08 15:01:10 -07006607 VM_BUG_ON(from == memcg);
Johannes Weiner247b1442014-12-10 15:44:11 -08006608
Tejun Heo9f2115f2015-09-08 15:01:10 -07006609 mm = get_task_mm(p);
6610 if (!mm)
6611 return 0;
6612 /* We move charges only when we move a owner of the mm */
6613 if (mm->owner == p) {
6614 VM_BUG_ON(mc.from);
6615 VM_BUG_ON(mc.to);
6616 VM_BUG_ON(mc.precharge);
6617 VM_BUG_ON(mc.moved_charge);
6618 VM_BUG_ON(mc.moved_swap);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006619
Tejun Heo9f2115f2015-09-08 15:01:10 -07006620 spin_lock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04006621 mc.mm = mm;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006622 mc.from = from;
6623 mc.to = memcg;
6624 mc.flags = move_flags;
6625 spin_unlock(&mc.lock);
6626 /* We set mc.moving_task later */
6627
6628 ret = mem_cgroup_precharge_mc(mm);
6629 if (ret)
6630 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04006631 } else {
6632 mmput(mm);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006633 }
6634 return ret;
6635}
6636
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006637static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006638{
Johannes Weiner4e2f2452014-12-10 15:44:08 -08006639 if (mc.to)
6640 mem_cgroup_clear_mc();
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006641}
6642
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006643static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6644 unsigned long addr, unsigned long end,
6645 struct mm_walk *walk)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006646{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006647 int ret = 0;
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08006648 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006649 pte_t *pte;
6650 spinlock_t *ptl;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006651 enum mc_target_type target_type;
6652 union mc_target target;
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006653 struct folio *folio;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006654
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08006655 ptl = pmd_trans_huge_lock(pmd, vma);
6656 if (ptl) {
Hugh Dickins62ade862012-05-18 11:28:34 -07006657 if (mc.precharge < HPAGE_PMD_NR) {
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08006658 spin_unlock(ptl);
Naoya Horiguchi12724852012-03-21 16:34:28 -07006659 return 0;
6660 }
6661 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6662 if (target_type == MC_TARGET_PAGE) {
Matthew Wilcox (Oracle)b46777d2024-01-11 18:12:17 +00006663 folio = target.folio;
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006664 if (folio_isolate_lru(folio)) {
6665 if (!mem_cgroup_move_account(folio, true,
Johannes Weiner1306a852014-12-10 15:44:52 -08006666 mc.from, mc.to)) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07006667 mc.precharge -= HPAGE_PMD_NR;
6668 mc.moved_charge += HPAGE_PMD_NR;
6669 }
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006670 folio_putback_lru(folio);
Naoya Horiguchi12724852012-03-21 16:34:28 -07006671 }
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006672 folio_unlock(folio);
6673 folio_put(folio);
Jérôme Glissec733a822017-09-08 16:11:54 -07006674 } else if (target_type == MC_TARGET_DEVICE) {
Matthew Wilcox (Oracle)b46777d2024-01-11 18:12:17 +00006675 folio = target.folio;
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006676 if (!mem_cgroup_move_account(folio, true,
Jérôme Glissec733a822017-09-08 16:11:54 -07006677 mc.from, mc.to)) {
6678 mc.precharge -= HPAGE_PMD_NR;
6679 mc.moved_charge += HPAGE_PMD_NR;
6680 }
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006681 folio_unlock(folio);
6682 folio_put(folio);
Naoya Horiguchi12724852012-03-21 16:34:28 -07006683 }
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08006684 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07006685 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006686 }
6687
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006688retry:
6689 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
Hugh Dickins04dee9e2023-06-08 18:29:22 -07006690 if (!pte)
6691 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006692 for (; addr != end; addr += PAGE_SIZE) {
Ryan Robertsc33c7942023-06-12 16:15:45 +01006693 pte_t ptent = ptep_get(pte++);
Jérôme Glissec733a822017-09-08 16:11:54 -07006694 bool device = false;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006695 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006696
6697 if (!mc.precharge)
6698 break;
6699
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006700 switch (get_mctgt_type(vma, addr, ptent, &target)) {
Jérôme Glissec733a822017-09-08 16:11:54 -07006701 case MC_TARGET_DEVICE:
6702 device = true;
Joe Perchese4a9bc52020-04-06 20:08:39 -07006703 fallthrough;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006704 case MC_TARGET_PAGE:
Matthew Wilcox (Oracle)b46777d2024-01-11 18:12:17 +00006705 folio = target.folio;
Kirill A. Shutemov53f92632016-01-15 16:53:42 -08006706 /*
6707 * We can have a part of the split pmd here. Moving it
6708 * can be done but it would be too convoluted so simply
6709 * ignore such a partial THP and keep it in original
6710 * memcg. There should be somebody mapping the head.
6711 */
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006712 if (folio_test_large(folio))
Kirill A. Shutemov53f92632016-01-15 16:53:42 -08006713 goto put;
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006714 if (!device && !folio_isolate_lru(folio))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006715 goto put;
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006716 if (!mem_cgroup_move_account(folio, false,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006717 mc.from, mc.to)) {
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006718 mc.precharge--;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006719 /* we uncharge from mc.from later. */
6720 mc.moved_charge++;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006721 }
Jérôme Glissec733a822017-09-08 16:11:54 -07006722 if (!device)
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006723 folio_putback_lru(folio);
Johannes Weiner4e0cf052022-12-06 18:13:39 +01006724put: /* get_mctgt_type() gets & locks the page */
Matthew Wilcox (Oracle)b267e1a2024-01-11 18:12:16 +00006725 folio_unlock(folio);
6726 folio_put(folio);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006727 break;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006728 case MC_TARGET_SWAP:
6729 ent = target.ent;
Hugh Dickinse91cbb42012-05-29 15:06:51 -07006730 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08006731 mc.precharge--;
Hugh Dickins8d22a932020-07-23 21:15:24 -07006732 mem_cgroup_id_get_many(mc.to, 1);
6733 /* we fixup other refcnts and charges later. */
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006734 mc.moved_swap++;
6735 }
Daisuke Nishimura02491442010-03-10 15:22:17 -08006736 break;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006737 default:
6738 break;
6739 }
6740 }
6741 pte_unmap_unlock(pte - 1, ptl);
6742 cond_resched();
6743
6744 if (addr != end) {
6745 /*
6746 * We have consumed all precharges we got in can_attach().
6747 * We try charge one by one, but don't do any additional
6748 * charges to mc.to if we have failed in charge once in attach()
6749 * phase.
6750 */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006751 ret = mem_cgroup_do_precharge(1);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006752 if (!ret)
6753 goto retry;
6754 }
6755
6756 return ret;
6757}
6758
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006759static const struct mm_walk_ops charge_walk_ops = {
6760 .pmd_entry = mem_cgroup_move_charge_pte_range,
Suren Baghdasaryan49b06382023-08-04 08:27:19 -07006761 .walk_lock = PGWALK_RDLOCK,
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006762};
6763
Tejun Heo264a0ae2016-04-21 19:09:02 -04006764static void mem_cgroup_move_charge(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006765{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006766 lru_add_drain_all();
Johannes Weiner312722c2014-12-10 15:44:25 -08006767 /*
Kefeng Wang6c77b602023-06-14 22:36:12 +08006768 * Signal folio_memcg_lock() to take the memcg's move_lock
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07006769 * while we're moving its pages to another memcg. Then wait
6770 * for already started RCU-only updates to finish.
Johannes Weiner312722c2014-12-10 15:44:25 -08006771 */
6772 atomic_inc(&mc.from->moving_account);
6773 synchronize_rcu();
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006774retry:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006775 if (unlikely(!mmap_read_trylock(mc.mm))) {
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006776 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07006777 * Someone who are holding the mmap_lock might be waiting in
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006778 * waitq. So we cancel all extra charges, wake up all waiters,
6779 * and retry. Because we cancel precharges, we might not be able
6780 * to move enough charges, but moving charge is a best-effort
6781 * feature anyway, so it wouldn't be a big problem.
6782 */
6783 __mem_cgroup_clear_mc();
6784 cond_resched();
6785 goto retry;
6786 }
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08006787 /*
6788 * When we have consumed all precharges and failed in doing
6789 * additional charge, the page walk just aborts.
6790 */
Liam R. Howlettba0aff82022-09-06 19:49:01 +00006791 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006792 mmap_read_unlock(mc.mm);
Johannes Weiner312722c2014-12-10 15:44:25 -08006793 atomic_dec(&mc.from->moving_account);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006794}
6795
Tejun Heo264a0ae2016-04-21 19:09:02 -04006796static void mem_cgroup_move_task(void)
Balbir Singh67e465a2008-02-07 00:13:54 -08006797{
Tejun Heo264a0ae2016-04-21 19:09:02 -04006798 if (mc.to) {
6799 mem_cgroup_move_charge();
KOSAKI Motohiroa4336582011-06-15 15:08:13 -07006800 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04006801 }
Balbir Singh67e465a2008-02-07 00:13:54 -08006802}
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006803
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006804#else /* !CONFIG_MMU */
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006805static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006806{
6807 return 0;
6808}
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006809static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006810{
6811}
Tejun Heo264a0ae2016-04-21 19:09:02 -04006812static void mem_cgroup_move_task(void)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006813{
6814}
6815#endif
Balbir Singh67e465a2008-02-07 00:13:54 -08006816
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006817#ifdef CONFIG_MEMCG_KMEM
6818static void mem_cgroup_fork(struct task_struct *task)
6819{
6820 /*
6821 * Set the update flag to cause task->objcg to be initialized lazily
6822 * on the first allocation. It can be done without any synchronization
6823 * because it's always performed on the current task, so does
6824 * current_objcg_update().
6825 */
6826 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
6827}
6828
6829static void mem_cgroup_exit(struct task_struct *task)
6830{
6831 struct obj_cgroup *objcg = task->objcg;
6832
6833 objcg = (struct obj_cgroup *)
6834 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
Yosry Ahmed91b71e782024-03-16 01:58:03 +00006835 obj_cgroup_put(objcg);
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006836
6837 /*
6838 * Some kernel allocations can happen after this point,
6839 * but let's ignore them. It can be done without any synchronization
6840 * because it's always performed on the current task, so does
6841 * current_objcg_update().
6842 */
6843 task->objcg = NULL;
6844}
6845#endif
6846
Yu Zhaobd74fda2022-09-18 02:00:05 -06006847#ifdef CONFIG_LRU_GEN
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006848static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
Yu Zhaobd74fda2022-09-18 02:00:05 -06006849{
6850 struct task_struct *task;
6851 struct cgroup_subsys_state *css;
6852
6853 /* find the first leader if there is any */
6854 cgroup_taskset_for_each_leader(task, css, tset)
6855 break;
6856
6857 if (!task)
6858 return;
6859
6860 task_lock(task);
6861 if (task->mm && READ_ONCE(task->mm->owner) == task)
6862 lru_gen_migrate_mm(task->mm);
6863 task_unlock(task);
6864}
6865#else
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006866static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
6867#endif /* CONFIG_LRU_GEN */
6868
6869#ifdef CONFIG_MEMCG_KMEM
6870static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
6871{
6872 struct task_struct *task;
6873 struct cgroup_subsys_state *css;
6874
6875 cgroup_taskset_for_each(task, css, tset) {
6876 /* atomically set the update bit */
6877 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
6878 }
6879}
6880#else
6881static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset) {}
6882#endif /* CONFIG_MEMCG_KMEM */
6883
6884#if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
Yu Zhaobd74fda2022-09-18 02:00:05 -06006885static void mem_cgroup_attach(struct cgroup_taskset *tset)
6886{
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006887 mem_cgroup_lru_gen_attach(tset);
6888 mem_cgroup_kmem_attach(tset);
Yu Zhaobd74fda2022-09-18 02:00:05 -06006889}
Roman Gushchin1aacbd32023-10-19 15:53:42 -07006890#endif
Yu Zhaobd74fda2022-09-18 02:00:05 -06006891
Chris Down677dc972019-03-05 15:45:55 -08006892static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6893{
6894 if (value == PAGE_COUNTER_MAX)
6895 seq_puts(m, "max\n");
6896 else
6897 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6898
6899 return 0;
6900}
6901
Johannes Weiner241994ed2015-02-11 15:26:06 -08006902static u64 memory_current_read(struct cgroup_subsys_state *css,
6903 struct cftype *cft)
6904{
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08006905 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6906
6907 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006908}
6909
Ganesan Rajagopal8e20d4b2022-05-13 16:48:57 -07006910static u64 memory_peak_read(struct cgroup_subsys_state *css,
6911 struct cftype *cft)
6912{
6913 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6914
6915 return (u64)memcg->memory.watermark * PAGE_SIZE;
6916}
6917
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006918static int memory_min_show(struct seq_file *m, void *v)
6919{
Chris Down677dc972019-03-05 15:45:55 -08006920 return seq_puts_memcg_tunable(m,
6921 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006922}
6923
6924static ssize_t memory_min_write(struct kernfs_open_file *of,
6925 char *buf, size_t nbytes, loff_t off)
6926{
6927 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6928 unsigned long min;
6929 int err;
6930
6931 buf = strstrip(buf);
6932 err = page_counter_memparse(buf, "max", &min);
6933 if (err)
6934 return err;
6935
6936 page_counter_set_min(&memcg->memory, min);
6937
6938 return nbytes;
6939}
6940
Johannes Weiner241994ed2015-02-11 15:26:06 -08006941static int memory_low_show(struct seq_file *m, void *v)
6942{
Chris Down677dc972019-03-05 15:45:55 -08006943 return seq_puts_memcg_tunable(m,
6944 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006945}
6946
6947static ssize_t memory_low_write(struct kernfs_open_file *of,
6948 char *buf, size_t nbytes, loff_t off)
6949{
6950 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6951 unsigned long low;
6952 int err;
6953
6954 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006955 err = page_counter_memparse(buf, "max", &low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006956 if (err)
6957 return err;
6958
Roman Gushchin23067152018-06-07 17:06:22 -07006959 page_counter_set_low(&memcg->memory, low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006960
6961 return nbytes;
6962}
6963
6964static int memory_high_show(struct seq_file *m, void *v)
6965{
Jakub Kicinskid1663a92020-06-01 21:49:49 -07006966 return seq_puts_memcg_tunable(m,
6967 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006968}
6969
6970static ssize_t memory_high_write(struct kernfs_open_file *of,
6971 char *buf, size_t nbytes, loff_t off)
6972{
6973 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Chris Downd977aa92020-08-06 23:21:58 -07006974 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006975 bool drained = false;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006976 unsigned long high;
6977 int err;
6978
6979 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006980 err = page_counter_memparse(buf, "max", &high);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006981 if (err)
6982 return err;
6983
Johannes Weinere82553c2021-02-09 13:42:28 -08006984 page_counter_set_high(&memcg->memory, high);
6985
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006986 for (;;) {
6987 unsigned long nr_pages = page_counter_read(&memcg->memory);
6988 unsigned long reclaimed;
Johannes Weiner588083b2016-03-17 14:20:25 -07006989
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006990 if (nr_pages <= high)
6991 break;
6992
6993 if (signal_pending(current))
6994 break;
6995
6996 if (!drained) {
6997 drain_all_stock(memcg);
6998 drained = true;
6999 continue;
7000 }
7001
7002 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
Michal Hocko55ab8342022-12-16 10:46:33 +01007003 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
Johannes Weiner8c8c3832019-11-30 17:50:09 -08007004
7005 if (!reclaimed && !nr_retries--)
7006 break;
7007 }
7008
Johannes Weiner19ce33a2020-08-06 23:22:12 -07007009 memcg_wb_domain_size_changed(memcg);
Johannes Weiner241994ed2015-02-11 15:26:06 -08007010 return nbytes;
7011}
7012
7013static int memory_max_show(struct seq_file *m, void *v)
7014{
Chris Down677dc972019-03-05 15:45:55 -08007015 return seq_puts_memcg_tunable(m,
7016 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
Johannes Weiner241994ed2015-02-11 15:26:06 -08007017}
7018
7019static ssize_t memory_max_write(struct kernfs_open_file *of,
7020 char *buf, size_t nbytes, loff_t off)
7021{
7022 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Chris Downd977aa92020-08-06 23:21:58 -07007023 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007024 bool drained = false;
Johannes Weiner241994ed2015-02-11 15:26:06 -08007025 unsigned long max;
7026 int err;
7027
7028 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08007029 err = page_counter_memparse(buf, "max", &max);
Johannes Weiner241994ed2015-02-11 15:26:06 -08007030 if (err)
7031 return err;
7032
Roman Gushchinbbec2e12018-06-07 17:06:18 -07007033 xchg(&memcg->memory.max, max);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007034
7035 for (;;) {
7036 unsigned long nr_pages = page_counter_read(&memcg->memory);
7037
7038 if (nr_pages <= max)
7039 break;
7040
Johannes Weiner7249c9f2019-11-30 17:50:06 -08007041 if (signal_pending(current))
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007042 break;
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007043
7044 if (!drained) {
7045 drain_all_stock(memcg);
7046 drained = true;
7047 continue;
7048 }
7049
7050 if (nr_reclaims) {
7051 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
Michal Hocko55ab8342022-12-16 10:46:33 +01007052 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007053 nr_reclaims--;
7054 continue;
7055 }
7056
Johannes Weinere27be242018-04-10 16:29:45 -07007057 memcg_memory_event(memcg, MEMCG_OOM);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07007058 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
7059 break;
7060 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08007061
Tejun Heo2529bb32015-05-22 18:23:34 -04007062 memcg_wb_domain_size_changed(memcg);
Johannes Weiner241994ed2015-02-11 15:26:06 -08007063 return nbytes;
7064}
7065
Dmitry Rokosov664dc212023-11-23 10:19:45 +03007066/*
7067 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
7068 * if any new events become available.
7069 */
Shakeel Butt1e577f92019-07-11 20:55:55 -07007070static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
7071{
7072 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
7073 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
7074 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
7075 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
7076 seq_printf(m, "oom_kill %lu\n",
7077 atomic_long_read(&events[MEMCG_OOM_KILL]));
Dan Schatzbergb6bf9ab2022-01-14 14:05:35 -08007078 seq_printf(m, "oom_group_kill %lu\n",
7079 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
Shakeel Butt1e577f92019-07-11 20:55:55 -07007080}
7081
Johannes Weiner241994ed2015-02-11 15:26:06 -08007082static int memory_events_show(struct seq_file *m, void *v)
7083{
Chris Downaa9694b2019-03-05 15:45:52 -08007084 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weiner241994ed2015-02-11 15:26:06 -08007085
Shakeel Butt1e577f92019-07-11 20:55:55 -07007086 __memory_events_show(m, memcg->memory_events);
7087 return 0;
7088}
Johannes Weiner241994ed2015-02-11 15:26:06 -08007089
Shakeel Butt1e577f92019-07-11 20:55:55 -07007090static int memory_events_local_show(struct seq_file *m, void *v)
7091{
7092 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7093
7094 __memory_events_show(m, memcg->memory_events_local);
Johannes Weiner241994ed2015-02-11 15:26:06 -08007095 return 0;
7096}
7097
Johannes Weiner587d9f72016-01-20 15:03:19 -08007098static int memory_stat_show(struct seq_file *m, void *v)
7099{
Chris Downaa9694b2019-03-05 15:45:52 -08007100 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Tetsuo Handa68aaee12022-07-22 19:45:39 +09007101 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
Yosry Ahmed5b423602023-04-28 13:24:05 +00007102 struct seq_buf s;
Johannes Weiner587d9f72016-01-20 15:03:19 -08007103
Johannes Weinerc8713d02019-07-11 20:55:59 -07007104 if (!buf)
7105 return -ENOMEM;
Yosry Ahmed5b423602023-04-28 13:24:05 +00007106 seq_buf_init(&s, buf, PAGE_SIZE);
7107 memory_stat_format(memcg, &s);
Johannes Weinerc8713d02019-07-11 20:55:59 -07007108 seq_puts(m, buf);
7109 kfree(buf);
Johannes Weiner587d9f72016-01-20 15:03:19 -08007110 return 0;
7111}
7112
Muchun Song5f9a4f42020-10-13 16:52:59 -07007113#ifdef CONFIG_NUMA
Muchun Songfff66b72021-02-24 12:03:43 -08007114static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
7115 int item)
7116{
Yosry Ahmedff841a02023-09-22 17:57:39 +00007117 return lruvec_page_state(lruvec, item) *
7118 memcg_page_state_output_unit(item);
Muchun Songfff66b72021-02-24 12:03:43 -08007119}
7120
Muchun Song5f9a4f42020-10-13 16:52:59 -07007121static int memory_numa_stat_show(struct seq_file *m, void *v)
7122{
7123 int i;
7124 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7125
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00007126 mem_cgroup_flush_stats(memcg);
Shakeel Butt7e1c0d62021-09-02 14:55:00 -07007127
Muchun Song5f9a4f42020-10-13 16:52:59 -07007128 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
7129 int nid;
7130
7131 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
7132 continue;
7133
7134 seq_printf(m, "%s", memory_stats[i].name);
7135 for_each_node_state(nid, N_MEMORY) {
7136 u64 size;
7137 struct lruvec *lruvec;
7138
7139 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
Muchun Songfff66b72021-02-24 12:03:43 -08007140 size = lruvec_page_state_output(lruvec,
7141 memory_stats[i].idx);
Muchun Song5f9a4f42020-10-13 16:52:59 -07007142 seq_printf(m, " N%d=%llu", nid, size);
7143 }
7144 seq_putc(m, '\n');
7145 }
7146
7147 return 0;
7148}
7149#endif
7150
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07007151static int memory_oom_group_show(struct seq_file *m, void *v)
7152{
Chris Downaa9694b2019-03-05 15:45:52 -08007153 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07007154
Yue Zhaoeaf7b662023-03-06 23:41:35 +08007155 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07007156
7157 return 0;
7158}
7159
7160static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
7161 char *buf, size_t nbytes, loff_t off)
7162{
7163 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7164 int ret, oom_group;
7165
7166 buf = strstrip(buf);
7167 if (!buf)
7168 return -EINVAL;
7169
7170 ret = kstrtoint(buf, 0, &oom_group);
7171 if (ret)
7172 return ret;
7173
7174 if (oom_group != 0 && oom_group != 1)
7175 return -EINVAL;
7176
Yue Zhaoeaf7b662023-03-06 23:41:35 +08007177 WRITE_ONCE(memcg->oom_group, oom_group);
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07007178
7179 return nbytes;
7180}
7181
Shakeel Butt94968382022-04-29 14:36:59 -07007182static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
7183 size_t nbytes, loff_t off)
7184{
7185 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7186 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
7187 unsigned long nr_to_reclaim, nr_reclaimed = 0;
Michal Hocko55ab8342022-12-16 10:46:33 +01007188 unsigned int reclaim_options;
7189 int err;
Shakeel Butt94968382022-04-29 14:36:59 -07007190
7191 buf = strstrip(buf);
Michal Hocko55ab8342022-12-16 10:46:33 +01007192 err = page_counter_memparse(buf, "", &nr_to_reclaim);
7193 if (err)
7194 return err;
Shakeel Butt94968382022-04-29 14:36:59 -07007195
Michal Hocko55ab8342022-12-16 10:46:33 +01007196 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
Shakeel Butt94968382022-04-29 14:36:59 -07007197 while (nr_reclaimed < nr_to_reclaim) {
T.J. Mercier287d5fe2024-02-02 23:38:54 +00007198 /* Will converge on zero, but reclaim enforces a minimum */
7199 unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
Shakeel Butt94968382022-04-29 14:36:59 -07007200 unsigned long reclaimed;
7201
7202 if (signal_pending(current))
7203 return -EINTR;
7204
7205 /*
7206 * This is the final attempt, drain percpu lru caches in the
7207 * hope of introducing more evictable pages for
7208 * try_to_free_mem_cgroup_pages().
7209 */
7210 if (!nr_retries)
7211 lru_add_drain_all();
7212
7213 reclaimed = try_to_free_mem_cgroup_pages(memcg,
T.J. Mercier287d5fe2024-02-02 23:38:54 +00007214 batch_size, GFP_KERNEL, reclaim_options);
Shakeel Butt94968382022-04-29 14:36:59 -07007215
7216 if (!reclaimed && !nr_retries--)
7217 return -EAGAIN;
7218
7219 nr_reclaimed += reclaimed;
7220 }
7221
7222 return nbytes;
7223}
7224
Johannes Weiner241994ed2015-02-11 15:26:06 -08007225static struct cftype memory_files[] = {
7226 {
7227 .name = "current",
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08007228 .flags = CFTYPE_NOT_ON_ROOT,
Johannes Weiner241994ed2015-02-11 15:26:06 -08007229 .read_u64 = memory_current_read,
7230 },
7231 {
Ganesan Rajagopal8e20d4b2022-05-13 16:48:57 -07007232 .name = "peak",
7233 .flags = CFTYPE_NOT_ON_ROOT,
7234 .read_u64 = memory_peak_read,
7235 },
7236 {
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07007237 .name = "min",
7238 .flags = CFTYPE_NOT_ON_ROOT,
7239 .seq_show = memory_min_show,
7240 .write = memory_min_write,
7241 },
7242 {
Johannes Weiner241994ed2015-02-11 15:26:06 -08007243 .name = "low",
7244 .flags = CFTYPE_NOT_ON_ROOT,
7245 .seq_show = memory_low_show,
7246 .write = memory_low_write,
7247 },
7248 {
7249 .name = "high",
7250 .flags = CFTYPE_NOT_ON_ROOT,
7251 .seq_show = memory_high_show,
7252 .write = memory_high_write,
7253 },
7254 {
7255 .name = "max",
7256 .flags = CFTYPE_NOT_ON_ROOT,
7257 .seq_show = memory_max_show,
7258 .write = memory_max_write,
7259 },
7260 {
7261 .name = "events",
7262 .flags = CFTYPE_NOT_ON_ROOT,
Tejun Heo472912a2015-09-18 18:01:59 -04007263 .file_offset = offsetof(struct mem_cgroup, events_file),
Johannes Weiner241994ed2015-02-11 15:26:06 -08007264 .seq_show = memory_events_show,
7265 },
Johannes Weiner587d9f72016-01-20 15:03:19 -08007266 {
Shakeel Butt1e577f92019-07-11 20:55:55 -07007267 .name = "events.local",
7268 .flags = CFTYPE_NOT_ON_ROOT,
7269 .file_offset = offsetof(struct mem_cgroup, events_local_file),
7270 .seq_show = memory_events_local_show,
7271 },
7272 {
Johannes Weiner587d9f72016-01-20 15:03:19 -08007273 .name = "stat",
Johannes Weiner587d9f72016-01-20 15:03:19 -08007274 .seq_show = memory_stat_show,
7275 },
Muchun Song5f9a4f42020-10-13 16:52:59 -07007276#ifdef CONFIG_NUMA
7277 {
7278 .name = "numa_stat",
7279 .seq_show = memory_numa_stat_show,
7280 },
7281#endif
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07007282 {
7283 .name = "oom.group",
7284 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
7285 .seq_show = memory_oom_group_show,
7286 .write = memory_oom_group_write,
7287 },
Shakeel Butt94968382022-04-29 14:36:59 -07007288 {
7289 .name = "reclaim",
7290 .flags = CFTYPE_NS_DELEGATABLE,
7291 .write = memory_reclaim,
7292 },
Johannes Weiner241994ed2015-02-11 15:26:06 -08007293 { } /* terminate */
7294};
7295
Tejun Heo073219e2014-02-08 10:36:58 -05007296struct cgroup_subsys memory_cgrp_subsys = {
Tejun Heo92fb9742012-11-19 08:13:38 -08007297 .css_alloc = mem_cgroup_css_alloc,
Glauber Costad142e3e2013-02-22 16:34:52 -08007298 .css_online = mem_cgroup_css_online,
Tejun Heo92fb9742012-11-19 08:13:38 -08007299 .css_offline = mem_cgroup_css_offline,
Vladimir Davydov6df38682015-12-29 14:54:10 -08007300 .css_released = mem_cgroup_css_released,
Tejun Heo92fb9742012-11-19 08:13:38 -08007301 .css_free = mem_cgroup_css_free,
Tejun Heo1ced953b2014-07-08 18:02:57 -04007302 .css_reset = mem_cgroup_css_reset,
Johannes Weiner2d146aa2021-04-29 22:56:26 -07007303 .css_rstat_flush = mem_cgroup_css_rstat_flush,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08007304 .can_attach = mem_cgroup_can_attach,
Roman Gushchin1aacbd32023-10-19 15:53:42 -07007305#if defined(CONFIG_LRU_GEN) || defined(CONFIG_MEMCG_KMEM)
Yu Zhaobd74fda2022-09-18 02:00:05 -06007306 .attach = mem_cgroup_attach,
Roman Gushchin1aacbd32023-10-19 15:53:42 -07007307#endif
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08007308 .cancel_attach = mem_cgroup_cancel_attach,
Tejun Heo264a0ae2016-04-21 19:09:02 -04007309 .post_attach = mem_cgroup_move_task,
Roman Gushchin1aacbd32023-10-19 15:53:42 -07007310#ifdef CONFIG_MEMCG_KMEM
7311 .fork = mem_cgroup_fork,
7312 .exit = mem_cgroup_exit,
7313#endif
Johannes Weiner241994ed2015-02-11 15:26:06 -08007314 .dfl_cftypes = memory_files,
7315 .legacy_cftypes = mem_cgroup_legacy_files,
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08007316 .early_init = 0,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08007317};
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -08007318
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007319/*
7320 * This function calculates an individual cgroup's effective
7321 * protection which is derived from its own memory.min/low, its
7322 * parent's and siblings' settings, as well as the actual memory
7323 * distribution in the tree.
7324 *
7325 * The following rules apply to the effective protection values:
7326 *
7327 * 1. At the first level of reclaim, effective protection is equal to
7328 * the declared protection in memory.min and memory.low.
7329 *
7330 * 2. To enable safe delegation of the protection configuration, at
7331 * subsequent levels the effective protection is capped to the
7332 * parent's effective protection.
7333 *
7334 * 3. To make complex and dynamic subtrees easier to configure, the
7335 * user is allowed to overcommit the declared protection at a given
7336 * level. If that is the case, the parent's effective protection is
7337 * distributed to the children in proportion to how much protection
7338 * they have declared and how much of it they are utilizing.
7339 *
7340 * This makes distribution proportional, but also work-conserving:
7341 * if one cgroup claims much more protection than it uses memory,
7342 * the unused remainder is available to its siblings.
7343 *
7344 * 4. Conversely, when the declared protection is undercommitted at a
7345 * given level, the distribution of the larger parental protection
7346 * budget is NOT proportional. A cgroup's protection from a sibling
7347 * is capped to its own memory.min/low setting.
7348 *
Johannes Weiner8a931f82020-04-01 21:07:07 -07007349 * 5. However, to allow protecting recursive subtrees from each other
7350 * without having to declare each individual cgroup's fixed share
7351 * of the ancestor's claim to protection, any unutilized -
7352 * "floating" - protection from up the tree is distributed in
7353 * proportion to each cgroup's *usage*. This makes the protection
7354 * neutral wrt sibling cgroups and lets them compete freely over
7355 * the shared parental protection budget, but it protects the
7356 * subtree as a whole from neighboring subtrees.
7357 *
7358 * Note that 4. and 5. are not in conflict: 4. is about protecting
7359 * against immediate siblings whereas 5. is about protecting against
7360 * neighboring subtrees.
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007361 */
7362static unsigned long effective_protection(unsigned long usage,
Johannes Weiner8a931f82020-04-01 21:07:07 -07007363 unsigned long parent_usage,
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007364 unsigned long setting,
7365 unsigned long parent_effective,
7366 unsigned long siblings_protected)
7367{
7368 unsigned long protected;
Johannes Weiner8a931f82020-04-01 21:07:07 -07007369 unsigned long ep;
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007370
7371 protected = min(usage, setting);
7372 /*
7373 * If all cgroups at this level combined claim and use more
Haifeng Xu08e0f492023-05-22 09:52:32 +00007374 * protection than what the parent affords them, distribute
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007375 * shares in proportion to utilization.
7376 *
7377 * We are using actual utilization rather than the statically
7378 * claimed protection in order to be work-conserving: claimed
7379 * but unused protection is available to siblings that would
7380 * otherwise get a smaller chunk than what they claimed.
7381 */
7382 if (siblings_protected > parent_effective)
7383 return protected * parent_effective / siblings_protected;
7384
7385 /*
7386 * Ok, utilized protection of all children is within what the
7387 * parent affords them, so we know whatever this child claims
7388 * and utilizes is effectively protected.
7389 *
7390 * If there is unprotected usage beyond this value, reclaim
7391 * will apply pressure in proportion to that amount.
7392 *
7393 * If there is unutilized protection, the cgroup will be fully
7394 * shielded from reclaim, but we do return a smaller value for
7395 * protection than what the group could enjoy in theory. This
7396 * is okay. With the overcommit distribution above, effective
7397 * protection is always dependent on how memory is actually
7398 * consumed among the siblings anyway.
7399 */
Johannes Weiner8a931f82020-04-01 21:07:07 -07007400 ep = protected;
7401
7402 /*
7403 * If the children aren't claiming (all of) the protection
7404 * afforded to them by the parent, distribute the remainder in
7405 * proportion to the (unprotected) memory of each cgroup. That
7406 * way, cgroups that aren't explicitly prioritized wrt each
7407 * other compete freely over the allowance, but they are
7408 * collectively protected from neighboring trees.
7409 *
7410 * We're using unprotected memory for the weight so that if
7411 * some cgroups DO claim explicit protection, we don't protect
7412 * the same bytes twice.
Johannes Weinercd324ed2020-06-25 20:30:16 -07007413 *
7414 * Check both usage and parent_usage against the respective
7415 * protected values. One should imply the other, but they
7416 * aren't read atomically - make sure the division is sane.
Johannes Weiner8a931f82020-04-01 21:07:07 -07007417 */
7418 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
7419 return ep;
Johannes Weinercd324ed2020-06-25 20:30:16 -07007420 if (parent_effective > siblings_protected &&
7421 parent_usage > siblings_protected &&
7422 usage > protected) {
Johannes Weiner8a931f82020-04-01 21:07:07 -07007423 unsigned long unclaimed;
7424
7425 unclaimed = parent_effective - siblings_protected;
7426 unclaimed *= usage - protected;
7427 unclaimed /= parent_usage - siblings_protected;
7428
7429 ep += unclaimed;
7430 }
7431
7432 return ep;
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007433}
7434
Johannes Weiner241994ed2015-02-11 15:26:06 -08007435/**
Mel Gorman053957182021-06-30 18:53:32 -07007436 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
Sean Christopherson34c81052017-07-10 15:48:05 -07007437 * @root: the top ancestor of the sub-tree being checked
Johannes Weiner241994ed2015-02-11 15:26:06 -08007438 * @memcg: the memory cgroup to check
7439 *
Roman Gushchin23067152018-06-07 17:06:22 -07007440 * WARNING: This function is not stateless! It can only be used as part
7441 * of a top-down tree iteration, not for isolated queries.
Johannes Weiner241994ed2015-02-11 15:26:06 -08007442 */
Chris Down45c7f7e2020-08-06 23:22:05 -07007443void mem_cgroup_calculate_protection(struct mem_cgroup *root,
7444 struct mem_cgroup *memcg)
Johannes Weiner241994ed2015-02-11 15:26:06 -08007445{
Johannes Weiner8a931f82020-04-01 21:07:07 -07007446 unsigned long usage, parent_usage;
Roman Gushchin23067152018-06-07 17:06:22 -07007447 struct mem_cgroup *parent;
7448
Johannes Weiner241994ed2015-02-11 15:26:06 -08007449 if (mem_cgroup_disabled())
Chris Down45c7f7e2020-08-06 23:22:05 -07007450 return;
Johannes Weiner241994ed2015-02-11 15:26:06 -08007451
Sean Christopherson34c81052017-07-10 15:48:05 -07007452 if (!root)
7453 root = root_mem_cgroup;
Yafang Shao22f74962020-08-06 23:22:01 -07007454
7455 /*
7456 * Effective values of the reclaim targets are ignored so they
7457 * can be stale. Have a look at mem_cgroup_protection for more
7458 * details.
7459 * TODO: calculation should be more robust so that we do not need
7460 * that special casing.
7461 */
Sean Christopherson34c81052017-07-10 15:48:05 -07007462 if (memcg == root)
Chris Down45c7f7e2020-08-06 23:22:05 -07007463 return;
Johannes Weiner241994ed2015-02-11 15:26:06 -08007464
Roman Gushchin23067152018-06-07 17:06:22 -07007465 usage = page_counter_read(&memcg->memory);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07007466 if (!usage)
Chris Down45c7f7e2020-08-06 23:22:05 -07007467 return;
Sean Christopherson34c81052017-07-10 15:48:05 -07007468
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07007469 parent = parent_mem_cgroup(memcg);
Roman Gushchindf2a4192018-06-14 15:26:17 -07007470
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07007471 if (parent == root) {
Chris Downc3d53202020-04-01 21:07:27 -07007472 memcg->memory.emin = READ_ONCE(memcg->memory.min);
Chris Down03960e32020-06-25 20:30:22 -07007473 memcg->memory.elow = READ_ONCE(memcg->memory.low);
Chris Down45c7f7e2020-08-06 23:22:05 -07007474 return;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07007475 }
7476
Johannes Weiner8a931f82020-04-01 21:07:07 -07007477 parent_usage = page_counter_read(&parent->memory);
7478
Chris Downb3a78222020-04-01 21:07:33 -07007479 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
Chris Downc3d53202020-04-01 21:07:27 -07007480 READ_ONCE(memcg->memory.min),
7481 READ_ONCE(parent->memory.emin),
Chris Downb3a78222020-04-01 21:07:33 -07007482 atomic_long_read(&parent->memory.children_min_usage)));
Roman Gushchin23067152018-06-07 17:06:22 -07007483
Chris Downb3a78222020-04-01 21:07:33 -07007484 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
Chris Down03960e32020-06-25 20:30:22 -07007485 READ_ONCE(memcg->memory.low),
7486 READ_ONCE(parent->memory.elow),
Chris Downb3a78222020-04-01 21:07:33 -07007487 atomic_long_read(&parent->memory.children_low_usage)));
Johannes Weiner241994ed2015-02-11 15:26:06 -08007488}
7489
Matthew Wilcox (Oracle)8f425e42021-06-25 09:27:04 -04007490static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
7491 gfp_t gfp)
Shakeel Butt0add0c72021-04-29 22:56:36 -07007492{
Shakeel Butt0add0c72021-04-29 22:56:36 -07007493 int ret;
7494
Nhat Pham4b569382023-10-06 11:46:26 -07007495 ret = try_charge(memcg, gfp, folio_nr_pages(folio));
Shakeel Butt0add0c72021-04-29 22:56:36 -07007496 if (ret)
7497 goto out;
7498
Nhat Pham4b569382023-10-06 11:46:26 -07007499 mem_cgroup_commit_charge(folio, memcg);
Shakeel Butt0add0c72021-04-29 22:56:36 -07007500out:
7501 return ret;
7502}
7503
Matthew Wilcox (Oracle)8f425e42021-06-25 09:27:04 -04007504int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
Johannes Weiner00501b52014-08-08 14:19:20 -07007505{
Shakeel Butt0add0c72021-04-29 22:56:36 -07007506 struct mem_cgroup *memcg;
7507 int ret;
Johannes Weiner00501b52014-08-08 14:19:20 -07007508
Shakeel Butt0add0c72021-04-29 22:56:36 -07007509 memcg = get_mem_cgroup_from_mm(mm);
Matthew Wilcox (Oracle)8f425e42021-06-25 09:27:04 -04007510 ret = charge_memcg(folio, memcg, gfp);
Shakeel Butt0add0c72021-04-29 22:56:36 -07007511 css_put(&memcg->css);
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007512
Shakeel Butt0add0c72021-04-29 22:56:36 -07007513 return ret;
7514}
Vladimir Davydove993d902015-09-09 15:35:35 -07007515
Shakeel Butt0add0c72021-04-29 22:56:36 -07007516/**
Nhat Pham8cba9572023-10-06 11:46:28 -07007517 * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
7518 * @memcg: memcg to charge.
7519 * @gfp: reclaim mode.
7520 * @nr_pages: number of pages to charge.
7521 *
7522 * This function is called when allocating a huge page folio to determine if
7523 * the memcg has the capacity for it. It does not commit the charge yet,
7524 * as the hugetlb folio itself has not been obtained from the hugetlb pool.
7525 *
7526 * Once we have obtained the hugetlb folio, we can call
7527 * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
7528 * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
7529 * of try_charge().
7530 *
7531 * Returns 0 on success. Otherwise, an error code is returned.
7532 */
7533int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
7534 long nr_pages)
7535{
7536 /*
7537 * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
7538 * but do not attempt to commit charge later (or cancel on error) either.
7539 */
7540 if (mem_cgroup_disabled() || !memcg ||
7541 !cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
7542 !(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
7543 return -EOPNOTSUPP;
7544
7545 if (try_charge(memcg, gfp, nr_pages))
7546 return -ENOMEM;
7547
7548 return 0;
7549}
7550
7551/**
Matthew Wilcox (Oracle)65995912022-09-02 20:46:12 +01007552 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
7553 * @folio: folio to charge.
Shakeel Butt0add0c72021-04-29 22:56:36 -07007554 * @mm: mm context of the victim
7555 * @gfp: reclaim mode
Matthew Wilcox (Oracle)65995912022-09-02 20:46:12 +01007556 * @entry: swap entry for which the folio is allocated
Shakeel Butt0add0c72021-04-29 22:56:36 -07007557 *
Matthew Wilcox (Oracle)65995912022-09-02 20:46:12 +01007558 * This function charges a folio allocated for swapin. Please call this before
7559 * adding the folio to the swapcache.
Shakeel Butt0add0c72021-04-29 22:56:36 -07007560 *
7561 * Returns 0 on success. Otherwise, an error code is returned.
7562 */
Matthew Wilcox (Oracle)65995912022-09-02 20:46:12 +01007563int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
Shakeel Butt0add0c72021-04-29 22:56:36 -07007564 gfp_t gfp, swp_entry_t entry)
7565{
7566 struct mem_cgroup *memcg;
7567 unsigned short id;
7568 int ret;
Johannes Weiner00501b52014-08-08 14:19:20 -07007569
Shakeel Butt0add0c72021-04-29 22:56:36 -07007570 if (mem_cgroup_disabled())
7571 return 0;
7572
7573 id = lookup_swap_cgroup_id(entry);
7574 rcu_read_lock();
7575 memcg = mem_cgroup_from_id(id);
7576 if (!memcg || !css_tryget_online(&memcg->css))
Johannes Weiner00501b52014-08-08 14:19:20 -07007577 memcg = get_mem_cgroup_from_mm(mm);
Shakeel Butt0add0c72021-04-29 22:56:36 -07007578 rcu_read_unlock();
Johannes Weiner00501b52014-08-08 14:19:20 -07007579
Matthew Wilcox (Oracle)8f425e42021-06-25 09:27:04 -04007580 ret = charge_memcg(folio, memcg, gfp);
Johannes Weiner00501b52014-08-08 14:19:20 -07007581
Shakeel Butt0add0c72021-04-29 22:56:36 -07007582 css_put(&memcg->css);
7583 return ret;
7584}
Johannes Weiner6abb5a82014-08-08 14:19:33 -07007585
Shakeel Butt0add0c72021-04-29 22:56:36 -07007586/*
7587 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
7588 * @entry: swap entry for which the page is charged
7589 *
7590 * Call this function after successfully adding the charged page to swapcache.
7591 *
7592 * Note: This function assumes the page for which swap slot is being uncharged
7593 * is order 0 page.
7594 */
7595void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
7596{
Muchun Songcae3af62021-02-24 12:04:19 -08007597 /*
7598 * Cgroup1's unified memory+swap counter has been charged with the
7599 * new swapcache page, finish the transfer by uncharging the swap
7600 * slot. The swap slot would also get uncharged when it dies, but
7601 * it can stick around indefinitely and we'd count the page twice
7602 * the entire time.
7603 *
7604 * Cgroup2 has separate resource counters for memory and swap,
7605 * so this is a non-issue here. Memory and swap charge lifetimes
7606 * correspond 1:1 to page and swap slot lifetimes: we charge the
7607 * page to memory here, and uncharge swap when the slot is freed.
7608 */
Shakeel Butt0add0c72021-04-29 22:56:36 -07007609 if (!mem_cgroup_disabled() && do_memsw_account()) {
Johannes Weiner00501b52014-08-08 14:19:20 -07007610 /*
7611 * The swap entry might not get freed for a long time,
7612 * let's not wait for it. The page already received a
7613 * memory+swap charge, drop the swap entry duplicate.
7614 */
Shakeel Butt0add0c72021-04-29 22:56:36 -07007615 mem_cgroup_uncharge_swap(entry, 1);
Johannes Weiner00501b52014-08-08 14:19:20 -07007616 }
Johannes Weiner3fea5a42020-06-03 16:01:41 -07007617}
7618
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007619struct uncharge_gather {
7620 struct mem_cgroup *memcg;
Muchun Songb4e0b682021-04-29 22:56:52 -07007621 unsigned long nr_memory;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007622 unsigned long pgpgout;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007623 unsigned long nr_kmem;
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04007624 int nid;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007625};
7626
7627static inline void uncharge_gather_clear(struct uncharge_gather *ug)
Johannes Weiner747db952014-08-08 14:19:24 -07007628{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007629 memset(ug, 0, sizeof(*ug));
7630}
7631
7632static void uncharge_batch(const struct uncharge_gather *ug)
7633{
Johannes Weiner747db952014-08-08 14:19:24 -07007634 unsigned long flags;
7635
Muchun Songb4e0b682021-04-29 22:56:52 -07007636 if (ug->nr_memory) {
7637 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
Johannes Weiner7941d212016-01-14 15:21:23 -08007638 if (do_memsw_account())
Muchun Songb4e0b682021-04-29 22:56:52 -07007639 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
Yosry Ahmeda8c49af2022-03-22 14:40:10 -07007640 if (ug->nr_kmem)
7641 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007642 memcg_oom_recover(ug->memcg);
Johannes Weinerce00a962014-09-05 08:43:57 -04007643 }
Johannes Weiner747db952014-08-08 14:19:24 -07007644
7645 local_irq_save(flags);
Johannes Weinerc9019e92018-01-31 16:16:37 -08007646 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
Muchun Songb4e0b682021-04-29 22:56:52 -07007647 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
Matthew Wilcox (Oracle)8e88bd22021-06-25 09:05:47 -04007648 memcg_check_events(ug->memcg, ug->nid);
Johannes Weiner747db952014-08-08 14:19:24 -07007649 local_irq_restore(flags);
Michal Hockof1796542020-09-04 16:35:24 -07007650
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007651 /* drop reference from uncharge_folio */
Michal Hockof1796542020-09-04 16:35:24 -07007652 css_put(&ug->memcg->css);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007653}
7654
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007655static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007656{
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007657 long nr_pages;
Muchun Songb4e0b682021-04-29 22:56:52 -07007658 struct mem_cgroup *memcg;
7659 struct obj_cgroup *objcg;
Johannes Weiner9f762db2020-06-03 16:01:44 -07007660
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007661 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
Matthew Wilcox (Oracle)b7b098c2024-03-21 14:24:39 +00007662 VM_BUG_ON_FOLIO(folio_order(folio) > 1 &&
7663 !folio_test_hugetlb(folio) &&
7664 !list_empty(&folio->_deferred_list), folio);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007665
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007666 /*
7667 * Nobody should be changing or seriously looking at
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007668 * folio memcg or objcg at this point, we have fully
7669 * exclusive access to the folio.
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007670 */
Michal Hockofead2b82022-03-22 14:40:35 -07007671 if (folio_memcg_kmem(folio)) {
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04007672 objcg = __folio_objcg(folio);
Muchun Songb4e0b682021-04-29 22:56:52 -07007673 /*
7674 * This get matches the put at the end of the function and
7675 * kmem pages do not hold memcg references anymore.
7676 */
7677 memcg = get_mem_cgroup_from_objcg(objcg);
7678 } else {
Matthew Wilcox (Oracle)1b7e4462021-06-28 14:59:26 -04007679 memcg = __folio_memcg(folio);
Muchun Songb4e0b682021-04-29 22:56:52 -07007680 }
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007681
Muchun Songb4e0b682021-04-29 22:56:52 -07007682 if (!memcg)
7683 return;
7684
7685 if (ug->memcg != memcg) {
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007686 if (ug->memcg) {
7687 uncharge_batch(ug);
7688 uncharge_gather_clear(ug);
7689 }
Muchun Songb4e0b682021-04-29 22:56:52 -07007690 ug->memcg = memcg;
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007691 ug->nid = folio_nid(folio);
Michal Hockof1796542020-09-04 16:35:24 -07007692
7693 /* pairs with css_put in uncharge_batch */
Muchun Songb4e0b682021-04-29 22:56:52 -07007694 css_get(&memcg->css);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007695 }
7696
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007697 nr_pages = folio_nr_pages(folio);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007698
Michal Hockofead2b82022-03-22 14:40:35 -07007699 if (folio_memcg_kmem(folio)) {
Muchun Songb4e0b682021-04-29 22:56:52 -07007700 ug->nr_memory += nr_pages;
Johannes Weiner9f762db2020-06-03 16:01:44 -07007701 ug->nr_kmem += nr_pages;
Muchun Songb4e0b682021-04-29 22:56:52 -07007702
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007703 folio->memcg_data = 0;
Muchun Songb4e0b682021-04-29 22:56:52 -07007704 obj_cgroup_put(objcg);
7705 } else {
7706 /* LRU pages aren't accounted at the root level */
7707 if (!mem_cgroup_is_root(memcg))
7708 ug->nr_memory += nr_pages;
Roman Gushchin18b2db32020-12-01 13:58:30 -08007709 ug->pgpgout++;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007710
Matthew Wilcox (Oracle)c4ed6eb2021-06-29 21:47:12 -04007711 folio->memcg_data = 0;
Muchun Songb4e0b682021-04-29 22:56:52 -07007712 }
7713
7714 css_put(&memcg->css);
Johannes Weiner747db952014-08-08 14:19:24 -07007715}
7716
Matthew Wilcox (Oracle)bbc6b702021-05-01 20:42:23 -04007717void __mem_cgroup_uncharge(struct folio *folio)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007718{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007719 struct uncharge_gather ug;
7720
Matthew Wilcox (Oracle)bbc6b702021-05-01 20:42:23 -04007721 /* Don't touch folio->lru of any random page, pre-check: */
7722 if (!folio_memcg(folio))
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007723 return;
7724
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007725 uncharge_gather_clear(&ug);
Matthew Wilcox (Oracle)bbc6b702021-05-01 20:42:23 -04007726 uncharge_folio(folio, &ug);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07007727 uncharge_batch(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07007728}
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007729
Matthew Wilcox (Oracle)4882c8092024-02-27 17:42:39 +00007730void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
7731{
7732 struct uncharge_gather ug;
7733 unsigned int i;
7734
7735 uncharge_gather_clear(&ug);
7736 for (i = 0; i < folios->nr; i++)
7737 uncharge_folio(folios->folios[i], &ug);
7738 if (ug.memcg)
7739 uncharge_batch(&ug);
7740}
7741
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007742/**
Nhat Pham85ce2c52023-10-06 11:46:27 -07007743 * mem_cgroup_replace_folio - Charge a folio's replacement.
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007744 * @old: Currently circulating folio.
7745 * @new: Replacement folio.
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007746 *
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007747 * Charge @new as a replacement folio for @old. @old will
Baolin Wang9094b4a2024-06-13 16:21:19 +08007748 * be uncharged upon free.
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007749 *
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007750 * Both folios must be locked, @new->mapping must be set up.
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007751 */
Nhat Pham85ce2c52023-10-06 11:46:27 -07007752void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007753{
Johannes Weiner29833312014-12-10 15:44:02 -08007754 struct mem_cgroup *memcg;
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007755 long nr_pages = folio_nr_pages(new);
Tejun Heod93c4132016-06-24 14:49:54 -07007756 unsigned long flags;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007757
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007758 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7759 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7760 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7761 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007762
7763 if (mem_cgroup_disabled())
7764 return;
7765
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007766 /* Page cache replacement: new folio already charged? */
7767 if (folio_memcg(new))
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007768 return;
7769
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007770 memcg = folio_memcg(old);
7771 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
Johannes Weiner29833312014-12-10 15:44:02 -08007772 if (!memcg)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007773 return;
7774
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08007775 /* Force-charge the new page. The old one will be freed soon */
Muchun Song8dc87c72021-06-28 19:37:47 -07007776 if (!mem_cgroup_is_root(memcg)) {
7777 page_counter_charge(&memcg->memory, nr_pages);
7778 if (do_memsw_account())
7779 page_counter_charge(&memcg->memsw, nr_pages);
7780 }
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007781
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07007782 css_get(&memcg->css);
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007783 commit_charge(new, memcg);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08007784
Tejun Heod93c4132016-06-24 14:49:54 -07007785 local_irq_save(flags);
Matthew Wilcox (Oracle)6e0110c2021-04-29 13:40:11 -04007786 mem_cgroup_charge_statistics(memcg, nr_pages);
Matthew Wilcox (Oracle)d21bba22021-05-06 18:14:59 -04007787 memcg_check_events(memcg, folio_nid(new));
Tejun Heod93c4132016-06-24 14:49:54 -07007788 local_irq_restore(flags);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007789}
7790
Nhat Pham85ce2c52023-10-06 11:46:27 -07007791/**
7792 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
7793 * @old: Currently circulating folio.
7794 * @new: Replacement folio.
7795 *
7796 * Transfer the memcg data from the old folio to the new folio for migration.
7797 * The old folio's data info will be cleared. Note that the memory counters
7798 * will remain unchanged throughout the process.
7799 *
7800 * Both folios must be locked, @new->mapping must be set up.
7801 */
7802void mem_cgroup_migrate(struct folio *old, struct folio *new)
7803{
7804 struct mem_cgroup *memcg;
7805
7806 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7807 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7808 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7809 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
7810
7811 if (mem_cgroup_disabled())
7812 return;
7813
7814 memcg = folio_memcg(old);
Nhat Pham8cba9572023-10-06 11:46:28 -07007815 /*
7816 * Note that it is normal to see !memcg for a hugetlb folio.
7817 * For e.g, itt could have been allocated when memory_hugetlb_accounting
7818 * was not selected.
7819 */
7820 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
Nhat Pham85ce2c52023-10-06 11:46:27 -07007821 if (!memcg)
7822 return;
7823
7824 /* Transfer the charge and the css ref */
7825 commit_charge(new, memcg);
Baolin Wang9bcef592023-12-20 14:51:40 +08007826 /*
7827 * If the old folio is a large folio and is in the split queue, it needs
7828 * to be removed from the split queue now, in case getting an incorrect
7829 * split queue in destroy_large_folio() after the memcg of the old folio
7830 * is cleared.
7831 *
7832 * In addition, the old folio is about to be freed after migration, so
7833 * removing from the split queue a bit earlier seems reasonable.
7834 */
7835 if (folio_test_large(old) && folio_test_large_rmappable(old))
7836 folio_undo_large_rmappable(old);
Nhat Pham85ce2c52023-10-06 11:46:27 -07007837 old->memcg_data = 0;
7838}
7839
Johannes Weineref129472016-01-14 15:21:34 -08007840DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
Johannes Weiner11092082016-01-14 15:21:26 -08007841EXPORT_SYMBOL(memcg_sockets_enabled_key);
7842
Johannes Weiner2d758072016-10-07 17:00:58 -07007843void mem_cgroup_sk_alloc(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08007844{
7845 struct mem_cgroup *memcg;
7846
Johannes Weiner2d758072016-10-07 17:00:58 -07007847 if (!mem_cgroup_sockets_enabled)
7848 return;
7849
Shakeel Butte876ecc2020-03-09 22:16:05 -07007850 /* Do not associate the sock with unrelated interrupted task's memcg. */
Shakeel Butt086f6942022-03-22 14:40:07 -07007851 if (!in_task())
Shakeel Butte876ecc2020-03-09 22:16:05 -07007852 return;
7853
Johannes Weiner11092082016-01-14 15:21:26 -08007854 rcu_read_lock();
7855 memcg = mem_cgroup_from_task(current);
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05307856 if (mem_cgroup_is_root(memcg))
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007857 goto out;
Johannes Weiner0db15292016-01-20 15:02:50 -08007858 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007859 goto out;
Shakeel Butt8965aa22020-04-01 21:07:10 -07007860 if (css_tryget(&memcg->css))
Johannes Weiner11092082016-01-14 15:21:26 -08007861 sk->sk_memcg = memcg;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007862out:
Johannes Weiner11092082016-01-14 15:21:26 -08007863 rcu_read_unlock();
7864}
Johannes Weiner11092082016-01-14 15:21:26 -08007865
Johannes Weiner2d758072016-10-07 17:00:58 -07007866void mem_cgroup_sk_free(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08007867{
Johannes Weiner2d758072016-10-07 17:00:58 -07007868 if (sk->sk_memcg)
7869 css_put(&sk->sk_memcg->css);
Johannes Weiner11092082016-01-14 15:21:26 -08007870}
7871
7872/**
7873 * mem_cgroup_charge_skmem - charge socket memory
7874 * @memcg: memcg to charge
7875 * @nr_pages: number of pages to charge
Wei Wang4b1327b2021-08-17 12:40:03 -07007876 * @gfp_mask: reclaim mode
Johannes Weiner11092082016-01-14 15:21:26 -08007877 *
7878 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
Wei Wang4b1327b2021-08-17 12:40:03 -07007879 * @memcg's configured limit, %false if it doesn't.
Johannes Weiner11092082016-01-14 15:21:26 -08007880 */
Wei Wang4b1327b2021-08-17 12:40:03 -07007881bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7882 gfp_t gfp_mask)
Johannes Weiner11092082016-01-14 15:21:26 -08007883{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007884 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08007885 struct page_counter *fail;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007886
Johannes Weiner0db15292016-01-20 15:02:50 -08007887 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7888 memcg->tcpmem_pressure = 0;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007889 return true;
7890 }
Johannes Weiner0db15292016-01-20 15:02:50 -08007891 memcg->tcpmem_pressure = 1;
Wei Wang4b1327b2021-08-17 12:40:03 -07007892 if (gfp_mask & __GFP_NOFAIL) {
7893 page_counter_charge(&memcg->tcpmem, nr_pages);
7894 return true;
7895 }
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007896 return false;
Johannes Weiner11092082016-01-14 15:21:26 -08007897 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08007898
Wei Wang4b1327b2021-08-17 12:40:03 -07007899 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7900 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007901 return true;
Wei Wang4b1327b2021-08-17 12:40:03 -07007902 }
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007903
Johannes Weiner11092082016-01-14 15:21:26 -08007904 return false;
7905}
7906
7907/**
7908 * mem_cgroup_uncharge_skmem - uncharge socket memory
Mike Rapoportb7701a52018-02-06 15:42:13 -08007909 * @memcg: memcg to uncharge
7910 * @nr_pages: number of pages to uncharge
Johannes Weiner11092082016-01-14 15:21:26 -08007911 */
7912void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7913{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007914 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08007915 page_counter_uncharge(&memcg->tcpmem, nr_pages);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007916 return;
7917 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08007918
Johannes Weinerc9019e92018-01-31 16:16:37 -08007919 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
Johannes Weinerb2807f02016-01-20 15:03:22 -08007920
Roman Gushchin475d0482017-09-08 16:13:09 -07007921 refill_stock(memcg, nr_pages);
Johannes Weiner11092082016-01-14 15:21:26 -08007922}
7923
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007924static int __init cgroup_memory(char *s)
7925{
7926 char *token;
7927
7928 while ((token = strsep(&s, ",")) != NULL) {
7929 if (!*token)
7930 continue;
7931 if (!strcmp(token, "nosocket"))
7932 cgroup_memory_nosocket = true;
Vladimir Davydov04823c82016-01-20 15:02:38 -08007933 if (!strcmp(token, "nokmem"))
7934 cgroup_memory_nokmem = true;
Yafang Shaob6c1a8a2023-02-10 15:47:31 +00007935 if (!strcmp(token, "nobpf"))
7936 cgroup_memory_nobpf = true;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007937 }
Randy Dunlap460a79e2022-03-22 14:40:31 -07007938 return 1;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007939}
7940__setup("cgroup.memory=", cgroup_memory);
Johannes Weiner11092082016-01-14 15:21:26 -08007941
Michal Hocko2d110852013-02-22 16:34:43 -08007942/*
Michal Hocko10813122013-02-22 16:35:41 -08007943 * subsys_initcall() for memory controller.
7944 *
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01007945 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7946 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7947 * basically everything that doesn't depend on a specific mem_cgroup structure
7948 * should be initialized from here.
Michal Hocko2d110852013-02-22 16:34:43 -08007949 */
7950static int __init mem_cgroup_init(void)
7951{
Johannes Weiner95a045f2015-02-11 15:26:33 -08007952 int cpu, node;
7953
Muchun Songf3344ad2021-02-24 12:03:15 -08007954 /*
7955 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7956 * used for per-memcg-per-cpu caching of per-node statistics. In order
7957 * to work fine, we should make sure that the overfill threshold can't
7958 * exceed S32_MAX / PAGE_SIZE.
7959 */
7960 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7961
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01007962 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7963 memcg_hotplug_cpu_dead);
Johannes Weiner95a045f2015-02-11 15:26:33 -08007964
7965 for_each_possible_cpu(cpu)
7966 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7967 drain_local_stock);
7968
7969 for_each_node(node) {
7970 struct mem_cgroup_tree_per_node *rtpn;
Johannes Weiner95a045f2015-02-11 15:26:33 -08007971
Haifeng Xu91f0dcc2023-06-19 13:04:42 +00007972 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, node);
Johannes Weiner95a045f2015-02-11 15:26:33 -08007973
Mel Gormanef8f2322016-07-28 15:46:05 -07007974 rtpn->rb_root = RB_ROOT;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -07007975 rtpn->rb_rightmost = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -07007976 spin_lock_init(&rtpn->lock);
Johannes Weiner95a045f2015-02-11 15:26:33 -08007977 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7978 }
7979
Michal Hocko2d110852013-02-22 16:34:43 -08007980 return 0;
7981}
7982subsys_initcall(mem_cgroup_init);
Johannes Weiner21afa382015-02-11 15:26:36 -08007983
Johannes Weinere55b9f92022-09-26 09:57:04 -04007984#ifdef CONFIG_SWAP
Arnd Bergmann358c07f2016-08-25 15:17:08 -07007985static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7986{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07007987 while (!refcount_inc_not_zero(&memcg->id.ref)) {
Arnd Bergmann358c07f2016-08-25 15:17:08 -07007988 /*
7989 * The root cgroup cannot be destroyed, so it's refcount must
7990 * always be >= 1.
7991 */
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05307992 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
Arnd Bergmann358c07f2016-08-25 15:17:08 -07007993 VM_BUG_ON(1);
7994 break;
7995 }
7996 memcg = parent_mem_cgroup(memcg);
7997 if (!memcg)
7998 memcg = root_mem_cgroup;
7999 }
8000 return memcg;
8001}
8002
Johannes Weiner21afa382015-02-11 15:26:36 -08008003/**
8004 * mem_cgroup_swapout - transfer a memsw charge to swap
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008005 * @folio: folio whose memsw charge to transfer
Johannes Weiner21afa382015-02-11 15:26:36 -08008006 * @entry: swap entry to move the charge to
8007 *
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008008 * Transfer the memsw charge of @folio to @entry.
Johannes Weiner21afa382015-02-11 15:26:36 -08008009 */
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008010void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
Johannes Weiner21afa382015-02-11 15:26:36 -08008011{
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008012 struct mem_cgroup *memcg, *swap_memcg;
Huang Yingd6810d732017-09-06 16:22:45 -07008013 unsigned int nr_entries;
Johannes Weiner21afa382015-02-11 15:26:36 -08008014 unsigned short oldid;
8015
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008016 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
8017 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
Johannes Weiner21afa382015-02-11 15:26:36 -08008018
Alex Shi76358ab2020-12-18 14:01:28 -08008019 if (mem_cgroup_disabled())
8020 return;
8021
Johannes Weinerb94c4e92022-09-26 09:57:03 -04008022 if (!do_memsw_account())
Johannes Weiner21afa382015-02-11 15:26:36 -08008023 return;
8024
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008025 memcg = folio_memcg(folio);
Johannes Weiner21afa382015-02-11 15:26:36 -08008026
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008027 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
Johannes Weiner21afa382015-02-11 15:26:36 -08008028 if (!memcg)
8029 return;
8030
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008031 /*
8032 * In case the memcg owning these pages has been offlined and doesn't
8033 * have an ID allocated to it anymore, charge the closest online
8034 * ancestor for the swap instead and transfer the memory+swap charge.
8035 */
8036 swap_memcg = mem_cgroup_id_get_online(memcg);
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008037 nr_entries = folio_nr_pages(folio);
Huang Yingd6810d732017-09-06 16:22:45 -07008038 /* Get references for the tail pages, too */
8039 if (nr_entries > 1)
8040 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
8041 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
8042 nr_entries);
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008043 VM_BUG_ON_FOLIO(oldid, folio);
Johannes Weinerc9019e92018-01-31 16:16:37 -08008044 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08008045
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008046 folio->memcg_data = 0;
Johannes Weiner21afa382015-02-11 15:26:36 -08008047
8048 if (!mem_cgroup_is_root(memcg))
Huang Yingd6810d732017-09-06 16:22:45 -07008049 page_counter_uncharge(&memcg->memory, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08008050
Johannes Weinerb25806d2022-09-26 09:57:02 -04008051 if (memcg != swap_memcg) {
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008052 if (!mem_cgroup_is_root(swap_memcg))
Huang Yingd6810d732017-09-06 16:22:45 -07008053 page_counter_charge(&swap_memcg->memsw, nr_entries);
8054 page_counter_uncharge(&memcg->memsw, nr_entries);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008055 }
8056
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07008057 /*
8058 * Interrupts should be disabled here because the caller holds the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07008059 * i_pages lock which is taken with interrupts-off. It is
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07008060 * important here to have the interrupts disabled because it is the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07008061 * only synchronisation we have for updating the per-CPU variables.
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07008062 */
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07008063 memcg_stats_lock();
Matthew Wilcox (Oracle)6e0110c2021-04-29 13:40:11 -04008064 mem_cgroup_charge_statistics(memcg, -nr_entries);
Sebastian Andrzej Siewiorbe3e67b2022-03-22 14:40:41 -07008065 memcg_stats_unlock();
Matthew Wilcox (Oracle)3ecb0082021-12-27 21:11:34 -05008066 memcg_check_events(memcg, folio_nid(folio));
Johannes Weiner73f576c2016-07-20 15:44:57 -07008067
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07008068 css_put(&memcg->css);
Johannes Weiner21afa382015-02-11 15:26:36 -08008069}
8070
Huang Ying38d8b4e2017-07-06 15:37:18 -07008071/**
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008072 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
8073 * @folio: folio being added to swap
Vladimir Davydov37e84352016-01-20 15:02:56 -08008074 * @entry: swap entry to charge
8075 *
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008076 * Try to charge @folio's memcg for the swap space at @entry.
Vladimir Davydov37e84352016-01-20 15:02:56 -08008077 *
8078 * Returns 0 on success, -ENOMEM on failure.
8079 */
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008080int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
Vladimir Davydov37e84352016-01-20 15:02:56 -08008081{
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008082 unsigned int nr_pages = folio_nr_pages(folio);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008083 struct page_counter *counter;
Huang Ying38d8b4e2017-07-06 15:37:18 -07008084 struct mem_cgroup *memcg;
Vladimir Davydov37e84352016-01-20 15:02:56 -08008085 unsigned short oldid;
8086
Johannes Weinerb94c4e92022-09-26 09:57:03 -04008087 if (do_memsw_account())
Vladimir Davydov37e84352016-01-20 15:02:56 -08008088 return 0;
8089
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008090 memcg = folio_memcg(folio);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008091
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008092 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008093 if (!memcg)
8094 return 0;
8095
Tejun Heof3a53a32018-06-07 17:05:35 -07008096 if (!entry.val) {
8097 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Tejun Heobb98f2c2018-06-07 17:05:31 -07008098 return 0;
Tejun Heof3a53a32018-06-07 17:05:35 -07008099 }
Tejun Heobb98f2c2018-06-07 17:05:31 -07008100
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008101 memcg = mem_cgroup_id_get_online(memcg);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008102
Johannes Weinerb25806d2022-09-26 09:57:02 -04008103 if (!mem_cgroup_is_root(memcg) &&
Huang Ying38d8b4e2017-07-06 15:37:18 -07008104 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
Tejun Heof3a53a32018-06-07 17:05:35 -07008105 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
8106 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07008107 mem_cgroup_id_put(memcg);
8108 return -ENOMEM;
8109 }
8110
Huang Ying38d8b4e2017-07-06 15:37:18 -07008111 /* Get references for the tail pages, too */
8112 if (nr_pages > 1)
8113 mem_cgroup_id_get_many(memcg, nr_pages - 1);
8114 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
Matthew Wilcox (Oracle)e2e3fdc2022-05-12 20:23:02 -07008115 VM_BUG_ON_FOLIO(oldid, folio);
Johannes Weinerc9019e92018-01-31 16:16:37 -08008116 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008117
Vladimir Davydov37e84352016-01-20 15:02:56 -08008118 return 0;
8119}
8120
Johannes Weiner21afa382015-02-11 15:26:36 -08008121/**
Suren Baghdasaryan01c4b282021-09-02 14:54:54 -07008122 * __mem_cgroup_uncharge_swap - uncharge swap space
Johannes Weiner21afa382015-02-11 15:26:36 -08008123 * @entry: swap entry to uncharge
Huang Ying38d8b4e2017-07-06 15:37:18 -07008124 * @nr_pages: the amount of swap space to uncharge
Johannes Weiner21afa382015-02-11 15:26:36 -08008125 */
Suren Baghdasaryan01c4b282021-09-02 14:54:54 -07008126void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
Johannes Weiner21afa382015-02-11 15:26:36 -08008127{
8128 struct mem_cgroup *memcg;
8129 unsigned short id;
8130
Huang Ying38d8b4e2017-07-06 15:37:18 -07008131 id = swap_cgroup_record(entry, 0, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08008132 rcu_read_lock();
Vladimir Davydovadbe4272015-04-15 16:13:00 -07008133 memcg = mem_cgroup_from_id(id);
Johannes Weiner21afa382015-02-11 15:26:36 -08008134 if (memcg) {
Johannes Weinerb25806d2022-09-26 09:57:02 -04008135 if (!mem_cgroup_is_root(memcg)) {
Johannes Weinerb94c4e92022-09-26 09:57:03 -04008136 if (do_memsw_account())
Huang Ying38d8b4e2017-07-06 15:37:18 -07008137 page_counter_uncharge(&memcg->memsw, nr_pages);
Johannes Weinerb94c4e92022-09-26 09:57:03 -04008138 else
8139 page_counter_uncharge(&memcg->swap, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008140 }
Johannes Weinerc9019e92018-01-31 16:16:37 -08008141 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
Huang Ying38d8b4e2017-07-06 15:37:18 -07008142 mem_cgroup_id_put_many(memcg, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08008143 }
8144 rcu_read_unlock();
8145}
8146
Vladimir Davydovd8b38432016-01-20 15:03:07 -08008147long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
8148{
8149 long nr_swap_pages = get_nr_swap_pages();
8150
Johannes Weinerb25806d2022-09-26 09:57:02 -04008151 if (mem_cgroup_disabled() || do_memsw_account())
Vladimir Davydovd8b38432016-01-20 15:03:07 -08008152 return nr_swap_pages;
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05308153 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
Vladimir Davydovd8b38432016-01-20 15:03:07 -08008154 nr_swap_pages = min_t(long, nr_swap_pages,
Roman Gushchinbbec2e12018-06-07 17:06:18 -07008155 READ_ONCE(memcg->swap.max) -
Vladimir Davydovd8b38432016-01-20 15:03:07 -08008156 page_counter_read(&memcg->swap));
8157 return nr_swap_pages;
8158}
8159
Matthew Wilcox (Oracle)9202d527b2022-09-02 20:46:43 +01008160bool mem_cgroup_swap_full(struct folio *folio)
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008161{
8162 struct mem_cgroup *memcg;
8163
Matthew Wilcox (Oracle)9202d527b2022-09-02 20:46:43 +01008164 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008165
8166 if (vm_swap_full())
8167 return true;
Johannes Weinerb25806d2022-09-26 09:57:02 -04008168 if (do_memsw_account())
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008169 return false;
8170
Matthew Wilcox (Oracle)9202d527b2022-09-02 20:46:43 +01008171 memcg = folio_memcg(folio);
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008172 if (!memcg)
8173 return false;
8174
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05308175 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07008176 unsigned long usage = page_counter_read(&memcg->swap);
8177
8178 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
8179 usage * 2 >= READ_ONCE(memcg->swap.max))
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008180 return true;
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07008181 }
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08008182
8183 return false;
8184}
8185
Johannes Weinereccb52e2020-06-03 16:02:11 -07008186static int __init setup_swap_account(char *s)
Johannes Weiner21afa382015-02-11 15:26:36 -08008187{
Johannes Weiner118642d2024-02-13 03:16:34 -05008188 bool res;
8189
8190 if (!kstrtobool(s, &res) && !res)
8191 pr_warn_once("The swapaccount=0 commandline option is deprecated "
8192 "in favor of configuring swap control via cgroupfs. "
8193 "Please report your usecase to linux-mm@kvack.org if you "
8194 "depend on this functionality.\n");
Johannes Weiner21afa382015-02-11 15:26:36 -08008195 return 1;
8196}
Johannes Weinereccb52e2020-06-03 16:02:11 -07008197__setup("swapaccount=", setup_swap_account);
Johannes Weiner21afa382015-02-11 15:26:36 -08008198
Vladimir Davydov37e84352016-01-20 15:02:56 -08008199static u64 swap_current_read(struct cgroup_subsys_state *css,
8200 struct cftype *cft)
8201{
8202 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8203
8204 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
8205}
8206
Lars R. Damerowe0e0b412023-05-24 11:17:33 -07008207static u64 swap_peak_read(struct cgroup_subsys_state *css,
8208 struct cftype *cft)
8209{
8210 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8211
8212 return (u64)memcg->swap.watermark * PAGE_SIZE;
8213}
8214
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07008215static int swap_high_show(struct seq_file *m, void *v)
8216{
8217 return seq_puts_memcg_tunable(m,
8218 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
8219}
8220
8221static ssize_t swap_high_write(struct kernfs_open_file *of,
8222 char *buf, size_t nbytes, loff_t off)
8223{
8224 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8225 unsigned long high;
8226 int err;
8227
8228 buf = strstrip(buf);
8229 err = page_counter_memparse(buf, "max", &high);
8230 if (err)
8231 return err;
8232
8233 page_counter_set_high(&memcg->swap, high);
8234
8235 return nbytes;
8236}
8237
Vladimir Davydov37e84352016-01-20 15:02:56 -08008238static int swap_max_show(struct seq_file *m, void *v)
8239{
Chris Down677dc972019-03-05 15:45:55 -08008240 return seq_puts_memcg_tunable(m,
8241 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
Vladimir Davydov37e84352016-01-20 15:02:56 -08008242}
8243
8244static ssize_t swap_max_write(struct kernfs_open_file *of,
8245 char *buf, size_t nbytes, loff_t off)
8246{
8247 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8248 unsigned long max;
8249 int err;
8250
8251 buf = strstrip(buf);
8252 err = page_counter_memparse(buf, "max", &max);
8253 if (err)
8254 return err;
8255
Tejun Heobe091022018-06-07 17:09:21 -07008256 xchg(&memcg->swap.max, max);
Vladimir Davydov37e84352016-01-20 15:02:56 -08008257
8258 return nbytes;
8259}
8260
Tejun Heof3a53a32018-06-07 17:05:35 -07008261static int swap_events_show(struct seq_file *m, void *v)
8262{
Chris Downaa9694b2019-03-05 15:45:52 -08008263 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Tejun Heof3a53a32018-06-07 17:05:35 -07008264
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07008265 seq_printf(m, "high %lu\n",
8266 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
Tejun Heof3a53a32018-06-07 17:05:35 -07008267 seq_printf(m, "max %lu\n",
8268 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
8269 seq_printf(m, "fail %lu\n",
8270 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
8271
8272 return 0;
8273}
8274
Vladimir Davydov37e84352016-01-20 15:02:56 -08008275static struct cftype swap_files[] = {
8276 {
8277 .name = "swap.current",
8278 .flags = CFTYPE_NOT_ON_ROOT,
8279 .read_u64 = swap_current_read,
8280 },
8281 {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07008282 .name = "swap.high",
8283 .flags = CFTYPE_NOT_ON_ROOT,
8284 .seq_show = swap_high_show,
8285 .write = swap_high_write,
8286 },
8287 {
Vladimir Davydov37e84352016-01-20 15:02:56 -08008288 .name = "swap.max",
8289 .flags = CFTYPE_NOT_ON_ROOT,
8290 .seq_show = swap_max_show,
8291 .write = swap_max_write,
8292 },
Tejun Heof3a53a32018-06-07 17:05:35 -07008293 {
Lars R. Damerowe0e0b412023-05-24 11:17:33 -07008294 .name = "swap.peak",
8295 .flags = CFTYPE_NOT_ON_ROOT,
8296 .read_u64 = swap_peak_read,
8297 },
8298 {
Tejun Heof3a53a32018-06-07 17:05:35 -07008299 .name = "swap.events",
8300 .flags = CFTYPE_NOT_ON_ROOT,
8301 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
8302 .seq_show = swap_events_show,
8303 },
Vladimir Davydov37e84352016-01-20 15:02:56 -08008304 { } /* terminate */
8305};
8306
Johannes Weinereccb52e2020-06-03 16:02:11 -07008307static struct cftype memsw_files[] = {
Johannes Weiner21afa382015-02-11 15:26:36 -08008308 {
8309 .name = "memsw.usage_in_bytes",
8310 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
8311 .read_u64 = mem_cgroup_read_u64,
8312 },
8313 {
8314 .name = "memsw.max_usage_in_bytes",
8315 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
8316 .write = mem_cgroup_reset,
8317 .read_u64 = mem_cgroup_read_u64,
8318 },
8319 {
8320 .name = "memsw.limit_in_bytes",
8321 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
8322 .write = mem_cgroup_write,
8323 .read_u64 = mem_cgroup_read_u64,
8324 },
8325 {
8326 .name = "memsw.failcnt",
8327 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
8328 .write = mem_cgroup_reset,
8329 .read_u64 = mem_cgroup_read_u64,
8330 },
8331 { }, /* terminate */
8332};
8333
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008334#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8335/**
8336 * obj_cgroup_may_zswap - check if this cgroup can zswap
8337 * @objcg: the object cgroup
8338 *
8339 * Check if the hierarchical zswap limit has been reached.
8340 *
8341 * This doesn't check for specific headroom, and it is not atomic
8342 * either. But with zswap, the size of the allocation is only known
Muhammad Muzammilbe16dd762023-10-23 17:44:05 +05008343 * once compression has occurred, and this optimistic pre-check avoids
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008344 * spending cycles on compression when there is already no room left
8345 * or zswap is disabled altogether somewhere in the hierarchy.
8346 */
8347bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
8348{
8349 struct mem_cgroup *memcg, *original_memcg;
8350 bool ret = true;
8351
8352 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8353 return true;
8354
8355 original_memcg = get_mem_cgroup_from_objcg(objcg);
Kamalesh Babulal7848ed62022-09-30 19:14:33 +05308356 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008357 memcg = parent_mem_cgroup(memcg)) {
8358 unsigned long max = READ_ONCE(memcg->zswap_max);
8359 unsigned long pages;
8360
8361 if (max == PAGE_COUNTER_MAX)
8362 continue;
8363 if (max == 0) {
8364 ret = false;
8365 break;
8366 }
8367
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00008368 /*
8369 * mem_cgroup_flush_stats() ignores small changes. Use
8370 * do_flush_stats() directly to get accurate stats for charging.
8371 */
8372 do_flush_stats(memcg);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008373 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
8374 if (pages < max)
8375 continue;
8376 ret = false;
8377 break;
8378 }
8379 mem_cgroup_put(original_memcg);
8380 return ret;
8381}
8382
8383/**
8384 * obj_cgroup_charge_zswap - charge compression backend memory
8385 * @objcg: the object cgroup
8386 * @size: size of compressed object
8387 *
Miaohe Lin3a1060c2023-08-03 20:00:21 +08008388 * This forces the charge after obj_cgroup_may_zswap() allowed
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008389 * compression and storage in zwap for this cgroup to go ahead.
8390 */
8391void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
8392{
8393 struct mem_cgroup *memcg;
8394
8395 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8396 return;
8397
8398 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
8399
8400 /* PF_MEMALLOC context, charging must succeed */
8401 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
8402 VM_WARN_ON_ONCE(1);
8403
8404 rcu_read_lock();
8405 memcg = obj_cgroup_memcg(objcg);
8406 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
8407 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
8408 rcu_read_unlock();
8409}
8410
8411/**
8412 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
8413 * @objcg: the object cgroup
8414 * @size: size of compressed object
8415 *
8416 * Uncharges zswap memory on page in.
8417 */
8418void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
8419{
8420 struct mem_cgroup *memcg;
8421
8422 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
8423 return;
8424
8425 obj_cgroup_uncharge(objcg, size);
8426
8427 rcu_read_lock();
8428 memcg = obj_cgroup_memcg(objcg);
8429 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
8430 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
8431 rcu_read_unlock();
8432}
8433
Nhat Pham501a06f2023-12-07 11:24:06 -08008434bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
8435{
8436 /* if zswap is disabled, do not block pages going to the swapping device */
8437 return !is_zswap_enabled() || !memcg || READ_ONCE(memcg->zswap_writeback);
8438}
8439
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008440static u64 zswap_current_read(struct cgroup_subsys_state *css,
8441 struct cftype *cft)
8442{
Yosry Ahmed7d7ef0a2023-11-29 03:21:53 +00008443 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
8444
8445 mem_cgroup_flush_stats(memcg);
8446 return memcg_page_state(memcg, MEMCG_ZSWAP_B);
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008447}
8448
8449static int zswap_max_show(struct seq_file *m, void *v)
8450{
8451 return seq_puts_memcg_tunable(m,
8452 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
8453}
8454
8455static ssize_t zswap_max_write(struct kernfs_open_file *of,
8456 char *buf, size_t nbytes, loff_t off)
8457{
8458 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8459 unsigned long max;
8460 int err;
8461
8462 buf = strstrip(buf);
8463 err = page_counter_memparse(buf, "max", &max);
8464 if (err)
8465 return err;
8466
8467 xchg(&memcg->zswap_max, max);
8468
8469 return nbytes;
8470}
8471
Nhat Pham501a06f2023-12-07 11:24:06 -08008472static int zswap_writeback_show(struct seq_file *m, void *v)
8473{
8474 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8475
8476 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
8477 return 0;
8478}
8479
8480static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
8481 char *buf, size_t nbytes, loff_t off)
8482{
8483 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8484 int zswap_writeback;
8485 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
8486
8487 if (parse_ret)
8488 return parse_ret;
8489
8490 if (zswap_writeback != 0 && zswap_writeback != 1)
8491 return -EINVAL;
8492
8493 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
8494 return nbytes;
8495}
8496
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008497static struct cftype zswap_files[] = {
8498 {
8499 .name = "zswap.current",
8500 .flags = CFTYPE_NOT_ON_ROOT,
8501 .read_u64 = zswap_current_read,
8502 },
8503 {
8504 .name = "zswap.max",
8505 .flags = CFTYPE_NOT_ON_ROOT,
8506 .seq_show = zswap_max_show,
8507 .write = zswap_max_write,
8508 },
Nhat Pham501a06f2023-12-07 11:24:06 -08008509 {
8510 .name = "zswap.writeback",
8511 .seq_show = zswap_writeback_show,
8512 .write = zswap_writeback_write,
8513 },
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008514 { } /* terminate */
8515};
8516#endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
8517
Johannes Weiner21afa382015-02-11 15:26:36 -08008518static int __init mem_cgroup_swap_init(void)
8519{
Johannes Weiner2d1c4982020-06-03 16:02:14 -07008520 if (mem_cgroup_disabled())
Johannes Weinereccb52e2020-06-03 16:02:11 -07008521 return 0;
8522
8523 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
8524 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
Johannes Weinerf4840cc2022-05-19 14:08:53 -07008525#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
8526 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
8527#endif
Johannes Weiner21afa382015-02-11 15:26:36 -08008528 return 0;
8529}
Johannes Weinerb25806d2022-09-26 09:57:02 -04008530subsys_initcall(mem_cgroup_swap_init);
Johannes Weiner21afa382015-02-11 15:26:36 -08008531
Johannes Weinere55b9f92022-09-26 09:57:04 -04008532#endif /* CONFIG_SWAP */