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