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