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