]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - mm/memcontrol.c
mm: memcontrol: don't allocate cgroup swap arrays when memcg is disabled
[thirdparty/kernel/stable.git] / mm / memcontrol.c
CommitLineData
c942fddf 1// SPDX-License-Identifier: GPL-2.0-or-later
8cdea7c0
BS
2/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
78fb7466
PE
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
2e72b634
KS
10 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
7ae1e1d0
GC
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
1575e68b
JW
18 * Native page reclaim
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
6168d0da
AS
23 *
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
8cdea7c0
BS
26 */
27
3e32cb2e 28#include <linux/page_counter.h>
8cdea7c0
BS
29#include <linux/memcontrol.h>
30#include <linux/cgroup.h>
a520110e 31#include <linux/pagewalk.h>
6e84f315 32#include <linux/sched/mm.h>
3a4f8a0b 33#include <linux/shmem_fs.h>
4ffef5fe 34#include <linux/hugetlb.h>
d13d1443 35#include <linux/pagemap.h>
1ff9e6e1 36#include <linux/vm_event_item.h>
d52aa412 37#include <linux/smp.h>
8a9f3ccd 38#include <linux/page-flags.h>
66e1707b 39#include <linux/backing-dev.h>
8a9f3ccd
BS
40#include <linux/bit_spinlock.h>
41#include <linux/rcupdate.h>
e222432b 42#include <linux/limits.h>
b9e15baf 43#include <linux/export.h>
8c7c6e34 44#include <linux/mutex.h>
bb4cc1a8 45#include <linux/rbtree.h>
b6ac57d5 46#include <linux/slab.h>
66e1707b 47#include <linux/swap.h>
02491447 48#include <linux/swapops.h>
66e1707b 49#include <linux/spinlock.h>
2e72b634 50#include <linux/eventfd.h>
79bd9814 51#include <linux/poll.h>
2e72b634 52#include <linux/sort.h>
66e1707b 53#include <linux/fs.h>
d2ceb9b7 54#include <linux/seq_file.h>
70ddf637 55#include <linux/vmpressure.h>
dc90f084 56#include <linux/memremap.h>
b69408e8 57#include <linux/mm_inline.h>
5d1ea48b 58#include <linux/swap_cgroup.h>
cdec2e42 59#include <linux/cpu.h>
158e0a2d 60#include <linux/oom.h>
0056f4e6 61#include <linux/lockdep.h>
79bd9814 62#include <linux/file.h>
03248add 63#include <linux/resume_user_mode.h>
0e4b01df 64#include <linux/psi.h>
c8713d0b 65#include <linux/seq_buf.h>
08e552c6 66#include "internal.h"
d1a4c0b3 67#include <net/sock.h>
4bd2c1ee 68#include <net/ip.h>
f35c3a8e 69#include "slab.h"
014bb1de 70#include "swap.h"
8cdea7c0 71
7c0f6ba6 72#include <linux/uaccess.h>
8697d331 73
cc8e970c
KM
74#include <trace/events/vmscan.h>
75
073219e9
TH
76struct cgroup_subsys memory_cgrp_subsys __read_mostly;
77EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 78
7d828602
JW
79struct mem_cgroup *root_mem_cgroup __read_mostly;
80
37d5985c
RG
81/* Active memory cgroup to use from an interrupt context */
82DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
c74d40e8 83EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
37d5985c 84
f7e1cb6e 85/* Socket memory accounting disabled? */
0f0cace3 86static bool cgroup_memory_nosocket __ro_after_init;
f7e1cb6e 87
04823c83 88/* Kernel memory accounting disabled? */
17c17367 89static bool cgroup_memory_nokmem __ro_after_init;
04823c83 90
21afa38e 91/* Whether the swap controller is active */
c255a458 92#ifdef CONFIG_MEMCG_SWAP
c1b8fdae
KS
93static bool cgroup_memory_noswap __initdata;
94
95static DEFINE_STATIC_KEY_FALSE(memcg_swap_enabled_key);
96static inline bool memcg_swap_enabled(void)
97{
98 return static_branch_likely(&memcg_swap_enabled_key);
99}
c077719b 100#else
c1b8fdae
KS
101static inline bool memcg_swap_enabled(void)
102{
103 return false;
104}
2d1c4980 105#endif
c077719b 106
97b27821
TH
107#ifdef CONFIG_CGROUP_WRITEBACK
108static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
109#endif
110
7941d214
JW
111/* Whether legacy memory+swap accounting is active */
112static bool do_memsw_account(void)
113{
c1b8fdae 114 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg_swap_enabled();
7941d214
JW
115}
116
a0db00fc
KS
117#define THRESHOLDS_EVENTS_TARGET 128
118#define SOFTLIMIT_EVENTS_TARGET 1024
e9f8974f 119
bb4cc1a8
AM
120/*
121 * Cgroups above their limits are maintained in a RB-Tree, independent of
122 * their hierarchy representation
123 */
124
ef8f2327 125struct mem_cgroup_tree_per_node {
bb4cc1a8 126 struct rb_root rb_root;
fa90b2fd 127 struct rb_node *rb_rightmost;
bb4cc1a8
AM
128 spinlock_t lock;
129};
130
bb4cc1a8
AM
131struct mem_cgroup_tree {
132 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
133};
134
135static struct mem_cgroup_tree soft_limit_tree __read_mostly;
136
9490ff27
KH
137/* for OOM */
138struct mem_cgroup_eventfd_list {
139 struct list_head list;
140 struct eventfd_ctx *eventfd;
141};
2e72b634 142
79bd9814
TH
143/*
144 * cgroup_event represents events which userspace want to receive.
145 */
3bc942f3 146struct mem_cgroup_event {
79bd9814 147 /*
59b6f873 148 * memcg which the event belongs to.
79bd9814 149 */
59b6f873 150 struct mem_cgroup *memcg;
79bd9814
TH
151 /*
152 * eventfd to signal userspace about the event.
153 */
154 struct eventfd_ctx *eventfd;
155 /*
156 * Each of these stored in a list by the cgroup.
157 */
158 struct list_head list;
fba94807
TH
159 /*
160 * register_event() callback will be used to add new userspace
161 * waiter for changes related to this event. Use eventfd_signal()
162 * on eventfd to send notification to userspace.
163 */
59b6f873 164 int (*register_event)(struct mem_cgroup *memcg,
347c4a87 165 struct eventfd_ctx *eventfd, const char *args);
fba94807
TH
166 /*
167 * unregister_event() callback will be called when userspace closes
168 * the eventfd or on cgroup removing. This callback must be set,
169 * if you want provide notification functionality.
170 */
59b6f873 171 void (*unregister_event)(struct mem_cgroup *memcg,
fba94807 172 struct eventfd_ctx *eventfd);
79bd9814
TH
173 /*
174 * All fields below needed to unregister event when
175 * userspace closes eventfd.
176 */
177 poll_table pt;
178 wait_queue_head_t *wqh;
ac6424b9 179 wait_queue_entry_t wait;
79bd9814
TH
180 struct work_struct remove;
181};
182
c0ff4b85
R
183static void mem_cgroup_threshold(struct mem_cgroup *memcg);
184static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 185
7dc74be0
DN
186/* Stuffs for move charges at task migration. */
187/*
1dfab5ab 188 * Types of charges to be moved.
7dc74be0 189 */
1dfab5ab
JW
190#define MOVE_ANON 0x1U
191#define MOVE_FILE 0x2U
192#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
7dc74be0 193
4ffef5fe
DN
194/* "mc" and its members are protected by cgroup_mutex */
195static struct move_charge_struct {
b1dd693e 196 spinlock_t lock; /* for from, to */
264a0ae1 197 struct mm_struct *mm;
4ffef5fe
DN
198 struct mem_cgroup *from;
199 struct mem_cgroup *to;
1dfab5ab 200 unsigned long flags;
4ffef5fe 201 unsigned long precharge;
854ffa8d 202 unsigned long moved_charge;
483c30b5 203 unsigned long moved_swap;
8033b97c
DN
204 struct task_struct *moving_task; /* a task moving charges */
205 wait_queue_head_t waitq; /* a waitq for other context */
206} mc = {
2bd9bb20 207 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
208 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
209};
4ffef5fe 210
4e416953
BS
211/*
212 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
213 * limit reclaim to prevent infinite loops, if they ever occur.
214 */
a0db00fc 215#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
bb4cc1a8 216#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 217
8c7c6e34 218/* for encoding cft->private value on file */
86ae53e1
GC
219enum res_type {
220 _MEM,
221 _MEMSWAP,
510fc4e1 222 _KMEM,
d55f90bf 223 _TCP,
86ae53e1
GC
224};
225
a0db00fc
KS
226#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
227#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34
KH
228#define MEMFILE_ATTR(val) ((val) & 0xffff)
229
b05706f1
KT
230/*
231 * Iteration constructs for visiting all cgroups (under a tree). If
232 * loops are exited prematurely (break), mem_cgroup_iter_break() must
233 * be used for reference counting.
234 */
235#define for_each_mem_cgroup_tree(iter, root) \
236 for (iter = mem_cgroup_iter(root, NULL, NULL); \
237 iter != NULL; \
238 iter = mem_cgroup_iter(root, iter, NULL))
239
240#define for_each_mem_cgroup(iter) \
241 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
242 iter != NULL; \
243 iter = mem_cgroup_iter(NULL, iter, NULL))
244
a4ebf1b6 245static inline bool task_is_dying(void)
7775face
TH
246{
247 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
248 (current->flags & PF_EXITING);
249}
250
70ddf637
AV
251/* Some nice accessors for the vmpressure. */
252struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
253{
254 if (!memcg)
255 memcg = root_mem_cgroup;
256 return &memcg->vmpressure;
257}
258
9647875b 259struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
70ddf637 260{
9647875b 261 return container_of(vmpr, struct mem_cgroup, vmpressure);
70ddf637
AV
262}
263
84c07d11 264#ifdef CONFIG_MEMCG_KMEM
0764db9b 265static DEFINE_SPINLOCK(objcg_lock);
bf4f0599 266
4d5c8aed
RG
267bool mem_cgroup_kmem_disabled(void)
268{
269 return cgroup_memory_nokmem;
270}
271
f1286fae
MS
272static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
273 unsigned int nr_pages);
c1a660de 274
bf4f0599
RG
275static void obj_cgroup_release(struct percpu_ref *ref)
276{
277 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
bf4f0599
RG
278 unsigned int nr_bytes;
279 unsigned int nr_pages;
280 unsigned long flags;
281
282 /*
283 * At this point all allocated objects are freed, and
284 * objcg->nr_charged_bytes can't have an arbitrary byte value.
285 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
286 *
287 * The following sequence can lead to it:
288 * 1) CPU0: objcg == stock->cached_objcg
289 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
290 * PAGE_SIZE bytes are charged
291 * 3) CPU1: a process from another memcg is allocating something,
292 * the stock if flushed,
293 * objcg->nr_charged_bytes = PAGE_SIZE - 92
294 * 5) CPU0: we do release this object,
295 * 92 bytes are added to stock->nr_bytes
296 * 6) CPU0: stock is flushed,
297 * 92 bytes are added to objcg->nr_charged_bytes
298 *
299 * In the result, nr_charged_bytes == PAGE_SIZE.
300 * This page will be uncharged in obj_cgroup_release().
301 */
302 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
303 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
304 nr_pages = nr_bytes >> PAGE_SHIFT;
305
bf4f0599 306 if (nr_pages)
f1286fae 307 obj_cgroup_uncharge_pages(objcg, nr_pages);
271dd6b1 308
0764db9b 309 spin_lock_irqsave(&objcg_lock, flags);
bf4f0599 310 list_del(&objcg->list);
0764db9b 311 spin_unlock_irqrestore(&objcg_lock, flags);
bf4f0599
RG
312
313 percpu_ref_exit(ref);
314 kfree_rcu(objcg, rcu);
315}
316
317static struct obj_cgroup *obj_cgroup_alloc(void)
318{
319 struct obj_cgroup *objcg;
320 int ret;
321
322 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
323 if (!objcg)
324 return NULL;
325
326 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
327 GFP_KERNEL);
328 if (ret) {
329 kfree(objcg);
330 return NULL;
331 }
332 INIT_LIST_HEAD(&objcg->list);
333 return objcg;
334}
335
336static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
337 struct mem_cgroup *parent)
338{
339 struct obj_cgroup *objcg, *iter;
340
341 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
342
0764db9b 343 spin_lock_irq(&objcg_lock);
bf4f0599 344
9838354e
MS
345 /* 1) Ready to reparent active objcg. */
346 list_add(&objcg->list, &memcg->objcg_list);
347 /* 2) Reparent active objcg and already reparented objcgs to parent. */
348 list_for_each_entry(iter, &memcg->objcg_list, list)
349 WRITE_ONCE(iter->memcg, parent);
350 /* 3) Move already reparented objcgs to the parent's list */
bf4f0599
RG
351 list_splice(&memcg->objcg_list, &parent->objcg_list);
352
0764db9b 353 spin_unlock_irq(&objcg_lock);
bf4f0599
RG
354
355 percpu_ref_kill(&objcg->refcnt);
356}
357
d7f25f8a
GC
358/*
359 * A lot of the calls to the cache allocation functions are expected to be
272911a4 360 * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
d7f25f8a
GC
361 * conditional to this static branch, we'll have to allow modules that does
362 * kmem_cache_alloc and the such to see this symbol as well
363 */
ef12947c 364DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
d7f25f8a 365EXPORT_SYMBOL(memcg_kmem_enabled_key);
0a432dcb 366#endif
17cc4dfe 367
ad7fa852
TH
368/**
369 * mem_cgroup_css_from_page - css of the memcg associated with a page
370 * @page: page of interest
371 *
372 * If memcg is bound to the default hierarchy, css of the memcg associated
373 * with @page is returned. The returned css remains associated with @page
374 * until it is released.
375 *
376 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
377 * is returned.
ad7fa852
TH
378 */
379struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
380{
381 struct mem_cgroup *memcg;
382
bcfe06bf 383 memcg = page_memcg(page);
ad7fa852 384
9e10a130 385 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
ad7fa852
TH
386 memcg = root_mem_cgroup;
387
ad7fa852
TH
388 return &memcg->css;
389}
390
2fc04524
VD
391/**
392 * page_cgroup_ino - return inode number of the memcg a page is charged to
393 * @page: the page
394 *
395 * Look up the closest online ancestor of the memory cgroup @page is charged to
396 * and return its inode number or 0 if @page is not charged to any cgroup. It
397 * is safe to call this function without holding a reference to @page.
398 *
399 * Note, this function is inherently racy, because there is nothing to prevent
400 * the cgroup inode from getting torn down and potentially reallocated a moment
401 * after page_cgroup_ino() returns, so it only should be used by callers that
402 * do not care (such as procfs interfaces).
403 */
404ino_t page_cgroup_ino(struct page *page)
405{
406 struct mem_cgroup *memcg;
407 unsigned long ino = 0;
408
409 rcu_read_lock();
bcfe06bf 410 memcg = page_memcg_check(page);
286e04b8 411
2fc04524
VD
412 while (memcg && !(memcg->css.flags & CSS_ONLINE))
413 memcg = parent_mem_cgroup(memcg);
414 if (memcg)
415 ino = cgroup_ino(memcg->css.cgroup);
416 rcu_read_unlock();
417 return ino;
418}
419
ef8f2327
MG
420static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
421 struct mem_cgroup_tree_per_node *mctz,
3e32cb2e 422 unsigned long new_usage_in_excess)
bb4cc1a8
AM
423{
424 struct rb_node **p = &mctz->rb_root.rb_node;
425 struct rb_node *parent = NULL;
ef8f2327 426 struct mem_cgroup_per_node *mz_node;
fa90b2fd 427 bool rightmost = true;
bb4cc1a8
AM
428
429 if (mz->on_tree)
430 return;
431
432 mz->usage_in_excess = new_usage_in_excess;
433 if (!mz->usage_in_excess)
434 return;
435 while (*p) {
436 parent = *p;
ef8f2327 437 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
bb4cc1a8 438 tree_node);
fa90b2fd 439 if (mz->usage_in_excess < mz_node->usage_in_excess) {
bb4cc1a8 440 p = &(*p)->rb_left;
fa90b2fd 441 rightmost = false;
378876b0 442 } else {
bb4cc1a8 443 p = &(*p)->rb_right;
378876b0 444 }
bb4cc1a8 445 }
fa90b2fd
DB
446
447 if (rightmost)
448 mctz->rb_rightmost = &mz->tree_node;
449
bb4cc1a8
AM
450 rb_link_node(&mz->tree_node, parent, p);
451 rb_insert_color(&mz->tree_node, &mctz->rb_root);
452 mz->on_tree = true;
453}
454
ef8f2327
MG
455static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
456 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8
AM
457{
458 if (!mz->on_tree)
459 return;
fa90b2fd
DB
460
461 if (&mz->tree_node == mctz->rb_rightmost)
462 mctz->rb_rightmost = rb_prev(&mz->tree_node);
463
bb4cc1a8
AM
464 rb_erase(&mz->tree_node, &mctz->rb_root);
465 mz->on_tree = false;
466}
467
ef8f2327
MG
468static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
469 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 470{
0a31bc97
JW
471 unsigned long flags;
472
473 spin_lock_irqsave(&mctz->lock, flags);
cf2c8127 474 __mem_cgroup_remove_exceeded(mz, mctz);
0a31bc97 475 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
476}
477
3e32cb2e
JW
478static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
479{
480 unsigned long nr_pages = page_counter_read(&memcg->memory);
4db0c3c2 481 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
3e32cb2e
JW
482 unsigned long excess = 0;
483
484 if (nr_pages > soft_limit)
485 excess = nr_pages - soft_limit;
486
487 return excess;
488}
bb4cc1a8 489
658b69c9 490static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
bb4cc1a8 491{
3e32cb2e 492 unsigned long excess;
ef8f2327
MG
493 struct mem_cgroup_per_node *mz;
494 struct mem_cgroup_tree_per_node *mctz;
bb4cc1a8 495
2ab082ba 496 mctz = soft_limit_tree.rb_tree_per_node[nid];
bfc7228b
LD
497 if (!mctz)
498 return;
bb4cc1a8
AM
499 /*
500 * Necessary to update all ancestors when hierarchy is used.
501 * because their event counter is not touched.
502 */
503 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
658b69c9 504 mz = memcg->nodeinfo[nid];
3e32cb2e 505 excess = soft_limit_excess(memcg);
bb4cc1a8
AM
506 /*
507 * We have to update the tree if mz is on RB-tree or
508 * mem is over its softlimit.
509 */
510 if (excess || mz->on_tree) {
0a31bc97
JW
511 unsigned long flags;
512
513 spin_lock_irqsave(&mctz->lock, flags);
bb4cc1a8
AM
514 /* if on-tree, remove it */
515 if (mz->on_tree)
cf2c8127 516 __mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
517 /*
518 * Insert again. mz->usage_in_excess will be updated.
519 * If excess is 0, no tree ops.
520 */
cf2c8127 521 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 522 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
523 }
524 }
525}
526
527static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
528{
ef8f2327
MG
529 struct mem_cgroup_tree_per_node *mctz;
530 struct mem_cgroup_per_node *mz;
531 int nid;
bb4cc1a8 532
e231875b 533 for_each_node(nid) {
a3747b53 534 mz = memcg->nodeinfo[nid];
2ab082ba 535 mctz = soft_limit_tree.rb_tree_per_node[nid];
bfc7228b
LD
536 if (mctz)
537 mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
538 }
539}
540
ef8f2327
MG
541static struct mem_cgroup_per_node *
542__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 543{
ef8f2327 544 struct mem_cgroup_per_node *mz;
bb4cc1a8
AM
545
546retry:
547 mz = NULL;
fa90b2fd 548 if (!mctz->rb_rightmost)
bb4cc1a8
AM
549 goto done; /* Nothing to reclaim from */
550
fa90b2fd
DB
551 mz = rb_entry(mctz->rb_rightmost,
552 struct mem_cgroup_per_node, tree_node);
bb4cc1a8
AM
553 /*
554 * Remove the node now but someone else can add it back,
555 * we will to add it back at the end of reclaim to its correct
556 * position in the tree.
557 */
cf2c8127 558 __mem_cgroup_remove_exceeded(mz, mctz);
3e32cb2e 559 if (!soft_limit_excess(mz->memcg) ||
8965aa28 560 !css_tryget(&mz->memcg->css))
bb4cc1a8
AM
561 goto retry;
562done:
563 return mz;
564}
565
ef8f2327
MG
566static struct mem_cgroup_per_node *
567mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 568{
ef8f2327 569 struct mem_cgroup_per_node *mz;
bb4cc1a8 570
0a31bc97 571 spin_lock_irq(&mctz->lock);
bb4cc1a8 572 mz = __mem_cgroup_largest_soft_limit_node(mctz);
0a31bc97 573 spin_unlock_irq(&mctz->lock);
bb4cc1a8
AM
574 return mz;
575}
576
11192d9c
SB
577/*
578 * memcg and lruvec stats flushing
579 *
580 * Many codepaths leading to stats update or read are performance sensitive and
581 * adding stats flushing in such codepaths is not desirable. So, to optimize the
582 * flushing the kernel does:
583 *
584 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
585 * rstat update tree grow unbounded.
586 *
587 * 2) Flush the stats synchronously on reader side only when there are more than
588 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
589 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
590 * only for 2 seconds due to (1).
591 */
592static void flush_memcg_stats_dwork(struct work_struct *w);
593static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
594static DEFINE_SPINLOCK(stats_flush_lock);
595static DEFINE_PER_CPU(unsigned int, stats_updates);
596static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
9b301615
SB
597static u64 flush_next_time;
598
599#define FLUSH_TIME (2UL*HZ)
11192d9c 600
be3e67b5
SAS
601/*
602 * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
603 * not rely on this as part of an acquired spinlock_t lock. These functions are
604 * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
605 * is sufficient.
606 */
607static void memcg_stats_lock(void)
608{
609#ifdef CONFIG_PREEMPT_RT
610 preempt_disable();
611#else
612 VM_BUG_ON(!irqs_disabled());
613#endif
614}
615
616static void __memcg_stats_lock(void)
617{
618#ifdef CONFIG_PREEMPT_RT
619 preempt_disable();
620#endif
621}
622
623static void memcg_stats_unlock(void)
624{
625#ifdef CONFIG_PREEMPT_RT
626 preempt_enable();
627#endif
628}
629
5b3be698 630static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
11192d9c 631{
5b3be698
SB
632 unsigned int x;
633
11192d9c 634 cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
5b3be698
SB
635
636 x = __this_cpu_add_return(stats_updates, abs(val));
637 if (x > MEMCG_CHARGE_BATCH) {
873f64b7
JS
638 /*
639 * If stats_flush_threshold exceeds the threshold
640 * (>num_online_cpus()), cgroup stats update will be triggered
641 * in __mem_cgroup_flush_stats(). Increasing this var further
642 * is redundant and simply adds overhead in atomic update.
643 */
644 if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
645 atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
5b3be698
SB
646 __this_cpu_write(stats_updates, 0);
647 }
11192d9c
SB
648}
649
650static void __mem_cgroup_flush_stats(void)
651{
fd25a9e0
SB
652 unsigned long flag;
653
654 if (!spin_trylock_irqsave(&stats_flush_lock, flag))
11192d9c
SB
655 return;
656
9b301615 657 flush_next_time = jiffies_64 + 2*FLUSH_TIME;
11192d9c
SB
658 cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
659 atomic_set(&stats_flush_threshold, 0);
fd25a9e0 660 spin_unlock_irqrestore(&stats_flush_lock, flag);
11192d9c
SB
661}
662
663void mem_cgroup_flush_stats(void)
664{
665 if (atomic_read(&stats_flush_threshold) > num_online_cpus())
666 __mem_cgroup_flush_stats();
667}
668
9b301615
SB
669void mem_cgroup_flush_stats_delayed(void)
670{
671 if (time_after64(jiffies_64, flush_next_time))
672 mem_cgroup_flush_stats();
673}
674
11192d9c
SB
675static void flush_memcg_stats_dwork(struct work_struct *w)
676{
5b3be698 677 __mem_cgroup_flush_stats();
9b301615 678 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
11192d9c
SB
679}
680
d396def5
SB
681/* Subset of vm_event_item to report for memcg event stats */
682static const unsigned int memcg_vm_event_stat[] = {
8278f1c7
SB
683 PGPGIN,
684 PGPGOUT,
d396def5
SB
685 PGSCAN_KSWAPD,
686 PGSCAN_DIRECT,
687 PGSTEAL_KSWAPD,
688 PGSTEAL_DIRECT,
689 PGFAULT,
690 PGMAJFAULT,
691 PGREFILL,
692 PGACTIVATE,
693 PGDEACTIVATE,
694 PGLAZYFREE,
695 PGLAZYFREED,
696#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
697 ZSWPIN,
698 ZSWPOUT,
699#endif
700#ifdef CONFIG_TRANSPARENT_HUGEPAGE
701 THP_FAULT_ALLOC,
702 THP_COLLAPSE_ALLOC,
703#endif
704};
705
8278f1c7
SB
706#define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
707static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
708
709static void init_memcg_events(void)
710{
711 int i;
712
713 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
714 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
715}
716
717static inline int memcg_events_index(enum vm_event_item idx)
718{
719 return mem_cgroup_events_index[idx] - 1;
720}
721
410f8e82
SB
722struct memcg_vmstats_percpu {
723 /* Local (CPU and cgroup) page state & events */
724 long state[MEMCG_NR_STAT];
8278f1c7 725 unsigned long events[NR_MEMCG_EVENTS];
410f8e82
SB
726
727 /* Delta calculation for lockless upward propagation */
728 long state_prev[MEMCG_NR_STAT];
8278f1c7 729 unsigned long events_prev[NR_MEMCG_EVENTS];
410f8e82
SB
730
731 /* Cgroup1: threshold notifications & softlimit tree updates */
732 unsigned long nr_page_events;
733 unsigned long targets[MEM_CGROUP_NTARGETS];
734};
735
736struct memcg_vmstats {
737 /* Aggregated (CPU and subtree) page state & events */
738 long state[MEMCG_NR_STAT];
8278f1c7 739 unsigned long events[NR_MEMCG_EVENTS];
410f8e82
SB
740
741 /* Pending child counts during tree propagation */
742 long state_pending[MEMCG_NR_STAT];
8278f1c7 743 unsigned long events_pending[NR_MEMCG_EVENTS];
410f8e82
SB
744};
745
746unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
747{
748 long x = READ_ONCE(memcg->vmstats->state[idx]);
749#ifdef CONFIG_SMP
750 if (x < 0)
751 x = 0;
752#endif
753 return x;
754}
755
db9adbcb
JW
756/**
757 * __mod_memcg_state - update cgroup memory statistics
758 * @memcg: the memory cgroup
759 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
760 * @val: delta to add to the counter, can be negative
761 */
762void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
763{
db9adbcb
JW
764 if (mem_cgroup_disabled())
765 return;
766
2d146aa3 767 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
5b3be698 768 memcg_rstat_updated(memcg, val);
db9adbcb
JW
769}
770
2d146aa3 771/* idx can be of type enum memcg_stat_item or node_stat_item. */
a18e6e6e
JW
772static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
773{
774 long x = 0;
775 int cpu;
776
777 for_each_possible_cpu(cpu)
2d146aa3 778 x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
a18e6e6e
JW
779#ifdef CONFIG_SMP
780 if (x < 0)
781 x = 0;
782#endif
783 return x;
784}
785
eedc4e5a
RG
786void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
787 int val)
db9adbcb
JW
788{
789 struct mem_cgroup_per_node *pn;
42a30035 790 struct mem_cgroup *memcg;
db9adbcb 791
db9adbcb 792 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
42a30035 793 memcg = pn->memcg;
db9adbcb 794
be3e67b5
SAS
795 /*
796 * The caller from rmap relay on disabled preemption becase they never
797 * update their counter from in-interrupt context. For these two
798 * counters we check that the update is never performed from an
799 * interrupt context while other caller need to have disabled interrupt.
800 */
801 __memcg_stats_lock();
802 if (IS_ENABLED(CONFIG_DEBUG_VM) && !IS_ENABLED(CONFIG_PREEMPT_RT)) {
803 switch (idx) {
804 case NR_ANON_MAPPED:
805 case NR_FILE_MAPPED:
806 case NR_ANON_THPS:
807 case NR_SHMEM_PMDMAPPED:
808 case NR_FILE_PMDMAPPED:
809 WARN_ON_ONCE(!in_task());
810 break;
811 default:
812 WARN_ON_ONCE(!irqs_disabled());
813 }
814 }
815
db9adbcb 816 /* Update memcg */
11192d9c 817 __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
db9adbcb 818
b4c46484 819 /* Update lruvec */
7e1c0d6f 820 __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
11192d9c 821
5b3be698 822 memcg_rstat_updated(memcg, val);
be3e67b5 823 memcg_stats_unlock();
db9adbcb
JW
824}
825
eedc4e5a
RG
826/**
827 * __mod_lruvec_state - update lruvec memory statistics
828 * @lruvec: the lruvec
829 * @idx: the stat item
830 * @val: delta to add to the counter, can be negative
831 *
832 * The lruvec is the intersection of the NUMA node and a cgroup. This
833 * function updates the all three counters that are affected by a
834 * change of state at this level: per-node, per-cgroup, per-lruvec.
835 */
836void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
837 int val)
838{
839 /* Update node */
840 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
841
842 /* Update memcg and lruvec */
843 if (!mem_cgroup_disabled())
844 __mod_memcg_lruvec_state(lruvec, idx, val);
845}
846
c47d5032
SB
847void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
848 int val)
849{
850 struct page *head = compound_head(page); /* rmap on tail pages */
b4e0b68f 851 struct mem_cgroup *memcg;
c47d5032
SB
852 pg_data_t *pgdat = page_pgdat(page);
853 struct lruvec *lruvec;
854
b4e0b68f
MS
855 rcu_read_lock();
856 memcg = page_memcg(head);
c47d5032 857 /* Untracked pages have no memcg, no lruvec. Update only the node */
d635a69d 858 if (!memcg) {
b4e0b68f 859 rcu_read_unlock();
c47d5032
SB
860 __mod_node_page_state(pgdat, idx, val);
861 return;
862 }
863
d635a69d 864 lruvec = mem_cgroup_lruvec(memcg, pgdat);
c47d5032 865 __mod_lruvec_state(lruvec, idx, val);
b4e0b68f 866 rcu_read_unlock();
c47d5032 867}
f0c0c115 868EXPORT_SYMBOL(__mod_lruvec_page_state);
c47d5032 869
da3ceeff 870void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
ec9f0238 871{
4f103c63 872 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
ec9f0238
RG
873 struct mem_cgroup *memcg;
874 struct lruvec *lruvec;
875
876 rcu_read_lock();
fc4db90f 877 memcg = mem_cgroup_from_slab_obj(p);
ec9f0238 878
8faeb1ff
MS
879 /*
880 * Untracked pages have no memcg, no lruvec. Update only the
881 * node. If we reparent the slab objects to the root memcg,
882 * when we free the slab object, we need to update the per-memcg
883 * vmstats to keep it correct for the root memcg.
884 */
885 if (!memcg) {
ec9f0238
RG
886 __mod_node_page_state(pgdat, idx, val);
887 } else {
867e5e1d 888 lruvec = mem_cgroup_lruvec(memcg, pgdat);
ec9f0238
RG
889 __mod_lruvec_state(lruvec, idx, val);
890 }
891 rcu_read_unlock();
892}
893
db9adbcb
JW
894/**
895 * __count_memcg_events - account VM events in a cgroup
896 * @memcg: the memory cgroup
897 * @idx: the event item
f0953a1b 898 * @count: the number of events that occurred
db9adbcb
JW
899 */
900void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
901 unsigned long count)
902{
8278f1c7
SB
903 int index = memcg_events_index(idx);
904
905 if (mem_cgroup_disabled() || index < 0)
db9adbcb
JW
906 return;
907
be3e67b5 908 memcg_stats_lock();
8278f1c7 909 __this_cpu_add(memcg->vmstats_percpu->events[index], count);
5b3be698 910 memcg_rstat_updated(memcg, count);
be3e67b5 911 memcg_stats_unlock();
db9adbcb
JW
912}
913
42a30035 914static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
e9f8974f 915{
8278f1c7
SB
916 int index = memcg_events_index(event);
917
918 if (index < 0)
919 return 0;
920 return READ_ONCE(memcg->vmstats->events[index]);
e9f8974f
JW
921}
922
42a30035
JW
923static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
924{
815744d7
JW
925 long x = 0;
926 int cpu;
8278f1c7
SB
927 int index = memcg_events_index(event);
928
929 if (index < 0)
930 return 0;
815744d7
JW
931
932 for_each_possible_cpu(cpu)
8278f1c7 933 x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
815744d7 934 return x;
42a30035
JW
935}
936
c0ff4b85 937static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
3fba69a5 938 int nr_pages)
d52aa412 939{
e401f176
KH
940 /* pagein of a big page is an event. So, ignore page size */
941 if (nr_pages > 0)
c9019e9b 942 __count_memcg_events(memcg, PGPGIN, 1);
3751d604 943 else {
c9019e9b 944 __count_memcg_events(memcg, PGPGOUT, 1);
3751d604
KH
945 nr_pages = -nr_pages; /* for event */
946 }
e401f176 947
871789d4 948 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
6d12e2d8
KH
949}
950
f53d7ce3
JW
951static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
952 enum mem_cgroup_events_target target)
7a159cc9
JW
953{
954 unsigned long val, next;
955
871789d4
CD
956 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
957 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
7a159cc9 958 /* from time_after() in jiffies.h */
6a1a8b80 959 if ((long)(next - val) < 0) {
f53d7ce3
JW
960 switch (target) {
961 case MEM_CGROUP_TARGET_THRESH:
962 next = val + THRESHOLDS_EVENTS_TARGET;
963 break;
bb4cc1a8
AM
964 case MEM_CGROUP_TARGET_SOFTLIMIT:
965 next = val + SOFTLIMIT_EVENTS_TARGET;
966 break;
f53d7ce3
JW
967 default:
968 break;
969 }
871789d4 970 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
f53d7ce3 971 return true;
7a159cc9 972 }
f53d7ce3 973 return false;
d2265e6f
KH
974}
975
976/*
977 * Check events in order.
978 *
979 */
8e88bd2d 980static void memcg_check_events(struct mem_cgroup *memcg, int nid)
d2265e6f 981{
2343e88d
SAS
982 if (IS_ENABLED(CONFIG_PREEMPT_RT))
983 return;
984
d2265e6f 985 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
986 if (unlikely(mem_cgroup_event_ratelimit(memcg,
987 MEM_CGROUP_TARGET_THRESH))) {
bb4cc1a8 988 bool do_softlimit;
f53d7ce3 989
bb4cc1a8
AM
990 do_softlimit = mem_cgroup_event_ratelimit(memcg,
991 MEM_CGROUP_TARGET_SOFTLIMIT);
c0ff4b85 992 mem_cgroup_threshold(memcg);
bb4cc1a8 993 if (unlikely(do_softlimit))
8e88bd2d 994 mem_cgroup_update_tree(memcg, nid);
0a31bc97 995 }
d2265e6f
KH
996}
997
cf475ad2 998struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 999{
31a78f23
BS
1000 /*
1001 * mm_update_next_owner() may clear mm->owner to NULL
1002 * if it races with swapoff, page migration, etc.
1003 * So this can be called with p == NULL.
1004 */
1005 if (unlikely(!p))
1006 return NULL;
1007
073219e9 1008 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466 1009}
33398cf2 1010EXPORT_SYMBOL(mem_cgroup_from_task);
78fb7466 1011
04f94e3f
DS
1012static __always_inline struct mem_cgroup *active_memcg(void)
1013{
55a68c82 1014 if (!in_task())
04f94e3f
DS
1015 return this_cpu_read(int_active_memcg);
1016 else
1017 return current->active_memcg;
1018}
1019
d46eb14b
SB
1020/**
1021 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1022 * @mm: mm from which memcg should be extracted. It can be NULL.
1023 *
04f94e3f
DS
1024 * Obtain a reference on mm->memcg and returns it if successful. If mm
1025 * is NULL, then the memcg is chosen as follows:
1026 * 1) The active memcg, if set.
1027 * 2) current->mm->memcg, if available
1028 * 3) root memcg
1029 * If mem_cgroup is disabled, NULL is returned.
d46eb14b
SB
1030 */
1031struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 1032{
d46eb14b
SB
1033 struct mem_cgroup *memcg;
1034
1035 if (mem_cgroup_disabled())
1036 return NULL;
0b7f569e 1037
2884b6b7
MS
1038 /*
1039 * Page cache insertions can happen without an
1040 * actual mm context, e.g. during disk probing
1041 * on boot, loopback IO, acct() writes etc.
1042 *
1043 * No need to css_get on root memcg as the reference
1044 * counting is disabled on the root level in the
1045 * cgroup core. See CSS_NO_REF.
1046 */
04f94e3f
DS
1047 if (unlikely(!mm)) {
1048 memcg = active_memcg();
1049 if (unlikely(memcg)) {
1050 /* remote memcg must hold a ref */
1051 css_get(&memcg->css);
1052 return memcg;
1053 }
1054 mm = current->mm;
1055 if (unlikely(!mm))
1056 return root_mem_cgroup;
1057 }
2884b6b7 1058
54595fe2
KH
1059 rcu_read_lock();
1060 do {
2884b6b7
MS
1061 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1062 if (unlikely(!memcg))
df381975 1063 memcg = root_mem_cgroup;
00d484f3 1064 } while (!css_tryget(&memcg->css));
54595fe2 1065 rcu_read_unlock();
c0ff4b85 1066 return memcg;
54595fe2 1067}
d46eb14b
SB
1068EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1069
4127c650
RG
1070static __always_inline bool memcg_kmem_bypass(void)
1071{
1072 /* Allow remote memcg charging from any context. */
1073 if (unlikely(active_memcg()))
1074 return false;
1075
1076 /* Memcg to charge can't be determined. */
6126891c 1077 if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
4127c650
RG
1078 return true;
1079
1080 return false;
1081}
1082
5660048c
JW
1083/**
1084 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1085 * @root: hierarchy root
1086 * @prev: previously returned memcg, NULL on first invocation
1087 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1088 *
1089 * Returns references to children of the hierarchy below @root, or
1090 * @root itself, or %NULL after a full round-trip.
1091 *
1092 * Caller must pass the return value in @prev on subsequent
1093 * invocations for reference counting, or use mem_cgroup_iter_break()
1094 * to cancel a hierarchy walk before the round-trip is complete.
1095 *
05bdc520
ML
1096 * Reclaimers can specify a node in @reclaim to divide up the memcgs
1097 * in the hierarchy among all concurrent reclaimers operating on the
1098 * same node.
5660048c 1099 */
694fbc0f 1100struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 1101 struct mem_cgroup *prev,
694fbc0f 1102 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1103{
3f649ab7 1104 struct mem_cgroup_reclaim_iter *iter;
5ac8fb31 1105 struct cgroup_subsys_state *css = NULL;
9f3a0d09 1106 struct mem_cgroup *memcg = NULL;
5ac8fb31 1107 struct mem_cgroup *pos = NULL;
711d3d2c 1108
694fbc0f
AM
1109 if (mem_cgroup_disabled())
1110 return NULL;
5660048c 1111
9f3a0d09
JW
1112 if (!root)
1113 root = root_mem_cgroup;
7d74b06f 1114
542f85f9 1115 rcu_read_lock();
5f578161 1116
5ac8fb31 1117 if (reclaim) {
ef8f2327 1118 struct mem_cgroup_per_node *mz;
5ac8fb31 1119
a3747b53 1120 mz = root->nodeinfo[reclaim->pgdat->node_id];
9da83f3f 1121 iter = &mz->iter;
5ac8fb31 1122
a9320aae
WY
1123 /*
1124 * On start, join the current reclaim iteration cycle.
1125 * Exit when a concurrent walker completes it.
1126 */
1127 if (!prev)
1128 reclaim->generation = iter->generation;
1129 else if (reclaim->generation != iter->generation)
5ac8fb31
JW
1130 goto out_unlock;
1131
6df38689 1132 while (1) {
4db0c3c2 1133 pos = READ_ONCE(iter->position);
6df38689
VD
1134 if (!pos || css_tryget(&pos->css))
1135 break;
5ac8fb31 1136 /*
6df38689
VD
1137 * css reference reached zero, so iter->position will
1138 * be cleared by ->css_released. However, we should not
1139 * rely on this happening soon, because ->css_released
1140 * is called from a work queue, and by busy-waiting we
1141 * might block it. So we clear iter->position right
1142 * away.
5ac8fb31 1143 */
6df38689
VD
1144 (void)cmpxchg(&iter->position, pos, NULL);
1145 }
89d8330c
WY
1146 } else if (prev) {
1147 pos = prev;
5ac8fb31
JW
1148 }
1149
1150 if (pos)
1151 css = &pos->css;
1152
1153 for (;;) {
1154 css = css_next_descendant_pre(css, &root->css);
1155 if (!css) {
1156 /*
1157 * Reclaimers share the hierarchy walk, and a
1158 * new one might jump in right at the end of
1159 * the hierarchy - make sure they see at least
1160 * one group and restart from the beginning.
1161 */
1162 if (!prev)
1163 continue;
1164 break;
527a5ec9 1165 }
7d74b06f 1166
5ac8fb31
JW
1167 /*
1168 * Verify the css and acquire a reference. The root
1169 * is provided by the caller, so we know it's alive
1170 * and kicking, and don't take an extra reference.
1171 */
41555dad
WY
1172 if (css == &root->css || css_tryget(css)) {
1173 memcg = mem_cgroup_from_css(css);
0b8f73e1 1174 break;
41555dad 1175 }
9f3a0d09 1176 }
5ac8fb31
JW
1177
1178 if (reclaim) {
5ac8fb31 1179 /*
6df38689
VD
1180 * The position could have already been updated by a competing
1181 * thread, so check that the value hasn't changed since we read
1182 * it to avoid reclaiming from the same cgroup twice.
5ac8fb31 1183 */
6df38689
VD
1184 (void)cmpxchg(&iter->position, pos, memcg);
1185
5ac8fb31
JW
1186 if (pos)
1187 css_put(&pos->css);
1188
1189 if (!memcg)
1190 iter->generation++;
9f3a0d09 1191 }
5ac8fb31 1192
542f85f9
MH
1193out_unlock:
1194 rcu_read_unlock();
c40046f3
MH
1195 if (prev && prev != root)
1196 css_put(&prev->css);
1197
9f3a0d09 1198 return memcg;
14067bb3 1199}
7d74b06f 1200
5660048c
JW
1201/**
1202 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1203 * @root: hierarchy root
1204 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1205 */
1206void mem_cgroup_iter_break(struct mem_cgroup *root,
1207 struct mem_cgroup *prev)
9f3a0d09
JW
1208{
1209 if (!root)
1210 root = root_mem_cgroup;
1211 if (prev && prev != root)
1212 css_put(&prev->css);
1213}
7d74b06f 1214
54a83d6b
MC
1215static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1216 struct mem_cgroup *dead_memcg)
6df38689 1217{
6df38689 1218 struct mem_cgroup_reclaim_iter *iter;
ef8f2327
MG
1219 struct mem_cgroup_per_node *mz;
1220 int nid;
6df38689 1221
54a83d6b 1222 for_each_node(nid) {
a3747b53 1223 mz = from->nodeinfo[nid];
9da83f3f
YS
1224 iter = &mz->iter;
1225 cmpxchg(&iter->position, dead_memcg, NULL);
6df38689
VD
1226 }
1227}
1228
54a83d6b
MC
1229static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1230{
1231 struct mem_cgroup *memcg = dead_memcg;
1232 struct mem_cgroup *last;
1233
1234 do {
1235 __invalidate_reclaim_iterators(memcg, dead_memcg);
1236 last = memcg;
1237 } while ((memcg = parent_mem_cgroup(memcg)));
1238
1239 /*
b8dd3ee9 1240 * When cgroup1 non-hierarchy mode is used,
54a83d6b
MC
1241 * parent_mem_cgroup() does not walk all the way up to the
1242 * cgroup root (root_mem_cgroup). So we have to handle
1243 * dead_memcg from cgroup root separately.
1244 */
1245 if (last != root_mem_cgroup)
1246 __invalidate_reclaim_iterators(root_mem_cgroup,
1247 dead_memcg);
1248}
1249
7c5f64f8
VD
1250/**
1251 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1252 * @memcg: hierarchy root
1253 * @fn: function to call for each task
1254 * @arg: argument passed to @fn
1255 *
1256 * This function iterates over tasks attached to @memcg or to any of its
1257 * descendants and calls @fn for each task. If @fn returns a non-zero
1258 * value, the function breaks the iteration loop and returns the value.
1259 * Otherwise, it will iterate over all tasks and return 0.
1260 *
1261 * This function must not be called for the root memory cgroup.
1262 */
1263int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1264 int (*fn)(struct task_struct *, void *), void *arg)
1265{
1266 struct mem_cgroup *iter;
1267 int ret = 0;
1268
1269 BUG_ON(memcg == root_mem_cgroup);
1270
1271 for_each_mem_cgroup_tree(iter, memcg) {
1272 struct css_task_iter it;
1273 struct task_struct *task;
1274
f168a9a5 1275 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
7c5f64f8
VD
1276 while (!ret && (task = css_task_iter_next(&it)))
1277 ret = fn(task, arg);
1278 css_task_iter_end(&it);
1279 if (ret) {
1280 mem_cgroup_iter_break(memcg, iter);
1281 break;
1282 }
1283 }
1284 return ret;
1285}
1286
6168d0da 1287#ifdef CONFIG_DEBUG_VM
e809c3fe 1288void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
6168d0da
AS
1289{
1290 struct mem_cgroup *memcg;
1291
1292 if (mem_cgroup_disabled())
1293 return;
1294
e809c3fe 1295 memcg = folio_memcg(folio);
6168d0da
AS
1296
1297 if (!memcg)
e809c3fe 1298 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
6168d0da 1299 else
e809c3fe 1300 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
6168d0da
AS
1301}
1302#endif
1303
6168d0da 1304/**
e809c3fe
MWO
1305 * folio_lruvec_lock - Lock the lruvec for a folio.
1306 * @folio: Pointer to the folio.
6168d0da 1307 *
d7e3aba5 1308 * These functions are safe to use under any of the following conditions:
e809c3fe
MWO
1309 * - folio locked
1310 * - folio_test_lru false
1311 * - folio_memcg_lock()
1312 * - folio frozen (refcount of 0)
1313 *
1314 * Return: The lruvec this folio is on with its lock held.
6168d0da 1315 */
e809c3fe 1316struct lruvec *folio_lruvec_lock(struct folio *folio)
6168d0da 1317{
e809c3fe 1318 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1319
6168d0da 1320 spin_lock(&lruvec->lru_lock);
e809c3fe 1321 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1322
1323 return lruvec;
1324}
1325
e809c3fe
MWO
1326/**
1327 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1328 * @folio: Pointer to the folio.
1329 *
1330 * These functions are safe to use under any of the following conditions:
1331 * - folio locked
1332 * - folio_test_lru false
1333 * - folio_memcg_lock()
1334 * - folio frozen (refcount of 0)
1335 *
1336 * Return: The lruvec this folio is on with its lock held and interrupts
1337 * disabled.
1338 */
1339struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
6168d0da 1340{
e809c3fe 1341 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1342
6168d0da 1343 spin_lock_irq(&lruvec->lru_lock);
e809c3fe 1344 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1345
1346 return lruvec;
1347}
1348
e809c3fe
MWO
1349/**
1350 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1351 * @folio: Pointer to the folio.
1352 * @flags: Pointer to irqsave flags.
1353 *
1354 * These functions are safe to use under any of the following conditions:
1355 * - folio locked
1356 * - folio_test_lru false
1357 * - folio_memcg_lock()
1358 * - folio frozen (refcount of 0)
1359 *
1360 * Return: The lruvec this folio is on with its lock held and interrupts
1361 * disabled.
1362 */
1363struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1364 unsigned long *flags)
6168d0da 1365{
e809c3fe 1366 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1367
6168d0da 1368 spin_lock_irqsave(&lruvec->lru_lock, *flags);
e809c3fe 1369 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1370
1371 return lruvec;
1372}
1373
925b7673 1374/**
fa9add64
HD
1375 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1376 * @lruvec: mem_cgroup per zone lru vector
1377 * @lru: index of lru list the page is sitting on
b4536f0c 1378 * @zid: zone id of the accounted pages
fa9add64 1379 * @nr_pages: positive when adding or negative when removing
925b7673 1380 *
ca707239 1381 * This function must be called under lru_lock, just before a page is added
07ca7606 1382 * to or just after a page is removed from an lru list.
3f58a829 1383 */
fa9add64 1384void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
b4536f0c 1385 int zid, int nr_pages)
3f58a829 1386{
ef8f2327 1387 struct mem_cgroup_per_node *mz;
fa9add64 1388 unsigned long *lru_size;
ca707239 1389 long size;
3f58a829
MK
1390
1391 if (mem_cgroup_disabled())
1392 return;
1393
ef8f2327 1394 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
b4536f0c 1395 lru_size = &mz->lru_zone_size[zid][lru];
ca707239
HD
1396
1397 if (nr_pages < 0)
1398 *lru_size += nr_pages;
1399
1400 size = *lru_size;
b4536f0c
MH
1401 if (WARN_ONCE(size < 0,
1402 "%s(%p, %d, %d): lru_size %ld\n",
1403 __func__, lruvec, lru, nr_pages, size)) {
ca707239
HD
1404 VM_BUG_ON(1);
1405 *lru_size = 0;
1406 }
1407
1408 if (nr_pages > 0)
1409 *lru_size += nr_pages;
08e552c6 1410}
544122e5 1411
19942822 1412/**
9d11ea9f 1413 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1414 * @memcg: the memory cgroup
19942822 1415 *
9d11ea9f 1416 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1417 * pages.
19942822 1418 */
c0ff4b85 1419static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1420{
3e32cb2e
JW
1421 unsigned long margin = 0;
1422 unsigned long count;
1423 unsigned long limit;
9d11ea9f 1424
3e32cb2e 1425 count = page_counter_read(&memcg->memory);
bbec2e15 1426 limit = READ_ONCE(memcg->memory.max);
3e32cb2e
JW
1427 if (count < limit)
1428 margin = limit - count;
1429
7941d214 1430 if (do_memsw_account()) {
3e32cb2e 1431 count = page_counter_read(&memcg->memsw);
bbec2e15 1432 limit = READ_ONCE(memcg->memsw.max);
1c4448ed 1433 if (count < limit)
3e32cb2e 1434 margin = min(margin, limit - count);
cbedbac3
LR
1435 else
1436 margin = 0;
3e32cb2e
JW
1437 }
1438
1439 return margin;
19942822
JW
1440}
1441
32047e2a 1442/*
bdcbb659 1443 * A routine for checking "mem" is under move_account() or not.
32047e2a 1444 *
bdcbb659
QH
1445 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1446 * moving cgroups. This is for waiting at high-memory pressure
1447 * caused by "move".
32047e2a 1448 */
c0ff4b85 1449static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1450{
2bd9bb20
KH
1451 struct mem_cgroup *from;
1452 struct mem_cgroup *to;
4b534334 1453 bool ret = false;
2bd9bb20
KH
1454 /*
1455 * Unlike task_move routines, we access mc.to, mc.from not under
1456 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1457 */
1458 spin_lock(&mc.lock);
1459 from = mc.from;
1460 to = mc.to;
1461 if (!from)
1462 goto unlock;
3e92041d 1463
2314b42d
JW
1464 ret = mem_cgroup_is_descendant(from, memcg) ||
1465 mem_cgroup_is_descendant(to, memcg);
2bd9bb20
KH
1466unlock:
1467 spin_unlock(&mc.lock);
4b534334
KH
1468 return ret;
1469}
1470
c0ff4b85 1471static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1472{
1473 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1474 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1475 DEFINE_WAIT(wait);
1476 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1477 /* moving charge context might have finished. */
1478 if (mc.moving_task)
1479 schedule();
1480 finish_wait(&mc.waitq, &wait);
1481 return true;
1482 }
1483 }
1484 return false;
1485}
1486
5f9a4f4a
MS
1487struct memory_stat {
1488 const char *name;
5f9a4f4a
MS
1489 unsigned int idx;
1490};
1491
57b2847d 1492static const struct memory_stat memory_stats[] = {
fff66b79
MS
1493 { "anon", NR_ANON_MAPPED },
1494 { "file", NR_FILE_PAGES },
a8c49af3 1495 { "kernel", MEMCG_KMEM },
fff66b79
MS
1496 { "kernel_stack", NR_KERNEL_STACK_KB },
1497 { "pagetables", NR_PAGETABLE },
1498 { "percpu", MEMCG_PERCPU_B },
1499 { "sock", MEMCG_SOCK },
4e5aa1f4 1500 { "vmalloc", MEMCG_VMALLOC },
fff66b79 1501 { "shmem", NR_SHMEM },
f4840ccf
JW
1502#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
1503 { "zswap", MEMCG_ZSWAP_B },
1504 { "zswapped", MEMCG_ZSWAPPED },
1505#endif
fff66b79
MS
1506 { "file_mapped", NR_FILE_MAPPED },
1507 { "file_dirty", NR_FILE_DIRTY },
1508 { "file_writeback", NR_WRITEBACK },
b6038942
SB
1509#ifdef CONFIG_SWAP
1510 { "swapcached", NR_SWAPCACHE },
1511#endif
5f9a4f4a 1512#ifdef CONFIG_TRANSPARENT_HUGEPAGE
fff66b79
MS
1513 { "anon_thp", NR_ANON_THPS },
1514 { "file_thp", NR_FILE_THPS },
1515 { "shmem_thp", NR_SHMEM_THPS },
5f9a4f4a 1516#endif
fff66b79
MS
1517 { "inactive_anon", NR_INACTIVE_ANON },
1518 { "active_anon", NR_ACTIVE_ANON },
1519 { "inactive_file", NR_INACTIVE_FILE },
1520 { "active_file", NR_ACTIVE_FILE },
1521 { "unevictable", NR_UNEVICTABLE },
1522 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1523 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
5f9a4f4a
MS
1524
1525 /* The memory events */
fff66b79
MS
1526 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1527 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1528 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1529 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1530 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1531 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1532 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
5f9a4f4a
MS
1533};
1534
fff66b79
MS
1535/* Translate stat items to the correct unit for memory.stat output */
1536static int memcg_page_state_unit(int item)
1537{
1538 switch (item) {
1539 case MEMCG_PERCPU_B:
f4840ccf 1540 case MEMCG_ZSWAP_B:
fff66b79
MS
1541 case NR_SLAB_RECLAIMABLE_B:
1542 case NR_SLAB_UNRECLAIMABLE_B:
1543 case WORKINGSET_REFAULT_ANON:
1544 case WORKINGSET_REFAULT_FILE:
1545 case WORKINGSET_ACTIVATE_ANON:
1546 case WORKINGSET_ACTIVATE_FILE:
1547 case WORKINGSET_RESTORE_ANON:
1548 case WORKINGSET_RESTORE_FILE:
1549 case WORKINGSET_NODERECLAIM:
1550 return 1;
1551 case NR_KERNEL_STACK_KB:
1552 return SZ_1K;
1553 default:
1554 return PAGE_SIZE;
1555 }
1556}
1557
1558static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
1559 int item)
1560{
1561 return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
1562}
1563
68aaee14 1564static void memory_stat_format(struct mem_cgroup *memcg, char *buf, int bufsize)
c8713d0b
JW
1565{
1566 struct seq_buf s;
1567 int i;
71cd3113 1568
68aaee14 1569 seq_buf_init(&s, buf, bufsize);
c8713d0b
JW
1570
1571 /*
1572 * Provide statistics on the state of the memory subsystem as
1573 * well as cumulative event counters that show past behavior.
1574 *
1575 * This list is ordered following a combination of these gradients:
1576 * 1) generic big picture -> specifics and details
1577 * 2) reflecting userspace activity -> reflecting kernel heuristics
1578 *
1579 * Current memory state:
1580 */
fd25a9e0 1581 mem_cgroup_flush_stats();
c8713d0b 1582
5f9a4f4a
MS
1583 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1584 u64 size;
c8713d0b 1585
fff66b79 1586 size = memcg_page_state_output(memcg, memory_stats[i].idx);
5f9a4f4a 1587 seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
c8713d0b 1588
5f9a4f4a 1589 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
fff66b79
MS
1590 size += memcg_page_state_output(memcg,
1591 NR_SLAB_RECLAIMABLE_B);
5f9a4f4a
MS
1592 seq_buf_printf(&s, "slab %llu\n", size);
1593 }
1594 }
c8713d0b
JW
1595
1596 /* Accumulated memory events */
c8713d0b
JW
1597 seq_buf_printf(&s, "pgscan %lu\n",
1598 memcg_events(memcg, PGSCAN_KSWAPD) +
1599 memcg_events(memcg, PGSCAN_DIRECT));
1600 seq_buf_printf(&s, "pgsteal %lu\n",
1601 memcg_events(memcg, PGSTEAL_KSWAPD) +
1602 memcg_events(memcg, PGSTEAL_DIRECT));
c8713d0b 1603
8278f1c7
SB
1604 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1605 if (memcg_vm_event_stat[i] == PGPGIN ||
1606 memcg_vm_event_stat[i] == PGPGOUT)
1607 continue;
1608
673520f8
QZ
1609 seq_buf_printf(&s, "%s %lu\n",
1610 vm_event_name(memcg_vm_event_stat[i]),
1611 memcg_events(memcg, memcg_vm_event_stat[i]));
8278f1c7 1612 }
c8713d0b
JW
1613
1614 /* The above should easily fit into one page */
1615 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
c8713d0b 1616}
71cd3113 1617
58cf188e 1618#define K(x) ((x) << (PAGE_SHIFT-10))
e222432b 1619/**
f0c867d9 1620 * mem_cgroup_print_oom_context: Print OOM information relevant to
1621 * memory controller.
e222432b
BS
1622 * @memcg: The memory cgroup that went over limit
1623 * @p: Task that is going to be killed
1624 *
1625 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1626 * enabled
1627 */
f0c867d9 1628void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
e222432b 1629{
e222432b
BS
1630 rcu_read_lock();
1631
f0c867d9 1632 if (memcg) {
1633 pr_cont(",oom_memcg=");
1634 pr_cont_cgroup_path(memcg->css.cgroup);
1635 } else
1636 pr_cont(",global_oom");
2415b9f5 1637 if (p) {
f0c867d9 1638 pr_cont(",task_memcg=");
2415b9f5 1639 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
2415b9f5 1640 }
e222432b 1641 rcu_read_unlock();
f0c867d9 1642}
1643
1644/**
1645 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1646 * memory controller.
1647 * @memcg: The memory cgroup that went over limit
1648 */
1649void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1650{
68aaee14
TH
1651 /* Use static buffer, for the caller is holding oom_lock. */
1652 static char buf[PAGE_SIZE];
1653
1654 lockdep_assert_held(&oom_lock);
e222432b 1655
3e32cb2e
JW
1656 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1657 K((u64)page_counter_read(&memcg->memory)),
15b42562 1658 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
c8713d0b
JW
1659 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1660 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1661 K((u64)page_counter_read(&memcg->swap)),
32d087cd 1662 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
c8713d0b
JW
1663 else {
1664 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1665 K((u64)page_counter_read(&memcg->memsw)),
1666 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1667 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1668 K((u64)page_counter_read(&memcg->kmem)),
1669 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
58cf188e 1670 }
c8713d0b
JW
1671
1672 pr_info("Memory cgroup stats for ");
1673 pr_cont_cgroup_path(memcg->css.cgroup);
1674 pr_cont(":");
68aaee14 1675 memory_stat_format(memcg, buf, sizeof(buf));
c8713d0b 1676 pr_info("%s", buf);
e222432b
BS
1677}
1678
a63d83f4
DR
1679/*
1680 * Return the memory (and swap, if configured) limit for a memcg.
1681 */
bbec2e15 1682unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
a63d83f4 1683{
8d387a5f
WL
1684 unsigned long max = READ_ONCE(memcg->memory.max);
1685
1686 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
1687 if (mem_cgroup_swappiness(memcg))
1688 max += min(READ_ONCE(memcg->swap.max),
1689 (unsigned long)total_swap_pages);
1690 } else { /* v1 */
1691 if (mem_cgroup_swappiness(memcg)) {
1692 /* Calculate swap excess capacity from memsw limit */
1693 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1694
1695 max += min(swap, (unsigned long)total_swap_pages);
1696 }
9a5a8f19 1697 }
bbec2e15 1698 return max;
a63d83f4
DR
1699}
1700
9783aa99
CD
1701unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1702{
1703 return page_counter_read(&memcg->memory);
1704}
1705
b6e6edcf 1706static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
19965460 1707 int order)
9cbb78bb 1708{
6e0fc46d
DR
1709 struct oom_control oc = {
1710 .zonelist = NULL,
1711 .nodemask = NULL,
2a966b77 1712 .memcg = memcg,
6e0fc46d
DR
1713 .gfp_mask = gfp_mask,
1714 .order = order,
6e0fc46d 1715 };
1378b37d 1716 bool ret = true;
9cbb78bb 1717
7775face
TH
1718 if (mutex_lock_killable(&oom_lock))
1719 return true;
1378b37d
YS
1720
1721 if (mem_cgroup_margin(memcg) >= (1 << order))
1722 goto unlock;
1723
7775face
TH
1724 /*
1725 * A few threads which were not waiting at mutex_lock_killable() can
1726 * fail to bail out. Therefore, check again after holding oom_lock.
1727 */
a4ebf1b6 1728 ret = task_is_dying() || out_of_memory(&oc);
1378b37d
YS
1729
1730unlock:
dc56401f 1731 mutex_unlock(&oom_lock);
7c5f64f8 1732 return ret;
9cbb78bb
DR
1733}
1734
0608f43d 1735static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
ef8f2327 1736 pg_data_t *pgdat,
0608f43d
AM
1737 gfp_t gfp_mask,
1738 unsigned long *total_scanned)
1739{
1740 struct mem_cgroup *victim = NULL;
1741 int total = 0;
1742 int loop = 0;
1743 unsigned long excess;
1744 unsigned long nr_scanned;
1745 struct mem_cgroup_reclaim_cookie reclaim = {
ef8f2327 1746 .pgdat = pgdat,
0608f43d
AM
1747 };
1748
3e32cb2e 1749 excess = soft_limit_excess(root_memcg);
0608f43d
AM
1750
1751 while (1) {
1752 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1753 if (!victim) {
1754 loop++;
1755 if (loop >= 2) {
1756 /*
1757 * If we have not been able to reclaim
1758 * anything, it might because there are
1759 * no reclaimable pages under this hierarchy
1760 */
1761 if (!total)
1762 break;
1763 /*
1764 * We want to do more targeted reclaim.
1765 * excess >> 2 is not to excessive so as to
1766 * reclaim too much, nor too less that we keep
1767 * coming back to reclaim from this cgroup
1768 */
1769 if (total >= (excess >> 2) ||
1770 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1771 break;
1772 }
1773 continue;
1774 }
a9dd0a83 1775 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
ef8f2327 1776 pgdat, &nr_scanned);
0608f43d 1777 *total_scanned += nr_scanned;
3e32cb2e 1778 if (!soft_limit_excess(root_memcg))
0608f43d 1779 break;
6d61ef40 1780 }
0608f43d
AM
1781 mem_cgroup_iter_break(root_memcg, victim);
1782 return total;
6d61ef40
BS
1783}
1784
0056f4e6
JW
1785#ifdef CONFIG_LOCKDEP
1786static struct lockdep_map memcg_oom_lock_dep_map = {
1787 .name = "memcg_oom_lock",
1788};
1789#endif
1790
fb2a6fc5
JW
1791static DEFINE_SPINLOCK(memcg_oom_lock);
1792
867578cb
KH
1793/*
1794 * Check OOM-Killer is already running under our hierarchy.
1795 * If someone is running, return false.
1796 */
fb2a6fc5 1797static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
867578cb 1798{
79dfdacc 1799 struct mem_cgroup *iter, *failed = NULL;
a636b327 1800
fb2a6fc5
JW
1801 spin_lock(&memcg_oom_lock);
1802
9f3a0d09 1803 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1804 if (iter->oom_lock) {
79dfdacc
MH
1805 /*
1806 * this subtree of our hierarchy is already locked
1807 * so we cannot give a lock.
1808 */
79dfdacc 1809 failed = iter;
9f3a0d09
JW
1810 mem_cgroup_iter_break(memcg, iter);
1811 break;
23751be0
JW
1812 } else
1813 iter->oom_lock = true;
7d74b06f 1814 }
867578cb 1815
fb2a6fc5
JW
1816 if (failed) {
1817 /*
1818 * OK, we failed to lock the whole subtree so we have
1819 * to clean up what we set up to the failing subtree
1820 */
1821 for_each_mem_cgroup_tree(iter, memcg) {
1822 if (iter == failed) {
1823 mem_cgroup_iter_break(memcg, iter);
1824 break;
1825 }
1826 iter->oom_lock = false;
79dfdacc 1827 }
0056f4e6
JW
1828 } else
1829 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
fb2a6fc5
JW
1830
1831 spin_unlock(&memcg_oom_lock);
1832
1833 return !failed;
a636b327 1834}
0b7f569e 1835
fb2a6fc5 1836static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1837{
7d74b06f
KH
1838 struct mem_cgroup *iter;
1839
fb2a6fc5 1840 spin_lock(&memcg_oom_lock);
5facae4f 1841 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
c0ff4b85 1842 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1843 iter->oom_lock = false;
fb2a6fc5 1844 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1845}
1846
c0ff4b85 1847static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1848{
1849 struct mem_cgroup *iter;
1850
c2b42d3c 1851 spin_lock(&memcg_oom_lock);
c0ff4b85 1852 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1853 iter->under_oom++;
1854 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1855}
1856
c0ff4b85 1857static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1858{
1859 struct mem_cgroup *iter;
1860
867578cb 1861 /*
f0953a1b 1862 * Be careful about under_oom underflows because a child memcg
7a52d4d8 1863 * could have been added after mem_cgroup_mark_under_oom.
867578cb 1864 */
c2b42d3c 1865 spin_lock(&memcg_oom_lock);
c0ff4b85 1866 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1867 if (iter->under_oom > 0)
1868 iter->under_oom--;
1869 spin_unlock(&memcg_oom_lock);
0b7f569e
KH
1870}
1871
867578cb
KH
1872static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1873
dc98df5a 1874struct oom_wait_info {
d79154bb 1875 struct mem_cgroup *memcg;
ac6424b9 1876 wait_queue_entry_t wait;
dc98df5a
KH
1877};
1878
ac6424b9 1879static int memcg_oom_wake_function(wait_queue_entry_t *wait,
dc98df5a
KH
1880 unsigned mode, int sync, void *arg)
1881{
d79154bb
HD
1882 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1883 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1884 struct oom_wait_info *oom_wait_info;
1885
1886 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1887 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1888
2314b42d
JW
1889 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1890 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
dc98df5a 1891 return 0;
dc98df5a
KH
1892 return autoremove_wake_function(wait, mode, sync, arg);
1893}
1894
c0ff4b85 1895static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1896{
c2b42d3c
TH
1897 /*
1898 * For the following lockless ->under_oom test, the only required
1899 * guarantee is that it must see the state asserted by an OOM when
1900 * this function is called as a result of userland actions
1901 * triggered by the notification of the OOM. This is trivially
1902 * achieved by invoking mem_cgroup_mark_under_oom() before
1903 * triggering notification.
1904 */
1905 if (memcg && memcg->under_oom)
f4b90b70 1906 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
3c11ecf4
KH
1907}
1908
becdf89d
SB
1909/*
1910 * Returns true if successfully killed one or more processes. Though in some
1911 * corner cases it can return true even without killing any process.
1912 */
1913static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1914{
becdf89d 1915 bool locked, ret;
7056d3a3 1916
29ef680a 1917 if (order > PAGE_ALLOC_COSTLY_ORDER)
becdf89d 1918 return false;
29ef680a 1919
7a1adfdd
RG
1920 memcg_memory_event(memcg, MEMCG_OOM);
1921
867578cb 1922 /*
49426420
JW
1923 * We are in the middle of the charge context here, so we
1924 * don't want to block when potentially sitting on a callstack
1925 * that holds all kinds of filesystem and mm locks.
1926 *
29ef680a
MH
1927 * cgroup1 allows disabling the OOM killer and waiting for outside
1928 * handling until the charge can succeed; remember the context and put
1929 * the task to sleep at the end of the page fault when all locks are
1930 * released.
49426420 1931 *
29ef680a
MH
1932 * On the other hand, in-kernel OOM killer allows for an async victim
1933 * memory reclaim (oom_reaper) and that means that we are not solely
1934 * relying on the oom victim to make a forward progress and we can
1935 * invoke the oom killer here.
1936 *
1937 * Please note that mem_cgroup_out_of_memory might fail to find a
1938 * victim and then we have to bail out from the charge path.
867578cb 1939 */
29ef680a 1940 if (memcg->oom_kill_disable) {
becdf89d
SB
1941 if (current->in_user_fault) {
1942 css_get(&memcg->css);
1943 current->memcg_in_oom = memcg;
1944 current->memcg_oom_gfp_mask = mask;
1945 current->memcg_oom_order = order;
1946 }
1947 return false;
29ef680a
MH
1948 }
1949
7056d3a3
MH
1950 mem_cgroup_mark_under_oom(memcg);
1951
1952 locked = mem_cgroup_oom_trylock(memcg);
1953
1954 if (locked)
1955 mem_cgroup_oom_notify(memcg);
1956
1957 mem_cgroup_unmark_under_oom(memcg);
becdf89d 1958 ret = mem_cgroup_out_of_memory(memcg, mask, order);
7056d3a3
MH
1959
1960 if (locked)
1961 mem_cgroup_oom_unlock(memcg);
29ef680a 1962
7056d3a3 1963 return ret;
3812c8c8
JW
1964}
1965
1966/**
1967 * mem_cgroup_oom_synchronize - complete memcg OOM handling
49426420 1968 * @handle: actually kill/wait or just clean up the OOM state
3812c8c8 1969 *
49426420
JW
1970 * This has to be called at the end of a page fault if the memcg OOM
1971 * handler was enabled.
3812c8c8 1972 *
49426420 1973 * Memcg supports userspace OOM handling where failed allocations must
3812c8c8
JW
1974 * sleep on a waitqueue until the userspace task resolves the
1975 * situation. Sleeping directly in the charge context with all kinds
1976 * of locks held is not a good idea, instead we remember an OOM state
1977 * in the task and mem_cgroup_oom_synchronize() has to be called at
49426420 1978 * the end of the page fault to complete the OOM handling.
3812c8c8
JW
1979 *
1980 * Returns %true if an ongoing memcg OOM situation was detected and
49426420 1981 * completed, %false otherwise.
3812c8c8 1982 */
49426420 1983bool mem_cgroup_oom_synchronize(bool handle)
3812c8c8 1984{
626ebc41 1985 struct mem_cgroup *memcg = current->memcg_in_oom;
3812c8c8 1986 struct oom_wait_info owait;
49426420 1987 bool locked;
3812c8c8
JW
1988
1989 /* OOM is global, do not handle */
3812c8c8 1990 if (!memcg)
49426420 1991 return false;
3812c8c8 1992
7c5f64f8 1993 if (!handle)
49426420 1994 goto cleanup;
3812c8c8
JW
1995
1996 owait.memcg = memcg;
1997 owait.wait.flags = 0;
1998 owait.wait.func = memcg_oom_wake_function;
1999 owait.wait.private = current;
2055da97 2000 INIT_LIST_HEAD(&owait.wait.entry);
867578cb 2001
3812c8c8 2002 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
49426420
JW
2003 mem_cgroup_mark_under_oom(memcg);
2004
2005 locked = mem_cgroup_oom_trylock(memcg);
2006
2007 if (locked)
2008 mem_cgroup_oom_notify(memcg);
2009
2010 if (locked && !memcg->oom_kill_disable) {
2011 mem_cgroup_unmark_under_oom(memcg);
2012 finish_wait(&memcg_oom_waitq, &owait.wait);
626ebc41
TH
2013 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
2014 current->memcg_oom_order);
49426420 2015 } else {
3812c8c8 2016 schedule();
49426420
JW
2017 mem_cgroup_unmark_under_oom(memcg);
2018 finish_wait(&memcg_oom_waitq, &owait.wait);
2019 }
2020
2021 if (locked) {
fb2a6fc5
JW
2022 mem_cgroup_oom_unlock(memcg);
2023 /*
2024 * There is no guarantee that an OOM-lock contender
2025 * sees the wakeups triggered by the OOM kill
f0953a1b 2026 * uncharges. Wake any sleepers explicitly.
fb2a6fc5
JW
2027 */
2028 memcg_oom_recover(memcg);
2029 }
49426420 2030cleanup:
626ebc41 2031 current->memcg_in_oom = NULL;
3812c8c8 2032 css_put(&memcg->css);
867578cb 2033 return true;
0b7f569e
KH
2034}
2035
3d8b38eb
RG
2036/**
2037 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2038 * @victim: task to be killed by the OOM killer
2039 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2040 *
2041 * Returns a pointer to a memory cgroup, which has to be cleaned up
2042 * by killing all belonging OOM-killable tasks.
2043 *
2044 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2045 */
2046struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2047 struct mem_cgroup *oom_domain)
2048{
2049 struct mem_cgroup *oom_group = NULL;
2050 struct mem_cgroup *memcg;
2051
2052 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2053 return NULL;
2054
2055 if (!oom_domain)
2056 oom_domain = root_mem_cgroup;
2057
2058 rcu_read_lock();
2059
2060 memcg = mem_cgroup_from_task(victim);
2061 if (memcg == root_mem_cgroup)
2062 goto out;
2063
48fe267c
RG
2064 /*
2065 * If the victim task has been asynchronously moved to a different
2066 * memory cgroup, we might end up killing tasks outside oom_domain.
2067 * In this case it's better to ignore memory.group.oom.
2068 */
2069 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2070 goto out;
2071
3d8b38eb
RG
2072 /*
2073 * Traverse the memory cgroup hierarchy from the victim task's
2074 * cgroup up to the OOMing cgroup (or root) to find the
2075 * highest-level memory cgroup with oom.group set.
2076 */
2077 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2078 if (memcg->oom_group)
2079 oom_group = memcg;
2080
2081 if (memcg == oom_domain)
2082 break;
2083 }
2084
2085 if (oom_group)
2086 css_get(&oom_group->css);
2087out:
2088 rcu_read_unlock();
2089
2090 return oom_group;
2091}
2092
2093void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2094{
2095 pr_info("Tasks in ");
2096 pr_cont_cgroup_path(memcg->css.cgroup);
2097 pr_cont(" are going to be killed due to memory.oom.group set\n");
2098}
2099
d7365e78 2100/**
f70ad448
MWO
2101 * folio_memcg_lock - Bind a folio to its memcg.
2102 * @folio: The folio.
32047e2a 2103 *
f70ad448 2104 * This function prevents unlocked LRU folios from being moved to
739f79fc
JW
2105 * another cgroup.
2106 *
f70ad448
MWO
2107 * It ensures lifetime of the bound memcg. The caller is responsible
2108 * for the lifetime of the folio.
d69b042f 2109 */
f70ad448 2110void folio_memcg_lock(struct folio *folio)
89c06bd5
KH
2111{
2112 struct mem_cgroup *memcg;
6de22619 2113 unsigned long flags;
89c06bd5 2114
6de22619
JW
2115 /*
2116 * The RCU lock is held throughout the transaction. The fast
2117 * path can get away without acquiring the memcg->move_lock
2118 * because page moving starts with an RCU grace period.
739f79fc 2119 */
d7365e78
JW
2120 rcu_read_lock();
2121
2122 if (mem_cgroup_disabled())
1c824a68 2123 return;
89c06bd5 2124again:
f70ad448 2125 memcg = folio_memcg(folio);
29833315 2126 if (unlikely(!memcg))
1c824a68 2127 return;
d7365e78 2128
20ad50d6
AS
2129#ifdef CONFIG_PROVE_LOCKING
2130 local_irq_save(flags);
2131 might_lock(&memcg->move_lock);
2132 local_irq_restore(flags);
2133#endif
2134
bdcbb659 2135 if (atomic_read(&memcg->moving_account) <= 0)
1c824a68 2136 return;
89c06bd5 2137
6de22619 2138 spin_lock_irqsave(&memcg->move_lock, flags);
f70ad448 2139 if (memcg != folio_memcg(folio)) {
6de22619 2140 spin_unlock_irqrestore(&memcg->move_lock, flags);
89c06bd5
KH
2141 goto again;
2142 }
6de22619
JW
2143
2144 /*
1c824a68
JW
2145 * When charge migration first begins, we can have multiple
2146 * critical sections holding the fast-path RCU lock and one
2147 * holding the slowpath move_lock. Track the task who has the
2148 * move_lock for unlock_page_memcg().
6de22619
JW
2149 */
2150 memcg->move_lock_task = current;
2151 memcg->move_lock_flags = flags;
89c06bd5 2152}
f70ad448
MWO
2153
2154void lock_page_memcg(struct page *page)
2155{
2156 folio_memcg_lock(page_folio(page));
2157}
89c06bd5 2158
f70ad448 2159static void __folio_memcg_unlock(struct mem_cgroup *memcg)
89c06bd5 2160{
6de22619
JW
2161 if (memcg && memcg->move_lock_task == current) {
2162 unsigned long flags = memcg->move_lock_flags;
2163
2164 memcg->move_lock_task = NULL;
2165 memcg->move_lock_flags = 0;
2166
2167 spin_unlock_irqrestore(&memcg->move_lock, flags);
2168 }
89c06bd5 2169
d7365e78 2170 rcu_read_unlock();
89c06bd5 2171}
739f79fc
JW
2172
2173/**
f70ad448
MWO
2174 * folio_memcg_unlock - Release the binding between a folio and its memcg.
2175 * @folio: The folio.
2176 *
2177 * This releases the binding created by folio_memcg_lock(). This does
2178 * not change the accounting of this folio to its memcg, but it does
2179 * permit others to change it.
739f79fc 2180 */
f70ad448 2181void folio_memcg_unlock(struct folio *folio)
739f79fc 2182{
f70ad448
MWO
2183 __folio_memcg_unlock(folio_memcg(folio));
2184}
9da7b521 2185
f70ad448
MWO
2186void unlock_page_memcg(struct page *page)
2187{
2188 folio_memcg_unlock(page_folio(page));
739f79fc 2189}
89c06bd5 2190
fead2b86 2191struct memcg_stock_pcp {
56751146 2192 local_lock_t stock_lock;
fead2b86
MH
2193 struct mem_cgroup *cached; /* this never be root cgroup */
2194 unsigned int nr_pages;
2195
bf4f0599
RG
2196#ifdef CONFIG_MEMCG_KMEM
2197 struct obj_cgroup *cached_objcg;
68ac5b3c 2198 struct pglist_data *cached_pgdat;
bf4f0599 2199 unsigned int nr_bytes;
68ac5b3c
WL
2200 int nr_slab_reclaimable_b;
2201 int nr_slab_unreclaimable_b;
bf4f0599
RG
2202#endif
2203
cdec2e42 2204 struct work_struct work;
26fe6168 2205 unsigned long flags;
a0db00fc 2206#define FLUSHING_CACHED_CHARGE 0
cdec2e42 2207};
56751146
SAS
2208static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
2209 .stock_lock = INIT_LOCAL_LOCK(stock_lock),
2210};
9f50fad6 2211static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 2212
bf4f0599 2213#ifdef CONFIG_MEMCG_KMEM
56751146 2214static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
bf4f0599
RG
2215static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2216 struct mem_cgroup *root_memcg);
a8c49af3 2217static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
bf4f0599
RG
2218
2219#else
56751146 2220static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
bf4f0599 2221{
56751146 2222 return NULL;
bf4f0599
RG
2223}
2224static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2225 struct mem_cgroup *root_memcg)
2226{
2227 return false;
2228}
a8c49af3
YA
2229static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2230{
2231}
bf4f0599
RG
2232#endif
2233
a0956d54
SS
2234/**
2235 * consume_stock: Try to consume stocked charge on this cpu.
2236 * @memcg: memcg to consume from.
2237 * @nr_pages: how many pages to charge.
2238 *
2239 * The charges will only happen if @memcg matches the current cpu's memcg
2240 * stock, and at least @nr_pages are available in that stock. Failure to
2241 * service an allocation will refill the stock.
2242 *
2243 * returns true if successful, false otherwise.
cdec2e42 2244 */
a0956d54 2245static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2246{
2247 struct memcg_stock_pcp *stock;
db2ba40c 2248 unsigned long flags;
3e32cb2e 2249 bool ret = false;
cdec2e42 2250
a983b5eb 2251 if (nr_pages > MEMCG_CHARGE_BATCH)
3e32cb2e 2252 return ret;
a0956d54 2253
56751146 2254 local_lock_irqsave(&memcg_stock.stock_lock, flags);
db2ba40c
JW
2255
2256 stock = this_cpu_ptr(&memcg_stock);
3e32cb2e 2257 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
a0956d54 2258 stock->nr_pages -= nr_pages;
3e32cb2e
JW
2259 ret = true;
2260 }
db2ba40c 2261
56751146 2262 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
db2ba40c 2263
cdec2e42
KH
2264 return ret;
2265}
2266
2267/*
3e32cb2e 2268 * Returns stocks cached in percpu and reset cached information.
cdec2e42
KH
2269 */
2270static void drain_stock(struct memcg_stock_pcp *stock)
2271{
2272 struct mem_cgroup *old = stock->cached;
2273
1a3e1f40
JW
2274 if (!old)
2275 return;
2276
11c9ea4e 2277 if (stock->nr_pages) {
3e32cb2e 2278 page_counter_uncharge(&old->memory, stock->nr_pages);
7941d214 2279 if (do_memsw_account())
3e32cb2e 2280 page_counter_uncharge(&old->memsw, stock->nr_pages);
11c9ea4e 2281 stock->nr_pages = 0;
cdec2e42 2282 }
1a3e1f40
JW
2283
2284 css_put(&old->css);
cdec2e42 2285 stock->cached = NULL;
cdec2e42
KH
2286}
2287
cdec2e42
KH
2288static void drain_local_stock(struct work_struct *dummy)
2289{
db2ba40c 2290 struct memcg_stock_pcp *stock;
56751146 2291 struct obj_cgroup *old = NULL;
db2ba40c
JW
2292 unsigned long flags;
2293
72f0184c 2294 /*
5c49cf9a
MH
2295 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
2296 * drain_stock races is that we always operate on local CPU stock
2297 * here with IRQ disabled
72f0184c 2298 */
56751146 2299 local_lock_irqsave(&memcg_stock.stock_lock, flags);
db2ba40c
JW
2300
2301 stock = this_cpu_ptr(&memcg_stock);
56751146 2302 old = drain_obj_stock(stock);
cdec2e42 2303 drain_stock(stock);
26fe6168 2304 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
db2ba40c 2305
56751146
SAS
2306 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2307 if (old)
2308 obj_cgroup_put(old);
cdec2e42
KH
2309}
2310
2311/*
3e32cb2e 2312 * Cache charges(val) to local per_cpu area.
320cc51d 2313 * This will be consumed by consume_stock() function, later.
cdec2e42 2314 */
af9a3b69 2315static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42 2316{
db2ba40c 2317 struct memcg_stock_pcp *stock;
cdec2e42 2318
db2ba40c 2319 stock = this_cpu_ptr(&memcg_stock);
c0ff4b85 2320 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2321 drain_stock(stock);
1a3e1f40 2322 css_get(&memcg->css);
c0ff4b85 2323 stock->cached = memcg;
cdec2e42 2324 }
11c9ea4e 2325 stock->nr_pages += nr_pages;
db2ba40c 2326
a983b5eb 2327 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
475d0487 2328 drain_stock(stock);
af9a3b69
JW
2329}
2330
2331static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2332{
2333 unsigned long flags;
475d0487 2334
56751146 2335 local_lock_irqsave(&memcg_stock.stock_lock, flags);
af9a3b69 2336 __refill_stock(memcg, nr_pages);
56751146 2337 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
cdec2e42
KH
2338}
2339
2340/*
c0ff4b85 2341 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 2342 * of the hierarchy under it.
cdec2e42 2343 */
6d3d6aa2 2344static void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 2345{
26fe6168 2346 int cpu, curcpu;
d38144b7 2347
6d3d6aa2
JW
2348 /* If someone's already draining, avoid adding running more workers. */
2349 if (!mutex_trylock(&percpu_charge_mutex))
2350 return;
72f0184c
MH
2351 /*
2352 * Notify other cpus that system-wide "drain" is running
2353 * We do not care about races with the cpu hotplug because cpu down
2354 * as well as workers from this path always operate on the local
2355 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2356 */
0790ed62
SAS
2357 migrate_disable();
2358 curcpu = smp_processor_id();
cdec2e42
KH
2359 for_each_online_cpu(cpu) {
2360 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2361 struct mem_cgroup *memcg;
e1a366be 2362 bool flush = false;
26fe6168 2363
e1a366be 2364 rcu_read_lock();
c0ff4b85 2365 memcg = stock->cached;
e1a366be
RG
2366 if (memcg && stock->nr_pages &&
2367 mem_cgroup_is_descendant(memcg, root_memcg))
2368 flush = true;
27fb0956 2369 else if (obj_stock_flush_required(stock, root_memcg))
bf4f0599 2370 flush = true;
e1a366be
RG
2371 rcu_read_unlock();
2372
2373 if (flush &&
2374 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
d1a05b69
MH
2375 if (cpu == curcpu)
2376 drain_local_stock(&stock->work);
2377 else
2378 schedule_work_on(cpu, &stock->work);
2379 }
cdec2e42 2380 }
0790ed62 2381 migrate_enable();
9f50fad6 2382 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2383}
2384
2cd21c89
JW
2385static int memcg_hotplug_cpu_dead(unsigned int cpu)
2386{
2387 struct memcg_stock_pcp *stock;
a3d4c05a 2388
2cd21c89
JW
2389 stock = &per_cpu(memcg_stock, cpu);
2390 drain_stock(stock);
a3d4c05a 2391
308167fc 2392 return 0;
cdec2e42
KH
2393}
2394
b3ff9291
CD
2395static unsigned long reclaim_high(struct mem_cgroup *memcg,
2396 unsigned int nr_pages,
2397 gfp_t gfp_mask)
f7e1cb6e 2398{
b3ff9291
CD
2399 unsigned long nr_reclaimed = 0;
2400
f7e1cb6e 2401 do {
e22c6ed9
JW
2402 unsigned long pflags;
2403
d1663a90
JK
2404 if (page_counter_read(&memcg->memory) <=
2405 READ_ONCE(memcg->memory.high))
f7e1cb6e 2406 continue;
e22c6ed9 2407
e27be240 2408 memcg_memory_event(memcg, MEMCG_HIGH);
e22c6ed9
JW
2409
2410 psi_memstall_enter(&pflags);
b3ff9291 2411 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
73b73bac
YA
2412 gfp_mask,
2413 MEMCG_RECLAIM_MAY_SWAP);
e22c6ed9 2414 psi_memstall_leave(&pflags);
4bf17307
CD
2415 } while ((memcg = parent_mem_cgroup(memcg)) &&
2416 !mem_cgroup_is_root(memcg));
b3ff9291
CD
2417
2418 return nr_reclaimed;
f7e1cb6e
JW
2419}
2420
2421static void high_work_func(struct work_struct *work)
2422{
2423 struct mem_cgroup *memcg;
2424
2425 memcg = container_of(work, struct mem_cgroup, high_work);
a983b5eb 2426 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
f7e1cb6e
JW
2427}
2428
0e4b01df
CD
2429/*
2430 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2431 * enough to still cause a significant slowdown in most cases, while still
2432 * allowing diagnostics and tracing to proceed without becoming stuck.
2433 */
2434#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2435
2436/*
2437 * When calculating the delay, we use these either side of the exponentiation to
2438 * maintain precision and scale to a reasonable number of jiffies (see the table
2439 * below.
2440 *
2441 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2442 * overage ratio to a delay.
ac5ddd0f 2443 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
0e4b01df
CD
2444 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2445 * to produce a reasonable delay curve.
2446 *
2447 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2448 * reasonable delay curve compared to precision-adjusted overage, not
2449 * penalising heavily at first, but still making sure that growth beyond the
2450 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2451 * example, with a high of 100 megabytes:
2452 *
2453 * +-------+------------------------+
2454 * | usage | time to allocate in ms |
2455 * +-------+------------------------+
2456 * | 100M | 0 |
2457 * | 101M | 6 |
2458 * | 102M | 25 |
2459 * | 103M | 57 |
2460 * | 104M | 102 |
2461 * | 105M | 159 |
2462 * | 106M | 230 |
2463 * | 107M | 313 |
2464 * | 108M | 409 |
2465 * | 109M | 518 |
2466 * | 110M | 639 |
2467 * | 111M | 774 |
2468 * | 112M | 921 |
2469 * | 113M | 1081 |
2470 * | 114M | 1254 |
2471 * | 115M | 1439 |
2472 * | 116M | 1638 |
2473 * | 117M | 1849 |
2474 * | 118M | 2000 |
2475 * | 119M | 2000 |
2476 * | 120M | 2000 |
2477 * +-------+------------------------+
2478 */
2479 #define MEMCG_DELAY_PRECISION_SHIFT 20
2480 #define MEMCG_DELAY_SCALING_SHIFT 14
2481
8a5dbc65 2482static u64 calculate_overage(unsigned long usage, unsigned long high)
b23afb93 2483{
8a5dbc65 2484 u64 overage;
b23afb93 2485
8a5dbc65
JK
2486 if (usage <= high)
2487 return 0;
e26733e0 2488
8a5dbc65
JK
2489 /*
2490 * Prevent division by 0 in overage calculation by acting as if
2491 * it was a threshold of 1 page
2492 */
2493 high = max(high, 1UL);
9b8b1754 2494
8a5dbc65
JK
2495 overage = usage - high;
2496 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2497 return div64_u64(overage, high);
2498}
e26733e0 2499
8a5dbc65
JK
2500static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2501{
2502 u64 overage, max_overage = 0;
e26733e0 2503
8a5dbc65
JK
2504 do {
2505 overage = calculate_overage(page_counter_read(&memcg->memory),
d1663a90 2506 READ_ONCE(memcg->memory.high));
8a5dbc65 2507 max_overage = max(overage, max_overage);
e26733e0
CD
2508 } while ((memcg = parent_mem_cgroup(memcg)) &&
2509 !mem_cgroup_is_root(memcg));
2510
8a5dbc65
JK
2511 return max_overage;
2512}
2513
4b82ab4f
JK
2514static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2515{
2516 u64 overage, max_overage = 0;
2517
2518 do {
2519 overage = calculate_overage(page_counter_read(&memcg->swap),
2520 READ_ONCE(memcg->swap.high));
2521 if (overage)
2522 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2523 max_overage = max(overage, max_overage);
2524 } while ((memcg = parent_mem_cgroup(memcg)) &&
2525 !mem_cgroup_is_root(memcg));
2526
2527 return max_overage;
2528}
2529
8a5dbc65
JK
2530/*
2531 * Get the number of jiffies that we should penalise a mischievous cgroup which
2532 * is exceeding its memory.high by checking both it and its ancestors.
2533 */
2534static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2535 unsigned int nr_pages,
2536 u64 max_overage)
2537{
2538 unsigned long penalty_jiffies;
2539
e26733e0
CD
2540 if (!max_overage)
2541 return 0;
0e4b01df
CD
2542
2543 /*
0e4b01df
CD
2544 * We use overage compared to memory.high to calculate the number of
2545 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2546 * fairly lenient on small overages, and increasingly harsh when the
2547 * memcg in question makes it clear that it has no intention of stopping
2548 * its crazy behaviour, so we exponentially increase the delay based on
2549 * overage amount.
2550 */
e26733e0
CD
2551 penalty_jiffies = max_overage * max_overage * HZ;
2552 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2553 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
0e4b01df
CD
2554
2555 /*
2556 * Factor in the task's own contribution to the overage, such that four
2557 * N-sized allocations are throttled approximately the same as one
2558 * 4N-sized allocation.
2559 *
2560 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2561 * larger the current charge patch is than that.
2562 */
ff144e69 2563 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
e26733e0
CD
2564}
2565
2566/*
2567 * Scheduled by try_charge() to be executed from the userland return path
2568 * and reclaims memory over the high limit.
2569 */
2570void mem_cgroup_handle_over_high(void)
2571{
2572 unsigned long penalty_jiffies;
2573 unsigned long pflags;
b3ff9291 2574 unsigned long nr_reclaimed;
e26733e0 2575 unsigned int nr_pages = current->memcg_nr_pages_over_high;
d977aa93 2576 int nr_retries = MAX_RECLAIM_RETRIES;
e26733e0 2577 struct mem_cgroup *memcg;
b3ff9291 2578 bool in_retry = false;
e26733e0
CD
2579
2580 if (likely(!nr_pages))
2581 return;
2582
2583 memcg = get_mem_cgroup_from_mm(current->mm);
e26733e0
CD
2584 current->memcg_nr_pages_over_high = 0;
2585
b3ff9291
CD
2586retry_reclaim:
2587 /*
2588 * The allocating task should reclaim at least the batch size, but for
2589 * subsequent retries we only want to do what's necessary to prevent oom
2590 * or breaching resource isolation.
2591 *
2592 * This is distinct from memory.max or page allocator behaviour because
2593 * memory.high is currently batched, whereas memory.max and the page
2594 * allocator run every time an allocation is made.
2595 */
2596 nr_reclaimed = reclaim_high(memcg,
2597 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2598 GFP_KERNEL);
2599
e26733e0
CD
2600 /*
2601 * memory.high is breached and reclaim is unable to keep up. Throttle
2602 * allocators proactively to slow down excessive growth.
2603 */
8a5dbc65
JK
2604 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2605 mem_find_max_overage(memcg));
0e4b01df 2606
4b82ab4f
JK
2607 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2608 swap_find_max_overage(memcg));
2609
ff144e69
JK
2610 /*
2611 * Clamp the max delay per usermode return so as to still keep the
2612 * application moving forwards and also permit diagnostics, albeit
2613 * extremely slowly.
2614 */
2615 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2616
0e4b01df
CD
2617 /*
2618 * Don't sleep if the amount of jiffies this memcg owes us is so low
2619 * that it's not even worth doing, in an attempt to be nice to those who
2620 * go only a small amount over their memory.high value and maybe haven't
2621 * been aggressively reclaimed enough yet.
2622 */
2623 if (penalty_jiffies <= HZ / 100)
2624 goto out;
2625
b3ff9291
CD
2626 /*
2627 * If reclaim is making forward progress but we're still over
2628 * memory.high, we want to encourage that rather than doing allocator
2629 * throttling.
2630 */
2631 if (nr_reclaimed || nr_retries--) {
2632 in_retry = true;
2633 goto retry_reclaim;
2634 }
2635
0e4b01df
CD
2636 /*
2637 * If we exit early, we're guaranteed to die (since
2638 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2639 * need to account for any ill-begotten jiffies to pay them off later.
2640 */
2641 psi_memstall_enter(&pflags);
2642 schedule_timeout_killable(penalty_jiffies);
2643 psi_memstall_leave(&pflags);
2644
2645out:
2646 css_put(&memcg->css);
b23afb93
TH
2647}
2648
c5c8b16b
MS
2649static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2650 unsigned int nr_pages)
8a9f3ccd 2651{
a983b5eb 2652 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
d977aa93 2653 int nr_retries = MAX_RECLAIM_RETRIES;
6539cc05 2654 struct mem_cgroup *mem_over_limit;
3e32cb2e 2655 struct page_counter *counter;
6539cc05 2656 unsigned long nr_reclaimed;
a4ebf1b6 2657 bool passed_oom = false;
73b73bac 2658 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
b70a2a21 2659 bool drained = false;
d6e103a7 2660 bool raised_max_event = false;
e22c6ed9 2661 unsigned long pflags;
a636b327 2662
6539cc05 2663retry:
b6b6cc72 2664 if (consume_stock(memcg, nr_pages))
10d53c74 2665 return 0;
8a9f3ccd 2666
7941d214 2667 if (!do_memsw_account() ||
6071ca52
JW
2668 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2669 if (page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2670 goto done_restock;
7941d214 2671 if (do_memsw_account())
3e32cb2e
JW
2672 page_counter_uncharge(&memcg->memsw, batch);
2673 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2674 } else {
3e32cb2e 2675 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
73b73bac 2676 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
3fbe7244 2677 }
7a81b88c 2678
6539cc05
JW
2679 if (batch > nr_pages) {
2680 batch = nr_pages;
2681 goto retry;
2682 }
6d61ef40 2683
89a28483
JW
2684 /*
2685 * Prevent unbounded recursion when reclaim operations need to
2686 * allocate memory. This might exceed the limits temporarily,
2687 * but we prefer facilitating memory reclaim and getting back
2688 * under the limit over triggering OOM kills in these cases.
2689 */
2690 if (unlikely(current->flags & PF_MEMALLOC))
2691 goto force;
2692
06b078fc
JW
2693 if (unlikely(task_in_memcg_oom(current)))
2694 goto nomem;
2695
d0164adc 2696 if (!gfpflags_allow_blocking(gfp_mask))
6539cc05 2697 goto nomem;
4b534334 2698
e27be240 2699 memcg_memory_event(mem_over_limit, MEMCG_MAX);
d6e103a7 2700 raised_max_event = true;
241994ed 2701
e22c6ed9 2702 psi_memstall_enter(&pflags);
b70a2a21 2703 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
73b73bac 2704 gfp_mask, reclaim_options);
e22c6ed9 2705 psi_memstall_leave(&pflags);
6539cc05 2706
61e02c74 2707 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2708 goto retry;
28c34c29 2709
b70a2a21 2710 if (!drained) {
6d3d6aa2 2711 drain_all_stock(mem_over_limit);
b70a2a21
JW
2712 drained = true;
2713 goto retry;
2714 }
2715
28c34c29
JW
2716 if (gfp_mask & __GFP_NORETRY)
2717 goto nomem;
6539cc05
JW
2718 /*
2719 * Even though the limit is exceeded at this point, reclaim
2720 * may have been able to free some pages. Retry the charge
2721 * before killing the task.
2722 *
2723 * Only for regular pages, though: huge pages are rather
2724 * unlikely to succeed so close to the limit, and we fall back
2725 * to regular pages anyway in case of failure.
2726 */
61e02c74 2727 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05
JW
2728 goto retry;
2729 /*
2730 * At task move, charge accounts can be doubly counted. So, it's
2731 * better to wait until the end of task_move if something is going on.
2732 */
2733 if (mem_cgroup_wait_acct_move(mem_over_limit))
2734 goto retry;
2735
9b130619
JW
2736 if (nr_retries--)
2737 goto retry;
2738
38d38493 2739 if (gfp_mask & __GFP_RETRY_MAYFAIL)
29ef680a
MH
2740 goto nomem;
2741
a4ebf1b6
VA
2742 /* Avoid endless loop for tasks bypassed by the oom killer */
2743 if (passed_oom && task_is_dying())
2744 goto nomem;
6539cc05 2745
29ef680a
MH
2746 /*
2747 * keep retrying as long as the memcg oom killer is able to make
2748 * a forward progress or bypass the charge if the oom killer
2749 * couldn't make any progress.
2750 */
becdf89d
SB
2751 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2752 get_order(nr_pages * PAGE_SIZE))) {
a4ebf1b6 2753 passed_oom = true;
d977aa93 2754 nr_retries = MAX_RECLAIM_RETRIES;
29ef680a 2755 goto retry;
29ef680a 2756 }
7a81b88c 2757nomem:
1461e8c2
SB
2758 /*
2759 * Memcg doesn't have a dedicated reserve for atomic
2760 * allocations. But like the global atomic pool, we need to
2761 * put the burden of reclaim on regular allocation requests
2762 * and let these go through as privileged allocations.
2763 */
2764 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
3168ecbe 2765 return -ENOMEM;
10d53c74 2766force:
d6e103a7
RG
2767 /*
2768 * If the allocation has to be enforced, don't forget to raise
2769 * a MEMCG_MAX event.
2770 */
2771 if (!raised_max_event)
2772 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2773
10d53c74
TH
2774 /*
2775 * The allocation either can't fail or will lead to more memory
2776 * being freed very soon. Allow memory usage go over the limit
2777 * temporarily by force charging it.
2778 */
2779 page_counter_charge(&memcg->memory, nr_pages);
7941d214 2780 if (do_memsw_account())
10d53c74 2781 page_counter_charge(&memcg->memsw, nr_pages);
10d53c74
TH
2782
2783 return 0;
6539cc05
JW
2784
2785done_restock:
2786 if (batch > nr_pages)
2787 refill_stock(memcg, batch - nr_pages);
b23afb93 2788
241994ed 2789 /*
b23afb93
TH
2790 * If the hierarchy is above the normal consumption range, schedule
2791 * reclaim on returning to userland. We can perform reclaim here
71baba4b 2792 * if __GFP_RECLAIM but let's always punt for simplicity and so that
b23afb93
TH
2793 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2794 * not recorded as it most likely matches current's and won't
2795 * change in the meantime. As high limit is checked again before
2796 * reclaim, the cost of mismatch is negligible.
241994ed
JW
2797 */
2798 do {
4b82ab4f
JK
2799 bool mem_high, swap_high;
2800
2801 mem_high = page_counter_read(&memcg->memory) >
2802 READ_ONCE(memcg->memory.high);
2803 swap_high = page_counter_read(&memcg->swap) >
2804 READ_ONCE(memcg->swap.high);
2805
2806 /* Don't bother a random interrupted task */
086f694a 2807 if (!in_task()) {
4b82ab4f 2808 if (mem_high) {
f7e1cb6e
JW
2809 schedule_work(&memcg->high_work);
2810 break;
2811 }
4b82ab4f
JK
2812 continue;
2813 }
2814
2815 if (mem_high || swap_high) {
2816 /*
2817 * The allocating tasks in this cgroup will need to do
2818 * reclaim or be throttled to prevent further growth
2819 * of the memory or swap footprints.
2820 *
2821 * Target some best-effort fairness between the tasks,
2822 * and distribute reclaim work and delay penalties
2823 * based on how much each task is actually allocating.
2824 */
9516a18a 2825 current->memcg_nr_pages_over_high += batch;
b23afb93
TH
2826 set_notify_resume(current);
2827 break;
2828 }
241994ed 2829 } while ((memcg = parent_mem_cgroup(memcg)));
10d53c74 2830
c9afe31e
SB
2831 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2832 !(current->flags & PF_MEMALLOC) &&
2833 gfpflags_allow_blocking(gfp_mask)) {
2834 mem_cgroup_handle_over_high();
2835 }
10d53c74 2836 return 0;
7a81b88c 2837}
8a9f3ccd 2838
c5c8b16b
MS
2839static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2840 unsigned int nr_pages)
2841{
2842 if (mem_cgroup_is_root(memcg))
2843 return 0;
2844
2845 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2846}
2847
58056f77 2848static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
a3032a2c 2849{
ce00a967
JW
2850 if (mem_cgroup_is_root(memcg))
2851 return;
2852
3e32cb2e 2853 page_counter_uncharge(&memcg->memory, nr_pages);
7941d214 2854 if (do_memsw_account())
3e32cb2e 2855 page_counter_uncharge(&memcg->memsw, nr_pages);
d01dd17f
KH
2856}
2857
118f2875 2858static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
0a31bc97 2859{
118f2875 2860 VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
0a31bc97 2861 /*
a5eb011a 2862 * Any of the following ensures page's memcg stability:
0a31bc97 2863 *
a0b5b414
JW
2864 * - the page lock
2865 * - LRU isolation
2866 * - lock_page_memcg()
2867 * - exclusive reference
018ee47f 2868 * - mem_cgroup_trylock_pages()
0a31bc97 2869 */
118f2875 2870 folio->memcg_data = (unsigned long)memcg;
7a81b88c 2871}
66e1707b 2872
84c07d11 2873#ifdef CONFIG_MEMCG_KMEM
41eb5df1
WL
2874/*
2875 * The allocated objcg pointers array is not accounted directly.
2876 * Moreover, it should not come from DMA buffer and is not readily
2877 * reclaimable. So those GFP bits should be masked off.
2878 */
2879#define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | __GFP_ACCOUNT)
2880
a7ebf564
WL
2881/*
2882 * mod_objcg_mlstate() may be called with irq enabled, so
2883 * mod_memcg_lruvec_state() should be used.
2884 */
2885static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2886 struct pglist_data *pgdat,
2887 enum node_stat_item idx, int nr)
2888{
2889 struct mem_cgroup *memcg;
2890 struct lruvec *lruvec;
2891
2892 rcu_read_lock();
2893 memcg = obj_cgroup_memcg(objcg);
2894 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2895 mod_memcg_lruvec_state(lruvec, idx, nr);
2896 rcu_read_unlock();
2897}
2898
4b5f8d9a
VB
2899int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
2900 gfp_t gfp, bool new_slab)
10befea9 2901{
4b5f8d9a 2902 unsigned int objects = objs_per_slab(s, slab);
2e9bd483 2903 unsigned long memcg_data;
10befea9
RG
2904 void *vec;
2905
41eb5df1 2906 gfp &= ~OBJCGS_CLEAR_MASK;
10befea9 2907 vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
4b5f8d9a 2908 slab_nid(slab));
10befea9
RG
2909 if (!vec)
2910 return -ENOMEM;
2911
2e9bd483 2912 memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
4b5f8d9a 2913 if (new_slab) {
2e9bd483 2914 /*
4b5f8d9a
VB
2915 * If the slab is brand new and nobody can yet access its
2916 * memcg_data, no synchronization is required and memcg_data can
2917 * be simply assigned.
2e9bd483 2918 */
4b5f8d9a
VB
2919 slab->memcg_data = memcg_data;
2920 } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
2e9bd483 2921 /*
4b5f8d9a
VB
2922 * If the slab is already in use, somebody can allocate and
2923 * assign obj_cgroups in parallel. In this case the existing
2e9bd483
RG
2924 * objcg vector should be reused.
2925 */
10befea9 2926 kfree(vec);
2e9bd483
RG
2927 return 0;
2928 }
10befea9 2929
2e9bd483 2930 kmemleak_not_leak(vec);
10befea9
RG
2931 return 0;
2932}
2933
fc4db90f
RG
2934static __always_inline
2935struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
8380ce47 2936{
8380ce47 2937 /*
9855609b
RG
2938 * Slab objects are accounted individually, not per-page.
2939 * Memcg membership data for each individual object is saved in
4b5f8d9a 2940 * slab->memcg_data.
8380ce47 2941 */
4b5f8d9a
VB
2942 if (folio_test_slab(folio)) {
2943 struct obj_cgroup **objcgs;
2944 struct slab *slab;
9855609b
RG
2945 unsigned int off;
2946
4b5f8d9a
VB
2947 slab = folio_slab(folio);
2948 objcgs = slab_objcgs(slab);
2949 if (!objcgs)
2950 return NULL;
2951
2952 off = obj_to_index(slab->slab_cache, slab, p);
2953 if (objcgs[off])
2954 return obj_cgroup_memcg(objcgs[off]);
10befea9
RG
2955
2956 return NULL;
9855609b 2957 }
8380ce47 2958
bcfe06bf 2959 /*
4b5f8d9a
VB
2960 * page_memcg_check() is used here, because in theory we can encounter
2961 * a folio where the slab flag has been cleared already, but
2962 * slab->memcg_data has not been freed yet
bcfe06bf
RG
2963 * page_memcg_check(page) will guarantee that a proper memory
2964 * cgroup pointer or NULL will be returned.
2965 */
4b5f8d9a 2966 return page_memcg_check(folio_page(folio, 0));
8380ce47
RG
2967}
2968
fc4db90f
RG
2969/*
2970 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2971 *
2972 * A passed kernel object can be a slab object, vmalloc object or a generic
2973 * kernel page, so different mechanisms for getting the memory cgroup pointer
2974 * should be used.
2975 *
2976 * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
2977 * can not know for sure how the kernel object is implemented.
2978 * mem_cgroup_from_obj() can be safely used in such cases.
2979 *
2980 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2981 * cgroup_mutex, etc.
2982 */
2983struct mem_cgroup *mem_cgroup_from_obj(void *p)
2984{
2985 struct folio *folio;
2986
2987 if (mem_cgroup_disabled())
2988 return NULL;
2989
2990 if (unlikely(is_vmalloc_addr(p)))
2991 folio = page_folio(vmalloc_to_page(p));
2992 else
2993 folio = virt_to_folio(p);
2994
2995 return mem_cgroup_from_obj_folio(folio, p);
2996}
2997
2998/*
2999 * Returns a pointer to the memory cgroup to which the kernel object is charged.
3000 * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
3001 * allocated using vmalloc().
3002 *
3003 * A passed kernel object must be a slab object or a generic kernel page.
3004 *
3005 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3006 * cgroup_mutex, etc.
3007 */
3008struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
3009{
3010 if (mem_cgroup_disabled())
3011 return NULL;
3012
3013 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
3014}
3015
f4840ccf
JW
3016static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
3017{
3018 struct obj_cgroup *objcg = NULL;
3019
3020 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
3021 objcg = rcu_dereference(memcg->objcg);
3022 if (objcg && obj_cgroup_tryget(objcg))
3023 break;
3024 objcg = NULL;
3025 }
3026 return objcg;
3027}
3028
bf4f0599
RG
3029__always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
3030{
3031 struct obj_cgroup *objcg = NULL;
3032 struct mem_cgroup *memcg;
3033
279c3393
RG
3034 if (memcg_kmem_bypass())
3035 return NULL;
3036
bf4f0599 3037 rcu_read_lock();
37d5985c
RG
3038 if (unlikely(active_memcg()))
3039 memcg = active_memcg();
bf4f0599
RG
3040 else
3041 memcg = mem_cgroup_from_task(current);
f4840ccf 3042 objcg = __get_obj_cgroup_from_memcg(memcg);
bf4f0599 3043 rcu_read_unlock();
f4840ccf
JW
3044 return objcg;
3045}
3046
3047struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
3048{
3049 struct obj_cgroup *objcg;
3050
3051 if (!memcg_kmem_enabled() || memcg_kmem_bypass())
3052 return NULL;
3053
3054 if (PageMemcgKmem(page)) {
3055 objcg = __folio_objcg(page_folio(page));
3056 obj_cgroup_get(objcg);
3057 } else {
3058 struct mem_cgroup *memcg;
bf4f0599 3059
f4840ccf
JW
3060 rcu_read_lock();
3061 memcg = __folio_memcg(page_folio(page));
3062 if (memcg)
3063 objcg = __get_obj_cgroup_from_memcg(memcg);
3064 else
3065 objcg = NULL;
3066 rcu_read_unlock();
3067 }
bf4f0599
RG
3068 return objcg;
3069}
3070
a8c49af3
YA
3071static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
3072{
3073 mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
3074 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
3075 if (nr_pages > 0)
3076 page_counter_charge(&memcg->kmem, nr_pages);
3077 else
3078 page_counter_uncharge(&memcg->kmem, -nr_pages);
3079 }
3080}
3081
3082
f1286fae
MS
3083/*
3084 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3085 * @objcg: object cgroup to uncharge
3086 * @nr_pages: number of pages to uncharge
3087 */
e74d2259
MS
3088static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3089 unsigned int nr_pages)
3090{
3091 struct mem_cgroup *memcg;
3092
3093 memcg = get_mem_cgroup_from_objcg(objcg);
e74d2259 3094
a8c49af3 3095 memcg_account_kmem(memcg, -nr_pages);
f1286fae 3096 refill_stock(memcg, nr_pages);
e74d2259 3097
e74d2259 3098 css_put(&memcg->css);
e74d2259
MS
3099}
3100
f1286fae
MS
3101/*
3102 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3103 * @objcg: object cgroup to charge
45264778 3104 * @gfp: reclaim mode
92d0510c 3105 * @nr_pages: number of pages to charge
45264778
VD
3106 *
3107 * Returns 0 on success, an error code on failure.
3108 */
f1286fae
MS
3109static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3110 unsigned int nr_pages)
7ae1e1d0 3111{
f1286fae 3112 struct mem_cgroup *memcg;
7ae1e1d0
GC
3113 int ret;
3114
f1286fae
MS
3115 memcg = get_mem_cgroup_from_objcg(objcg);
3116
c5c8b16b 3117 ret = try_charge_memcg(memcg, gfp, nr_pages);
52c29b04 3118 if (ret)
f1286fae 3119 goto out;
52c29b04 3120
a8c49af3 3121 memcg_account_kmem(memcg, nr_pages);
f1286fae
MS
3122out:
3123 css_put(&memcg->css);
4b13f64d 3124
f1286fae 3125 return ret;
4b13f64d
RG
3126}
3127
45264778 3128/**
f4b00eab 3129 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
45264778
VD
3130 * @page: page to charge
3131 * @gfp: reclaim mode
3132 * @order: allocation order
3133 *
3134 * Returns 0 on success, an error code on failure.
3135 */
f4b00eab 3136int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
7ae1e1d0 3137{
b4e0b68f 3138 struct obj_cgroup *objcg;
fcff7d7e 3139 int ret = 0;
7ae1e1d0 3140
b4e0b68f
MS
3141 objcg = get_obj_cgroup_from_current();
3142 if (objcg) {
3143 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
4d96ba35 3144 if (!ret) {
b4e0b68f 3145 page->memcg_data = (unsigned long)objcg |
18b2db3b 3146 MEMCG_DATA_KMEM;
1a3e1f40 3147 return 0;
4d96ba35 3148 }
b4e0b68f 3149 obj_cgroup_put(objcg);
c4159a75 3150 }
d05e83a6 3151 return ret;
7ae1e1d0 3152}
49a18eae 3153
45264778 3154/**
f4b00eab 3155 * __memcg_kmem_uncharge_page: uncharge a kmem page
45264778
VD
3156 * @page: page to uncharge
3157 * @order: allocation order
3158 */
f4b00eab 3159void __memcg_kmem_uncharge_page(struct page *page, int order)
7ae1e1d0 3160{
1b7e4464 3161 struct folio *folio = page_folio(page);
b4e0b68f 3162 struct obj_cgroup *objcg;
f3ccb2c4 3163 unsigned int nr_pages = 1 << order;
7ae1e1d0 3164
1b7e4464 3165 if (!folio_memcg_kmem(folio))
7ae1e1d0
GC
3166 return;
3167
1b7e4464 3168 objcg = __folio_objcg(folio);
b4e0b68f 3169 obj_cgroup_uncharge_pages(objcg, nr_pages);
1b7e4464 3170 folio->memcg_data = 0;
b4e0b68f 3171 obj_cgroup_put(objcg);
60d3fd32 3172}
bf4f0599 3173
68ac5b3c
WL
3174void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
3175 enum node_stat_item idx, int nr)
3176{
fead2b86 3177 struct memcg_stock_pcp *stock;
56751146 3178 struct obj_cgroup *old = NULL;
68ac5b3c
WL
3179 unsigned long flags;
3180 int *bytes;
3181
56751146 3182 local_lock_irqsave(&memcg_stock.stock_lock, flags);
fead2b86
MH
3183 stock = this_cpu_ptr(&memcg_stock);
3184
68ac5b3c
WL
3185 /*
3186 * Save vmstat data in stock and skip vmstat array update unless
3187 * accumulating over a page of vmstat data or when pgdat or idx
3188 * changes.
3189 */
3190 if (stock->cached_objcg != objcg) {
56751146 3191 old = drain_obj_stock(stock);
68ac5b3c
WL
3192 obj_cgroup_get(objcg);
3193 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3194 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3195 stock->cached_objcg = objcg;
3196 stock->cached_pgdat = pgdat;
3197 } else if (stock->cached_pgdat != pgdat) {
3198 /* Flush the existing cached vmstat data */
7fa0dacb
WL
3199 struct pglist_data *oldpg = stock->cached_pgdat;
3200
68ac5b3c 3201 if (stock->nr_slab_reclaimable_b) {
7fa0dacb 3202 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
68ac5b3c
WL
3203 stock->nr_slab_reclaimable_b);
3204 stock->nr_slab_reclaimable_b = 0;
3205 }
3206 if (stock->nr_slab_unreclaimable_b) {
7fa0dacb 3207 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
68ac5b3c
WL
3208 stock->nr_slab_unreclaimable_b);
3209 stock->nr_slab_unreclaimable_b = 0;
3210 }
3211 stock->cached_pgdat = pgdat;
3212 }
3213
3214 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3215 : &stock->nr_slab_unreclaimable_b;
3216 /*
3217 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3218 * cached locally at least once before pushing it out.
3219 */
3220 if (!*bytes) {
3221 *bytes = nr;
3222 nr = 0;
3223 } else {
3224 *bytes += nr;
3225 if (abs(*bytes) > PAGE_SIZE) {
3226 nr = *bytes;
3227 *bytes = 0;
3228 } else {
3229 nr = 0;
3230 }
3231 }
3232 if (nr)
3233 mod_objcg_mlstate(objcg, pgdat, idx, nr);
3234
56751146
SAS
3235 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3236 if (old)
3237 obj_cgroup_put(old);
68ac5b3c
WL
3238}
3239
bf4f0599
RG
3240static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3241{
fead2b86 3242 struct memcg_stock_pcp *stock;
bf4f0599
RG
3243 unsigned long flags;
3244 bool ret = false;
3245
56751146 3246 local_lock_irqsave(&memcg_stock.stock_lock, flags);
fead2b86
MH
3247
3248 stock = this_cpu_ptr(&memcg_stock);
bf4f0599
RG
3249 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3250 stock->nr_bytes -= nr_bytes;
3251 ret = true;
3252 }
3253
56751146 3254 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
bf4f0599
RG
3255
3256 return ret;
3257}
3258
56751146 3259static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
bf4f0599
RG
3260{
3261 struct obj_cgroup *old = stock->cached_objcg;
3262
3263 if (!old)
56751146 3264 return NULL;
bf4f0599
RG
3265
3266 if (stock->nr_bytes) {
3267 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3268 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3269
af9a3b69
JW
3270 if (nr_pages) {
3271 struct mem_cgroup *memcg;
3272
3273 memcg = get_mem_cgroup_from_objcg(old);
3274
3275 memcg_account_kmem(memcg, -nr_pages);
3276 __refill_stock(memcg, nr_pages);
3277
3278 css_put(&memcg->css);
3279 }
bf4f0599
RG
3280
3281 /*
3282 * The leftover is flushed to the centralized per-memcg value.
3283 * On the next attempt to refill obj stock it will be moved
3284 * to a per-cpu stock (probably, on an other CPU), see
3285 * refill_obj_stock().
3286 *
3287 * How often it's flushed is a trade-off between the memory
3288 * limit enforcement accuracy and potential CPU contention,
3289 * so it might be changed in the future.
3290 */
3291 atomic_add(nr_bytes, &old->nr_charged_bytes);
3292 stock->nr_bytes = 0;
3293 }
3294
68ac5b3c
WL
3295 /*
3296 * Flush the vmstat data in current stock
3297 */
3298 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3299 if (stock->nr_slab_reclaimable_b) {
3300 mod_objcg_mlstate(old, stock->cached_pgdat,
3301 NR_SLAB_RECLAIMABLE_B,
3302 stock->nr_slab_reclaimable_b);
3303 stock->nr_slab_reclaimable_b = 0;
3304 }
3305 if (stock->nr_slab_unreclaimable_b) {
3306 mod_objcg_mlstate(old, stock->cached_pgdat,
3307 NR_SLAB_UNRECLAIMABLE_B,
3308 stock->nr_slab_unreclaimable_b);
3309 stock->nr_slab_unreclaimable_b = 0;
3310 }
3311 stock->cached_pgdat = NULL;
3312 }
3313
bf4f0599 3314 stock->cached_objcg = NULL;
56751146
SAS
3315 /*
3316 * The `old' objects needs to be released by the caller via
3317 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
3318 */
3319 return old;
bf4f0599
RG
3320}
3321
3322static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3323 struct mem_cgroup *root_memcg)
3324{
3325 struct mem_cgroup *memcg;
3326
fead2b86
MH
3327 if (stock->cached_objcg) {
3328 memcg = obj_cgroup_memcg(stock->cached_objcg);
bf4f0599
RG
3329 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3330 return true;
3331 }
3332
3333 return false;
3334}
3335
5387c904
WL
3336static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3337 bool allow_uncharge)
bf4f0599 3338{
fead2b86 3339 struct memcg_stock_pcp *stock;
56751146 3340 struct obj_cgroup *old = NULL;
bf4f0599 3341 unsigned long flags;
5387c904 3342 unsigned int nr_pages = 0;
bf4f0599 3343
56751146 3344 local_lock_irqsave(&memcg_stock.stock_lock, flags);
fead2b86
MH
3345
3346 stock = this_cpu_ptr(&memcg_stock);
bf4f0599 3347 if (stock->cached_objcg != objcg) { /* reset if necessary */
56751146 3348 old = drain_obj_stock(stock);
bf4f0599
RG
3349 obj_cgroup_get(objcg);
3350 stock->cached_objcg = objcg;
5387c904
WL
3351 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3352 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3353 allow_uncharge = true; /* Allow uncharge when objcg changes */
bf4f0599
RG
3354 }
3355 stock->nr_bytes += nr_bytes;
3356
5387c904
WL
3357 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3358 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3359 stock->nr_bytes &= (PAGE_SIZE - 1);
3360 }
bf4f0599 3361
56751146
SAS
3362 local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
3363 if (old)
3364 obj_cgroup_put(old);
5387c904
WL
3365
3366 if (nr_pages)
3367 obj_cgroup_uncharge_pages(objcg, nr_pages);
bf4f0599
RG
3368}
3369
3370int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3371{
bf4f0599
RG
3372 unsigned int nr_pages, nr_bytes;
3373 int ret;
3374
3375 if (consume_obj_stock(objcg, size))
3376 return 0;
3377
3378 /*
5387c904 3379 * In theory, objcg->nr_charged_bytes can have enough
bf4f0599 3380 * pre-charged bytes to satisfy the allocation. However,
5387c904
WL
3381 * flushing objcg->nr_charged_bytes requires two atomic
3382 * operations, and objcg->nr_charged_bytes can't be big.
3383 * The shared objcg->nr_charged_bytes can also become a
3384 * performance bottleneck if all tasks of the same memcg are
3385 * trying to update it. So it's better to ignore it and try
3386 * grab some new pages. The stock's nr_bytes will be flushed to
3387 * objcg->nr_charged_bytes later on when objcg changes.
3388 *
3389 * The stock's nr_bytes may contain enough pre-charged bytes
3390 * to allow one less page from being charged, but we can't rely
3391 * on the pre-charged bytes not being changed outside of
3392 * consume_obj_stock() or refill_obj_stock(). So ignore those
3393 * pre-charged bytes as well when charging pages. To avoid a
3394 * page uncharge right after a page charge, we set the
3395 * allow_uncharge flag to false when calling refill_obj_stock()
3396 * to temporarily allow the pre-charged bytes to exceed the page
3397 * size limit. The maximum reachable value of the pre-charged
3398 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3399 * race.
bf4f0599 3400 */
bf4f0599
RG
3401 nr_pages = size >> PAGE_SHIFT;
3402 nr_bytes = size & (PAGE_SIZE - 1);
3403
3404 if (nr_bytes)
3405 nr_pages += 1;
3406
e74d2259 3407 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
bf4f0599 3408 if (!ret && nr_bytes)
5387c904 3409 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
bf4f0599 3410
bf4f0599
RG
3411 return ret;
3412}
3413
3414void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3415{
5387c904 3416 refill_obj_stock(objcg, size, true);
bf4f0599
RG
3417}
3418
84c07d11 3419#endif /* CONFIG_MEMCG_KMEM */
7ae1e1d0 3420
ca3e0214 3421/*
be6c8982 3422 * Because page_memcg(head) is not set on tails, set it now.
ca3e0214 3423 */
be6c8982 3424void split_page_memcg(struct page *head, unsigned int nr)
ca3e0214 3425{
1b7e4464
MWO
3426 struct folio *folio = page_folio(head);
3427 struct mem_cgroup *memcg = folio_memcg(folio);
e94c8a9c 3428 int i;
ca3e0214 3429
be6c8982 3430 if (mem_cgroup_disabled() || !memcg)
3d37c4a9 3431 return;
b070e65c 3432
be6c8982 3433 for (i = 1; i < nr; i++)
1b7e4464 3434 folio_page(folio, i)->memcg_data = folio->memcg_data;
b4e0b68f 3435
1b7e4464
MWO
3436 if (folio_memcg_kmem(folio))
3437 obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
b4e0b68f
MS
3438 else
3439 css_get_many(&memcg->css, nr - 1);
ca3e0214 3440}
ca3e0214 3441
c255a458 3442#ifdef CONFIG_MEMCG_SWAP
02491447
DN
3443/**
3444 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3445 * @entry: swap entry to be moved
3446 * @from: mem_cgroup which the entry is moved from
3447 * @to: mem_cgroup which the entry is moved to
3448 *
3449 * It succeeds only when the swap_cgroup's record for this entry is the same
3450 * as the mem_cgroup's id of @from.
3451 *
3452 * Returns 0 on success, -EINVAL on failure.
3453 *
3e32cb2e 3454 * The caller must have charged to @to, IOW, called page_counter_charge() about
02491447
DN
3455 * both res and memsw, and called css_get().
3456 */
3457static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3458 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3459{
3460 unsigned short old_id, new_id;
3461
34c00c31
LZ
3462 old_id = mem_cgroup_id(from);
3463 new_id = mem_cgroup_id(to);
02491447
DN
3464
3465 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
c9019e9b
JW
3466 mod_memcg_state(from, MEMCG_SWAP, -1);
3467 mod_memcg_state(to, MEMCG_SWAP, 1);
02491447
DN
3468 return 0;
3469 }
3470 return -EINVAL;
3471}
3472#else
3473static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3474 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3475{
3476 return -EINVAL;
3477}
8c7c6e34 3478#endif
d13d1443 3479
bbec2e15 3480static DEFINE_MUTEX(memcg_max_mutex);
f212ad7c 3481
bbec2e15
RG
3482static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3483 unsigned long max, bool memsw)
628f4235 3484{
3e32cb2e 3485 bool enlarge = false;
bb4a7ea2 3486 bool drained = false;
3e32cb2e 3487 int ret;
c054a78c
YZ
3488 bool limits_invariant;
3489 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
81d39c20 3490
3e32cb2e 3491 do {
628f4235
KH
3492 if (signal_pending(current)) {
3493 ret = -EINTR;
3494 break;
3495 }
3e32cb2e 3496
bbec2e15 3497 mutex_lock(&memcg_max_mutex);
c054a78c
YZ
3498 /*
3499 * Make sure that the new limit (memsw or memory limit) doesn't
bbec2e15 3500 * break our basic invariant rule memory.max <= memsw.max.
c054a78c 3501 */
15b42562 3502 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
bbec2e15 3503 max <= memcg->memsw.max;
c054a78c 3504 if (!limits_invariant) {
bbec2e15 3505 mutex_unlock(&memcg_max_mutex);
8c7c6e34 3506 ret = -EINVAL;
8c7c6e34
KH
3507 break;
3508 }
bbec2e15 3509 if (max > counter->max)
3e32cb2e 3510 enlarge = true;
bbec2e15
RG
3511 ret = page_counter_set_max(counter, max);
3512 mutex_unlock(&memcg_max_mutex);
8c7c6e34
KH
3513
3514 if (!ret)
3515 break;
3516
bb4a7ea2
SB
3517 if (!drained) {
3518 drain_all_stock(memcg);
3519 drained = true;
3520 continue;
3521 }
3522
73b73bac
YA
3523 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3524 memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
1ab5c056
AR
3525 ret = -EBUSY;
3526 break;
3527 }
3528 } while (true);
3e32cb2e 3529
3c11ecf4
KH
3530 if (!ret && enlarge)
3531 memcg_oom_recover(memcg);
3e32cb2e 3532
628f4235
KH
3533 return ret;
3534}
3535
ef8f2327 3536unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
0608f43d
AM
3537 gfp_t gfp_mask,
3538 unsigned long *total_scanned)
3539{
3540 unsigned long nr_reclaimed = 0;
ef8f2327 3541 struct mem_cgroup_per_node *mz, *next_mz = NULL;
0608f43d
AM
3542 unsigned long reclaimed;
3543 int loop = 0;
ef8f2327 3544 struct mem_cgroup_tree_per_node *mctz;
3e32cb2e 3545 unsigned long excess;
0608f43d
AM
3546
3547 if (order > 0)
3548 return 0;
3549
2ab082ba 3550 mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
d6507ff5
MH
3551
3552 /*
3553 * Do not even bother to check the largest node if the root
3554 * is empty. Do it lockless to prevent lock bouncing. Races
3555 * are acceptable as soft limit is best effort anyway.
3556 */
bfc7228b 3557 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
d6507ff5
MH
3558 return 0;
3559
0608f43d
AM
3560 /*
3561 * This loop can run a while, specially if mem_cgroup's continuously
3562 * keep exceeding their soft limit and putting the system under
3563 * pressure
3564 */
3565 do {
3566 if (next_mz)
3567 mz = next_mz;
3568 else
3569 mz = mem_cgroup_largest_soft_limit_node(mctz);
3570 if (!mz)
3571 break;
3572
ef8f2327 3573 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
d8f65338 3574 gfp_mask, total_scanned);
0608f43d 3575 nr_reclaimed += reclaimed;
0a31bc97 3576 spin_lock_irq(&mctz->lock);
0608f43d
AM
3577
3578 /*
3579 * If we failed to reclaim anything from this memory cgroup
3580 * it is time to move on to the next cgroup
3581 */
3582 next_mz = NULL;
bc2f2e7f
VD
3583 if (!reclaimed)
3584 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3585
3e32cb2e 3586 excess = soft_limit_excess(mz->memcg);
0608f43d
AM
3587 /*
3588 * One school of thought says that we should not add
3589 * back the node to the tree if reclaim returns 0.
3590 * But our reclaim could return 0, simply because due
3591 * to priority we are exposing a smaller subset of
3592 * memory to reclaim from. Consider this as a longer
3593 * term TODO.
3594 */
3595 /* If excess == 0, no tree ops */
cf2c8127 3596 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 3597 spin_unlock_irq(&mctz->lock);
0608f43d
AM
3598 css_put(&mz->memcg->css);
3599 loop++;
3600 /*
3601 * Could not reclaim anything and there are no more
3602 * mem cgroups to try or we seem to be looping without
3603 * reclaiming anything.
3604 */
3605 if (!nr_reclaimed &&
3606 (next_mz == NULL ||
3607 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3608 break;
3609 } while (!nr_reclaimed);
3610 if (next_mz)
3611 css_put(&next_mz->memcg->css);
3612 return nr_reclaimed;
3613}
3614
c26251f9 3615/*
51038171 3616 * Reclaims as many pages from the given memcg as possible.
c26251f9
MH
3617 *
3618 * Caller is responsible for holding css reference for memcg.
3619 */
3620static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3621{
d977aa93 3622 int nr_retries = MAX_RECLAIM_RETRIES;
c26251f9 3623
c1e862c1
KH
3624 /* we call try-to-free pages for make this cgroup empty */
3625 lru_add_drain_all();
d12c60f6
JS
3626
3627 drain_all_stock(memcg);
3628
f817ed48 3629 /* try to free all pages in this cgroup */
3e32cb2e 3630 while (nr_retries && page_counter_read(&memcg->memory)) {
c26251f9
MH
3631 if (signal_pending(current))
3632 return -EINTR;
3633
73b73bac
YA
3634 if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
3635 MEMCG_RECLAIM_MAY_SWAP))
f817ed48 3636 nr_retries--;
f817ed48 3637 }
ab5196c2
MH
3638
3639 return 0;
cc847582
KH
3640}
3641
6770c64e
TH
3642static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3643 char *buf, size_t nbytes,
3644 loff_t off)
c1e862c1 3645{
6770c64e 3646 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
c26251f9 3647
d8423011
MH
3648 if (mem_cgroup_is_root(memcg))
3649 return -EINVAL;
6770c64e 3650 return mem_cgroup_force_empty(memcg) ?: nbytes;
c1e862c1
KH
3651}
3652
182446d0
TH
3653static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3654 struct cftype *cft)
18f59ea7 3655{
bef8620c 3656 return 1;
18f59ea7
BS
3657}
3658
182446d0
TH
3659static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3660 struct cftype *cft, u64 val)
18f59ea7 3661{
bef8620c 3662 if (val == 1)
0b8f73e1 3663 return 0;
567fb435 3664
bef8620c
RG
3665 pr_warn_once("Non-hierarchical mode is deprecated. "
3666 "Please report your usecase to linux-mm@kvack.org if you "
3667 "depend on this functionality.\n");
567fb435 3668
bef8620c 3669 return -EINVAL;
18f59ea7
BS
3670}
3671
6f646156 3672static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
ce00a967 3673{
42a30035 3674 unsigned long val;
ce00a967 3675
3e32cb2e 3676 if (mem_cgroup_is_root(memcg)) {
fd25a9e0 3677 mem_cgroup_flush_stats();
0d1c2072 3678 val = memcg_page_state(memcg, NR_FILE_PAGES) +
be5d0a74 3679 memcg_page_state(memcg, NR_ANON_MAPPED);
42a30035
JW
3680 if (swap)
3681 val += memcg_page_state(memcg, MEMCG_SWAP);
3e32cb2e 3682 } else {
ce00a967 3683 if (!swap)
3e32cb2e 3684 val = page_counter_read(&memcg->memory);
ce00a967 3685 else
3e32cb2e 3686 val = page_counter_read(&memcg->memsw);
ce00a967 3687 }
c12176d3 3688 return val;
ce00a967
JW
3689}
3690
3e32cb2e
JW
3691enum {
3692 RES_USAGE,
3693 RES_LIMIT,
3694 RES_MAX_USAGE,
3695 RES_FAILCNT,
3696 RES_SOFT_LIMIT,
3697};
ce00a967 3698
791badbd 3699static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
05b84301 3700 struct cftype *cft)
8cdea7c0 3701{
182446d0 3702 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3e32cb2e 3703 struct page_counter *counter;
af36f906 3704
3e32cb2e 3705 switch (MEMFILE_TYPE(cft->private)) {
8c7c6e34 3706 case _MEM:
3e32cb2e
JW
3707 counter = &memcg->memory;
3708 break;
8c7c6e34 3709 case _MEMSWAP:
3e32cb2e
JW
3710 counter = &memcg->memsw;
3711 break;
510fc4e1 3712 case _KMEM:
3e32cb2e 3713 counter = &memcg->kmem;
510fc4e1 3714 break;
d55f90bf 3715 case _TCP:
0db15298 3716 counter = &memcg->tcpmem;
d55f90bf 3717 break;
8c7c6e34
KH
3718 default:
3719 BUG();
8c7c6e34 3720 }
3e32cb2e
JW
3721
3722 switch (MEMFILE_ATTR(cft->private)) {
3723 case RES_USAGE:
3724 if (counter == &memcg->memory)
c12176d3 3725 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3e32cb2e 3726 if (counter == &memcg->memsw)
c12176d3 3727 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3e32cb2e
JW
3728 return (u64)page_counter_read(counter) * PAGE_SIZE;
3729 case RES_LIMIT:
bbec2e15 3730 return (u64)counter->max * PAGE_SIZE;
3e32cb2e
JW
3731 case RES_MAX_USAGE:
3732 return (u64)counter->watermark * PAGE_SIZE;
3733 case RES_FAILCNT:
3734 return counter->failcnt;
3735 case RES_SOFT_LIMIT:
3736 return (u64)memcg->soft_limit * PAGE_SIZE;
3737 default:
3738 BUG();
3739 }
8cdea7c0 3740}
510fc4e1 3741
84c07d11 3742#ifdef CONFIG_MEMCG_KMEM
567e9ab2 3743static int memcg_online_kmem(struct mem_cgroup *memcg)
d6441637 3744{
bf4f0599 3745 struct obj_cgroup *objcg;
d6441637 3746
9c94bef9 3747 if (mem_cgroup_kmem_disabled())
b313aeee
VD
3748 return 0;
3749
da0efe30
MS
3750 if (unlikely(mem_cgroup_is_root(memcg)))
3751 return 0;
d6441637 3752
bf4f0599 3753 objcg = obj_cgroup_alloc();
f9c69d63 3754 if (!objcg)
bf4f0599 3755 return -ENOMEM;
f9c69d63 3756
bf4f0599
RG
3757 objcg->memcg = memcg;
3758 rcu_assign_pointer(memcg->objcg, objcg);
3759
d648bcc7
RG
3760 static_branch_enable(&memcg_kmem_enabled_key);
3761
f9c69d63 3762 memcg->kmemcg_id = memcg->id.id;
0b8f73e1
JW
3763
3764 return 0;
d6441637
VD
3765}
3766
8e0a8912
JW
3767static void memcg_offline_kmem(struct mem_cgroup *memcg)
3768{
64268868 3769 struct mem_cgroup *parent;
8e0a8912 3770
9c94bef9 3771 if (mem_cgroup_kmem_disabled())
da0efe30
MS
3772 return;
3773
3774 if (unlikely(mem_cgroup_is_root(memcg)))
8e0a8912 3775 return;
9855609b 3776
8e0a8912
JW
3777 parent = parent_mem_cgroup(memcg);
3778 if (!parent)
3779 parent = root_mem_cgroup;
3780
bf4f0599 3781 memcg_reparent_objcgs(memcg, parent);
fb2f2b0a 3782
8e0a8912 3783 /*
64268868
MS
3784 * After we have finished memcg_reparent_objcgs(), all list_lrus
3785 * corresponding to this cgroup are guaranteed to remain empty.
3786 * The ordering is imposed by list_lru_node->lock taken by
1f391eb2 3787 * memcg_reparent_list_lrus().
8e0a8912 3788 */
1f391eb2 3789 memcg_reparent_list_lrus(memcg, parent);
8e0a8912 3790}
d6441637 3791#else
0b8f73e1 3792static int memcg_online_kmem(struct mem_cgroup *memcg)
127424c8
JW
3793{
3794 return 0;
3795}
3796static void memcg_offline_kmem(struct mem_cgroup *memcg)
3797{
3798}
84c07d11 3799#endif /* CONFIG_MEMCG_KMEM */
127424c8 3800
bbec2e15 3801static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
d55f90bf
VD
3802{
3803 int ret;
3804
bbec2e15 3805 mutex_lock(&memcg_max_mutex);
d55f90bf 3806
bbec2e15 3807 ret = page_counter_set_max(&memcg->tcpmem, max);
d55f90bf
VD
3808 if (ret)
3809 goto out;
3810
0db15298 3811 if (!memcg->tcpmem_active) {
d55f90bf
VD
3812 /*
3813 * The active flag needs to be written after the static_key
3814 * update. This is what guarantees that the socket activation
2d758073
JW
3815 * function is the last one to run. See mem_cgroup_sk_alloc()
3816 * for details, and note that we don't mark any socket as
3817 * belonging to this memcg until that flag is up.
d55f90bf
VD
3818 *
3819 * We need to do this, because static_keys will span multiple
3820 * sites, but we can't control their order. If we mark a socket
3821 * as accounted, but the accounting functions are not patched in
3822 * yet, we'll lose accounting.
3823 *
2d758073 3824 * We never race with the readers in mem_cgroup_sk_alloc(),
d55f90bf
VD
3825 * because when this value change, the code to process it is not
3826 * patched in yet.
3827 */
3828 static_branch_inc(&memcg_sockets_enabled_key);
0db15298 3829 memcg->tcpmem_active = true;
d55f90bf
VD
3830 }
3831out:
bbec2e15 3832 mutex_unlock(&memcg_max_mutex);
d55f90bf
VD
3833 return ret;
3834}
d55f90bf 3835
628f4235
KH
3836/*
3837 * The user of this function is...
3838 * RES_LIMIT.
3839 */
451af504
TH
3840static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3841 char *buf, size_t nbytes, loff_t off)
8cdea7c0 3842{
451af504 3843 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3844 unsigned long nr_pages;
628f4235
KH
3845 int ret;
3846
451af504 3847 buf = strstrip(buf);
650c5e56 3848 ret = page_counter_memparse(buf, "-1", &nr_pages);
3e32cb2e
JW
3849 if (ret)
3850 return ret;
af36f906 3851
3e32cb2e 3852 switch (MEMFILE_ATTR(of_cft(of)->private)) {
628f4235 3853 case RES_LIMIT:
4b3bde4c
BS
3854 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3855 ret = -EINVAL;
3856 break;
3857 }
3e32cb2e
JW
3858 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3859 case _MEM:
bbec2e15 3860 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
8c7c6e34 3861 break;
3e32cb2e 3862 case _MEMSWAP:
bbec2e15 3863 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
296c81d8 3864 break;
3e32cb2e 3865 case _KMEM:
58056f77
SB
3866 /* kmem.limit_in_bytes is deprecated. */
3867 ret = -EOPNOTSUPP;
3e32cb2e 3868 break;
d55f90bf 3869 case _TCP:
bbec2e15 3870 ret = memcg_update_tcp_max(memcg, nr_pages);
d55f90bf 3871 break;
3e32cb2e 3872 }
296c81d8 3873 break;
3e32cb2e 3874 case RES_SOFT_LIMIT:
2343e88d
SAS
3875 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
3876 ret = -EOPNOTSUPP;
3877 } else {
3878 memcg->soft_limit = nr_pages;
3879 ret = 0;
3880 }
628f4235
KH
3881 break;
3882 }
451af504 3883 return ret ?: nbytes;
8cdea7c0
BS
3884}
3885
6770c64e
TH
3886static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3887 size_t nbytes, loff_t off)
c84872e1 3888{
6770c64e 3889 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3890 struct page_counter *counter;
c84872e1 3891
3e32cb2e
JW
3892 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3893 case _MEM:
3894 counter = &memcg->memory;
3895 break;
3896 case _MEMSWAP:
3897 counter = &memcg->memsw;
3898 break;
3899 case _KMEM:
3900 counter = &memcg->kmem;
3901 break;
d55f90bf 3902 case _TCP:
0db15298 3903 counter = &memcg->tcpmem;
d55f90bf 3904 break;
3e32cb2e
JW
3905 default:
3906 BUG();
3907 }
af36f906 3908
3e32cb2e 3909 switch (MEMFILE_ATTR(of_cft(of)->private)) {
29f2a4da 3910 case RES_MAX_USAGE:
3e32cb2e 3911 page_counter_reset_watermark(counter);
29f2a4da
PE
3912 break;
3913 case RES_FAILCNT:
3e32cb2e 3914 counter->failcnt = 0;
29f2a4da 3915 break;
3e32cb2e
JW
3916 default:
3917 BUG();
29f2a4da 3918 }
f64c3f54 3919
6770c64e 3920 return nbytes;
c84872e1
PE
3921}
3922
182446d0 3923static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
7dc74be0
DN
3924 struct cftype *cft)
3925{
182446d0 3926 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
7dc74be0
DN
3927}
3928
02491447 3929#ifdef CONFIG_MMU
182446d0 3930static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
7dc74be0
DN
3931 struct cftype *cft, u64 val)
3932{
182446d0 3933 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7dc74be0 3934
1dfab5ab 3935 if (val & ~MOVE_MASK)
7dc74be0 3936 return -EINVAL;
ee5e8472 3937
7dc74be0 3938 /*
ee5e8472
GC
3939 * No kind of locking is needed in here, because ->can_attach() will
3940 * check this value once in the beginning of the process, and then carry
3941 * on with stale data. This means that changes to this value will only
3942 * affect task migrations starting after the change.
7dc74be0 3943 */
c0ff4b85 3944 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
3945 return 0;
3946}
02491447 3947#else
182446d0 3948static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
02491447
DN
3949 struct cftype *cft, u64 val)
3950{
3951 return -ENOSYS;
3952}
3953#endif
7dc74be0 3954
406eb0c9 3955#ifdef CONFIG_NUMA
113b7dfd
JW
3956
3957#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3958#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3959#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3960
3961static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
dd8657b6 3962 int nid, unsigned int lru_mask, bool tree)
113b7dfd 3963{
867e5e1d 3964 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
113b7dfd
JW
3965 unsigned long nr = 0;
3966 enum lru_list lru;
3967
3968 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3969
3970 for_each_lru(lru) {
3971 if (!(BIT(lru) & lru_mask))
3972 continue;
dd8657b6
SB
3973 if (tree)
3974 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3975 else
3976 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
113b7dfd
JW
3977 }
3978 return nr;
3979}
3980
3981static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
dd8657b6
SB
3982 unsigned int lru_mask,
3983 bool tree)
113b7dfd
JW
3984{
3985 unsigned long nr = 0;
3986 enum lru_list lru;
3987
3988 for_each_lru(lru) {
3989 if (!(BIT(lru) & lru_mask))
3990 continue;
dd8657b6
SB
3991 if (tree)
3992 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3993 else
3994 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
113b7dfd
JW
3995 }
3996 return nr;
3997}
3998
2da8ca82 3999static int memcg_numa_stat_show(struct seq_file *m, void *v)
406eb0c9 4000{
25485de6
GT
4001 struct numa_stat {
4002 const char *name;
4003 unsigned int lru_mask;
4004 };
4005
4006 static const struct numa_stat stats[] = {
4007 { "total", LRU_ALL },
4008 { "file", LRU_ALL_FILE },
4009 { "anon", LRU_ALL_ANON },
4010 { "unevictable", BIT(LRU_UNEVICTABLE) },
4011 };
4012 const struct numa_stat *stat;
406eb0c9 4013 int nid;
aa9694bb 4014 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
406eb0c9 4015
fd25a9e0 4016 mem_cgroup_flush_stats();
2d146aa3 4017
25485de6 4018 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
dd8657b6
SB
4019 seq_printf(m, "%s=%lu", stat->name,
4020 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4021 false));
4022 for_each_node_state(nid, N_MEMORY)
4023 seq_printf(m, " N%d=%lu", nid,
4024 mem_cgroup_node_nr_lru_pages(memcg, nid,
4025 stat->lru_mask, false));
25485de6 4026 seq_putc(m, '\n');
406eb0c9 4027 }
406eb0c9 4028
071aee13 4029 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
dd8657b6
SB
4030
4031 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4032 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4033 true));
4034 for_each_node_state(nid, N_MEMORY)
4035 seq_printf(m, " N%d=%lu", nid,
4036 mem_cgroup_node_nr_lru_pages(memcg, nid,
4037 stat->lru_mask, true));
071aee13 4038 seq_putc(m, '\n');
406eb0c9 4039 }
406eb0c9 4040
406eb0c9
YH
4041 return 0;
4042}
4043#endif /* CONFIG_NUMA */
4044
c8713d0b 4045static const unsigned int memcg1_stats[] = {
0d1c2072 4046 NR_FILE_PAGES,
be5d0a74 4047 NR_ANON_MAPPED,
468c3982
JW
4048#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4049 NR_ANON_THPS,
4050#endif
c8713d0b
JW
4051 NR_SHMEM,
4052 NR_FILE_MAPPED,
4053 NR_FILE_DIRTY,
4054 NR_WRITEBACK,
e09b0b61
YS
4055 WORKINGSET_REFAULT_ANON,
4056 WORKINGSET_REFAULT_FILE,
c8713d0b
JW
4057 MEMCG_SWAP,
4058};
4059
4060static const char *const memcg1_stat_names[] = {
4061 "cache",
4062 "rss",
468c3982 4063#ifdef CONFIG_TRANSPARENT_HUGEPAGE
c8713d0b 4064 "rss_huge",
468c3982 4065#endif
c8713d0b
JW
4066 "shmem",
4067 "mapped_file",
4068 "dirty",
4069 "writeback",
e09b0b61
YS
4070 "workingset_refault_anon",
4071 "workingset_refault_file",
c8713d0b
JW
4072 "swap",
4073};
4074
df0e53d0 4075/* Universal VM events cgroup1 shows, original sort order */
8dd53fd3 4076static const unsigned int memcg1_events[] = {
df0e53d0
JW
4077 PGPGIN,
4078 PGPGOUT,
4079 PGFAULT,
4080 PGMAJFAULT,
4081};
4082
2da8ca82 4083static int memcg_stat_show(struct seq_file *m, void *v)
d2ceb9b7 4084{
aa9694bb 4085 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3e32cb2e 4086 unsigned long memory, memsw;
af7c4b0e
JW
4087 struct mem_cgroup *mi;
4088 unsigned int i;
406eb0c9 4089
71cd3113 4090 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
70bc068c 4091
fd25a9e0 4092 mem_cgroup_flush_stats();
2d146aa3 4093
71cd3113 4094 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
468c3982
JW
4095 unsigned long nr;
4096
71cd3113 4097 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 4098 continue;
468c3982 4099 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
e09b0b61
YS
4100 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
4101 nr * memcg_page_state_unit(memcg1_stats[i]));
1dd3a273 4102 }
7b854121 4103
df0e53d0 4104 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
ebc5d83d 4105 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
205b20cc 4106 memcg_events_local(memcg, memcg1_events[i]));
af7c4b0e
JW
4107
4108 for (i = 0; i < NR_LRU_LISTS; i++)
ebc5d83d 4109 seq_printf(m, "%s %lu\n", lru_list_name(i),
205b20cc 4110 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
21d89d15 4111 PAGE_SIZE);
af7c4b0e 4112
14067bb3 4113 /* Hierarchical information */
3e32cb2e
JW
4114 memory = memsw = PAGE_COUNTER_MAX;
4115 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
15b42562
CD
4116 memory = min(memory, READ_ONCE(mi->memory.max));
4117 memsw = min(memsw, READ_ONCE(mi->memsw.max));
fee7b548 4118 }
3e32cb2e
JW
4119 seq_printf(m, "hierarchical_memory_limit %llu\n",
4120 (u64)memory * PAGE_SIZE);
7941d214 4121 if (do_memsw_account())
3e32cb2e
JW
4122 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4123 (u64)memsw * PAGE_SIZE);
7f016ee8 4124
8de7ecc6 4125 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
7de2e9f1 4126 unsigned long nr;
4127
71cd3113 4128 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 4129 continue;
7de2e9f1 4130 nr = memcg_page_state(memcg, memcg1_stats[i]);
8de7ecc6 4131 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
e09b0b61 4132 (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
af7c4b0e
JW
4133 }
4134
8de7ecc6 4135 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
ebc5d83d
KK
4136 seq_printf(m, "total_%s %llu\n",
4137 vm_event_name(memcg1_events[i]),
dd923990 4138 (u64)memcg_events(memcg, memcg1_events[i]));
af7c4b0e 4139
8de7ecc6 4140 for (i = 0; i < NR_LRU_LISTS; i++)
ebc5d83d 4141 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
42a30035
JW
4142 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4143 PAGE_SIZE);
14067bb3 4144
7f016ee8 4145#ifdef CONFIG_DEBUG_VM
7f016ee8 4146 {
ef8f2327
MG
4147 pg_data_t *pgdat;
4148 struct mem_cgroup_per_node *mz;
1431d4d1
JW
4149 unsigned long anon_cost = 0;
4150 unsigned long file_cost = 0;
7f016ee8 4151
ef8f2327 4152 for_each_online_pgdat(pgdat) {
a3747b53 4153 mz = memcg->nodeinfo[pgdat->node_id];
7f016ee8 4154
1431d4d1
JW
4155 anon_cost += mz->lruvec.anon_cost;
4156 file_cost += mz->lruvec.file_cost;
ef8f2327 4157 }
1431d4d1
JW
4158 seq_printf(m, "anon_cost %lu\n", anon_cost);
4159 seq_printf(m, "file_cost %lu\n", file_cost);
7f016ee8
KM
4160 }
4161#endif
4162
d2ceb9b7
KH
4163 return 0;
4164}
4165
182446d0
TH
4166static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4167 struct cftype *cft)
a7885eb8 4168{
182446d0 4169 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 4170
1f4c025b 4171 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
4172}
4173
182446d0
TH
4174static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4175 struct cftype *cft, u64 val)
a7885eb8 4176{
182446d0 4177 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 4178
37bc3cb9 4179 if (val > 200)
a7885eb8
KM
4180 return -EINVAL;
4181
a4792030 4182 if (!mem_cgroup_is_root(memcg))
3dae7fec
JW
4183 memcg->swappiness = val;
4184 else
4185 vm_swappiness = val;
068b38c1 4186
a7885eb8
KM
4187 return 0;
4188}
4189
2e72b634
KS
4190static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4191{
4192 struct mem_cgroup_threshold_ary *t;
3e32cb2e 4193 unsigned long usage;
2e72b634
KS
4194 int i;
4195
4196 rcu_read_lock();
4197 if (!swap)
2c488db2 4198 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 4199 else
2c488db2 4200 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
4201
4202 if (!t)
4203 goto unlock;
4204
ce00a967 4205 usage = mem_cgroup_usage(memcg, swap);
2e72b634
KS
4206
4207 /*
748dad36 4208 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
4209 * If it's not true, a threshold was crossed after last
4210 * call of __mem_cgroup_threshold().
4211 */
5407a562 4212 i = t->current_threshold;
2e72b634
KS
4213
4214 /*
4215 * Iterate backward over array of thresholds starting from
4216 * current_threshold and check if a threshold is crossed.
4217 * If none of thresholds below usage is crossed, we read
4218 * only one element of the array here.
4219 */
4220 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4221 eventfd_signal(t->entries[i].eventfd, 1);
4222
4223 /* i = current_threshold + 1 */
4224 i++;
4225
4226 /*
4227 * Iterate forward over array of thresholds starting from
4228 * current_threshold+1 and check if a threshold is crossed.
4229 * If none of thresholds above usage is crossed, we read
4230 * only one element of the array here.
4231 */
4232 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4233 eventfd_signal(t->entries[i].eventfd, 1);
4234
4235 /* Update current_threshold */
5407a562 4236 t->current_threshold = i - 1;
2e72b634
KS
4237unlock:
4238 rcu_read_unlock();
4239}
4240
4241static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4242{
ad4ca5f4
KS
4243 while (memcg) {
4244 __mem_cgroup_threshold(memcg, false);
7941d214 4245 if (do_memsw_account())
ad4ca5f4
KS
4246 __mem_cgroup_threshold(memcg, true);
4247
4248 memcg = parent_mem_cgroup(memcg);
4249 }
2e72b634
KS
4250}
4251
4252static int compare_thresholds(const void *a, const void *b)
4253{
4254 const struct mem_cgroup_threshold *_a = a;
4255 const struct mem_cgroup_threshold *_b = b;
4256
2bff24a3
GT
4257 if (_a->threshold > _b->threshold)
4258 return 1;
4259
4260 if (_a->threshold < _b->threshold)
4261 return -1;
4262
4263 return 0;
2e72b634
KS
4264}
4265
c0ff4b85 4266static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4267{
4268 struct mem_cgroup_eventfd_list *ev;
4269
2bcf2e92
MH
4270 spin_lock(&memcg_oom_lock);
4271
c0ff4b85 4272 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27 4273 eventfd_signal(ev->eventfd, 1);
2bcf2e92
MH
4274
4275 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4276 return 0;
4277}
4278
c0ff4b85 4279static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4280{
7d74b06f
KH
4281 struct mem_cgroup *iter;
4282
c0ff4b85 4283 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4284 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4285}
4286
59b6f873 4287static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87 4288 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
2e72b634 4289{
2c488db2
KS
4290 struct mem_cgroup_thresholds *thresholds;
4291 struct mem_cgroup_threshold_ary *new;
3e32cb2e
JW
4292 unsigned long threshold;
4293 unsigned long usage;
2c488db2 4294 int i, size, ret;
2e72b634 4295
650c5e56 4296 ret = page_counter_memparse(args, "-1", &threshold);
2e72b634
KS
4297 if (ret)
4298 return ret;
4299
4300 mutex_lock(&memcg->thresholds_lock);
2c488db2 4301
05b84301 4302 if (type == _MEM) {
2c488db2 4303 thresholds = &memcg->thresholds;
ce00a967 4304 usage = mem_cgroup_usage(memcg, false);
05b84301 4305 } else if (type == _MEMSWAP) {
2c488db2 4306 thresholds = &memcg->memsw_thresholds;
ce00a967 4307 usage = mem_cgroup_usage(memcg, true);
05b84301 4308 } else
2e72b634
KS
4309 BUG();
4310
2e72b634 4311 /* Check if a threshold crossed before adding a new one */
2c488db2 4312 if (thresholds->primary)
2e72b634
KS
4313 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4314
2c488db2 4315 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4316
4317 /* Allocate memory for new array of thresholds */
67b8046f 4318 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
2c488db2 4319 if (!new) {
2e72b634
KS
4320 ret = -ENOMEM;
4321 goto unlock;
4322 }
2c488db2 4323 new->size = size;
2e72b634
KS
4324
4325 /* Copy thresholds (if any) to new array */
e90342e6
GS
4326 if (thresholds->primary)
4327 memcpy(new->entries, thresholds->primary->entries,
4328 flex_array_size(new, entries, size - 1));
2c488db2 4329
2e72b634 4330 /* Add new threshold */
2c488db2
KS
4331 new->entries[size - 1].eventfd = eventfd;
4332 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4333
4334 /* Sort thresholds. Registering of new threshold isn't time-critical */
61e604e6 4335 sort(new->entries, size, sizeof(*new->entries),
2e72b634
KS
4336 compare_thresholds, NULL);
4337
4338 /* Find current threshold */
2c488db2 4339 new->current_threshold = -1;
2e72b634 4340 for (i = 0; i < size; i++) {
748dad36 4341 if (new->entries[i].threshold <= usage) {
2e72b634 4342 /*
2c488db2
KS
4343 * new->current_threshold will not be used until
4344 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4345 * it here.
4346 */
2c488db2 4347 ++new->current_threshold;
748dad36
SZ
4348 } else
4349 break;
2e72b634
KS
4350 }
4351
2c488db2
KS
4352 /* Free old spare buffer and save old primary buffer as spare */
4353 kfree(thresholds->spare);
4354 thresholds->spare = thresholds->primary;
4355
4356 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4357
907860ed 4358 /* To be sure that nobody uses thresholds */
2e72b634
KS
4359 synchronize_rcu();
4360
2e72b634
KS
4361unlock:
4362 mutex_unlock(&memcg->thresholds_lock);
4363
4364 return ret;
4365}
4366
59b6f873 4367static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4368 struct eventfd_ctx *eventfd, const char *args)
4369{
59b6f873 4370 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
347c4a87
TH
4371}
4372
59b6f873 4373static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4374 struct eventfd_ctx *eventfd, const char *args)
4375{
59b6f873 4376 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
347c4a87
TH
4377}
4378
59b6f873 4379static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87 4380 struct eventfd_ctx *eventfd, enum res_type type)
2e72b634 4381{
2c488db2
KS
4382 struct mem_cgroup_thresholds *thresholds;
4383 struct mem_cgroup_threshold_ary *new;
3e32cb2e 4384 unsigned long usage;
7d36665a 4385 int i, j, size, entries;
2e72b634
KS
4386
4387 mutex_lock(&memcg->thresholds_lock);
05b84301
JW
4388
4389 if (type == _MEM) {
2c488db2 4390 thresholds = &memcg->thresholds;
ce00a967 4391 usage = mem_cgroup_usage(memcg, false);
05b84301 4392 } else if (type == _MEMSWAP) {
2c488db2 4393 thresholds = &memcg->memsw_thresholds;
ce00a967 4394 usage = mem_cgroup_usage(memcg, true);
05b84301 4395 } else
2e72b634
KS
4396 BUG();
4397
371528ca
AV
4398 if (!thresholds->primary)
4399 goto unlock;
4400
2e72b634
KS
4401 /* Check if a threshold crossed before removing */
4402 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4403
4404 /* Calculate new number of threshold */
7d36665a 4405 size = entries = 0;
2c488db2
KS
4406 for (i = 0; i < thresholds->primary->size; i++) {
4407 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634 4408 size++;
7d36665a
CX
4409 else
4410 entries++;
2e72b634
KS
4411 }
4412
2c488db2 4413 new = thresholds->spare;
907860ed 4414
7d36665a
CX
4415 /* If no items related to eventfd have been cleared, nothing to do */
4416 if (!entries)
4417 goto unlock;
4418
2e72b634
KS
4419 /* Set thresholds array to NULL if we don't have thresholds */
4420 if (!size) {
2c488db2
KS
4421 kfree(new);
4422 new = NULL;
907860ed 4423 goto swap_buffers;
2e72b634
KS
4424 }
4425
2c488db2 4426 new->size = size;
2e72b634
KS
4427
4428 /* Copy thresholds and find current threshold */
2c488db2
KS
4429 new->current_threshold = -1;
4430 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4431 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4432 continue;
4433
2c488db2 4434 new->entries[j] = thresholds->primary->entries[i];
748dad36 4435 if (new->entries[j].threshold <= usage) {
2e72b634 4436 /*
2c488db2 4437 * new->current_threshold will not be used
2e72b634
KS
4438 * until rcu_assign_pointer(), so it's safe to increment
4439 * it here.
4440 */
2c488db2 4441 ++new->current_threshold;
2e72b634
KS
4442 }
4443 j++;
4444 }
4445
907860ed 4446swap_buffers:
2c488db2
KS
4447 /* Swap primary and spare array */
4448 thresholds->spare = thresholds->primary;
8c757763 4449
2c488db2 4450 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4451
907860ed 4452 /* To be sure that nobody uses thresholds */
2e72b634 4453 synchronize_rcu();
6611d8d7
MC
4454
4455 /* If all events are unregistered, free the spare array */
4456 if (!new) {
4457 kfree(thresholds->spare);
4458 thresholds->spare = NULL;
4459 }
371528ca 4460unlock:
2e72b634 4461 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4462}
c1e862c1 4463
59b6f873 4464static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4465 struct eventfd_ctx *eventfd)
4466{
59b6f873 4467 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
347c4a87
TH
4468}
4469
59b6f873 4470static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4471 struct eventfd_ctx *eventfd)
4472{
59b6f873 4473 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
347c4a87
TH
4474}
4475
59b6f873 4476static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
347c4a87 4477 struct eventfd_ctx *eventfd, const char *args)
9490ff27 4478{
9490ff27 4479 struct mem_cgroup_eventfd_list *event;
9490ff27 4480
9490ff27
KH
4481 event = kmalloc(sizeof(*event), GFP_KERNEL);
4482 if (!event)
4483 return -ENOMEM;
4484
1af8efe9 4485 spin_lock(&memcg_oom_lock);
9490ff27
KH
4486
4487 event->eventfd = eventfd;
4488 list_add(&event->list, &memcg->oom_notify);
4489
4490 /* already in OOM ? */
c2b42d3c 4491 if (memcg->under_oom)
9490ff27 4492 eventfd_signal(eventfd, 1);
1af8efe9 4493 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4494
4495 return 0;
4496}
4497
59b6f873 4498static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
347c4a87 4499 struct eventfd_ctx *eventfd)
9490ff27 4500{
9490ff27 4501 struct mem_cgroup_eventfd_list *ev, *tmp;
9490ff27 4502
1af8efe9 4503 spin_lock(&memcg_oom_lock);
9490ff27 4504
c0ff4b85 4505 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4506 if (ev->eventfd == eventfd) {
4507 list_del(&ev->list);
4508 kfree(ev);
4509 }
4510 }
4511
1af8efe9 4512 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4513}
4514
2da8ca82 4515static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3c11ecf4 4516{
aa9694bb 4517 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
3c11ecf4 4518
791badbd 4519 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
c2b42d3c 4520 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
fe6bdfc8
RG
4521 seq_printf(sf, "oom_kill %lu\n",
4522 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
3c11ecf4
KH
4523 return 0;
4524}
4525
182446d0 4526static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3c11ecf4
KH
4527 struct cftype *cft, u64 val)
4528{
182446d0 4529 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3c11ecf4
KH
4530
4531 /* cannot set to root cgroup and only 0 and 1 are allowed */
a4792030 4532 if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
3c11ecf4
KH
4533 return -EINVAL;
4534
c0ff4b85 4535 memcg->oom_kill_disable = val;
4d845ebf 4536 if (!val)
c0ff4b85 4537 memcg_oom_recover(memcg);
3dae7fec 4538
3c11ecf4
KH
4539 return 0;
4540}
4541
52ebea74
TH
4542#ifdef CONFIG_CGROUP_WRITEBACK
4543
3a8e9ac8
TH
4544#include <trace/events/writeback.h>
4545
841710aa
TH
4546static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4547{
4548 return wb_domain_init(&memcg->cgwb_domain, gfp);
4549}
4550
4551static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4552{
4553 wb_domain_exit(&memcg->cgwb_domain);
4554}
4555
2529bb3a
TH
4556static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4557{
4558 wb_domain_size_changed(&memcg->cgwb_domain);
4559}
4560
841710aa
TH
4561struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4562{
4563 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4564
4565 if (!memcg->css.parent)
4566 return NULL;
4567
4568 return &memcg->cgwb_domain;
4569}
4570
c2aa723a
TH
4571/**
4572 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4573 * @wb: bdi_writeback in question
c5edf9cd
TH
4574 * @pfilepages: out parameter for number of file pages
4575 * @pheadroom: out parameter for number of allocatable pages according to memcg
c2aa723a
TH
4576 * @pdirty: out parameter for number of dirty pages
4577 * @pwriteback: out parameter for number of pages under writeback
4578 *
c5edf9cd
TH
4579 * Determine the numbers of file, headroom, dirty, and writeback pages in
4580 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4581 * is a bit more involved.
c2aa723a 4582 *
c5edf9cd
TH
4583 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4584 * headroom is calculated as the lowest headroom of itself and the
4585 * ancestors. Note that this doesn't consider the actual amount of
4586 * available memory in the system. The caller should further cap
4587 * *@pheadroom accordingly.
c2aa723a 4588 */
c5edf9cd
TH
4589void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4590 unsigned long *pheadroom, unsigned long *pdirty,
4591 unsigned long *pwriteback)
c2aa723a
TH
4592{
4593 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4594 struct mem_cgroup *parent;
c2aa723a 4595
fd25a9e0 4596 mem_cgroup_flush_stats();
c2aa723a 4597
2d146aa3
JW
4598 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
4599 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
4600 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
4601 memcg_page_state(memcg, NR_ACTIVE_FILE);
c2aa723a 4602
2d146aa3 4603 *pheadroom = PAGE_COUNTER_MAX;
c2aa723a 4604 while ((parent = parent_mem_cgroup(memcg))) {
15b42562 4605 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
d1663a90 4606 READ_ONCE(memcg->memory.high));
c2aa723a
TH
4607 unsigned long used = page_counter_read(&memcg->memory);
4608
c5edf9cd 4609 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
c2aa723a
TH
4610 memcg = parent;
4611 }
c2aa723a
TH
4612}
4613
97b27821
TH
4614/*
4615 * Foreign dirty flushing
4616 *
4617 * There's an inherent mismatch between memcg and writeback. The former
f0953a1b 4618 * tracks ownership per-page while the latter per-inode. This was a
97b27821
TH
4619 * deliberate design decision because honoring per-page ownership in the
4620 * writeback path is complicated, may lead to higher CPU and IO overheads
4621 * and deemed unnecessary given that write-sharing an inode across
4622 * different cgroups isn't a common use-case.
4623 *
4624 * Combined with inode majority-writer ownership switching, this works well
4625 * enough in most cases but there are some pathological cases. For
4626 * example, let's say there are two cgroups A and B which keep writing to
4627 * different but confined parts of the same inode. B owns the inode and
4628 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4629 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4630 * triggering background writeback. A will be slowed down without a way to
4631 * make writeback of the dirty pages happen.
4632 *
f0953a1b 4633 * Conditions like the above can lead to a cgroup getting repeatedly and
97b27821 4634 * severely throttled after making some progress after each
f0953a1b 4635 * dirty_expire_interval while the underlying IO device is almost
97b27821
TH
4636 * completely idle.
4637 *
4638 * Solving this problem completely requires matching the ownership tracking
4639 * granularities between memcg and writeback in either direction. However,
4640 * the more egregious behaviors can be avoided by simply remembering the
4641 * most recent foreign dirtying events and initiating remote flushes on
4642 * them when local writeback isn't enough to keep the memory clean enough.
4643 *
4644 * The following two functions implement such mechanism. When a foreign
4645 * page - a page whose memcg and writeback ownerships don't match - is
4646 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4647 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4648 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4649 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4650 * foreign bdi_writebacks which haven't expired. Both the numbers of
4651 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4652 * limited to MEMCG_CGWB_FRN_CNT.
4653 *
4654 * The mechanism only remembers IDs and doesn't hold any object references.
4655 * As being wrong occasionally doesn't matter, updates and accesses to the
4656 * records are lockless and racy.
4657 */
9d8053fc 4658void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
97b27821
TH
4659 struct bdi_writeback *wb)
4660{
9d8053fc 4661 struct mem_cgroup *memcg = folio_memcg(folio);
97b27821
TH
4662 struct memcg_cgwb_frn *frn;
4663 u64 now = get_jiffies_64();
4664 u64 oldest_at = now;
4665 int oldest = -1;
4666 int i;
4667
9d8053fc 4668 trace_track_foreign_dirty(folio, wb);
3a8e9ac8 4669
97b27821
TH
4670 /*
4671 * Pick the slot to use. If there is already a slot for @wb, keep
4672 * using it. If not replace the oldest one which isn't being
4673 * written out.
4674 */
4675 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4676 frn = &memcg->cgwb_frn[i];
4677 if (frn->bdi_id == wb->bdi->id &&
4678 frn->memcg_id == wb->memcg_css->id)
4679 break;
4680 if (time_before64(frn->at, oldest_at) &&
4681 atomic_read(&frn->done.cnt) == 1) {
4682 oldest = i;
4683 oldest_at = frn->at;
4684 }
4685 }
4686
4687 if (i < MEMCG_CGWB_FRN_CNT) {
4688 /*
4689 * Re-using an existing one. Update timestamp lazily to
4690 * avoid making the cacheline hot. We want them to be
4691 * reasonably up-to-date and significantly shorter than
4692 * dirty_expire_interval as that's what expires the record.
4693 * Use the shorter of 1s and dirty_expire_interval / 8.
4694 */
4695 unsigned long update_intv =
4696 min_t(unsigned long, HZ,
4697 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4698
4699 if (time_before64(frn->at, now - update_intv))
4700 frn->at = now;
4701 } else if (oldest >= 0) {
4702 /* replace the oldest free one */
4703 frn = &memcg->cgwb_frn[oldest];
4704 frn->bdi_id = wb->bdi->id;
4705 frn->memcg_id = wb->memcg_css->id;
4706 frn->at = now;
4707 }
4708}
4709
4710/* issue foreign writeback flushes for recorded foreign dirtying events */
4711void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4712{
4713 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4714 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4715 u64 now = jiffies_64;
4716 int i;
4717
4718 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4719 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4720
4721 /*
4722 * If the record is older than dirty_expire_interval,
4723 * writeback on it has already started. No need to kick it
4724 * off again. Also, don't start a new one if there's
4725 * already one in flight.
4726 */
4727 if (time_after64(frn->at, now - intv) &&
4728 atomic_read(&frn->done.cnt) == 1) {
4729 frn->at = 0;
3a8e9ac8 4730 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
7490a2d2 4731 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
97b27821
TH
4732 WB_REASON_FOREIGN_FLUSH,
4733 &frn->done);
4734 }
4735 }
4736}
4737
841710aa
TH
4738#else /* CONFIG_CGROUP_WRITEBACK */
4739
4740static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4741{
4742 return 0;
4743}
4744
4745static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4746{
4747}
4748
2529bb3a
TH
4749static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4750{
4751}
4752
52ebea74
TH
4753#endif /* CONFIG_CGROUP_WRITEBACK */
4754
3bc942f3
TH
4755/*
4756 * DO NOT USE IN NEW FILES.
4757 *
4758 * "cgroup.event_control" implementation.
4759 *
4760 * This is way over-engineered. It tries to support fully configurable
4761 * events for each user. Such level of flexibility is completely
4762 * unnecessary especially in the light of the planned unified hierarchy.
4763 *
4764 * Please deprecate this and replace with something simpler if at all
4765 * possible.
4766 */
4767
79bd9814
TH
4768/*
4769 * Unregister event and free resources.
4770 *
4771 * Gets called from workqueue.
4772 */
3bc942f3 4773static void memcg_event_remove(struct work_struct *work)
79bd9814 4774{
3bc942f3
TH
4775 struct mem_cgroup_event *event =
4776 container_of(work, struct mem_cgroup_event, remove);
59b6f873 4777 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
4778
4779 remove_wait_queue(event->wqh, &event->wait);
4780
59b6f873 4781 event->unregister_event(memcg, event->eventfd);
79bd9814
TH
4782
4783 /* Notify userspace the event is going away. */
4784 eventfd_signal(event->eventfd, 1);
4785
4786 eventfd_ctx_put(event->eventfd);
4787 kfree(event);
59b6f873 4788 css_put(&memcg->css);
79bd9814
TH
4789}
4790
4791/*
a9a08845 4792 * Gets called on EPOLLHUP on eventfd when user closes it.
79bd9814
TH
4793 *
4794 * Called with wqh->lock held and interrupts disabled.
4795 */
ac6424b9 4796static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
3bc942f3 4797 int sync, void *key)
79bd9814 4798{
3bc942f3
TH
4799 struct mem_cgroup_event *event =
4800 container_of(wait, struct mem_cgroup_event, wait);
59b6f873 4801 struct mem_cgroup *memcg = event->memcg;
3ad6f93e 4802 __poll_t flags = key_to_poll(key);
79bd9814 4803
a9a08845 4804 if (flags & EPOLLHUP) {
79bd9814
TH
4805 /*
4806 * If the event has been detached at cgroup removal, we
4807 * can simply return knowing the other side will cleanup
4808 * for us.
4809 *
4810 * We can't race against event freeing since the other
4811 * side will require wqh->lock via remove_wait_queue(),
4812 * which we hold.
4813 */
fba94807 4814 spin_lock(&memcg->event_list_lock);
79bd9814
TH
4815 if (!list_empty(&event->list)) {
4816 list_del_init(&event->list);
4817 /*
4818 * We are in atomic context, but cgroup_event_remove()
4819 * may sleep, so we have to call it in workqueue.
4820 */
4821 schedule_work(&event->remove);
4822 }
fba94807 4823 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4824 }
4825
4826 return 0;
4827}
4828
3bc942f3 4829static void memcg_event_ptable_queue_proc(struct file *file,
79bd9814
TH
4830 wait_queue_head_t *wqh, poll_table *pt)
4831{
3bc942f3
TH
4832 struct mem_cgroup_event *event =
4833 container_of(pt, struct mem_cgroup_event, pt);
79bd9814
TH
4834
4835 event->wqh = wqh;
4836 add_wait_queue(wqh, &event->wait);
4837}
4838
4839/*
3bc942f3
TH
4840 * DO NOT USE IN NEW FILES.
4841 *
79bd9814
TH
4842 * Parse input and register new cgroup event handler.
4843 *
4844 * Input must be in format '<event_fd> <control_fd> <args>'.
4845 * Interpretation of args is defined by control file implementation.
4846 */
451af504
TH
4847static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4848 char *buf, size_t nbytes, loff_t off)
79bd9814 4849{
451af504 4850 struct cgroup_subsys_state *css = of_css(of);
fba94807 4851 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4852 struct mem_cgroup_event *event;
79bd9814
TH
4853 struct cgroup_subsys_state *cfile_css;
4854 unsigned int efd, cfd;
4855 struct fd efile;
4856 struct fd cfile;
fba94807 4857 const char *name;
79bd9814
TH
4858 char *endp;
4859 int ret;
4860
2343e88d
SAS
4861 if (IS_ENABLED(CONFIG_PREEMPT_RT))
4862 return -EOPNOTSUPP;
4863
451af504
TH
4864 buf = strstrip(buf);
4865
4866 efd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4867 if (*endp != ' ')
4868 return -EINVAL;
451af504 4869 buf = endp + 1;
79bd9814 4870
451af504 4871 cfd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4872 if ((*endp != ' ') && (*endp != '\0'))
4873 return -EINVAL;
451af504 4874 buf = endp + 1;
79bd9814
TH
4875
4876 event = kzalloc(sizeof(*event), GFP_KERNEL);
4877 if (!event)
4878 return -ENOMEM;
4879
59b6f873 4880 event->memcg = memcg;
79bd9814 4881 INIT_LIST_HEAD(&event->list);
3bc942f3
TH
4882 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4883 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4884 INIT_WORK(&event->remove, memcg_event_remove);
79bd9814
TH
4885
4886 efile = fdget(efd);
4887 if (!efile.file) {
4888 ret = -EBADF;
4889 goto out_kfree;
4890 }
4891
4892 event->eventfd = eventfd_ctx_fileget(efile.file);
4893 if (IS_ERR(event->eventfd)) {
4894 ret = PTR_ERR(event->eventfd);
4895 goto out_put_efile;
4896 }
4897
4898 cfile = fdget(cfd);
4899 if (!cfile.file) {
4900 ret = -EBADF;
4901 goto out_put_eventfd;
4902 }
4903
4904 /* the process need read permission on control file */
4905 /* AV: shouldn't we check that it's been opened for read instead? */
02f92b38 4906 ret = file_permission(cfile.file, MAY_READ);
79bd9814
TH
4907 if (ret < 0)
4908 goto out_put_cfile;
4909
fba94807
TH
4910 /*
4911 * Determine the event callbacks and set them in @event. This used
4912 * to be done via struct cftype but cgroup core no longer knows
4913 * about these events. The following is crude but the whole thing
4914 * is for compatibility anyway.
3bc942f3
TH
4915 *
4916 * DO NOT ADD NEW FILES.
fba94807 4917 */
b583043e 4918 name = cfile.file->f_path.dentry->d_name.name;
fba94807
TH
4919
4920 if (!strcmp(name, "memory.usage_in_bytes")) {
4921 event->register_event = mem_cgroup_usage_register_event;
4922 event->unregister_event = mem_cgroup_usage_unregister_event;
4923 } else if (!strcmp(name, "memory.oom_control")) {
4924 event->register_event = mem_cgroup_oom_register_event;
4925 event->unregister_event = mem_cgroup_oom_unregister_event;
4926 } else if (!strcmp(name, "memory.pressure_level")) {
4927 event->register_event = vmpressure_register_event;
4928 event->unregister_event = vmpressure_unregister_event;
4929 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
347c4a87
TH
4930 event->register_event = memsw_cgroup_usage_register_event;
4931 event->unregister_event = memsw_cgroup_usage_unregister_event;
fba94807
TH
4932 } else {
4933 ret = -EINVAL;
4934 goto out_put_cfile;
4935 }
4936
79bd9814 4937 /*
b5557c4c
TH
4938 * Verify @cfile should belong to @css. Also, remaining events are
4939 * automatically removed on cgroup destruction but the removal is
4940 * asynchronous, so take an extra ref on @css.
79bd9814 4941 */
b583043e 4942 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
ec903c0c 4943 &memory_cgrp_subsys);
79bd9814 4944 ret = -EINVAL;
5a17f543 4945 if (IS_ERR(cfile_css))
79bd9814 4946 goto out_put_cfile;
5a17f543
TH
4947 if (cfile_css != css) {
4948 css_put(cfile_css);
79bd9814 4949 goto out_put_cfile;
5a17f543 4950 }
79bd9814 4951
451af504 4952 ret = event->register_event(memcg, event->eventfd, buf);
79bd9814
TH
4953 if (ret)
4954 goto out_put_css;
4955
9965ed17 4956 vfs_poll(efile.file, &event->pt);
79bd9814 4957
4ba9515d 4958 spin_lock_irq(&memcg->event_list_lock);
fba94807 4959 list_add(&event->list, &memcg->event_list);
4ba9515d 4960 spin_unlock_irq(&memcg->event_list_lock);
79bd9814
TH
4961
4962 fdput(cfile);
4963 fdput(efile);
4964
451af504 4965 return nbytes;
79bd9814
TH
4966
4967out_put_css:
b5557c4c 4968 css_put(css);
79bd9814
TH
4969out_put_cfile:
4970 fdput(cfile);
4971out_put_eventfd:
4972 eventfd_ctx_put(event->eventfd);
4973out_put_efile:
4974 fdput(efile);
4975out_kfree:
4976 kfree(event);
4977
4978 return ret;
4979}
4980
c29b5b3d
MS
4981#if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4982static int mem_cgroup_slab_show(struct seq_file *m, void *p)
4983{
4984 /*
4985 * Deprecated.
df4ae285 4986 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
c29b5b3d
MS
4987 */
4988 return 0;
4989}
4990#endif
4991
241994ed 4992static struct cftype mem_cgroup_legacy_files[] = {
8cdea7c0 4993 {
0eea1030 4994 .name = "usage_in_bytes",
8c7c6e34 4995 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
791badbd 4996 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4997 },
c84872e1
PE
4998 {
4999 .name = "max_usage_in_bytes",
8c7c6e34 5000 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6770c64e 5001 .write = mem_cgroup_reset,
791badbd 5002 .read_u64 = mem_cgroup_read_u64,
c84872e1 5003 },
8cdea7c0 5004 {
0eea1030 5005 .name = "limit_in_bytes",
8c7c6e34 5006 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
451af504 5007 .write = mem_cgroup_write,
791badbd 5008 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 5009 },
296c81d8
BS
5010 {
5011 .name = "soft_limit_in_bytes",
5012 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
451af504 5013 .write = mem_cgroup_write,
791badbd 5014 .read_u64 = mem_cgroup_read_u64,
296c81d8 5015 },
8cdea7c0
BS
5016 {
5017 .name = "failcnt",
8c7c6e34 5018 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6770c64e 5019 .write = mem_cgroup_reset,
791badbd 5020 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 5021 },
d2ceb9b7
KH
5022 {
5023 .name = "stat",
2da8ca82 5024 .seq_show = memcg_stat_show,
d2ceb9b7 5025 },
c1e862c1
KH
5026 {
5027 .name = "force_empty",
6770c64e 5028 .write = mem_cgroup_force_empty_write,
c1e862c1 5029 },
18f59ea7
BS
5030 {
5031 .name = "use_hierarchy",
5032 .write_u64 = mem_cgroup_hierarchy_write,
5033 .read_u64 = mem_cgroup_hierarchy_read,
5034 },
79bd9814 5035 {
3bc942f3 5036 .name = "cgroup.event_control", /* XXX: for compat */
451af504 5037 .write = memcg_write_event_control,
7dbdb199 5038 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
79bd9814 5039 },
a7885eb8
KM
5040 {
5041 .name = "swappiness",
5042 .read_u64 = mem_cgroup_swappiness_read,
5043 .write_u64 = mem_cgroup_swappiness_write,
5044 },
7dc74be0
DN
5045 {
5046 .name = "move_charge_at_immigrate",
5047 .read_u64 = mem_cgroup_move_charge_read,
5048 .write_u64 = mem_cgroup_move_charge_write,
5049 },
9490ff27
KH
5050 {
5051 .name = "oom_control",
2da8ca82 5052 .seq_show = mem_cgroup_oom_control_read,
3c11ecf4 5053 .write_u64 = mem_cgroup_oom_control_write,
9490ff27 5054 },
70ddf637
AV
5055 {
5056 .name = "pressure_level",
70ddf637 5057 },
406eb0c9
YH
5058#ifdef CONFIG_NUMA
5059 {
5060 .name = "numa_stat",
2da8ca82 5061 .seq_show = memcg_numa_stat_show,
406eb0c9
YH
5062 },
5063#endif
510fc4e1
GC
5064 {
5065 .name = "kmem.limit_in_bytes",
5066 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
451af504 5067 .write = mem_cgroup_write,
791badbd 5068 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5069 },
5070 {
5071 .name = "kmem.usage_in_bytes",
5072 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
791badbd 5073 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5074 },
5075 {
5076 .name = "kmem.failcnt",
5077 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6770c64e 5078 .write = mem_cgroup_reset,
791badbd 5079 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
5080 },
5081 {
5082 .name = "kmem.max_usage_in_bytes",
5083 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6770c64e 5084 .write = mem_cgroup_reset,
791badbd 5085 .read_u64 = mem_cgroup_read_u64,
510fc4e1 5086 },
a87425a3
YS
5087#if defined(CONFIG_MEMCG_KMEM) && \
5088 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
749c5415
GC
5089 {
5090 .name = "kmem.slabinfo",
c29b5b3d 5091 .seq_show = mem_cgroup_slab_show,
749c5415
GC
5092 },
5093#endif
d55f90bf
VD
5094 {
5095 .name = "kmem.tcp.limit_in_bytes",
5096 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5097 .write = mem_cgroup_write,
5098 .read_u64 = mem_cgroup_read_u64,
5099 },
5100 {
5101 .name = "kmem.tcp.usage_in_bytes",
5102 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5103 .read_u64 = mem_cgroup_read_u64,
5104 },
5105 {
5106 .name = "kmem.tcp.failcnt",
5107 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5108 .write = mem_cgroup_reset,
5109 .read_u64 = mem_cgroup_read_u64,
5110 },
5111 {
5112 .name = "kmem.tcp.max_usage_in_bytes",
5113 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5114 .write = mem_cgroup_reset,
5115 .read_u64 = mem_cgroup_read_u64,
5116 },
6bc10349 5117 { }, /* terminate */
af36f906 5118};
8c7c6e34 5119
73f576c0
JW
5120/*
5121 * Private memory cgroup IDR
5122 *
5123 * Swap-out records and page cache shadow entries need to store memcg
5124 * references in constrained space, so we maintain an ID space that is
5125 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5126 * memory-controlled cgroups to 64k.
5127 *
b8f2935f 5128 * However, there usually are many references to the offline CSS after
73f576c0
JW
5129 * the cgroup has been destroyed, such as page cache or reclaimable
5130 * slab objects, that don't need to hang on to the ID. We want to keep
5131 * those dead CSS from occupying IDs, or we might quickly exhaust the
5132 * relatively small ID space and prevent the creation of new cgroups
5133 * even when there are much fewer than 64k cgroups - possibly none.
5134 *
5135 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5136 * be freed and recycled when it's no longer needed, which is usually
5137 * when the CSS is offlined.
5138 *
5139 * The only exception to that are records of swapped out tmpfs/shmem
5140 * pages that need to be attributed to live ancestors on swapin. But
5141 * those references are manageable from userspace.
5142 */
5143
5144static DEFINE_IDR(mem_cgroup_idr);
5145
7e97de0b
KT
5146static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5147{
5148 if (memcg->id.id > 0) {
5149 idr_remove(&mem_cgroup_idr, memcg->id.id);
5150 memcg->id.id = 0;
5151 }
5152}
5153
c1514c0a
VF
5154static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5155 unsigned int n)
73f576c0 5156{
1c2d479a 5157 refcount_add(n, &memcg->id.ref);
73f576c0
JW
5158}
5159
615d66c3 5160static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
73f576c0 5161{
1c2d479a 5162 if (refcount_sub_and_test(n, &memcg->id.ref)) {
7e97de0b 5163 mem_cgroup_id_remove(memcg);
73f576c0
JW
5164
5165 /* Memcg ID pins CSS */
5166 css_put(&memcg->css);
5167 }
5168}
5169
615d66c3
VD
5170static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5171{
5172 mem_cgroup_id_put_many(memcg, 1);
5173}
5174
73f576c0
JW
5175/**
5176 * mem_cgroup_from_id - look up a memcg from a memcg id
5177 * @id: the memcg id to look up
5178 *
5179 * Caller must hold rcu_read_lock().
5180 */
5181struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5182{
5183 WARN_ON_ONCE(!rcu_read_lock_held());
5184 return idr_find(&mem_cgroup_idr, id);
5185}
5186
c15187a4
RG
5187#ifdef CONFIG_SHRINKER_DEBUG
5188struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
5189{
5190 struct cgroup *cgrp;
5191 struct cgroup_subsys_state *css;
5192 struct mem_cgroup *memcg;
5193
5194 cgrp = cgroup_get_from_id(ino);
5195 if (!cgrp)
5196 return ERR_PTR(-ENOENT);
5197
5198 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
5199 if (css)
5200 memcg = container_of(css, struct mem_cgroup, css);
5201 else
5202 memcg = ERR_PTR(-ENOENT);
5203
5204 cgroup_put(cgrp);
5205
5206 return memcg;
5207}
5208#endif
5209
ef8f2327 5210static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
5211{
5212 struct mem_cgroup_per_node *pn;
8c9bb398
WY
5213
5214 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
6d12e2d8
KH
5215 if (!pn)
5216 return 1;
1ecaab2b 5217
7e1c0d6f
SB
5218 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
5219 GFP_KERNEL_ACCOUNT);
5220 if (!pn->lruvec_stats_percpu) {
00f3ca2c
JW
5221 kfree(pn);
5222 return 1;
5223 }
5224
ef8f2327 5225 lruvec_init(&pn->lruvec);
ef8f2327
MG
5226 pn->memcg = memcg;
5227
54f72fe0 5228 memcg->nodeinfo[node] = pn;
6d12e2d8
KH
5229 return 0;
5230}
5231
ef8f2327 5232static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
1ecaab2b 5233{
00f3ca2c
JW
5234 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5235
4eaf431f
MH
5236 if (!pn)
5237 return;
5238
7e1c0d6f 5239 free_percpu(pn->lruvec_stats_percpu);
00f3ca2c 5240 kfree(pn);
1ecaab2b
KH
5241}
5242
40e952f9 5243static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 5244{
c8b2a36f 5245 int node;
59927fb9 5246
c8b2a36f 5247 for_each_node(node)
ef8f2327 5248 free_mem_cgroup_per_node_info(memcg, node);
410f8e82 5249 kfree(memcg->vmstats);
871789d4 5250 free_percpu(memcg->vmstats_percpu);
8ff69e2c 5251 kfree(memcg);
59927fb9 5252}
3afe36b1 5253
40e952f9
TE
5254static void mem_cgroup_free(struct mem_cgroup *memcg)
5255{
ec1c86b2 5256 lru_gen_exit_memcg(memcg);
40e952f9
TE
5257 memcg_wb_domain_exit(memcg);
5258 __mem_cgroup_free(memcg);
5259}
5260
0b8f73e1 5261static struct mem_cgroup *mem_cgroup_alloc(void)
8cdea7c0 5262{
d142e3e6 5263 struct mem_cgroup *memcg;
6d12e2d8 5264 int node;
97b27821 5265 int __maybe_unused i;
11d67612 5266 long error = -ENOMEM;
8cdea7c0 5267
06b2c3b0 5268 memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
c0ff4b85 5269 if (!memcg)
11d67612 5270 return ERR_PTR(error);
0b8f73e1 5271
73f576c0 5272 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
be740503 5273 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
11d67612
YS
5274 if (memcg->id.id < 0) {
5275 error = memcg->id.id;
73f576c0 5276 goto fail;
11d67612 5277 }
73f576c0 5278
410f8e82
SB
5279 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
5280 if (!memcg->vmstats)
5281 goto fail;
5282
3e38e0aa
RG
5283 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
5284 GFP_KERNEL_ACCOUNT);
871789d4 5285 if (!memcg->vmstats_percpu)
0b8f73e1 5286 goto fail;
78fb7466 5287
3ed28fa1 5288 for_each_node(node)
ef8f2327 5289 if (alloc_mem_cgroup_per_node_info(memcg, node))
0b8f73e1 5290 goto fail;
f64c3f54 5291
0b8f73e1
JW
5292 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5293 goto fail;
28dbc4b6 5294
f7e1cb6e 5295 INIT_WORK(&memcg->high_work, high_work_func);
d142e3e6 5296 INIT_LIST_HEAD(&memcg->oom_notify);
d142e3e6
GC
5297 mutex_init(&memcg->thresholds_lock);
5298 spin_lock_init(&memcg->move_lock);
70ddf637 5299 vmpressure_init(&memcg->vmpressure);
fba94807
TH
5300 INIT_LIST_HEAD(&memcg->event_list);
5301 spin_lock_init(&memcg->event_list_lock);
d886f4e4 5302 memcg->socket_pressure = jiffies;
84c07d11 5303#ifdef CONFIG_MEMCG_KMEM
900a38f0 5304 memcg->kmemcg_id = -1;
bf4f0599 5305 INIT_LIST_HEAD(&memcg->objcg_list);
900a38f0 5306#endif
52ebea74
TH
5307#ifdef CONFIG_CGROUP_WRITEBACK
5308 INIT_LIST_HEAD(&memcg->cgwb_list);
97b27821
TH
5309 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5310 memcg->cgwb_frn[i].done =
5311 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
87eaceb3
YS
5312#endif
5313#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5314 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5315 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5316 memcg->deferred_split_queue.split_queue_len = 0;
52ebea74 5317#endif
73f576c0 5318 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
ec1c86b2 5319 lru_gen_init_memcg(memcg);
0b8f73e1
JW
5320 return memcg;
5321fail:
7e97de0b 5322 mem_cgroup_id_remove(memcg);
40e952f9 5323 __mem_cgroup_free(memcg);
11d67612 5324 return ERR_PTR(error);
d142e3e6
GC
5325}
5326
0b8f73e1
JW
5327static struct cgroup_subsys_state * __ref
5328mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
d142e3e6 5329{
0b8f73e1 5330 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
b87d8cef 5331 struct mem_cgroup *memcg, *old_memcg;
d142e3e6 5332
b87d8cef 5333 old_memcg = set_active_memcg(parent);
0b8f73e1 5334 memcg = mem_cgroup_alloc();
b87d8cef 5335 set_active_memcg(old_memcg);
11d67612
YS
5336 if (IS_ERR(memcg))
5337 return ERR_CAST(memcg);
d142e3e6 5338
d1663a90 5339 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
0b8f73e1 5340 memcg->soft_limit = PAGE_COUNTER_MAX;
f4840ccf
JW
5341#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
5342 memcg->zswap_max = PAGE_COUNTER_MAX;
5343#endif
4b82ab4f 5344 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
0b8f73e1
JW
5345 if (parent) {
5346 memcg->swappiness = mem_cgroup_swappiness(parent);
5347 memcg->oom_kill_disable = parent->oom_kill_disable;
bef8620c 5348
3e32cb2e 5349 page_counter_init(&memcg->memory, &parent->memory);
37e84351 5350 page_counter_init(&memcg->swap, &parent->swap);
3e32cb2e 5351 page_counter_init(&memcg->kmem, &parent->kmem);
0db15298 5352 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
18f59ea7 5353 } else {
8278f1c7 5354 init_memcg_events();
bef8620c
RG
5355 page_counter_init(&memcg->memory, NULL);
5356 page_counter_init(&memcg->swap, NULL);
5357 page_counter_init(&memcg->kmem, NULL);
5358 page_counter_init(&memcg->tcpmem, NULL);
d6441637 5359
0b8f73e1
JW
5360 root_mem_cgroup = memcg;
5361 return &memcg->css;
5362 }
5363
f7e1cb6e 5364 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5365 static_branch_inc(&memcg_sockets_enabled_key);
f7e1cb6e 5366
0b8f73e1 5367 return &memcg->css;
0b8f73e1
JW
5368}
5369
73f576c0 5370static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
0b8f73e1 5371{
58fa2a55
VD
5372 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5373
da0efe30
MS
5374 if (memcg_online_kmem(memcg))
5375 goto remove_id;
5376
0a4465d3 5377 /*
e4262c4f 5378 * A memcg must be visible for expand_shrinker_info()
0a4465d3
KT
5379 * by the time the maps are allocated. So, we allocate maps
5380 * here, when for_each_mem_cgroup() can't skip it.
5381 */
da0efe30
MS
5382 if (alloc_shrinker_info(memcg))
5383 goto offline_kmem;
0a4465d3 5384
73f576c0 5385 /* Online state pins memcg ID, memcg ID pins CSS */
1c2d479a 5386 refcount_set(&memcg->id.ref, 1);
73f576c0 5387 css_get(css);
aa48e47e
SB
5388
5389 if (unlikely(mem_cgroup_is_root(memcg)))
5390 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
5391 2UL*HZ);
2f7dd7a4 5392 return 0;
da0efe30
MS
5393offline_kmem:
5394 memcg_offline_kmem(memcg);
5395remove_id:
5396 mem_cgroup_id_remove(memcg);
5397 return -ENOMEM;
8cdea7c0
BS
5398}
5399
eb95419b 5400static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 5401{
eb95419b 5402 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 5403 struct mem_cgroup_event *event, *tmp;
79bd9814
TH
5404
5405 /*
5406 * Unregister events and notify userspace.
5407 * Notify userspace about cgroup removing only after rmdir of cgroup
5408 * directory to avoid race between userspace and kernelspace.
5409 */
4ba9515d 5410 spin_lock_irq(&memcg->event_list_lock);
fba94807 5411 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
79bd9814
TH
5412 list_del_init(&event->list);
5413 schedule_work(&event->remove);
5414 }
4ba9515d 5415 spin_unlock_irq(&memcg->event_list_lock);
ec64f515 5416
bf8d5d52 5417 page_counter_set_min(&memcg->memory, 0);
23067153 5418 page_counter_set_low(&memcg->memory, 0);
63677c74 5419
567e9ab2 5420 memcg_offline_kmem(memcg);
a178015c 5421 reparent_shrinker_deferred(memcg);
52ebea74 5422 wb_memcg_offline(memcg);
73f576c0 5423
591edfb1
RG
5424 drain_all_stock(memcg);
5425
73f576c0 5426 mem_cgroup_id_put(memcg);
df878fb0
KH
5427}
5428
6df38689
VD
5429static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5430{
5431 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5432
5433 invalidate_reclaim_iterators(memcg);
5434}
5435
eb95419b 5436static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 5437{
eb95419b 5438 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
97b27821 5439 int __maybe_unused i;
c268e994 5440
97b27821
TH
5441#ifdef CONFIG_CGROUP_WRITEBACK
5442 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5443 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5444#endif
f7e1cb6e 5445 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5446 static_branch_dec(&memcg_sockets_enabled_key);
127424c8 5447
0db15298 5448 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
d55f90bf 5449 static_branch_dec(&memcg_sockets_enabled_key);
3893e302 5450
0b8f73e1
JW
5451 vmpressure_cleanup(&memcg->vmpressure);
5452 cancel_work_sync(&memcg->high_work);
5453 mem_cgroup_remove_from_trees(memcg);
e4262c4f 5454 free_shrinker_info(memcg);
0b8f73e1 5455 mem_cgroup_free(memcg);
8cdea7c0
BS
5456}
5457
1ced953b
TH
5458/**
5459 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5460 * @css: the target css
5461 *
5462 * Reset the states of the mem_cgroup associated with @css. This is
5463 * invoked when the userland requests disabling on the default hierarchy
5464 * but the memcg is pinned through dependency. The memcg should stop
5465 * applying policies and should revert to the vanilla state as it may be
5466 * made visible again.
5467 *
5468 * The current implementation only resets the essential configurations.
5469 * This needs to be expanded to cover all the visible parts.
5470 */
5471static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5472{
5473 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5474
bbec2e15
RG
5475 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5476 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
bbec2e15
RG
5477 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5478 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
bf8d5d52 5479 page_counter_set_min(&memcg->memory, 0);
23067153 5480 page_counter_set_low(&memcg->memory, 0);
d1663a90 5481 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
24d404dc 5482 memcg->soft_limit = PAGE_COUNTER_MAX;
4b82ab4f 5483 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
2529bb3a 5484 memcg_wb_domain_size_changed(memcg);
1ced953b
TH
5485}
5486
2d146aa3
JW
5487static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
5488{
5489 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5490 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5491 struct memcg_vmstats_percpu *statc;
5492 long delta, v;
7e1c0d6f 5493 int i, nid;
2d146aa3
JW
5494
5495 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
5496
5497 for (i = 0; i < MEMCG_NR_STAT; i++) {
5498 /*
5499 * Collect the aggregated propagation counts of groups
5500 * below us. We're in a per-cpu loop here and this is
5501 * a global counter, so the first cycle will get them.
5502 */
410f8e82 5503 delta = memcg->vmstats->state_pending[i];
2d146aa3 5504 if (delta)
410f8e82 5505 memcg->vmstats->state_pending[i] = 0;
2d146aa3
JW
5506
5507 /* Add CPU changes on this level since the last flush */
5508 v = READ_ONCE(statc->state[i]);
5509 if (v != statc->state_prev[i]) {
5510 delta += v - statc->state_prev[i];
5511 statc->state_prev[i] = v;
5512 }
5513
5514 if (!delta)
5515 continue;
5516
5517 /* Aggregate counts on this level and propagate upwards */
410f8e82 5518 memcg->vmstats->state[i] += delta;
2d146aa3 5519 if (parent)
410f8e82 5520 parent->vmstats->state_pending[i] += delta;
2d146aa3
JW
5521 }
5522
8278f1c7 5523 for (i = 0; i < NR_MEMCG_EVENTS; i++) {
410f8e82 5524 delta = memcg->vmstats->events_pending[i];
2d146aa3 5525 if (delta)
410f8e82 5526 memcg->vmstats->events_pending[i] = 0;
2d146aa3
JW
5527
5528 v = READ_ONCE(statc->events[i]);
5529 if (v != statc->events_prev[i]) {
5530 delta += v - statc->events_prev[i];
5531 statc->events_prev[i] = v;
5532 }
5533
5534 if (!delta)
5535 continue;
5536
410f8e82 5537 memcg->vmstats->events[i] += delta;
2d146aa3 5538 if (parent)
410f8e82 5539 parent->vmstats->events_pending[i] += delta;
2d146aa3 5540 }
7e1c0d6f
SB
5541
5542 for_each_node_state(nid, N_MEMORY) {
5543 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
5544 struct mem_cgroup_per_node *ppn = NULL;
5545 struct lruvec_stats_percpu *lstatc;
5546
5547 if (parent)
5548 ppn = parent->nodeinfo[nid];
5549
5550 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
5551
5552 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
5553 delta = pn->lruvec_stats.state_pending[i];
5554 if (delta)
5555 pn->lruvec_stats.state_pending[i] = 0;
5556
5557 v = READ_ONCE(lstatc->state[i]);
5558 if (v != lstatc->state_prev[i]) {
5559 delta += v - lstatc->state_prev[i];
5560 lstatc->state_prev[i] = v;
5561 }
5562
5563 if (!delta)
5564 continue;
5565
5566 pn->lruvec_stats.state[i] += delta;
5567 if (ppn)
5568 ppn->lruvec_stats.state_pending[i] += delta;
5569 }
5570 }
2d146aa3
JW
5571}
5572
02491447 5573#ifdef CONFIG_MMU
7dc74be0 5574/* Handlers for move charge at task migration. */
854ffa8d 5575static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 5576{
05b84301 5577 int ret;
9476db97 5578
d0164adc
MG
5579 /* Try a single bulk charge without reclaim first, kswapd may wake */
5580 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
9476db97 5581 if (!ret) {
854ffa8d 5582 mc.precharge += count;
854ffa8d
DN
5583 return ret;
5584 }
9476db97 5585
3674534b 5586 /* Try charges one by one with reclaim, but do not retry */
854ffa8d 5587 while (count--) {
3674534b 5588 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
38c5d72f 5589 if (ret)
38c5d72f 5590 return ret;
854ffa8d 5591 mc.precharge++;
9476db97 5592 cond_resched();
854ffa8d 5593 }
9476db97 5594 return 0;
4ffef5fe
DN
5595}
5596
4ffef5fe
DN
5597union mc_target {
5598 struct page *page;
02491447 5599 swp_entry_t ent;
4ffef5fe
DN
5600};
5601
4ffef5fe 5602enum mc_target_type {
8d32ff84 5603 MC_TARGET_NONE = 0,
4ffef5fe 5604 MC_TARGET_PAGE,
02491447 5605 MC_TARGET_SWAP,
c733a828 5606 MC_TARGET_DEVICE,
4ffef5fe
DN
5607};
5608
90254a65
DN
5609static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5610 unsigned long addr, pte_t ptent)
4ffef5fe 5611{
25b2995a 5612 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5613
90254a65
DN
5614 if (!page || !page_mapped(page))
5615 return NULL;
5616 if (PageAnon(page)) {
1dfab5ab 5617 if (!(mc.flags & MOVE_ANON))
90254a65 5618 return NULL;
1dfab5ab
JW
5619 } else {
5620 if (!(mc.flags & MOVE_FILE))
5621 return NULL;
5622 }
90254a65
DN
5623 if (!get_page_unless_zero(page))
5624 return NULL;
5625
5626 return page;
5627}
5628
c733a828 5629#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
90254a65 5630static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5631 pte_t ptent, swp_entry_t *entry)
90254a65 5632{
90254a65
DN
5633 struct page *page = NULL;
5634 swp_entry_t ent = pte_to_swp_entry(ptent);
5635
9a137153 5636 if (!(mc.flags & MOVE_ANON))
90254a65 5637 return NULL;
c733a828
JG
5638
5639 /*
27674ef6
CH
5640 * Handle device private pages that are not accessible by the CPU, but
5641 * stored as special swap entries in the page table.
c733a828
JG
5642 */
5643 if (is_device_private_entry(ent)) {
af5cdaf8 5644 page = pfn_swap_entry_to_page(ent);
27674ef6 5645 if (!get_page_unless_zero(page))
c733a828
JG
5646 return NULL;
5647 return page;
5648 }
5649
9a137153
RC
5650 if (non_swap_entry(ent))
5651 return NULL;
5652
4b91355e 5653 /*
cb691e2f 5654 * Because swap_cache_get_folio() updates some statistics counter,
4b91355e
KH
5655 * we call find_get_page() with swapper_space directly.
5656 */
f6ab1f7f 5657 page = find_get_page(swap_address_space(ent), swp_offset(ent));
2d1c4980 5658 entry->val = ent.val;
90254a65
DN
5659
5660 return page;
5661}
4b91355e
KH
5662#else
5663static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5664 pte_t ptent, swp_entry_t *entry)
4b91355e
KH
5665{
5666 return NULL;
5667}
5668#endif
90254a65 5669
87946a72 5670static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
48384b0b 5671 unsigned long addr, pte_t ptent)
87946a72 5672{
87946a72
DN
5673 if (!vma->vm_file) /* anonymous vma */
5674 return NULL;
1dfab5ab 5675 if (!(mc.flags & MOVE_FILE))
87946a72
DN
5676 return NULL;
5677
87946a72 5678 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895 5679 /* shmem/tmpfs may report page out on swap: account for that too. */
f5df8635
MWO
5680 return find_get_incore_page(vma->vm_file->f_mapping,
5681 linear_page_index(vma, addr));
87946a72
DN
5682}
5683
b1b0deab
CG
5684/**
5685 * mem_cgroup_move_account - move account of the page
5686 * @page: the page
25843c2b 5687 * @compound: charge the page as compound or small page
b1b0deab
CG
5688 * @from: mem_cgroup which the page is moved from.
5689 * @to: mem_cgroup which the page is moved to. @from != @to.
5690 *
3ac808fd 5691 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
b1b0deab
CG
5692 *
5693 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5694 * from old cgroup.
5695 */
5696static int mem_cgroup_move_account(struct page *page,
f627c2f5 5697 bool compound,
b1b0deab
CG
5698 struct mem_cgroup *from,
5699 struct mem_cgroup *to)
5700{
fcce4672 5701 struct folio *folio = page_folio(page);
ae8af438
KK
5702 struct lruvec *from_vec, *to_vec;
5703 struct pglist_data *pgdat;
fcce4672 5704 unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
8e88bd2d 5705 int nid, ret;
b1b0deab
CG
5706
5707 VM_BUG_ON(from == to);
fcce4672 5708 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
9c325215 5709 VM_BUG_ON(compound && !folio_test_large(folio));
b1b0deab
CG
5710
5711 /*
6a93ca8f 5712 * Prevent mem_cgroup_migrate() from looking at
bcfe06bf 5713 * page's memory cgroup of its source page while we change it.
b1b0deab 5714 */
f627c2f5 5715 ret = -EBUSY;
fcce4672 5716 if (!folio_trylock(folio))
b1b0deab
CG
5717 goto out;
5718
5719 ret = -EINVAL;
fcce4672 5720 if (folio_memcg(folio) != from)
b1b0deab
CG
5721 goto out_unlock;
5722
fcce4672 5723 pgdat = folio_pgdat(folio);
867e5e1d
JW
5724 from_vec = mem_cgroup_lruvec(from, pgdat);
5725 to_vec = mem_cgroup_lruvec(to, pgdat);
ae8af438 5726
fcce4672 5727 folio_memcg_lock(folio);
b1b0deab 5728
fcce4672
MWO
5729 if (folio_test_anon(folio)) {
5730 if (folio_mapped(folio)) {
be5d0a74
JW
5731 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5732 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
fcce4672 5733 if (folio_test_transhuge(folio)) {
69473e5d
MS
5734 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5735 -nr_pages);
5736 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5737 nr_pages);
468c3982 5738 }
be5d0a74
JW
5739 }
5740 } else {
0d1c2072
JW
5741 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5742 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5743
fcce4672 5744 if (folio_test_swapbacked(folio)) {
0d1c2072
JW
5745 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5746 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5747 }
5748
fcce4672 5749 if (folio_mapped(folio)) {
49e50d27
JW
5750 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5751 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5752 }
b1b0deab 5753
fcce4672
MWO
5754 if (folio_test_dirty(folio)) {
5755 struct address_space *mapping = folio_mapping(folio);
c4843a75 5756
f56753ac 5757 if (mapping_can_writeback(mapping)) {
49e50d27
JW
5758 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5759 -nr_pages);
5760 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5761 nr_pages);
5762 }
c4843a75
GT
5763 }
5764 }
5765
fcce4672 5766 if (folio_test_writeback(folio)) {
ae8af438
KK
5767 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5768 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
b1b0deab
CG
5769 }
5770
5771 /*
abb242f5
JW
5772 * All state has been migrated, let's switch to the new memcg.
5773 *
bcfe06bf 5774 * It is safe to change page's memcg here because the page
abb242f5
JW
5775 * is referenced, charged, isolated, and locked: we can't race
5776 * with (un)charging, migration, LRU putback, or anything else
bcfe06bf 5777 * that would rely on a stable page's memory cgroup.
abb242f5
JW
5778 *
5779 * Note that lock_page_memcg is a memcg lock, not a page lock,
bcfe06bf 5780 * to save space. As soon as we switch page's memory cgroup to a
abb242f5
JW
5781 * new memcg that isn't locked, the above state can change
5782 * concurrently again. Make sure we're truly done with it.
b1b0deab 5783 */
abb242f5 5784 smp_mb();
b1b0deab 5785
1a3e1f40
JW
5786 css_get(&to->css);
5787 css_put(&from->css);
5788
fcce4672 5789 folio->memcg_data = (unsigned long)to;
87eaceb3 5790
f70ad448 5791 __folio_memcg_unlock(from);
b1b0deab
CG
5792
5793 ret = 0;
fcce4672 5794 nid = folio_nid(folio);
b1b0deab
CG
5795
5796 local_irq_disable();
6e0110c2 5797 mem_cgroup_charge_statistics(to, nr_pages);
8e88bd2d 5798 memcg_check_events(to, nid);
6e0110c2 5799 mem_cgroup_charge_statistics(from, -nr_pages);
8e88bd2d 5800 memcg_check_events(from, nid);
b1b0deab
CG
5801 local_irq_enable();
5802out_unlock:
fcce4672 5803 folio_unlock(folio);
b1b0deab
CG
5804out:
5805 return ret;
5806}
5807
7cf7806c
LR
5808/**
5809 * get_mctgt_type - get target type of moving charge
5810 * @vma: the vma the pte to be checked belongs
5811 * @addr: the address corresponding to the pte to be checked
5812 * @ptent: the pte to be checked
5813 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5814 *
5815 * Returns
5816 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5817 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5818 * move charge. if @target is not NULL, the page is stored in target->page
5819 * with extra refcnt got(Callers should handle it).
5820 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5821 * target for charge migration. if @target is not NULL, the entry is stored
5822 * in target->ent.
f25cbb7a
AS
5823 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
5824 * thus not on the lru.
df6ad698
JG
5825 * For now we such page is charge like a regular page would be as for all
5826 * intent and purposes it is just special memory taking the place of a
5827 * regular page.
c733a828
JG
5828 *
5829 * See Documentations/vm/hmm.txt and include/linux/hmm.h
7cf7806c
LR
5830 *
5831 * Called with pte lock held.
5832 */
5833
8d32ff84 5834static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
5835 unsigned long addr, pte_t ptent, union mc_target *target)
5836{
5837 struct page *page = NULL;
8d32ff84 5838 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
5839 swp_entry_t ent = { .val = 0 };
5840
5841 if (pte_present(ptent))
5842 page = mc_handle_present_pte(vma, addr, ptent);
5c041f5d
PX
5843 else if (pte_none_mostly(ptent))
5844 /*
5845 * PTE markers should be treated as a none pte here, separated
5846 * from other swap handling below.
5847 */
5848 page = mc_handle_file_pte(vma, addr, ptent);
90254a65 5849 else if (is_swap_pte(ptent))
48406ef8 5850 page = mc_handle_swap_pte(vma, ptent, &ent);
90254a65
DN
5851
5852 if (!page && !ent.val)
8d32ff84 5853 return ret;
02491447 5854 if (page) {
02491447 5855 /*
0a31bc97 5856 * Do only loose check w/o serialization.
1306a85a 5857 * mem_cgroup_move_account() checks the page is valid or
0a31bc97 5858 * not under LRU exclusion.
02491447 5859 */
bcfe06bf 5860 if (page_memcg(page) == mc.from) {
02491447 5861 ret = MC_TARGET_PAGE;
f25cbb7a
AS
5862 if (is_device_private_page(page) ||
5863 is_device_coherent_page(page))
c733a828 5864 ret = MC_TARGET_DEVICE;
02491447
DN
5865 if (target)
5866 target->page = page;
5867 }
5868 if (!ret || !target)
5869 put_page(page);
5870 }
3e14a57b
HY
5871 /*
5872 * There is a swap entry and a page doesn't exist or isn't charged.
5873 * But we cannot move a tail-page in a THP.
5874 */
5875 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
34c00c31 5876 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
5877 ret = MC_TARGET_SWAP;
5878 if (target)
5879 target->ent = ent;
4ffef5fe 5880 }
4ffef5fe
DN
5881 return ret;
5882}
5883
12724850
NH
5884#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5885/*
d6810d73
HY
5886 * We don't consider PMD mapped swapping or file mapped pages because THP does
5887 * not support them for now.
12724850
NH
5888 * Caller should make sure that pmd_trans_huge(pmd) is true.
5889 */
5890static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5891 unsigned long addr, pmd_t pmd, union mc_target *target)
5892{
5893 struct page *page = NULL;
12724850
NH
5894 enum mc_target_type ret = MC_TARGET_NONE;
5895
84c3fc4e
ZY
5896 if (unlikely(is_swap_pmd(pmd))) {
5897 VM_BUG_ON(thp_migration_supported() &&
5898 !is_pmd_migration_entry(pmd));
5899 return ret;
5900 }
12724850 5901 page = pmd_page(pmd);
309381fe 5902 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
1dfab5ab 5903 if (!(mc.flags & MOVE_ANON))
12724850 5904 return ret;
bcfe06bf 5905 if (page_memcg(page) == mc.from) {
12724850
NH
5906 ret = MC_TARGET_PAGE;
5907 if (target) {
5908 get_page(page);
5909 target->page = page;
5910 }
5911 }
5912 return ret;
5913}
5914#else
5915static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5916 unsigned long addr, pmd_t pmd, union mc_target *target)
5917{
5918 return MC_TARGET_NONE;
5919}
5920#endif
5921
4ffef5fe
DN
5922static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5923 unsigned long addr, unsigned long end,
5924 struct mm_walk *walk)
5925{
26bcd64a 5926 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
5927 pte_t *pte;
5928 spinlock_t *ptl;
5929
b6ec57f4
KS
5930 ptl = pmd_trans_huge_lock(pmd, vma);
5931 if (ptl) {
c733a828
JG
5932 /*
5933 * Note their can not be MC_TARGET_DEVICE for now as we do not
25b2995a
CH
5934 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5935 * this might change.
c733a828 5936 */
12724850
NH
5937 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5938 mc.precharge += HPAGE_PMD_NR;
bf929152 5939 spin_unlock(ptl);
1a5a9906 5940 return 0;
12724850 5941 }
03319327 5942
45f83cef
AA
5943 if (pmd_trans_unstable(pmd))
5944 return 0;
4ffef5fe
DN
5945 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5946 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 5947 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
5948 mc.precharge++; /* increment precharge temporarily */
5949 pte_unmap_unlock(pte - 1, ptl);
5950 cond_resched();
5951
7dc74be0
DN
5952 return 0;
5953}
5954
7b86ac33
CH
5955static const struct mm_walk_ops precharge_walk_ops = {
5956 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5957};
5958
4ffef5fe
DN
5959static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5960{
5961 unsigned long precharge;
4ffef5fe 5962
d8ed45c5 5963 mmap_read_lock(mm);
ba0aff8e 5964 walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
d8ed45c5 5965 mmap_read_unlock(mm);
4ffef5fe
DN
5966
5967 precharge = mc.precharge;
5968 mc.precharge = 0;
5969
5970 return precharge;
5971}
5972
4ffef5fe
DN
5973static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5974{
dfe076b0
DN
5975 unsigned long precharge = mem_cgroup_count_precharge(mm);
5976
5977 VM_BUG_ON(mc.moving_task);
5978 mc.moving_task = current;
5979 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5980}
5981
dfe076b0
DN
5982/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5983static void __mem_cgroup_clear_mc(void)
4ffef5fe 5984{
2bd9bb20
KH
5985 struct mem_cgroup *from = mc.from;
5986 struct mem_cgroup *to = mc.to;
5987
4ffef5fe 5988 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d 5989 if (mc.precharge) {
00501b53 5990 cancel_charge(mc.to, mc.precharge);
854ffa8d
DN
5991 mc.precharge = 0;
5992 }
5993 /*
5994 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5995 * we must uncharge here.
5996 */
5997 if (mc.moved_charge) {
00501b53 5998 cancel_charge(mc.from, mc.moved_charge);
854ffa8d 5999 mc.moved_charge = 0;
4ffef5fe 6000 }
483c30b5
DN
6001 /* we must fixup refcnts and charges */
6002 if (mc.moved_swap) {
483c30b5 6003 /* uncharge swap account from the old cgroup */
ce00a967 6004 if (!mem_cgroup_is_root(mc.from))
3e32cb2e 6005 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
483c30b5 6006
615d66c3
VD
6007 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
6008
05b84301 6009 /*
3e32cb2e
JW
6010 * we charged both to->memory and to->memsw, so we
6011 * should uncharge to->memory.
05b84301 6012 */
ce00a967 6013 if (!mem_cgroup_is_root(mc.to))
3e32cb2e
JW
6014 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6015
483c30b5
DN
6016 mc.moved_swap = 0;
6017 }
dfe076b0
DN
6018 memcg_oom_recover(from);
6019 memcg_oom_recover(to);
6020 wake_up_all(&mc.waitq);
6021}
6022
6023static void mem_cgroup_clear_mc(void)
6024{
264a0ae1
TH
6025 struct mm_struct *mm = mc.mm;
6026
dfe076b0
DN
6027 /*
6028 * we must clear moving_task before waking up waiters at the end of
6029 * task migration.
6030 */
6031 mc.moving_task = NULL;
6032 __mem_cgroup_clear_mc();
2bd9bb20 6033 spin_lock(&mc.lock);
4ffef5fe
DN
6034 mc.from = NULL;
6035 mc.to = NULL;
264a0ae1 6036 mc.mm = NULL;
2bd9bb20 6037 spin_unlock(&mc.lock);
264a0ae1
TH
6038
6039 mmput(mm);
4ffef5fe
DN
6040}
6041
1f7dd3e5 6042static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
7dc74be0 6043{
1f7dd3e5 6044 struct cgroup_subsys_state *css;
eed67d75 6045 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
9f2115f9 6046 struct mem_cgroup *from;
4530eddb 6047 struct task_struct *leader, *p;
9f2115f9 6048 struct mm_struct *mm;
1dfab5ab 6049 unsigned long move_flags;
9f2115f9 6050 int ret = 0;
7dc74be0 6051
1f7dd3e5
TH
6052 /* charge immigration isn't supported on the default hierarchy */
6053 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
9f2115f9
TH
6054 return 0;
6055
4530eddb
TH
6056 /*
6057 * Multi-process migrations only happen on the default hierarchy
6058 * where charge immigration is not used. Perform charge
6059 * immigration if @tset contains a leader and whine if there are
6060 * multiple.
6061 */
6062 p = NULL;
1f7dd3e5 6063 cgroup_taskset_for_each_leader(leader, css, tset) {
4530eddb
TH
6064 WARN_ON_ONCE(p);
6065 p = leader;
1f7dd3e5 6066 memcg = mem_cgroup_from_css(css);
4530eddb
TH
6067 }
6068 if (!p)
6069 return 0;
6070
1f7dd3e5 6071 /*
f0953a1b 6072 * We are now committed to this value whatever it is. Changes in this
1f7dd3e5
TH
6073 * tunable will only affect upcoming migrations, not the current one.
6074 * So we need to save it, and keep it going.
6075 */
6076 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6077 if (!move_flags)
6078 return 0;
6079
9f2115f9
TH
6080 from = mem_cgroup_from_task(p);
6081
6082 VM_BUG_ON(from == memcg);
6083
6084 mm = get_task_mm(p);
6085 if (!mm)
6086 return 0;
6087 /* We move charges only when we move a owner of the mm */
6088 if (mm->owner == p) {
6089 VM_BUG_ON(mc.from);
6090 VM_BUG_ON(mc.to);
6091 VM_BUG_ON(mc.precharge);
6092 VM_BUG_ON(mc.moved_charge);
6093 VM_BUG_ON(mc.moved_swap);
6094
6095 spin_lock(&mc.lock);
264a0ae1 6096 mc.mm = mm;
9f2115f9
TH
6097 mc.from = from;
6098 mc.to = memcg;
6099 mc.flags = move_flags;
6100 spin_unlock(&mc.lock);
6101 /* We set mc.moving_task later */
6102
6103 ret = mem_cgroup_precharge_mc(mm);
6104 if (ret)
6105 mem_cgroup_clear_mc();
264a0ae1
TH
6106 } else {
6107 mmput(mm);
7dc74be0
DN
6108 }
6109 return ret;
6110}
6111
1f7dd3e5 6112static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
7dc74be0 6113{
4e2f245d
JW
6114 if (mc.to)
6115 mem_cgroup_clear_mc();
7dc74be0
DN
6116}
6117
4ffef5fe
DN
6118static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6119 unsigned long addr, unsigned long end,
6120 struct mm_walk *walk)
7dc74be0 6121{
4ffef5fe 6122 int ret = 0;
26bcd64a 6123 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
6124 pte_t *pte;
6125 spinlock_t *ptl;
12724850
NH
6126 enum mc_target_type target_type;
6127 union mc_target target;
6128 struct page *page;
4ffef5fe 6129
b6ec57f4
KS
6130 ptl = pmd_trans_huge_lock(pmd, vma);
6131 if (ptl) {
62ade86a 6132 if (mc.precharge < HPAGE_PMD_NR) {
bf929152 6133 spin_unlock(ptl);
12724850
NH
6134 return 0;
6135 }
6136 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6137 if (target_type == MC_TARGET_PAGE) {
6138 page = target.page;
6139 if (!isolate_lru_page(page)) {
f627c2f5 6140 if (!mem_cgroup_move_account(page, true,
1306a85a 6141 mc.from, mc.to)) {
12724850
NH
6142 mc.precharge -= HPAGE_PMD_NR;
6143 mc.moved_charge += HPAGE_PMD_NR;
6144 }
6145 putback_lru_page(page);
6146 }
6147 put_page(page);
c733a828
JG
6148 } else if (target_type == MC_TARGET_DEVICE) {
6149 page = target.page;
6150 if (!mem_cgroup_move_account(page, true,
6151 mc.from, mc.to)) {
6152 mc.precharge -= HPAGE_PMD_NR;
6153 mc.moved_charge += HPAGE_PMD_NR;
6154 }
6155 put_page(page);
12724850 6156 }
bf929152 6157 spin_unlock(ptl);
1a5a9906 6158 return 0;
12724850
NH
6159 }
6160
45f83cef
AA
6161 if (pmd_trans_unstable(pmd))
6162 return 0;
4ffef5fe
DN
6163retry:
6164 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6165 for (; addr != end; addr += PAGE_SIZE) {
6166 pte_t ptent = *(pte++);
c733a828 6167 bool device = false;
02491447 6168 swp_entry_t ent;
4ffef5fe
DN
6169
6170 if (!mc.precharge)
6171 break;
6172
8d32ff84 6173 switch (get_mctgt_type(vma, addr, ptent, &target)) {
c733a828
JG
6174 case MC_TARGET_DEVICE:
6175 device = true;
e4a9bc58 6176 fallthrough;
4ffef5fe
DN
6177 case MC_TARGET_PAGE:
6178 page = target.page;
53f9263b
KS
6179 /*
6180 * We can have a part of the split pmd here. Moving it
6181 * can be done but it would be too convoluted so simply
6182 * ignore such a partial THP and keep it in original
6183 * memcg. There should be somebody mapping the head.
6184 */
6185 if (PageTransCompound(page))
6186 goto put;
c733a828 6187 if (!device && isolate_lru_page(page))
4ffef5fe 6188 goto put;
f627c2f5
KS
6189 if (!mem_cgroup_move_account(page, false,
6190 mc.from, mc.to)) {
4ffef5fe 6191 mc.precharge--;
854ffa8d
DN
6192 /* we uncharge from mc.from later. */
6193 mc.moved_charge++;
4ffef5fe 6194 }
c733a828
JG
6195 if (!device)
6196 putback_lru_page(page);
8d32ff84 6197put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
6198 put_page(page);
6199 break;
02491447
DN
6200 case MC_TARGET_SWAP:
6201 ent = target.ent;
e91cbb42 6202 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 6203 mc.precharge--;
8d22a935
HD
6204 mem_cgroup_id_get_many(mc.to, 1);
6205 /* we fixup other refcnts and charges later. */
483c30b5
DN
6206 mc.moved_swap++;
6207 }
02491447 6208 break;
4ffef5fe
DN
6209 default:
6210 break;
6211 }
6212 }
6213 pte_unmap_unlock(pte - 1, ptl);
6214 cond_resched();
6215
6216 if (addr != end) {
6217 /*
6218 * We have consumed all precharges we got in can_attach().
6219 * We try charge one by one, but don't do any additional
6220 * charges to mc.to if we have failed in charge once in attach()
6221 * phase.
6222 */
854ffa8d 6223 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
6224 if (!ret)
6225 goto retry;
6226 }
6227
6228 return ret;
6229}
6230
7b86ac33
CH
6231static const struct mm_walk_ops charge_walk_ops = {
6232 .pmd_entry = mem_cgroup_move_charge_pte_range,
6233};
6234
264a0ae1 6235static void mem_cgroup_move_charge(void)
4ffef5fe 6236{
4ffef5fe 6237 lru_add_drain_all();
312722cb 6238 /*
81f8c3a4
JW
6239 * Signal lock_page_memcg() to take the memcg's move_lock
6240 * while we're moving its pages to another memcg. Then wait
6241 * for already started RCU-only updates to finish.
312722cb
JW
6242 */
6243 atomic_inc(&mc.from->moving_account);
6244 synchronize_rcu();
dfe076b0 6245retry:
d8ed45c5 6246 if (unlikely(!mmap_read_trylock(mc.mm))) {
dfe076b0 6247 /*
c1e8d7c6 6248 * Someone who are holding the mmap_lock might be waiting in
dfe076b0
DN
6249 * waitq. So we cancel all extra charges, wake up all waiters,
6250 * and retry. Because we cancel precharges, we might not be able
6251 * to move enough charges, but moving charge is a best-effort
6252 * feature anyway, so it wouldn't be a big problem.
6253 */
6254 __mem_cgroup_clear_mc();
6255 cond_resched();
6256 goto retry;
6257 }
26bcd64a
NH
6258 /*
6259 * When we have consumed all precharges and failed in doing
6260 * additional charge, the page walk just aborts.
6261 */
ba0aff8e 6262 walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
d8ed45c5 6263 mmap_read_unlock(mc.mm);
312722cb 6264 atomic_dec(&mc.from->moving_account);
7dc74be0
DN
6265}
6266
264a0ae1 6267static void mem_cgroup_move_task(void)
67e465a7 6268{
264a0ae1
TH
6269 if (mc.to) {
6270 mem_cgroup_move_charge();
a433658c 6271 mem_cgroup_clear_mc();
264a0ae1 6272 }
67e465a7 6273}
5cfb80a7 6274#else /* !CONFIG_MMU */
1f7dd3e5 6275static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
6276{
6277 return 0;
6278}
1f7dd3e5 6279static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
6280{
6281}
264a0ae1 6282static void mem_cgroup_move_task(void)
5cfb80a7
DN
6283{
6284}
6285#endif
67e465a7 6286
bd74fdae
YZ
6287#ifdef CONFIG_LRU_GEN
6288static void mem_cgroup_attach(struct cgroup_taskset *tset)
6289{
6290 struct task_struct *task;
6291 struct cgroup_subsys_state *css;
6292
6293 /* find the first leader if there is any */
6294 cgroup_taskset_for_each_leader(task, css, tset)
6295 break;
6296
6297 if (!task)
6298 return;
6299
6300 task_lock(task);
6301 if (task->mm && READ_ONCE(task->mm->owner) == task)
6302 lru_gen_migrate_mm(task->mm);
6303 task_unlock(task);
6304}
6305#else
6306static void mem_cgroup_attach(struct cgroup_taskset *tset)
6307{
6308}
6309#endif /* CONFIG_LRU_GEN */
6310
677dc973
CD
6311static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6312{
6313 if (value == PAGE_COUNTER_MAX)
6314 seq_puts(m, "max\n");
6315 else
6316 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6317
6318 return 0;
6319}
6320
241994ed
JW
6321static u64 memory_current_read(struct cgroup_subsys_state *css,
6322 struct cftype *cft)
6323{
f5fc3c5d
JW
6324 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6325
6326 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
241994ed
JW
6327}
6328
8e20d4b3
GR
6329static u64 memory_peak_read(struct cgroup_subsys_state *css,
6330 struct cftype *cft)
6331{
6332 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6333
6334 return (u64)memcg->memory.watermark * PAGE_SIZE;
6335}
6336
bf8d5d52
RG
6337static int memory_min_show(struct seq_file *m, void *v)
6338{
677dc973
CD
6339 return seq_puts_memcg_tunable(m,
6340 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
bf8d5d52
RG
6341}
6342
6343static ssize_t memory_min_write(struct kernfs_open_file *of,
6344 char *buf, size_t nbytes, loff_t off)
6345{
6346 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6347 unsigned long min;
6348 int err;
6349
6350 buf = strstrip(buf);
6351 err = page_counter_memparse(buf, "max", &min);
6352 if (err)
6353 return err;
6354
6355 page_counter_set_min(&memcg->memory, min);
6356
6357 return nbytes;
6358}
6359
241994ed
JW
6360static int memory_low_show(struct seq_file *m, void *v)
6361{
677dc973
CD
6362 return seq_puts_memcg_tunable(m,
6363 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
241994ed
JW
6364}
6365
6366static ssize_t memory_low_write(struct kernfs_open_file *of,
6367 char *buf, size_t nbytes, loff_t off)
6368{
6369 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6370 unsigned long low;
6371 int err;
6372
6373 buf = strstrip(buf);
d2973697 6374 err = page_counter_memparse(buf, "max", &low);
241994ed
JW
6375 if (err)
6376 return err;
6377
23067153 6378 page_counter_set_low(&memcg->memory, low);
241994ed
JW
6379
6380 return nbytes;
6381}
6382
6383static int memory_high_show(struct seq_file *m, void *v)
6384{
d1663a90
JK
6385 return seq_puts_memcg_tunable(m,
6386 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
241994ed
JW
6387}
6388
6389static ssize_t memory_high_write(struct kernfs_open_file *of,
6390 char *buf, size_t nbytes, loff_t off)
6391{
6392 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
d977aa93 6393 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
8c8c383c 6394 bool drained = false;
241994ed
JW
6395 unsigned long high;
6396 int err;
6397
6398 buf = strstrip(buf);
d2973697 6399 err = page_counter_memparse(buf, "max", &high);
241994ed
JW
6400 if (err)
6401 return err;
6402
e82553c1
JW
6403 page_counter_set_high(&memcg->memory, high);
6404
8c8c383c
JW
6405 for (;;) {
6406 unsigned long nr_pages = page_counter_read(&memcg->memory);
6407 unsigned long reclaimed;
6408
6409 if (nr_pages <= high)
6410 break;
6411
6412 if (signal_pending(current))
6413 break;
6414
6415 if (!drained) {
6416 drain_all_stock(memcg);
6417 drained = true;
6418 continue;
6419 }
6420
6421 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
73b73bac 6422 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
8c8c383c
JW
6423
6424 if (!reclaimed && !nr_retries--)
6425 break;
6426 }
588083bb 6427
19ce33ac 6428 memcg_wb_domain_size_changed(memcg);
241994ed
JW
6429 return nbytes;
6430}
6431
6432static int memory_max_show(struct seq_file *m, void *v)
6433{
677dc973
CD
6434 return seq_puts_memcg_tunable(m,
6435 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
241994ed
JW
6436}
6437
6438static ssize_t memory_max_write(struct kernfs_open_file *of,
6439 char *buf, size_t nbytes, loff_t off)
6440{
6441 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
d977aa93 6442 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
b6e6edcf 6443 bool drained = false;
241994ed
JW
6444 unsigned long max;
6445 int err;
6446
6447 buf = strstrip(buf);
d2973697 6448 err = page_counter_memparse(buf, "max", &max);
241994ed
JW
6449 if (err)
6450 return err;
6451
bbec2e15 6452 xchg(&memcg->memory.max, max);
b6e6edcf
JW
6453
6454 for (;;) {
6455 unsigned long nr_pages = page_counter_read(&memcg->memory);
6456
6457 if (nr_pages <= max)
6458 break;
6459
7249c9f0 6460 if (signal_pending(current))
b6e6edcf 6461 break;
b6e6edcf
JW
6462
6463 if (!drained) {
6464 drain_all_stock(memcg);
6465 drained = true;
6466 continue;
6467 }
6468
6469 if (nr_reclaims) {
6470 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
73b73bac 6471 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
b6e6edcf
JW
6472 nr_reclaims--;
6473 continue;
6474 }
6475
e27be240 6476 memcg_memory_event(memcg, MEMCG_OOM);
b6e6edcf
JW
6477 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6478 break;
6479 }
241994ed 6480
2529bb3a 6481 memcg_wb_domain_size_changed(memcg);
241994ed
JW
6482 return nbytes;
6483}
6484
1e577f97
SB
6485static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6486{
6487 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6488 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6489 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6490 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6491 seq_printf(m, "oom_kill %lu\n",
6492 atomic_long_read(&events[MEMCG_OOM_KILL]));
b6bf9abb
DS
6493 seq_printf(m, "oom_group_kill %lu\n",
6494 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
1e577f97
SB
6495}
6496
241994ed
JW
6497static int memory_events_show(struct seq_file *m, void *v)
6498{
aa9694bb 6499 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6500
1e577f97
SB
6501 __memory_events_show(m, memcg->memory_events);
6502 return 0;
6503}
6504
6505static int memory_events_local_show(struct seq_file *m, void *v)
6506{
6507 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6508
1e577f97 6509 __memory_events_show(m, memcg->memory_events_local);
241994ed
JW
6510 return 0;
6511}
6512
587d9f72
JW
6513static int memory_stat_show(struct seq_file *m, void *v)
6514{
aa9694bb 6515 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
68aaee14 6516 char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1ff9e6e1 6517
c8713d0b
JW
6518 if (!buf)
6519 return -ENOMEM;
68aaee14 6520 memory_stat_format(memcg, buf, PAGE_SIZE);
c8713d0b
JW
6521 seq_puts(m, buf);
6522 kfree(buf);
587d9f72
JW
6523 return 0;
6524}
6525
5f9a4f4a 6526#ifdef CONFIG_NUMA
fff66b79
MS
6527static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
6528 int item)
6529{
6530 return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
6531}
6532
5f9a4f4a
MS
6533static int memory_numa_stat_show(struct seq_file *m, void *v)
6534{
6535 int i;
6536 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6537
fd25a9e0 6538 mem_cgroup_flush_stats();
7e1c0d6f 6539
5f9a4f4a
MS
6540 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
6541 int nid;
6542
6543 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
6544 continue;
6545
6546 seq_printf(m, "%s", memory_stats[i].name);
6547 for_each_node_state(nid, N_MEMORY) {
6548 u64 size;
6549 struct lruvec *lruvec;
6550
6551 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
fff66b79
MS
6552 size = lruvec_page_state_output(lruvec,
6553 memory_stats[i].idx);
5f9a4f4a
MS
6554 seq_printf(m, " N%d=%llu", nid, size);
6555 }
6556 seq_putc(m, '\n');
6557 }
6558
6559 return 0;
6560}
6561#endif
6562
3d8b38eb
RG
6563static int memory_oom_group_show(struct seq_file *m, void *v)
6564{
aa9694bb 6565 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3d8b38eb
RG
6566
6567 seq_printf(m, "%d\n", memcg->oom_group);
6568
6569 return 0;
6570}
6571
6572static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6573 char *buf, size_t nbytes, loff_t off)
6574{
6575 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6576 int ret, oom_group;
6577
6578 buf = strstrip(buf);
6579 if (!buf)
6580 return -EINVAL;
6581
6582 ret = kstrtoint(buf, 0, &oom_group);
6583 if (ret)
6584 return ret;
6585
6586 if (oom_group != 0 && oom_group != 1)
6587 return -EINVAL;
6588
6589 memcg->oom_group = oom_group;
6590
6591 return nbytes;
6592}
6593
94968384
SB
6594static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
6595 size_t nbytes, loff_t off)
6596{
6597 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6598 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
6599 unsigned long nr_to_reclaim, nr_reclaimed = 0;
73b73bac 6600 unsigned int reclaim_options;
94968384
SB
6601 int err;
6602
6603 buf = strstrip(buf);
6604 err = page_counter_memparse(buf, "", &nr_to_reclaim);
6605 if (err)
6606 return err;
6607
73b73bac 6608 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
94968384
SB
6609 while (nr_reclaimed < nr_to_reclaim) {
6610 unsigned long reclaimed;
6611
6612 if (signal_pending(current))
6613 return -EINTR;
6614
6615 /*
6616 * This is the final attempt, drain percpu lru caches in the
6617 * hope of introducing more evictable pages for
6618 * try_to_free_mem_cgroup_pages().
6619 */
6620 if (!nr_retries)
6621 lru_add_drain_all();
6622
6623 reclaimed = try_to_free_mem_cgroup_pages(memcg,
6624 nr_to_reclaim - nr_reclaimed,
73b73bac 6625 GFP_KERNEL, reclaim_options);
94968384
SB
6626
6627 if (!reclaimed && !nr_retries--)
6628 return -EAGAIN;
6629
6630 nr_reclaimed += reclaimed;
6631 }
6632
6633 return nbytes;
6634}
6635
241994ed
JW
6636static struct cftype memory_files[] = {
6637 {
6638 .name = "current",
f5fc3c5d 6639 .flags = CFTYPE_NOT_ON_ROOT,
241994ed
JW
6640 .read_u64 = memory_current_read,
6641 },
8e20d4b3
GR
6642 {
6643 .name = "peak",
6644 .flags = CFTYPE_NOT_ON_ROOT,
6645 .read_u64 = memory_peak_read,
6646 },
bf8d5d52
RG
6647 {
6648 .name = "min",
6649 .flags = CFTYPE_NOT_ON_ROOT,
6650 .seq_show = memory_min_show,
6651 .write = memory_min_write,
6652 },
241994ed
JW
6653 {
6654 .name = "low",
6655 .flags = CFTYPE_NOT_ON_ROOT,
6656 .seq_show = memory_low_show,
6657 .write = memory_low_write,
6658 },
6659 {
6660 .name = "high",
6661 .flags = CFTYPE_NOT_ON_ROOT,
6662 .seq_show = memory_high_show,
6663 .write = memory_high_write,
6664 },
6665 {
6666 .name = "max",
6667 .flags = CFTYPE_NOT_ON_ROOT,
6668 .seq_show = memory_max_show,
6669 .write = memory_max_write,
6670 },
6671 {
6672 .name = "events",
6673 .flags = CFTYPE_NOT_ON_ROOT,
472912a2 6674 .file_offset = offsetof(struct mem_cgroup, events_file),
241994ed
JW
6675 .seq_show = memory_events_show,
6676 },
1e577f97
SB
6677 {
6678 .name = "events.local",
6679 .flags = CFTYPE_NOT_ON_ROOT,
6680 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6681 .seq_show = memory_events_local_show,
6682 },
587d9f72
JW
6683 {
6684 .name = "stat",
587d9f72
JW
6685 .seq_show = memory_stat_show,
6686 },
5f9a4f4a
MS
6687#ifdef CONFIG_NUMA
6688 {
6689 .name = "numa_stat",
6690 .seq_show = memory_numa_stat_show,
6691 },
6692#endif
3d8b38eb
RG
6693 {
6694 .name = "oom.group",
6695 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6696 .seq_show = memory_oom_group_show,
6697 .write = memory_oom_group_write,
6698 },
94968384
SB
6699 {
6700 .name = "reclaim",
6701 .flags = CFTYPE_NS_DELEGATABLE,
6702 .write = memory_reclaim,
6703 },
241994ed
JW
6704 { } /* terminate */
6705};
6706
073219e9 6707struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 6708 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 6709 .css_online = mem_cgroup_css_online,
92fb9748 6710 .css_offline = mem_cgroup_css_offline,
6df38689 6711 .css_released = mem_cgroup_css_released,
92fb9748 6712 .css_free = mem_cgroup_css_free,
1ced953b 6713 .css_reset = mem_cgroup_css_reset,
2d146aa3 6714 .css_rstat_flush = mem_cgroup_css_rstat_flush,
7dc74be0 6715 .can_attach = mem_cgroup_can_attach,
bd74fdae 6716 .attach = mem_cgroup_attach,
7dc74be0 6717 .cancel_attach = mem_cgroup_cancel_attach,
264a0ae1 6718 .post_attach = mem_cgroup_move_task,
241994ed
JW
6719 .dfl_cftypes = memory_files,
6720 .legacy_cftypes = mem_cgroup_legacy_files,
6d12e2d8 6721 .early_init = 0,
8cdea7c0 6722};
c077719b 6723
bc50bcc6
JW
6724/*
6725 * This function calculates an individual cgroup's effective
6726 * protection which is derived from its own memory.min/low, its
6727 * parent's and siblings' settings, as well as the actual memory
6728 * distribution in the tree.
6729 *
6730 * The following rules apply to the effective protection values:
6731 *
6732 * 1. At the first level of reclaim, effective protection is equal to
6733 * the declared protection in memory.min and memory.low.
6734 *
6735 * 2. To enable safe delegation of the protection configuration, at
6736 * subsequent levels the effective protection is capped to the
6737 * parent's effective protection.
6738 *
6739 * 3. To make complex and dynamic subtrees easier to configure, the
6740 * user is allowed to overcommit the declared protection at a given
6741 * level. If that is the case, the parent's effective protection is
6742 * distributed to the children in proportion to how much protection
6743 * they have declared and how much of it they are utilizing.
6744 *
6745 * This makes distribution proportional, but also work-conserving:
6746 * if one cgroup claims much more protection than it uses memory,
6747 * the unused remainder is available to its siblings.
6748 *
6749 * 4. Conversely, when the declared protection is undercommitted at a
6750 * given level, the distribution of the larger parental protection
6751 * budget is NOT proportional. A cgroup's protection from a sibling
6752 * is capped to its own memory.min/low setting.
6753 *
8a931f80
JW
6754 * 5. However, to allow protecting recursive subtrees from each other
6755 * without having to declare each individual cgroup's fixed share
6756 * of the ancestor's claim to protection, any unutilized -
6757 * "floating" - protection from up the tree is distributed in
6758 * proportion to each cgroup's *usage*. This makes the protection
6759 * neutral wrt sibling cgroups and lets them compete freely over
6760 * the shared parental protection budget, but it protects the
6761 * subtree as a whole from neighboring subtrees.
6762 *
6763 * Note that 4. and 5. are not in conflict: 4. is about protecting
6764 * against immediate siblings whereas 5. is about protecting against
6765 * neighboring subtrees.
bc50bcc6
JW
6766 */
6767static unsigned long effective_protection(unsigned long usage,
8a931f80 6768 unsigned long parent_usage,
bc50bcc6
JW
6769 unsigned long setting,
6770 unsigned long parent_effective,
6771 unsigned long siblings_protected)
6772{
6773 unsigned long protected;
8a931f80 6774 unsigned long ep;
bc50bcc6
JW
6775
6776 protected = min(usage, setting);
6777 /*
6778 * If all cgroups at this level combined claim and use more
6779 * protection then what the parent affords them, distribute
6780 * shares in proportion to utilization.
6781 *
6782 * We are using actual utilization rather than the statically
6783 * claimed protection in order to be work-conserving: claimed
6784 * but unused protection is available to siblings that would
6785 * otherwise get a smaller chunk than what they claimed.
6786 */
6787 if (siblings_protected > parent_effective)
6788 return protected * parent_effective / siblings_protected;
6789
6790 /*
6791 * Ok, utilized protection of all children is within what the
6792 * parent affords them, so we know whatever this child claims
6793 * and utilizes is effectively protected.
6794 *
6795 * If there is unprotected usage beyond this value, reclaim
6796 * will apply pressure in proportion to that amount.
6797 *
6798 * If there is unutilized protection, the cgroup will be fully
6799 * shielded from reclaim, but we do return a smaller value for
6800 * protection than what the group could enjoy in theory. This
6801 * is okay. With the overcommit distribution above, effective
6802 * protection is always dependent on how memory is actually
6803 * consumed among the siblings anyway.
6804 */
8a931f80
JW
6805 ep = protected;
6806
6807 /*
6808 * If the children aren't claiming (all of) the protection
6809 * afforded to them by the parent, distribute the remainder in
6810 * proportion to the (unprotected) memory of each cgroup. That
6811 * way, cgroups that aren't explicitly prioritized wrt each
6812 * other compete freely over the allowance, but they are
6813 * collectively protected from neighboring trees.
6814 *
6815 * We're using unprotected memory for the weight so that if
6816 * some cgroups DO claim explicit protection, we don't protect
6817 * the same bytes twice.
cd324edc
JW
6818 *
6819 * Check both usage and parent_usage against the respective
6820 * protected values. One should imply the other, but they
6821 * aren't read atomically - make sure the division is sane.
8a931f80
JW
6822 */
6823 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6824 return ep;
cd324edc
JW
6825 if (parent_effective > siblings_protected &&
6826 parent_usage > siblings_protected &&
6827 usage > protected) {
8a931f80
JW
6828 unsigned long unclaimed;
6829
6830 unclaimed = parent_effective - siblings_protected;
6831 unclaimed *= usage - protected;
6832 unclaimed /= parent_usage - siblings_protected;
6833
6834 ep += unclaimed;
6835 }
6836
6837 return ep;
bc50bcc6
JW
6838}
6839
241994ed 6840/**
05395718 6841 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
34c81057 6842 * @root: the top ancestor of the sub-tree being checked
241994ed
JW
6843 * @memcg: the memory cgroup to check
6844 *
23067153
RG
6845 * WARNING: This function is not stateless! It can only be used as part
6846 * of a top-down tree iteration, not for isolated queries.
241994ed 6847 */
45c7f7e1
CD
6848void mem_cgroup_calculate_protection(struct mem_cgroup *root,
6849 struct mem_cgroup *memcg)
241994ed 6850{
8a931f80 6851 unsigned long usage, parent_usage;
23067153
RG
6852 struct mem_cgroup *parent;
6853
241994ed 6854 if (mem_cgroup_disabled())
45c7f7e1 6855 return;
241994ed 6856
34c81057
SC
6857 if (!root)
6858 root = root_mem_cgroup;
22f7496f
YS
6859
6860 /*
6861 * Effective values of the reclaim targets are ignored so they
6862 * can be stale. Have a look at mem_cgroup_protection for more
6863 * details.
6864 * TODO: calculation should be more robust so that we do not need
6865 * that special casing.
6866 */
34c81057 6867 if (memcg == root)
45c7f7e1 6868 return;
241994ed 6869
23067153 6870 usage = page_counter_read(&memcg->memory);
bf8d5d52 6871 if (!usage)
45c7f7e1 6872 return;
bf8d5d52 6873
bf8d5d52 6874 parent = parent_mem_cgroup(memcg);
df2a4196 6875
bc50bcc6 6876 if (parent == root) {
c3d53200 6877 memcg->memory.emin = READ_ONCE(memcg->memory.min);
03960e33 6878 memcg->memory.elow = READ_ONCE(memcg->memory.low);
45c7f7e1 6879 return;
bf8d5d52
RG
6880 }
6881
8a931f80
JW
6882 parent_usage = page_counter_read(&parent->memory);
6883
b3a7822e 6884 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
c3d53200
CD
6885 READ_ONCE(memcg->memory.min),
6886 READ_ONCE(parent->memory.emin),
b3a7822e 6887 atomic_long_read(&parent->memory.children_min_usage)));
23067153 6888
b3a7822e 6889 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
03960e33
CD
6890 READ_ONCE(memcg->memory.low),
6891 READ_ONCE(parent->memory.elow),
b3a7822e 6892 atomic_long_read(&parent->memory.children_low_usage)));
241994ed
JW
6893}
6894
8f425e4e
MWO
6895static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
6896 gfp_t gfp)
0add0c77 6897{
118f2875 6898 long nr_pages = folio_nr_pages(folio);
0add0c77
SB
6899 int ret;
6900
6901 ret = try_charge(memcg, gfp, nr_pages);
6902 if (ret)
6903 goto out;
6904
6905 css_get(&memcg->css);
118f2875 6906 commit_charge(folio, memcg);
0add0c77
SB
6907
6908 local_irq_disable();
6e0110c2 6909 mem_cgroup_charge_statistics(memcg, nr_pages);
8f425e4e 6910 memcg_check_events(memcg, folio_nid(folio));
0add0c77
SB
6911 local_irq_enable();
6912out:
6913 return ret;
6914}
6915
8f425e4e 6916int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
00501b53 6917{
0add0c77
SB
6918 struct mem_cgroup *memcg;
6919 int ret;
00501b53 6920
0add0c77 6921 memcg = get_mem_cgroup_from_mm(mm);
8f425e4e 6922 ret = charge_memcg(folio, memcg, gfp);
0add0c77 6923 css_put(&memcg->css);
2d1c4980 6924
0add0c77
SB
6925 return ret;
6926}
e993d905 6927
0add0c77 6928/**
65995918
MWO
6929 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
6930 * @folio: folio to charge.
0add0c77
SB
6931 * @mm: mm context of the victim
6932 * @gfp: reclaim mode
65995918 6933 * @entry: swap entry for which the folio is allocated
0add0c77 6934 *
65995918
MWO
6935 * This function charges a folio allocated for swapin. Please call this before
6936 * adding the folio to the swapcache.
0add0c77
SB
6937 *
6938 * Returns 0 on success. Otherwise, an error code is returned.
6939 */
65995918 6940int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
0add0c77
SB
6941 gfp_t gfp, swp_entry_t entry)
6942{
6943 struct mem_cgroup *memcg;
6944 unsigned short id;
6945 int ret;
00501b53 6946
0add0c77
SB
6947 if (mem_cgroup_disabled())
6948 return 0;
00501b53 6949
0add0c77
SB
6950 id = lookup_swap_cgroup_id(entry);
6951 rcu_read_lock();
6952 memcg = mem_cgroup_from_id(id);
6953 if (!memcg || !css_tryget_online(&memcg->css))
6954 memcg = get_mem_cgroup_from_mm(mm);
6955 rcu_read_unlock();
00501b53 6956
8f425e4e 6957 ret = charge_memcg(folio, memcg, gfp);
6abb5a86 6958
0add0c77
SB
6959 css_put(&memcg->css);
6960 return ret;
6961}
00501b53 6962
0add0c77
SB
6963/*
6964 * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
6965 * @entry: swap entry for which the page is charged
6966 *
6967 * Call this function after successfully adding the charged page to swapcache.
6968 *
6969 * Note: This function assumes the page for which swap slot is being uncharged
6970 * is order 0 page.
6971 */
6972void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
6973{
cae3af62
MS
6974 /*
6975 * Cgroup1's unified memory+swap counter has been charged with the
6976 * new swapcache page, finish the transfer by uncharging the swap
6977 * slot. The swap slot would also get uncharged when it dies, but
6978 * it can stick around indefinitely and we'd count the page twice
6979 * the entire time.
6980 *
6981 * Cgroup2 has separate resource counters for memory and swap,
6982 * so this is a non-issue here. Memory and swap charge lifetimes
6983 * correspond 1:1 to page and swap slot lifetimes: we charge the
6984 * page to memory here, and uncharge swap when the slot is freed.
6985 */
0add0c77 6986 if (!mem_cgroup_disabled() && do_memsw_account()) {
00501b53
JW
6987 /*
6988 * The swap entry might not get freed for a long time,
6989 * let's not wait for it. The page already received a
6990 * memory+swap charge, drop the swap entry duplicate.
6991 */
0add0c77 6992 mem_cgroup_uncharge_swap(entry, 1);
00501b53 6993 }
3fea5a49
JW
6994}
6995
a9d5adee
JG
6996struct uncharge_gather {
6997 struct mem_cgroup *memcg;
b4e0b68f 6998 unsigned long nr_memory;
a9d5adee 6999 unsigned long pgpgout;
a9d5adee 7000 unsigned long nr_kmem;
8e88bd2d 7001 int nid;
a9d5adee
JG
7002};
7003
7004static inline void uncharge_gather_clear(struct uncharge_gather *ug)
747db954 7005{
a9d5adee
JG
7006 memset(ug, 0, sizeof(*ug));
7007}
7008
7009static void uncharge_batch(const struct uncharge_gather *ug)
7010{
747db954
JW
7011 unsigned long flags;
7012
b4e0b68f
MS
7013 if (ug->nr_memory) {
7014 page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
7941d214 7015 if (do_memsw_account())
b4e0b68f 7016 page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
a8c49af3
YA
7017 if (ug->nr_kmem)
7018 memcg_account_kmem(ug->memcg, -ug->nr_kmem);
a9d5adee 7019 memcg_oom_recover(ug->memcg);
ce00a967 7020 }
747db954
JW
7021
7022 local_irq_save(flags);
c9019e9b 7023 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
b4e0b68f 7024 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
8e88bd2d 7025 memcg_check_events(ug->memcg, ug->nid);
747db954 7026 local_irq_restore(flags);
f1796544 7027
c4ed6ebf 7028 /* drop reference from uncharge_folio */
f1796544 7029 css_put(&ug->memcg->css);
a9d5adee
JG
7030}
7031
c4ed6ebf 7032static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
a9d5adee 7033{
c4ed6ebf 7034 long nr_pages;
b4e0b68f
MS
7035 struct mem_cgroup *memcg;
7036 struct obj_cgroup *objcg;
9f762dbe 7037
c4ed6ebf 7038 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
a9d5adee 7039
a9d5adee
JG
7040 /*
7041 * Nobody should be changing or seriously looking at
c4ed6ebf
MWO
7042 * folio memcg or objcg at this point, we have fully
7043 * exclusive access to the folio.
a9d5adee 7044 */
fead2b86 7045 if (folio_memcg_kmem(folio)) {
1b7e4464 7046 objcg = __folio_objcg(folio);
b4e0b68f
MS
7047 /*
7048 * This get matches the put at the end of the function and
7049 * kmem pages do not hold memcg references anymore.
7050 */
7051 memcg = get_mem_cgroup_from_objcg(objcg);
7052 } else {
1b7e4464 7053 memcg = __folio_memcg(folio);
b4e0b68f 7054 }
a9d5adee 7055
b4e0b68f
MS
7056 if (!memcg)
7057 return;
7058
7059 if (ug->memcg != memcg) {
a9d5adee
JG
7060 if (ug->memcg) {
7061 uncharge_batch(ug);
7062 uncharge_gather_clear(ug);
7063 }
b4e0b68f 7064 ug->memcg = memcg;
c4ed6ebf 7065 ug->nid = folio_nid(folio);
f1796544
MH
7066
7067 /* pairs with css_put in uncharge_batch */
b4e0b68f 7068 css_get(&memcg->css);
a9d5adee
JG
7069 }
7070
c4ed6ebf 7071 nr_pages = folio_nr_pages(folio);
a9d5adee 7072
fead2b86 7073 if (folio_memcg_kmem(folio)) {
b4e0b68f 7074 ug->nr_memory += nr_pages;
9f762dbe 7075 ug->nr_kmem += nr_pages;
b4e0b68f 7076
c4ed6ebf 7077 folio->memcg_data = 0;
b4e0b68f
MS
7078 obj_cgroup_put(objcg);
7079 } else {
7080 /* LRU pages aren't accounted at the root level */
7081 if (!mem_cgroup_is_root(memcg))
7082 ug->nr_memory += nr_pages;
18b2db3b 7083 ug->pgpgout++;
a9d5adee 7084
c4ed6ebf 7085 folio->memcg_data = 0;
b4e0b68f
MS
7086 }
7087
7088 css_put(&memcg->css);
747db954
JW
7089}
7090
bbc6b703 7091void __mem_cgroup_uncharge(struct folio *folio)
0a31bc97 7092{
a9d5adee
JG
7093 struct uncharge_gather ug;
7094
bbc6b703
MWO
7095 /* Don't touch folio->lru of any random page, pre-check: */
7096 if (!folio_memcg(folio))
0a31bc97
JW
7097 return;
7098
a9d5adee 7099 uncharge_gather_clear(&ug);
bbc6b703 7100 uncharge_folio(folio, &ug);
a9d5adee 7101 uncharge_batch(&ug);
747db954 7102}
0a31bc97 7103
747db954 7104/**
2c8d8f97 7105 * __mem_cgroup_uncharge_list - uncharge a list of page
747db954
JW
7106 * @page_list: list of pages to uncharge
7107 *
7108 * Uncharge a list of pages previously charged with
2c8d8f97 7109 * __mem_cgroup_charge().
747db954 7110 */
2c8d8f97 7111void __mem_cgroup_uncharge_list(struct list_head *page_list)
747db954 7112{
c41a40b6 7113 struct uncharge_gather ug;
c4ed6ebf 7114 struct folio *folio;
c41a40b6 7115
c41a40b6 7116 uncharge_gather_clear(&ug);
c4ed6ebf
MWO
7117 list_for_each_entry(folio, page_list, lru)
7118 uncharge_folio(folio, &ug);
c41a40b6
MS
7119 if (ug.memcg)
7120 uncharge_batch(&ug);
0a31bc97
JW
7121}
7122
7123/**
d21bba2b
MWO
7124 * mem_cgroup_migrate - Charge a folio's replacement.
7125 * @old: Currently circulating folio.
7126 * @new: Replacement folio.
0a31bc97 7127 *
d21bba2b 7128 * Charge @new as a replacement folio for @old. @old will
6a93ca8f 7129 * be uncharged upon free.
0a31bc97 7130 *
d21bba2b 7131 * Both folios must be locked, @new->mapping must be set up.
0a31bc97 7132 */
d21bba2b 7133void mem_cgroup_migrate(struct folio *old, struct folio *new)
0a31bc97 7134{
29833315 7135 struct mem_cgroup *memcg;
d21bba2b 7136 long nr_pages = folio_nr_pages(new);
d93c4130 7137 unsigned long flags;
0a31bc97 7138
d21bba2b
MWO
7139 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
7140 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
7141 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
7142 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
0a31bc97
JW
7143
7144 if (mem_cgroup_disabled())
7145 return;
7146
d21bba2b
MWO
7147 /* Page cache replacement: new folio already charged? */
7148 if (folio_memcg(new))
0a31bc97
JW
7149 return;
7150
d21bba2b
MWO
7151 memcg = folio_memcg(old);
7152 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
29833315 7153 if (!memcg)
0a31bc97
JW
7154 return;
7155
44b7a8d3 7156 /* Force-charge the new page. The old one will be freed soon */
8dc87c7d
MS
7157 if (!mem_cgroup_is_root(memcg)) {
7158 page_counter_charge(&memcg->memory, nr_pages);
7159 if (do_memsw_account())
7160 page_counter_charge(&memcg->memsw, nr_pages);
7161 }
0a31bc97 7162
1a3e1f40 7163 css_get(&memcg->css);
d21bba2b 7164 commit_charge(new, memcg);
44b7a8d3 7165
d93c4130 7166 local_irq_save(flags);
6e0110c2 7167 mem_cgroup_charge_statistics(memcg, nr_pages);
d21bba2b 7168 memcg_check_events(memcg, folio_nid(new));
d93c4130 7169 local_irq_restore(flags);
0a31bc97
JW
7170}
7171
ef12947c 7172DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
11092087
JW
7173EXPORT_SYMBOL(memcg_sockets_enabled_key);
7174
2d758073 7175void mem_cgroup_sk_alloc(struct sock *sk)
11092087
JW
7176{
7177 struct mem_cgroup *memcg;
7178
2d758073
JW
7179 if (!mem_cgroup_sockets_enabled)
7180 return;
7181
e876ecc6 7182 /* Do not associate the sock with unrelated interrupted task's memcg. */
086f694a 7183 if (!in_task())
e876ecc6
SB
7184 return;
7185
11092087
JW
7186 rcu_read_lock();
7187 memcg = mem_cgroup_from_task(current);
f7e1cb6e
JW
7188 if (memcg == root_mem_cgroup)
7189 goto out;
0db15298 7190 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
f7e1cb6e 7191 goto out;
8965aa28 7192 if (css_tryget(&memcg->css))
11092087 7193 sk->sk_memcg = memcg;
f7e1cb6e 7194out:
11092087
JW
7195 rcu_read_unlock();
7196}
11092087 7197
2d758073 7198void mem_cgroup_sk_free(struct sock *sk)
11092087 7199{
2d758073
JW
7200 if (sk->sk_memcg)
7201 css_put(&sk->sk_memcg->css);
11092087
JW
7202}
7203
7204/**
7205 * mem_cgroup_charge_skmem - charge socket memory
7206 * @memcg: memcg to charge
7207 * @nr_pages: number of pages to charge
4b1327be 7208 * @gfp_mask: reclaim mode
11092087
JW
7209 *
7210 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
4b1327be 7211 * @memcg's configured limit, %false if it doesn't.
11092087 7212 */
4b1327be
WW
7213bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
7214 gfp_t gfp_mask)
11092087 7215{
f7e1cb6e 7216 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 7217 struct page_counter *fail;
f7e1cb6e 7218
0db15298
JW
7219 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7220 memcg->tcpmem_pressure = 0;
f7e1cb6e
JW
7221 return true;
7222 }
0db15298 7223 memcg->tcpmem_pressure = 1;
4b1327be
WW
7224 if (gfp_mask & __GFP_NOFAIL) {
7225 page_counter_charge(&memcg->tcpmem, nr_pages);
7226 return true;
7227 }
f7e1cb6e 7228 return false;
11092087 7229 }
d886f4e4 7230
4b1327be
WW
7231 if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
7232 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
f7e1cb6e 7233 return true;
4b1327be 7234 }
f7e1cb6e 7235
11092087
JW
7236 return false;
7237}
7238
7239/**
7240 * mem_cgroup_uncharge_skmem - uncharge socket memory
b7701a5f
MR
7241 * @memcg: memcg to uncharge
7242 * @nr_pages: number of pages to uncharge
11092087
JW
7243 */
7244void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7245{
f7e1cb6e 7246 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 7247 page_counter_uncharge(&memcg->tcpmem, nr_pages);
f7e1cb6e
JW
7248 return;
7249 }
d886f4e4 7250
c9019e9b 7251 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
b2807f07 7252
475d0487 7253 refill_stock(memcg, nr_pages);
11092087
JW
7254}
7255
f7e1cb6e
JW
7256static int __init cgroup_memory(char *s)
7257{
7258 char *token;
7259
7260 while ((token = strsep(&s, ",")) != NULL) {
7261 if (!*token)
7262 continue;
7263 if (!strcmp(token, "nosocket"))
7264 cgroup_memory_nosocket = true;
04823c83
VD
7265 if (!strcmp(token, "nokmem"))
7266 cgroup_memory_nokmem = true;
f7e1cb6e 7267 }
460a79e1 7268 return 1;
f7e1cb6e
JW
7269}
7270__setup("cgroup.memory=", cgroup_memory);
11092087 7271
2d11085e 7272/*
1081312f
MH
7273 * subsys_initcall() for memory controller.
7274 *
308167fc
SAS
7275 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7276 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7277 * basically everything that doesn't depend on a specific mem_cgroup structure
7278 * should be initialized from here.
2d11085e
MH
7279 */
7280static int __init mem_cgroup_init(void)
7281{
95a045f6
JW
7282 int cpu, node;
7283
f3344adf
MS
7284 /*
7285 * Currently s32 type (can refer to struct batched_lruvec_stat) is
7286 * used for per-memcg-per-cpu caching of per-node statistics. In order
7287 * to work fine, we should make sure that the overfill threshold can't
7288 * exceed S32_MAX / PAGE_SIZE.
7289 */
7290 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
7291
308167fc
SAS
7292 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7293 memcg_hotplug_cpu_dead);
95a045f6
JW
7294
7295 for_each_possible_cpu(cpu)
7296 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7297 drain_local_stock);
7298
7299 for_each_node(node) {
7300 struct mem_cgroup_tree_per_node *rtpn;
95a045f6
JW
7301
7302 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7303 node_online(node) ? node : NUMA_NO_NODE);
7304
ef8f2327 7305 rtpn->rb_root = RB_ROOT;
fa90b2fd 7306 rtpn->rb_rightmost = NULL;
ef8f2327 7307 spin_lock_init(&rtpn->lock);
95a045f6
JW
7308 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7309 }
7310
2d11085e
MH
7311 return 0;
7312}
7313subsys_initcall(mem_cgroup_init);
21afa38e
JW
7314
7315#ifdef CONFIG_MEMCG_SWAP
358c07fc
AB
7316static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7317{
1c2d479a 7318 while (!refcount_inc_not_zero(&memcg->id.ref)) {
358c07fc
AB
7319 /*
7320 * The root cgroup cannot be destroyed, so it's refcount must
7321 * always be >= 1.
7322 */
7323 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7324 VM_BUG_ON(1);
7325 break;
7326 }
7327 memcg = parent_mem_cgroup(memcg);
7328 if (!memcg)
7329 memcg = root_mem_cgroup;
7330 }
7331 return memcg;
7332}
7333
21afa38e
JW
7334/**
7335 * mem_cgroup_swapout - transfer a memsw charge to swap
3ecb0087 7336 * @folio: folio whose memsw charge to transfer
21afa38e
JW
7337 * @entry: swap entry to move the charge to
7338 *
3ecb0087 7339 * Transfer the memsw charge of @folio to @entry.
21afa38e 7340 */
3ecb0087 7341void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
21afa38e 7342{
1f47b61f 7343 struct mem_cgroup *memcg, *swap_memcg;
d6810d73 7344 unsigned int nr_entries;
21afa38e
JW
7345 unsigned short oldid;
7346
3ecb0087
MWO
7347 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
7348 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
21afa38e 7349
76358ab5
AS
7350 if (mem_cgroup_disabled())
7351 return;
7352
2d1c4980 7353 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
21afa38e
JW
7354 return;
7355
3ecb0087 7356 memcg = folio_memcg(folio);
21afa38e 7357
3ecb0087 7358 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
21afa38e
JW
7359 if (!memcg)
7360 return;
7361
1f47b61f
VD
7362 /*
7363 * In case the memcg owning these pages has been offlined and doesn't
7364 * have an ID allocated to it anymore, charge the closest online
7365 * ancestor for the swap instead and transfer the memory+swap charge.
7366 */
7367 swap_memcg = mem_cgroup_id_get_online(memcg);
3ecb0087 7368 nr_entries = folio_nr_pages(folio);
d6810d73
HY
7369 /* Get references for the tail pages, too */
7370 if (nr_entries > 1)
7371 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7372 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7373 nr_entries);
3ecb0087 7374 VM_BUG_ON_FOLIO(oldid, folio);
c9019e9b 7375 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
21afa38e 7376
3ecb0087 7377 folio->memcg_data = 0;
21afa38e
JW
7378
7379 if (!mem_cgroup_is_root(memcg))
d6810d73 7380 page_counter_uncharge(&memcg->memory, nr_entries);
21afa38e 7381
c1b8fdae 7382 if (memcg_swap_enabled() && memcg != swap_memcg) {
1f47b61f 7383 if (!mem_cgroup_is_root(swap_memcg))
d6810d73
HY
7384 page_counter_charge(&swap_memcg->memsw, nr_entries);
7385 page_counter_uncharge(&memcg->memsw, nr_entries);
1f47b61f
VD
7386 }
7387
ce9ce665
SAS
7388 /*
7389 * Interrupts should be disabled here because the caller holds the
b93b0163 7390 * i_pages lock which is taken with interrupts-off. It is
ce9ce665 7391 * important here to have the interrupts disabled because it is the
b93b0163 7392 * only synchronisation we have for updating the per-CPU variables.
ce9ce665 7393 */
be3e67b5 7394 memcg_stats_lock();
6e0110c2 7395 mem_cgroup_charge_statistics(memcg, -nr_entries);
be3e67b5 7396 memcg_stats_unlock();
3ecb0087 7397 memcg_check_events(memcg, folio_nid(folio));
73f576c0 7398
1a3e1f40 7399 css_put(&memcg->css);
21afa38e
JW
7400}
7401
38d8b4e6 7402/**
e2e3fdc7
MWO
7403 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
7404 * @folio: folio being added to swap
37e84351
VD
7405 * @entry: swap entry to charge
7406 *
e2e3fdc7 7407 * Try to charge @folio's memcg for the swap space at @entry.
37e84351
VD
7408 *
7409 * Returns 0 on success, -ENOMEM on failure.
7410 */
e2e3fdc7 7411int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
37e84351 7412{
e2e3fdc7 7413 unsigned int nr_pages = folio_nr_pages(folio);
37e84351 7414 struct page_counter *counter;
38d8b4e6 7415 struct mem_cgroup *memcg;
37e84351
VD
7416 unsigned short oldid;
7417
2d1c4980 7418 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
37e84351
VD
7419 return 0;
7420
e2e3fdc7 7421 memcg = folio_memcg(folio);
37e84351 7422
e2e3fdc7 7423 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
37e84351
VD
7424 if (!memcg)
7425 return 0;
7426
f3a53a3a
TH
7427 if (!entry.val) {
7428 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
bb98f2c5 7429 return 0;
f3a53a3a 7430 }
bb98f2c5 7431
1f47b61f
VD
7432 memcg = mem_cgroup_id_get_online(memcg);
7433
c1b8fdae 7434 if (memcg_swap_enabled() && !mem_cgroup_is_root(memcg) &&
38d8b4e6 7435 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
f3a53a3a
TH
7436 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7437 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
1f47b61f 7438 mem_cgroup_id_put(memcg);
37e84351 7439 return -ENOMEM;
1f47b61f 7440 }
37e84351 7441
38d8b4e6
HY
7442 /* Get references for the tail pages, too */
7443 if (nr_pages > 1)
7444 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7445 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
e2e3fdc7 7446 VM_BUG_ON_FOLIO(oldid, folio);
c9019e9b 7447 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
37e84351 7448
37e84351
VD
7449 return 0;
7450}
7451
21afa38e 7452/**
01c4b28c 7453 * __mem_cgroup_uncharge_swap - uncharge swap space
21afa38e 7454 * @entry: swap entry to uncharge
38d8b4e6 7455 * @nr_pages: the amount of swap space to uncharge
21afa38e 7456 */
01c4b28c 7457void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
21afa38e
JW
7458{
7459 struct mem_cgroup *memcg;
7460 unsigned short id;
7461
c91bdc93
JW
7462 if (mem_cgroup_disabled())
7463 return;
7464
38d8b4e6 7465 id = swap_cgroup_record(entry, 0, nr_pages);
21afa38e 7466 rcu_read_lock();
adbe427b 7467 memcg = mem_cgroup_from_id(id);
21afa38e 7468 if (memcg) {
c1b8fdae 7469 if (memcg_swap_enabled() && !mem_cgroup_is_root(memcg)) {
37e84351 7470 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
38d8b4e6 7471 page_counter_uncharge(&memcg->swap, nr_pages);
37e84351 7472 else
38d8b4e6 7473 page_counter_uncharge(&memcg->memsw, nr_pages);
37e84351 7474 }
c9019e9b 7475 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
38d8b4e6 7476 mem_cgroup_id_put_many(memcg, nr_pages);
21afa38e
JW
7477 }
7478 rcu_read_unlock();
7479}
7480
d8b38438
VD
7481long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7482{
7483 long nr_swap_pages = get_nr_swap_pages();
7484
c1b8fdae 7485 if (!memcg_swap_enabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
d8b38438
VD
7486 return nr_swap_pages;
7487 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7488 nr_swap_pages = min_t(long, nr_swap_pages,
bbec2e15 7489 READ_ONCE(memcg->swap.max) -
d8b38438
VD
7490 page_counter_read(&memcg->swap));
7491 return nr_swap_pages;
7492}
7493
9202d527 7494bool mem_cgroup_swap_full(struct folio *folio)
5ccc5aba
VD
7495{
7496 struct mem_cgroup *memcg;
7497
9202d527 7498 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5ccc5aba
VD
7499
7500 if (vm_swap_full())
7501 return true;
c1b8fdae 7502 if (!memcg_swap_enabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5ccc5aba
VD
7503 return false;
7504
9202d527 7505 memcg = folio_memcg(folio);
5ccc5aba
VD
7506 if (!memcg)
7507 return false;
7508
4b82ab4f
JK
7509 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7510 unsigned long usage = page_counter_read(&memcg->swap);
7511
7512 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7513 usage * 2 >= READ_ONCE(memcg->swap.max))
5ccc5aba 7514 return true;
4b82ab4f 7515 }
5ccc5aba
VD
7516
7517 return false;
7518}
7519
eccb52e7 7520static int __init setup_swap_account(char *s)
21afa38e 7521{
4988fe69
LS
7522 bool res;
7523
7524 if (!kstrtobool(s, &res))
7525 cgroup_memory_noswap = !res;
21afa38e
JW
7526 return 1;
7527}
eccb52e7 7528__setup("swapaccount=", setup_swap_account);
21afa38e 7529
37e84351
VD
7530static u64 swap_current_read(struct cgroup_subsys_state *css,
7531 struct cftype *cft)
7532{
7533 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7534
7535 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7536}
7537
4b82ab4f
JK
7538static int swap_high_show(struct seq_file *m, void *v)
7539{
7540 return seq_puts_memcg_tunable(m,
7541 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7542}
7543
7544static ssize_t swap_high_write(struct kernfs_open_file *of,
7545 char *buf, size_t nbytes, loff_t off)
7546{
7547 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7548 unsigned long high;
7549 int err;
7550
7551 buf = strstrip(buf);
7552 err = page_counter_memparse(buf, "max", &high);
7553 if (err)
7554 return err;
7555
7556 page_counter_set_high(&memcg->swap, high);
7557
7558 return nbytes;
7559}
7560
37e84351
VD
7561static int swap_max_show(struct seq_file *m, void *v)
7562{
677dc973
CD
7563 return seq_puts_memcg_tunable(m,
7564 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
37e84351
VD
7565}
7566
7567static ssize_t swap_max_write(struct kernfs_open_file *of,
7568 char *buf, size_t nbytes, loff_t off)
7569{
7570 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7571 unsigned long max;
7572 int err;
7573
7574 buf = strstrip(buf);
7575 err = page_counter_memparse(buf, "max", &max);
7576 if (err)
7577 return err;
7578
be09102b 7579 xchg(&memcg->swap.max, max);
37e84351
VD
7580
7581 return nbytes;
7582}
7583
f3a53a3a
TH
7584static int swap_events_show(struct seq_file *m, void *v)
7585{
aa9694bb 7586 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
f3a53a3a 7587
4b82ab4f
JK
7588 seq_printf(m, "high %lu\n",
7589 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
f3a53a3a
TH
7590 seq_printf(m, "max %lu\n",
7591 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7592 seq_printf(m, "fail %lu\n",
7593 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7594
7595 return 0;
7596}
7597
37e84351
VD
7598static struct cftype swap_files[] = {
7599 {
7600 .name = "swap.current",
7601 .flags = CFTYPE_NOT_ON_ROOT,
7602 .read_u64 = swap_current_read,
7603 },
4b82ab4f
JK
7604 {
7605 .name = "swap.high",
7606 .flags = CFTYPE_NOT_ON_ROOT,
7607 .seq_show = swap_high_show,
7608 .write = swap_high_write,
7609 },
37e84351
VD
7610 {
7611 .name = "swap.max",
7612 .flags = CFTYPE_NOT_ON_ROOT,
7613 .seq_show = swap_max_show,
7614 .write = swap_max_write,
7615 },
f3a53a3a
TH
7616 {
7617 .name = "swap.events",
7618 .flags = CFTYPE_NOT_ON_ROOT,
7619 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7620 .seq_show = swap_events_show,
7621 },
37e84351
VD
7622 { } /* terminate */
7623};
7624
eccb52e7 7625static struct cftype memsw_files[] = {
21afa38e
JW
7626 {
7627 .name = "memsw.usage_in_bytes",
7628 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7629 .read_u64 = mem_cgroup_read_u64,
7630 },
7631 {
7632 .name = "memsw.max_usage_in_bytes",
7633 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7634 .write = mem_cgroup_reset,
7635 .read_u64 = mem_cgroup_read_u64,
7636 },
7637 {
7638 .name = "memsw.limit_in_bytes",
7639 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7640 .write = mem_cgroup_write,
7641 .read_u64 = mem_cgroup_read_u64,
7642 },
7643 {
7644 .name = "memsw.failcnt",
7645 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7646 .write = mem_cgroup_reset,
7647 .read_u64 = mem_cgroup_read_u64,
7648 },
7649 { }, /* terminate */
7650};
7651
f4840ccf
JW
7652#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7653/**
7654 * obj_cgroup_may_zswap - check if this cgroup can zswap
7655 * @objcg: the object cgroup
7656 *
7657 * Check if the hierarchical zswap limit has been reached.
7658 *
7659 * This doesn't check for specific headroom, and it is not atomic
7660 * either. But with zswap, the size of the allocation is only known
7661 * once compression has occured, and this optimistic pre-check avoids
7662 * spending cycles on compression when there is already no room left
7663 * or zswap is disabled altogether somewhere in the hierarchy.
7664 */
7665bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
7666{
7667 struct mem_cgroup *memcg, *original_memcg;
7668 bool ret = true;
7669
7670 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7671 return true;
7672
7673 original_memcg = get_mem_cgroup_from_objcg(objcg);
7674 for (memcg = original_memcg; memcg != root_mem_cgroup;
7675 memcg = parent_mem_cgroup(memcg)) {
7676 unsigned long max = READ_ONCE(memcg->zswap_max);
7677 unsigned long pages;
7678
7679 if (max == PAGE_COUNTER_MAX)
7680 continue;
7681 if (max == 0) {
7682 ret = false;
7683 break;
7684 }
7685
7686 cgroup_rstat_flush(memcg->css.cgroup);
7687 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
7688 if (pages < max)
7689 continue;
7690 ret = false;
7691 break;
7692 }
7693 mem_cgroup_put(original_memcg);
7694 return ret;
7695}
7696
7697/**
7698 * obj_cgroup_charge_zswap - charge compression backend memory
7699 * @objcg: the object cgroup
7700 * @size: size of compressed object
7701 *
7702 * This forces the charge after obj_cgroup_may_swap() allowed
7703 * compression and storage in zwap for this cgroup to go ahead.
7704 */
7705void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
7706{
7707 struct mem_cgroup *memcg;
7708
7709 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7710 return;
7711
7712 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
7713
7714 /* PF_MEMALLOC context, charging must succeed */
7715 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
7716 VM_WARN_ON_ONCE(1);
7717
7718 rcu_read_lock();
7719 memcg = obj_cgroup_memcg(objcg);
7720 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
7721 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
7722 rcu_read_unlock();
7723}
7724
7725/**
7726 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
7727 * @objcg: the object cgroup
7728 * @size: size of compressed object
7729 *
7730 * Uncharges zswap memory on page in.
7731 */
7732void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
7733{
7734 struct mem_cgroup *memcg;
7735
7736 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
7737 return;
7738
7739 obj_cgroup_uncharge(objcg, size);
7740
7741 rcu_read_lock();
7742 memcg = obj_cgroup_memcg(objcg);
7743 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
7744 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
7745 rcu_read_unlock();
7746}
7747
7748static u64 zswap_current_read(struct cgroup_subsys_state *css,
7749 struct cftype *cft)
7750{
7751 cgroup_rstat_flush(css->cgroup);
7752 return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
7753}
7754
7755static int zswap_max_show(struct seq_file *m, void *v)
7756{
7757 return seq_puts_memcg_tunable(m,
7758 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
7759}
7760
7761static ssize_t zswap_max_write(struct kernfs_open_file *of,
7762 char *buf, size_t nbytes, loff_t off)
7763{
7764 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7765 unsigned long max;
7766 int err;
7767
7768 buf = strstrip(buf);
7769 err = page_counter_memparse(buf, "max", &max);
7770 if (err)
7771 return err;
7772
7773 xchg(&memcg->zswap_max, max);
7774
7775 return nbytes;
7776}
7777
7778static struct cftype zswap_files[] = {
7779 {
7780 .name = "zswap.current",
7781 .flags = CFTYPE_NOT_ON_ROOT,
7782 .read_u64 = zswap_current_read,
7783 },
7784 {
7785 .name = "zswap.max",
7786 .flags = CFTYPE_NOT_ON_ROOT,
7787 .seq_show = zswap_max_show,
7788 .write = zswap_max_write,
7789 },
7790 { } /* terminate */
7791};
7792#endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
7793
82ff165c
BS
7794/*
7795 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7796 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7797 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7798 * boot parameter. This may result in premature OOPS inside
7799 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7800 */
21afa38e
JW
7801static int __init mem_cgroup_swap_init(void)
7802{
2d1c4980
JW
7803 /* No memory control -> no swap control */
7804 if (mem_cgroup_disabled())
7805 cgroup_memory_noswap = true;
7806
7807 if (cgroup_memory_noswap)
eccb52e7
JW
7808 return 0;
7809
c1b8fdae
KS
7810 static_branch_enable(&memcg_swap_enabled_key);
7811
eccb52e7
JW
7812 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7813 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
f4840ccf
JW
7814#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
7815 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
7816#endif
21afa38e
JW
7817 return 0;
7818}
82ff165c 7819core_initcall(mem_cgroup_swap_init);
21afa38e
JW
7820
7821#endif /* CONFIG_MEMCG_SWAP */