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