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