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