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