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