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