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