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