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