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