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