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