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