Linux 6.17-rc6
[linux-2.6-block.git] / mm / memcontrol.c
CommitLineData
c942fddf 1// SPDX-License-Identifier: GPL-2.0-or-later
8cdea7c0
BS
2/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
78fb7466
PE
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
2e72b634
KS
10 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
7ae1e1d0
GC
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
1575e68b
JW
18 * Native page reclaim
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
6168d0da
AS
23 *
24 * Per memcg lru locking
25 * Copyright (C) 2020 Alibaba, Inc, Alex Shi
8cdea7c0
BS
26 */
27
c6f53ed8 28#include <linux/cgroup-defs.h>
3e32cb2e 29#include <linux/page_counter.h>
8cdea7c0
BS
30#include <linux/memcontrol.h>
31#include <linux/cgroup.h>
7d709f49 32#include <linux/cpuset.h>
6e84f315 33#include <linux/sched/mm.h>
3a4f8a0b 34#include <linux/shmem_fs.h>
4ffef5fe 35#include <linux/hugetlb.h>
d13d1443 36#include <linux/pagemap.h>
4882c809 37#include <linux/pagevec.h>
1ff9e6e1 38#include <linux/vm_event_item.h>
d52aa412 39#include <linux/smp.h>
8a9f3ccd 40#include <linux/page-flags.h>
66e1707b 41#include <linux/backing-dev.h>
8a9f3ccd
BS
42#include <linux/bit_spinlock.h>
43#include <linux/rcupdate.h>
e222432b 44#include <linux/limits.h>
b9e15baf 45#include <linux/export.h>
c6f53ed8 46#include <linux/list.h>
8c7c6e34 47#include <linux/mutex.h>
bb4cc1a8 48#include <linux/rbtree.h>
b6ac57d5 49#include <linux/slab.h>
02491447 50#include <linux/swapops.h>
66e1707b
BS
51#include <linux/spinlock.h>
52#include <linux/fs.h>
d2ceb9b7 53#include <linux/seq_file.h>
70ddf637 54#include <linux/vmpressure.h>
dc90f084 55#include <linux/memremap.h>
b69408e8 56#include <linux/mm_inline.h>
5d1ea48b 57#include <linux/swap_cgroup.h>
cdec2e42 58#include <linux/cpu.h>
158e0a2d 59#include <linux/oom.h>
0056f4e6 60#include <linux/lockdep.h>
03248add 61#include <linux/resume_user_mode.h>
0e4b01df 62#include <linux/psi.h>
c8713d0b 63#include <linux/seq_buf.h>
6a792697 64#include <linux/sched/isolation.h>
6011be59 65#include <linux/kmemleak.h>
08e552c6 66#include "internal.h"
d1a4c0b3 67#include <net/sock.h>
4bd2c1ee 68#include <net/ip.h>
f35c3a8e 69#include "slab.h"
d12f6d22 70#include "memcontrol-v1.h"
8cdea7c0 71
7c0f6ba6 72#include <linux/uaccess.h>
8697d331 73
0aa3ef36
SB
74#define CREATE_TRACE_POINTS
75#include <trace/events/memcg.h>
76#undef CREATE_TRACE_POINTS
77
cc8e970c
KM
78#include <trace/events/vmscan.h>
79
073219e9
TH
80struct cgroup_subsys memory_cgrp_subsys __read_mostly;
81EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 82
7d828602
JW
83struct mem_cgroup *root_mem_cgroup __read_mostly;
84
37d5985c
RG
85/* Active memory cgroup to use from an interrupt context */
86DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
c74d40e8 87EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
37d5985c 88
f7e1cb6e 89/* Socket memory accounting disabled? */
0f0cace3 90static bool cgroup_memory_nosocket __ro_after_init;
f7e1cb6e 91
04823c83 92/* Kernel memory accounting disabled? */
17c17367 93static bool cgroup_memory_nokmem __ro_after_init;
04823c83 94
b6c1a8af
YS
95/* BPF memory accounting disabled? */
96static bool cgroup_memory_nobpf __ro_after_init;
97
97e4fc4b 98static struct kmem_cache *memcg_cachep;
1b6a58e2 99static struct kmem_cache *memcg_pn_cachep;
97e4fc4b 100
97b27821
TH
101#ifdef CONFIG_CGROUP_WRITEBACK
102static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
103#endif
104
a4ebf1b6 105static inline bool task_is_dying(void)
7775face
TH
106{
107 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
108 (current->flags & PF_EXITING);
109}
110
70ddf637
AV
111/* Some nice accessors for the vmpressure. */
112struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
113{
114 if (!memcg)
115 memcg = root_mem_cgroup;
116 return &memcg->vmpressure;
117}
118
9647875b 119struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
70ddf637 120{
9647875b 121 return container_of(vmpr, struct mem_cgroup, vmpressure);
70ddf637
AV
122}
123
8717734f 124#define SEQ_BUF_SIZE SZ_4K
1aacbd35
RG
125#define CURRENT_OBJCG_UPDATE_BIT 0
126#define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
127
0764db9b 128static DEFINE_SPINLOCK(objcg_lock);
bf4f0599 129
4d5c8aed
RG
130bool mem_cgroup_kmem_disabled(void)
131{
132 return cgroup_memory_nokmem;
133}
134
b6d04711 135static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages);
c1a660de 136
bf4f0599
RG
137static void obj_cgroup_release(struct percpu_ref *ref)
138{
139 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
bf4f0599
RG
140 unsigned int nr_bytes;
141 unsigned int nr_pages;
142 unsigned long flags;
143
144 /*
145 * At this point all allocated objects are freed, and
146 * objcg->nr_charged_bytes can't have an arbitrary byte value.
147 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
148 *
149 * The following sequence can lead to it:
150 * 1) CPU0: objcg == stock->cached_objcg
151 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
152 * PAGE_SIZE bytes are charged
153 * 3) CPU1: a process from another memcg is allocating something,
154 * the stock if flushed,
155 * objcg->nr_charged_bytes = PAGE_SIZE - 92
156 * 5) CPU0: we do release this object,
157 * 92 bytes are added to stock->nr_bytes
158 * 6) CPU0: stock is flushed,
159 * 92 bytes are added to objcg->nr_charged_bytes
160 *
161 * In the result, nr_charged_bytes == PAGE_SIZE.
162 * This page will be uncharged in obj_cgroup_release().
163 */
164 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
165 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
166 nr_pages = nr_bytes >> PAGE_SHIFT;
167
b6d04711
SB
168 if (nr_pages) {
169 struct mem_cgroup *memcg;
170
171 memcg = get_mem_cgroup_from_objcg(objcg);
172 mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
173 memcg1_account_kmem(memcg, -nr_pages);
174 if (!mem_cgroup_is_root(memcg))
175 memcg_uncharge(memcg, nr_pages);
176 mem_cgroup_put(memcg);
177 }
271dd6b1 178
0764db9b 179 spin_lock_irqsave(&objcg_lock, flags);
bf4f0599 180 list_del(&objcg->list);
0764db9b 181 spin_unlock_irqrestore(&objcg_lock, flags);
bf4f0599
RG
182
183 percpu_ref_exit(ref);
184 kfree_rcu(objcg, rcu);
185}
186
187static struct obj_cgroup *obj_cgroup_alloc(void)
188{
189 struct obj_cgroup *objcg;
190 int ret;
191
192 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
193 if (!objcg)
194 return NULL;
195
196 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
197 GFP_KERNEL);
198 if (ret) {
199 kfree(objcg);
200 return NULL;
201 }
202 INIT_LIST_HEAD(&objcg->list);
203 return objcg;
204}
205
206static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
207 struct mem_cgroup *parent)
208{
209 struct obj_cgroup *objcg, *iter;
210
211 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
212
0764db9b 213 spin_lock_irq(&objcg_lock);
bf4f0599 214
9838354e
MS
215 /* 1) Ready to reparent active objcg. */
216 list_add(&objcg->list, &memcg->objcg_list);
217 /* 2) Reparent active objcg and already reparented objcgs to parent. */
218 list_for_each_entry(iter, &memcg->objcg_list, list)
219 WRITE_ONCE(iter->memcg, parent);
220 /* 3) Move already reparented objcgs to the parent's list */
bf4f0599
RG
221 list_splice(&memcg->objcg_list, &parent->objcg_list);
222
0764db9b 223 spin_unlock_irq(&objcg_lock);
bf4f0599
RG
224
225 percpu_ref_kill(&objcg->refcnt);
226}
227
d7f25f8a
GC
228/*
229 * A lot of the calls to the cache allocation functions are expected to be
9f9796b4 230 * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
d7f25f8a
GC
231 * conditional to this static branch, we'll have to allow modules that does
232 * kmem_cache_alloc and the such to see this symbol as well
233 */
f7a449f7
RG
234DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
235EXPORT_SYMBOL(memcg_kmem_online_key);
b6c1a8af
YS
236
237DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
238EXPORT_SYMBOL(memcg_bpf_enabled_key);
17cc4dfe 239
ad7fa852 240/**
75376c6f
MWO
241 * mem_cgroup_css_from_folio - css of the memcg associated with a folio
242 * @folio: folio of interest
ad7fa852
TH
243 *
244 * If memcg is bound to the default hierarchy, css of the memcg associated
75376c6f 245 * with @folio is returned. The returned css remains associated with @folio
ad7fa852
TH
246 * until it is released.
247 *
248 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
249 * is returned.
ad7fa852 250 */
75376c6f 251struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
ad7fa852 252{
75376c6f 253 struct mem_cgroup *memcg = folio_memcg(folio);
ad7fa852 254
9e10a130 255 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
ad7fa852
TH
256 memcg = root_mem_cgroup;
257
ad7fa852
TH
258 return &memcg->css;
259}
260
2fc04524
VD
261/**
262 * page_cgroup_ino - return inode number of the memcg a page is charged to
263 * @page: the page
264 *
265 * Look up the closest online ancestor of the memory cgroup @page is charged to
266 * and return its inode number or 0 if @page is not charged to any cgroup. It
267 * is safe to call this function without holding a reference to @page.
268 *
269 * Note, this function is inherently racy, because there is nothing to prevent
270 * the cgroup inode from getting torn down and potentially reallocated a moment
271 * after page_cgroup_ino() returns, so it only should be used by callers that
272 * do not care (such as procfs interfaces).
273 */
274ino_t page_cgroup_ino(struct page *page)
275{
276 struct mem_cgroup *memcg;
277 unsigned long ino = 0;
278
279 rcu_read_lock();
ec342603
YA
280 /* page_folio() is racy here, but the entire function is racy anyway */
281 memcg = folio_memcg_check(page_folio(page));
286e04b8 282
2fc04524
VD
283 while (memcg && !(memcg->css.flags & CSS_ONLINE))
284 memcg = parent_mem_cgroup(memcg);
285 if (memcg)
286 ino = cgroup_ino(memcg->css.cgroup);
287 rcu_read_unlock();
288 return ino;
289}
290
ff48c71c
SB
291/* Subset of node_stat_item for memcg stats */
292static const unsigned int memcg_node_stat_items[] = {
293 NR_INACTIVE_ANON,
294 NR_ACTIVE_ANON,
295 NR_INACTIVE_FILE,
296 NR_ACTIVE_FILE,
297 NR_UNEVICTABLE,
298 NR_SLAB_RECLAIMABLE_B,
299 NR_SLAB_UNRECLAIMABLE_B,
300 WORKINGSET_REFAULT_ANON,
301 WORKINGSET_REFAULT_FILE,
302 WORKINGSET_ACTIVATE_ANON,
303 WORKINGSET_ACTIVATE_FILE,
304 WORKINGSET_RESTORE_ANON,
305 WORKINGSET_RESTORE_FILE,
306 WORKINGSET_NODERECLAIM,
307 NR_ANON_MAPPED,
308 NR_FILE_MAPPED,
309 NR_FILE_PAGES,
310 NR_FILE_DIRTY,
311 NR_WRITEBACK,
312 NR_SHMEM,
313 NR_SHMEM_THPS,
314 NR_FILE_THPS,
315 NR_ANON_THPS,
316 NR_KERNEL_STACK_KB,
317 NR_PAGETABLE,
318 NR_SECONDARY_PAGETABLE,
319#ifdef CONFIG_SWAP
320 NR_SWAPCACHE,
321#endif
f77f0c75
KZ
322#ifdef CONFIG_NUMA_BALANCING
323 PGPROMOTE_SUCCESS,
324#endif
325 PGDEMOTE_KSWAPD,
326 PGDEMOTE_DIRECT,
327 PGDEMOTE_KHUGEPAGED,
e452872b 328 PGDEMOTE_PROACTIVE,
05d4532b
JH
329#ifdef CONFIG_HUGETLB_PAGE
330 NR_HUGETLB,
331#endif
ff48c71c
SB
332};
333
334static const unsigned int memcg_stat_items[] = {
335 MEMCG_SWAP,
336 MEMCG_SOCK,
337 MEMCG_PERCPU_B,
338 MEMCG_VMALLOC,
339 MEMCG_KMEM,
340 MEMCG_ZSWAP_B,
341 MEMCG_ZSWAPPED,
342};
343
344#define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
345#define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
346 ARRAY_SIZE(memcg_stat_items))
9db298a4
SB
347#define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
348static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
ff48c71c
SB
349
350static void init_memcg_stats(void)
351{
9db298a4 352 u8 i, j = 0;
ff48c71c 353
9db298a4 354 BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
ff48c71c 355
9db298a4 356 memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
ff48c71c 357
9db298a4
SB
358 for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
359 mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
ff48c71c 360
9db298a4
SB
361 for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
362 mem_cgroup_stats_index[memcg_stat_items[i]] = j;
ff48c71c
SB
363}
364
365static inline int memcg_stats_index(int idx)
366{
9db298a4 367 return mem_cgroup_stats_index[idx];
ff48c71c
SB
368}
369
70a64b79
SB
370struct lruvec_stats_percpu {
371 /* Local (CPU and cgroup) state */
ff48c71c 372 long state[NR_MEMCG_NODE_STAT_ITEMS];
70a64b79
SB
373
374 /* Delta calculation for lockless upward propagation */
ff48c71c 375 long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
70a64b79
SB
376};
377
378struct lruvec_stats {
379 /* Aggregated (CPU and subtree) state */
ff48c71c 380 long state[NR_MEMCG_NODE_STAT_ITEMS];
70a64b79
SB
381
382 /* Non-hierarchical (CPU aggregated) state */
ff48c71c 383 long state_local[NR_MEMCG_NODE_STAT_ITEMS];
70a64b79
SB
384
385 /* Pending child counts during tree propagation */
ff48c71c 386 long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
70a64b79
SB
387};
388
389unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
390{
391 struct mem_cgroup_per_node *pn;
392 long x;
ff48c71c 393 int i;
70a64b79
SB
394
395 if (mem_cgroup_disabled())
396 return node_page_state(lruvec_pgdat(lruvec), idx);
397
ff48c71c 398 i = memcg_stats_index(idx);
9db298a4 399 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
ff48c71c
SB
400 return 0;
401
70a64b79 402 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
ff48c71c 403 x = READ_ONCE(pn->lruvec_stats->state[i]);
70a64b79
SB
404#ifdef CONFIG_SMP
405 if (x < 0)
406 x = 0;
407#endif
408 return x;
409}
410
411unsigned long lruvec_page_state_local(struct lruvec *lruvec,
412 enum node_stat_item idx)
413{
414 struct mem_cgroup_per_node *pn;
acb5fe2f 415 long x;
ff48c71c 416 int i;
70a64b79
SB
417
418 if (mem_cgroup_disabled())
419 return node_page_state(lruvec_pgdat(lruvec), idx);
420
ff48c71c 421 i = memcg_stats_index(idx);
9db298a4 422 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
ff48c71c
SB
423 return 0;
424
70a64b79 425 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
ff48c71c 426 x = READ_ONCE(pn->lruvec_stats->state_local[i]);
70a64b79
SB
427#ifdef CONFIG_SMP
428 if (x < 0)
429 x = 0;
430#endif
431 return x;
432}
433
d396def5
SB
434/* Subset of vm_event_item to report for memcg event stats */
435static const unsigned int memcg_vm_event_stat[] = {
98455eef 436#ifdef CONFIG_MEMCG_V1
8278f1c7
SB
437 PGPGIN,
438 PGPGOUT,
98455eef 439#endif
15ff4d40
JZ
440 PSWPIN,
441 PSWPOUT,
d396def5
SB
442 PGSCAN_KSWAPD,
443 PGSCAN_DIRECT,
57e9cc50 444 PGSCAN_KHUGEPAGED,
e452872b 445 PGSCAN_PROACTIVE,
d396def5
SB
446 PGSTEAL_KSWAPD,
447 PGSTEAL_DIRECT,
57e9cc50 448 PGSTEAL_KHUGEPAGED,
e452872b 449 PGSTEAL_PROACTIVE,
d396def5
SB
450 PGFAULT,
451 PGMAJFAULT,
452 PGREFILL,
453 PGACTIVATE,
454 PGDEACTIVATE,
455 PGLAZYFREE,
456 PGLAZYFREED,
e7ac4dae
BS
457#ifdef CONFIG_SWAP
458 SWPIN_ZERO,
459 SWPOUT_ZERO,
460#endif
3a3b7fec 461#ifdef CONFIG_ZSWAP
d396def5
SB
462 ZSWPIN,
463 ZSWPOUT,
e0bf1dc8 464 ZSWPWB,
d396def5
SB
465#endif
466#ifdef CONFIG_TRANSPARENT_HUGEPAGE
467 THP_FAULT_ALLOC,
468 THP_COLLAPSE_ALLOC,
811244a5
XH
469 THP_SWPOUT,
470 THP_SWPOUT_FALLBACK,
d396def5 471#endif
f77f0c75
KZ
472#ifdef CONFIG_NUMA_BALANCING
473 NUMA_PAGE_MIGRATE,
474 NUMA_PTE_UPDATES,
475 NUMA_HINT_FAULTS,
476#endif
d396def5
SB
477};
478
8278f1c7 479#define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
9db298a4 480static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
8278f1c7
SB
481
482static void init_memcg_events(void)
483{
9db298a4 484 u8 i;
59142d87 485
9db298a4 486 BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
59142d87 487
9db298a4
SB
488 memset(mem_cgroup_events_index, U8_MAX,
489 sizeof(mem_cgroup_events_index));
8278f1c7
SB
490
491 for (i = 0; i < NR_MEMCG_EVENTS; ++i)
9db298a4 492 mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
8278f1c7
SB
493}
494
495static inline int memcg_events_index(enum vm_event_item idx)
496{
9db298a4 497 return mem_cgroup_events_index[idx];
8278f1c7
SB
498}
499
410f8e82 500struct memcg_vmstats_percpu {
9cee7e8e
YA
501 /* Stats updates since the last flush */
502 unsigned int stats_updates;
503
504 /* Cached pointers for fast iteration in memcg_rstat_updated() */
8a4b42b9
SB
505 struct memcg_vmstats_percpu __percpu *parent_pcpu;
506 struct memcg_vmstats *vmstats;
9cee7e8e
YA
507
508 /* The above should fit a single cacheline for memcg_rstat_updated() */
509
410f8e82 510 /* Local (CPU and cgroup) page state & events */
ff48c71c 511 long state[MEMCG_VMSTAT_SIZE];
8278f1c7 512 unsigned long events[NR_MEMCG_EVENTS];
410f8e82
SB
513
514 /* Delta calculation for lockless upward propagation */
ff48c71c 515 long state_prev[MEMCG_VMSTAT_SIZE];
8278f1c7 516 unsigned long events_prev[NR_MEMCG_EVENTS];
9cee7e8e 517} ____cacheline_aligned;
410f8e82
SB
518
519struct memcg_vmstats {
520 /* Aggregated (CPU and subtree) page state & events */
ff48c71c 521 long state[MEMCG_VMSTAT_SIZE];
8278f1c7 522 unsigned long events[NR_MEMCG_EVENTS];
410f8e82 523
f82e6bf9 524 /* Non-hierarchical (CPU aggregated) page state & events */
ff48c71c 525 long state_local[MEMCG_VMSTAT_SIZE];
f82e6bf9
YA
526 unsigned long events_local[NR_MEMCG_EVENTS];
527
410f8e82 528 /* Pending child counts during tree propagation */
ff48c71c 529 long state_pending[MEMCG_VMSTAT_SIZE];
8278f1c7 530 unsigned long events_pending[NR_MEMCG_EVENTS];
8d59d221
YA
531
532 /* Stats updates since the last flush */
3ac4638a 533 atomic_t stats_updates;
410f8e82
SB
534};
535
11192d9c
SB
536/*
537 * memcg and lruvec stats flushing
538 *
539 * Many codepaths leading to stats update or read are performance sensitive and
540 * adding stats flushing in such codepaths is not desirable. So, to optimize the
541 * flushing the kernel does:
542 *
543 * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
544 * rstat update tree grow unbounded.
545 *
546 * 2) Flush the stats synchronously on reader side only when there are more than
547 * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
548 * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
549 * only for 2 seconds due to (1).
550 */
551static void flush_memcg_stats_dwork(struct work_struct *w);
552static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
508bed88 553static u64 flush_last_time;
9b301615
SB
554
555#define FLUSH_TIME (2UL*HZ)
11192d9c 556
9cee7e8e 557static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
8d59d221 558{
3ac4638a 559 return atomic_read(&vmstats->stats_updates) >
8d59d221
YA
560 MEMCG_CHARGE_BATCH * num_online_cpus();
561}
562
c7163535
SB
563static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val,
564 int cpu)
11192d9c 565{
8a4b42b9 566 struct memcg_vmstats_percpu __percpu *statc_pcpu;
9cee7e8e 567 struct memcg_vmstats_percpu *statc;
78ec6f9d 568 unsigned int stats_updates;
5b3be698 569
f9d911ca
YA
570 if (!val)
571 return;
572
8dcb0ed8 573 css_rstat_updated(&memcg->css, cpu);
8a4b42b9
SB
574 statc_pcpu = memcg->vmstats_percpu;
575 for (; statc_pcpu; statc_pcpu = statc->parent_pcpu) {
576 statc = this_cpu_ptr(statc_pcpu);
60cada25
SB
577 /*
578 * If @memcg is already flushable then all its ancestors are
579 * flushable as well and also there is no need to increase
580 * stats_updates.
581 */
582 if (memcg_vmstats_needs_flush(statc->vmstats))
583 break;
584
8a4b42b9
SB
585 stats_updates = this_cpu_add_return(statc_pcpu->stats_updates,
586 abs(val));
78ec6f9d 587 if (stats_updates < MEMCG_CHARGE_BATCH)
8d59d221 588 continue;
5b3be698 589
8a4b42b9 590 stats_updates = this_cpu_xchg(statc_pcpu->stats_updates, 0);
3ac4638a 591 atomic_add(stats_updates, &statc->vmstats->stats_updates);
5b3be698 592 }
11192d9c
SB
593}
594
e1479b88 595static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force)
11192d9c 596{
f914ac96
JK
597 bool needs_flush = memcg_vmstats_needs_flush(memcg->vmstats);
598
3ac4638a 599 trace_memcg_flush_stats(memcg, atomic_read(&memcg->vmstats->stats_updates),
f914ac96
JK
600 force, needs_flush);
601
602 if (!force && !needs_flush)
e1479b88
JK
603 return;
604
7d7ef0a4
YA
605 if (mem_cgroup_is_root(memcg))
606 WRITE_ONCE(flush_last_time, jiffies_64);
9fad9aee 607
a9791555 608 css_rstat_flush(&memcg->css);
11192d9c
SB
609}
610
7d7ef0a4
YA
611/*
612 * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
613 * @memcg: root of the subtree to flush
614 *
615 * Flushing is serialized by the underlying global rstat lock. There is also a
616 * minimum amount of work to be done even if there are no stat updates to flush.
617 * Hence, we only flush the stats if the updates delta exceeds a threshold. This
618 * avoids unnecessary work and contention on the underlying lock.
619 */
620void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
11192d9c 621{
7d7ef0a4
YA
622 if (mem_cgroup_disabled())
623 return;
624
625 if (!memcg)
626 memcg = root_mem_cgroup;
627
e1479b88 628 __mem_cgroup_flush_stats(memcg, false);
9fad9aee
YA
629}
630
7d7ef0a4 631void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
9b301615 632{
508bed88
YA
633 /* Only flush if the periodic flusher is one full cycle late */
634 if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
7d7ef0a4 635 mem_cgroup_flush_stats(memcg);
9b301615
SB
636}
637
11192d9c
SB
638static void flush_memcg_stats_dwork(struct work_struct *w)
639{
9fad9aee 640 /*
9cee7e8e 641 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
8d59d221 642 * in latency-sensitive paths is as cheap as possible.
9fad9aee 643 */
e1479b88 644 __mem_cgroup_flush_stats(root_mem_cgroup, true);
9b301615 645 queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
11192d9c
SB
646}
647
410f8e82
SB
648unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
649{
ff48c71c
SB
650 long x;
651 int i = memcg_stats_index(idx);
652
9db298a4 653 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
ff48c71c
SB
654 return 0;
655
656 x = READ_ONCE(memcg->vmstats->state[i]);
410f8e82
SB
657#ifdef CONFIG_SMP
658 if (x < 0)
659 x = 0;
660#endif
661 return x;
662}
663
7bd5bc3c
YA
664static int memcg_page_state_unit(int item);
665
666/*
667 * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
668 * up non-zero sub-page updates to 1 page as zero page updates are ignored.
669 */
670static int memcg_state_val_in_pages(int idx, int val)
671{
672 int unit = memcg_page_state_unit(idx);
673
674 if (!val || unit == PAGE_SIZE)
675 return val;
676 else
677 return max(val * unit / PAGE_SIZE, 1UL);
678}
679
db9adbcb 680/**
8814e3b8 681 * mod_memcg_state - update cgroup memory statistics
db9adbcb
JW
682 * @memcg: the memory cgroup
683 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
684 * @val: delta to add to the counter, can be negative
685 */
8814e3b8 686void mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
a94032b3 687 int val)
db9adbcb 688{
ff48c71c 689 int i = memcg_stats_index(idx);
c7163535 690 int cpu;
ff48c71c 691
acb5fe2f
SB
692 if (mem_cgroup_disabled())
693 return;
694
9db298a4 695 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
db9adbcb
JW
696 return;
697
c7163535
SB
698 cpu = get_cpu();
699
8814e3b8 700 this_cpu_add(memcg->vmstats_percpu->state[i], val);
0aa3ef36 701 val = memcg_state_val_in_pages(idx, val);
c7163535 702 memcg_rstat_updated(memcg, val, cpu);
0aa3ef36 703 trace_mod_memcg_state(memcg, idx, val);
c7163535
SB
704
705 put_cpu();
db9adbcb
JW
706}
707
610dc18c 708#ifdef CONFIG_MEMCG_V1
2d146aa3 709/* idx can be of type enum memcg_stat_item or node_stat_item. */
ea1e8796 710unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
a18e6e6e 711{
ff48c71c
SB
712 long x;
713 int i = memcg_stats_index(idx);
714
9db298a4 715 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
ff48c71c 716 return 0;
a18e6e6e 717
ff48c71c 718 x = READ_ONCE(memcg->vmstats->state_local[i]);
a18e6e6e
JW
719#ifdef CONFIG_SMP
720 if (x < 0)
721 x = 0;
722#endif
723 return x;
724}
610dc18c 725#endif
a18e6e6e 726
eee8a177 727static void mod_memcg_lruvec_state(struct lruvec *lruvec,
91882c16
SB
728 enum node_stat_item idx,
729 int val)
db9adbcb
JW
730{
731 struct mem_cgroup_per_node *pn;
42a30035 732 struct mem_cgroup *memcg;
ff48c71c 733 int i = memcg_stats_index(idx);
c7163535 734 int cpu;
ff48c71c 735
9db298a4 736 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
ff48c71c 737 return;
db9adbcb 738
db9adbcb 739 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
42a30035 740 memcg = pn->memcg;
db9adbcb 741
c7163535 742 cpu = get_cpu();
be3e67b5 743
db9adbcb 744 /* Update memcg */
eee8a177 745 this_cpu_add(memcg->vmstats_percpu->state[i], val);
db9adbcb 746
b4c46484 747 /* Update lruvec */
eee8a177 748 this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
11192d9c 749
0aa3ef36 750 val = memcg_state_val_in_pages(idx, val);
c7163535 751 memcg_rstat_updated(memcg, val, cpu);
0aa3ef36 752 trace_mod_memcg_lruvec_state(memcg, idx, val);
c7163535
SB
753
754 put_cpu();
db9adbcb
JW
755}
756
eedc4e5a
RG
757/**
758 * __mod_lruvec_state - update lruvec memory statistics
759 * @lruvec: the lruvec
760 * @idx: the stat item
761 * @val: delta to add to the counter, can be negative
762 *
763 * The lruvec is the intersection of the NUMA node and a cgroup. This
764 * function updates the all three counters that are affected by a
765 * change of state at this level: per-node, per-cgroup, per-lruvec.
766 */
767void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
768 int val)
769{
770 /* Update node */
771 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
772
773 /* Update memcg and lruvec */
774 if (!mem_cgroup_disabled())
eee8a177 775 mod_memcg_lruvec_state(lruvec, idx, val);
eedc4e5a
RG
776}
777
c701123b 778void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
c47d5032
SB
779 int val)
780{
b4e0b68f 781 struct mem_cgroup *memcg;
c701123b 782 pg_data_t *pgdat = folio_pgdat(folio);
c47d5032
SB
783 struct lruvec *lruvec;
784
b4e0b68f 785 rcu_read_lock();
c701123b 786 memcg = folio_memcg(folio);
c47d5032 787 /* Untracked pages have no memcg, no lruvec. Update only the node */
d635a69d 788 if (!memcg) {
b4e0b68f 789 rcu_read_unlock();
c47d5032
SB
790 __mod_node_page_state(pgdat, idx, val);
791 return;
792 }
793
d635a69d 794 lruvec = mem_cgroup_lruvec(memcg, pgdat);
c47d5032 795 __mod_lruvec_state(lruvec, idx, val);
b4e0b68f 796 rcu_read_unlock();
c47d5032 797}
c701123b 798EXPORT_SYMBOL(__lruvec_stat_mod_folio);
c47d5032 799
da3ceeff 800void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
ec9f0238 801{
4f103c63 802 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
ec9f0238
RG
803 struct mem_cgroup *memcg;
804 struct lruvec *lruvec;
805
806 rcu_read_lock();
fc4db90f 807 memcg = mem_cgroup_from_slab_obj(p);
ec9f0238 808
8faeb1ff
MS
809 /*
810 * Untracked pages have no memcg, no lruvec. Update only the
811 * node. If we reparent the slab objects to the root memcg,
812 * when we free the slab object, we need to update the per-memcg
813 * vmstats to keep it correct for the root memcg.
814 */
815 if (!memcg) {
ec9f0238
RG
816 __mod_node_page_state(pgdat, idx, val);
817 } else {
867e5e1d 818 lruvec = mem_cgroup_lruvec(memcg, pgdat);
ec9f0238
RG
819 __mod_lruvec_state(lruvec, idx, val);
820 }
821 rcu_read_unlock();
822}
823
db9adbcb 824/**
e52401e7 825 * count_memcg_events - account VM events in a cgroup
db9adbcb
JW
826 * @memcg: the memory cgroup
827 * @idx: the event item
f0953a1b 828 * @count: the number of events that occurred
db9adbcb 829 */
e52401e7 830void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
db9adbcb
JW
831 unsigned long count)
832{
acb5fe2f 833 int i = memcg_events_index(idx);
c7163535 834 int cpu;
8278f1c7 835
acb5fe2f
SB
836 if (mem_cgroup_disabled())
837 return;
838
9db298a4 839 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
db9adbcb
JW
840 return;
841
c7163535
SB
842 cpu = get_cpu();
843
e52401e7 844 this_cpu_add(memcg->vmstats_percpu->events[i], count);
c7163535 845 memcg_rstat_updated(memcg, count, cpu);
0aa3ef36 846 trace_count_memcg_events(memcg, idx, count);
c7163535
SB
847
848 put_cpu();
db9adbcb
JW
849}
850
ea1e8796 851unsigned long memcg_events(struct mem_cgroup *memcg, int event)
e9f8974f 852{
acb5fe2f 853 int i = memcg_events_index(event);
8278f1c7 854
9db298a4 855 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
8278f1c7 856 return 0;
acb5fe2f
SB
857
858 return READ_ONCE(memcg->vmstats->events[i]);
e9f8974f
JW
859}
860
610dc18c 861#ifdef CONFIG_MEMCG_V1
ea1e8796 862unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
42a30035 863{
acb5fe2f 864 int i = memcg_events_index(event);
8278f1c7 865
9db298a4 866 if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
8278f1c7 867 return 0;
815744d7 868
acb5fe2f 869 return READ_ONCE(memcg->vmstats->events_local[i]);
42a30035 870}
610dc18c 871#endif
42a30035 872
cf475ad2 873struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 874{
31a78f23
BS
875 /*
876 * mm_update_next_owner() may clear mm->owner to NULL
877 * if it races with swapoff, page migration, etc.
878 * So this can be called with p == NULL.
879 */
880 if (unlikely(!p))
881 return NULL;
882
073219e9 883 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466 884}
33398cf2 885EXPORT_SYMBOL(mem_cgroup_from_task);
78fb7466 886
04f94e3f
DS
887static __always_inline struct mem_cgroup *active_memcg(void)
888{
55a68c82 889 if (!in_task())
04f94e3f
DS
890 return this_cpu_read(int_active_memcg);
891 else
892 return current->active_memcg;
893}
894
d46eb14b
SB
895/**
896 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
897 * @mm: mm from which memcg should be extracted. It can be NULL.
898 *
04f94e3f
DS
899 * Obtain a reference on mm->memcg and returns it if successful. If mm
900 * is NULL, then the memcg is chosen as follows:
901 * 1) The active memcg, if set.
902 * 2) current->mm->memcg, if available
903 * 3) root memcg
904 * If mem_cgroup is disabled, NULL is returned.
d46eb14b
SB
905 */
906struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 907{
d46eb14b
SB
908 struct mem_cgroup *memcg;
909
910 if (mem_cgroup_disabled())
911 return NULL;
0b7f569e 912
2884b6b7
MS
913 /*
914 * Page cache insertions can happen without an
915 * actual mm context, e.g. during disk probing
916 * on boot, loopback IO, acct() writes etc.
917 *
918 * No need to css_get on root memcg as the reference
919 * counting is disabled on the root level in the
920 * cgroup core. See CSS_NO_REF.
921 */
04f94e3f
DS
922 if (unlikely(!mm)) {
923 memcg = active_memcg();
924 if (unlikely(memcg)) {
925 /* remote memcg must hold a ref */
926 css_get(&memcg->css);
927 return memcg;
928 }
929 mm = current->mm;
930 if (unlikely(!mm))
931 return root_mem_cgroup;
932 }
2884b6b7 933
54595fe2
KH
934 rcu_read_lock();
935 do {
2884b6b7
MS
936 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
937 if (unlikely(!memcg))
df381975 938 memcg = root_mem_cgroup;
00d484f3 939 } while (!css_tryget(&memcg->css));
54595fe2 940 rcu_read_unlock();
c0ff4b85 941 return memcg;
54595fe2 942}
d46eb14b
SB
943EXPORT_SYMBOL(get_mem_cgroup_from_mm);
944
4b569387
NP
945/**
946 * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
947 */
948struct mem_cgroup *get_mem_cgroup_from_current(void)
949{
950 struct mem_cgroup *memcg;
951
952 if (mem_cgroup_disabled())
953 return NULL;
954
955again:
956 rcu_read_lock();
957 memcg = mem_cgroup_from_task(current);
958 if (!css_tryget(&memcg->css)) {
959 rcu_read_unlock();
960 goto again;
961 }
962 rcu_read_unlock();
963 return memcg;
964}
965
f77f0c75
KZ
966/**
967 * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg.
968 * @folio: folio from which memcg should be extracted.
969 */
970struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
971{
972 struct mem_cgroup *memcg = folio_memcg(folio);
973
974 if (mem_cgroup_disabled())
975 return NULL;
976
977 rcu_read_lock();
978 if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
979 memcg = root_mem_cgroup;
980 rcu_read_unlock();
981 return memcg;
982}
983
5660048c
JW
984/**
985 * mem_cgroup_iter - iterate over memory cgroup hierarchy
986 * @root: hierarchy root
987 * @prev: previously returned memcg, NULL on first invocation
988 * @reclaim: cookie for shared reclaim walks, NULL for full walks
989 *
990 * Returns references to children of the hierarchy below @root, or
991 * @root itself, or %NULL after a full round-trip.
992 *
993 * Caller must pass the return value in @prev on subsequent
994 * invocations for reference counting, or use mem_cgroup_iter_break()
995 * to cancel a hierarchy walk before the round-trip is complete.
996 *
05bdc520
ML
997 * Reclaimers can specify a node in @reclaim to divide up the memcgs
998 * in the hierarchy among all concurrent reclaimers operating on the
999 * same node.
5660048c 1000 */
694fbc0f 1001struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 1002 struct mem_cgroup *prev,
694fbc0f 1003 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1004{
3f649ab7 1005 struct mem_cgroup_reclaim_iter *iter;
ec0db74b 1006 struct cgroup_subsys_state *css;
aa50b501
KH
1007 struct mem_cgroup *pos;
1008 struct mem_cgroup *next;
711d3d2c 1009
694fbc0f
AM
1010 if (mem_cgroup_disabled())
1011 return NULL;
5660048c 1012
9f3a0d09
JW
1013 if (!root)
1014 root = root_mem_cgroup;
7d74b06f 1015
542f85f9 1016 rcu_read_lock();
3d150e31 1017restart:
aa50b501 1018 next = NULL;
5f578161 1019
5ac8fb31 1020 if (reclaim) {
ec0db74b 1021 int gen;
aa50b501 1022 int nid = reclaim->pgdat->node_id;
5ac8fb31 1023
aa50b501 1024 iter = &root->nodeinfo[nid]->iter;
ec0db74b 1025 gen = atomic_read(&iter->generation);
5ac8fb31 1026
a9320aae
WY
1027 /*
1028 * On start, join the current reclaim iteration cycle.
1029 * Exit when a concurrent walker completes it.
1030 */
1031 if (!prev)
ec0db74b
KH
1032 reclaim->generation = gen;
1033 else if (reclaim->generation != gen)
5ac8fb31
JW
1034 goto out_unlock;
1035
4a2698b0 1036 pos = READ_ONCE(iter->position);
aa50b501 1037 } else
89d8330c 1038 pos = prev;
5ac8fb31 1039
ec0db74b 1040 css = pos ? &pos->css : NULL;
7d74b06f 1041
aa50b501 1042 while ((css = css_next_descendant_pre(css, &root->css))) {
5ac8fb31
JW
1043 /*
1044 * Verify the css and acquire a reference. The root
1045 * is provided by the caller, so we know it's alive
1046 * and kicking, and don't take an extra reference.
1047 */
aa50b501 1048 if (css == &root->css || css_tryget(css))
0b8f73e1 1049 break;
9f3a0d09 1050 }
5ac8fb31 1051
aa50b501 1052 next = mem_cgroup_from_css(css);
ec0db74b 1053
5ac8fb31 1054 if (reclaim) {
5ac8fb31 1055 /*
6df38689
VD
1056 * The position could have already been updated by a competing
1057 * thread, so check that the value hasn't changed since we read
1058 * it to avoid reclaiming from the same cgroup twice.
5ac8fb31 1059 */
aa50b501 1060 if (cmpxchg(&iter->position, pos, next) != pos) {
ec0db74b
KH
1061 if (css && css != &root->css)
1062 css_put(css);
1063 goto restart;
1064 }
6df38689 1065
aa50b501 1066 if (!next) {
ec0db74b 1067 atomic_inc(&iter->generation);
5ac8fb31 1068
3d150e31
KH
1069 /*
1070 * Reclaimers share the hierarchy walk, and a
1071 * new one might jump in right at the end of
1072 * the hierarchy - make sure they see at least
1073 * one group and restart from the beginning.
1074 */
1075 if (!prev)
1076 goto restart;
1077 }
9f3a0d09 1078 }
5ac8fb31 1079
542f85f9
MH
1080out_unlock:
1081 rcu_read_unlock();
c40046f3
MH
1082 if (prev && prev != root)
1083 css_put(&prev->css);
1084
aa50b501 1085 return next;
14067bb3 1086}
7d74b06f 1087
5660048c
JW
1088/**
1089 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1090 * @root: hierarchy root
1091 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1092 */
1093void mem_cgroup_iter_break(struct mem_cgroup *root,
1094 struct mem_cgroup *prev)
9f3a0d09
JW
1095{
1096 if (!root)
1097 root = root_mem_cgroup;
1098 if (prev && prev != root)
1099 css_put(&prev->css);
1100}
7d74b06f 1101
54a83d6b
MC
1102static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1103 struct mem_cgroup *dead_memcg)
6df38689 1104{
6df38689 1105 struct mem_cgroup_reclaim_iter *iter;
ef8f2327
MG
1106 struct mem_cgroup_per_node *mz;
1107 int nid;
6df38689 1108
54a83d6b 1109 for_each_node(nid) {
a3747b53 1110 mz = from->nodeinfo[nid];
9da83f3f
YS
1111 iter = &mz->iter;
1112 cmpxchg(&iter->position, dead_memcg, NULL);
6df38689
VD
1113 }
1114}
1115
54a83d6b
MC
1116static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1117{
1118 struct mem_cgroup *memcg = dead_memcg;
1119 struct mem_cgroup *last;
1120
1121 do {
1122 __invalidate_reclaim_iterators(memcg, dead_memcg);
1123 last = memcg;
1124 } while ((memcg = parent_mem_cgroup(memcg)));
1125
1126 /*
b8dd3ee9 1127 * When cgroup1 non-hierarchy mode is used,
54a83d6b
MC
1128 * parent_mem_cgroup() does not walk all the way up to the
1129 * cgroup root (root_mem_cgroup). So we have to handle
1130 * dead_memcg from cgroup root separately.
1131 */
7848ed62 1132 if (!mem_cgroup_is_root(last))
54a83d6b
MC
1133 __invalidate_reclaim_iterators(root_mem_cgroup,
1134 dead_memcg);
1135}
1136
7c5f64f8
VD
1137/**
1138 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1139 * @memcg: hierarchy root
1140 * @fn: function to call for each task
1141 * @arg: argument passed to @fn
1142 *
1143 * This function iterates over tasks attached to @memcg or to any of its
1144 * descendants and calls @fn for each task. If @fn returns a non-zero
025b7799
Z
1145 * value, the function breaks the iteration loop. Otherwise, it will iterate
1146 * over all tasks and return 0.
7c5f64f8
VD
1147 *
1148 * This function must not be called for the root memory cgroup.
1149 */
025b7799
Z
1150void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1151 int (*fn)(struct task_struct *, void *), void *arg)
7c5f64f8
VD
1152{
1153 struct mem_cgroup *iter;
1154 int ret = 0;
1155
7848ed62 1156 BUG_ON(mem_cgroup_is_root(memcg));
7c5f64f8
VD
1157
1158 for_each_mem_cgroup_tree(iter, memcg) {
1159 struct css_task_iter it;
1160 struct task_struct *task;
1161
f168a9a5 1162 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
ade81479 1163 while (!ret && (task = css_task_iter_next(&it))) {
7c5f64f8 1164 ret = fn(task, arg);
06717a7b
BL
1165 /* Avoid potential softlockup warning */
1166 cond_resched();
ade81479 1167 }
7c5f64f8
VD
1168 css_task_iter_end(&it);
1169 if (ret) {
1170 mem_cgroup_iter_break(memcg, iter);
1171 break;
1172 }
1173 }
7c5f64f8
VD
1174}
1175
6168d0da 1176#ifdef CONFIG_DEBUG_VM
e809c3fe 1177void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
6168d0da
AS
1178{
1179 struct mem_cgroup *memcg;
1180
1181 if (mem_cgroup_disabled())
1182 return;
1183
e809c3fe 1184 memcg = folio_memcg(folio);
6168d0da
AS
1185
1186 if (!memcg)
7848ed62 1187 VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
6168d0da 1188 else
e809c3fe 1189 VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
6168d0da
AS
1190}
1191#endif
1192
6168d0da 1193/**
e809c3fe
MWO
1194 * folio_lruvec_lock - Lock the lruvec for a folio.
1195 * @folio: Pointer to the folio.
6168d0da 1196 *
d7e3aba5 1197 * These functions are safe to use under any of the following conditions:
e809c3fe
MWO
1198 * - folio locked
1199 * - folio_test_lru false
e809c3fe
MWO
1200 * - folio frozen (refcount of 0)
1201 *
1202 * Return: The lruvec this folio is on with its lock held.
6168d0da 1203 */
e809c3fe 1204struct lruvec *folio_lruvec_lock(struct folio *folio)
6168d0da 1205{
e809c3fe 1206 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1207
6168d0da 1208 spin_lock(&lruvec->lru_lock);
e809c3fe 1209 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1210
1211 return lruvec;
1212}
1213
e809c3fe
MWO
1214/**
1215 * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1216 * @folio: Pointer to the folio.
1217 *
1218 * These functions are safe to use under any of the following conditions:
1219 * - folio locked
1220 * - folio_test_lru false
e809c3fe
MWO
1221 * - folio frozen (refcount of 0)
1222 *
1223 * Return: The lruvec this folio is on with its lock held and interrupts
1224 * disabled.
1225 */
1226struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
6168d0da 1227{
e809c3fe 1228 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1229
6168d0da 1230 spin_lock_irq(&lruvec->lru_lock);
e809c3fe 1231 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1232
1233 return lruvec;
1234}
1235
e809c3fe
MWO
1236/**
1237 * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1238 * @folio: Pointer to the folio.
1239 * @flags: Pointer to irqsave flags.
1240 *
1241 * These functions are safe to use under any of the following conditions:
1242 * - folio locked
1243 * - folio_test_lru false
e809c3fe
MWO
1244 * - folio frozen (refcount of 0)
1245 *
1246 * Return: The lruvec this folio is on with its lock held and interrupts
1247 * disabled.
1248 */
1249struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1250 unsigned long *flags)
6168d0da 1251{
e809c3fe 1252 struct lruvec *lruvec = folio_lruvec(folio);
6168d0da 1253
6168d0da 1254 spin_lock_irqsave(&lruvec->lru_lock, *flags);
e809c3fe 1255 lruvec_memcg_debug(lruvec, folio);
6168d0da
AS
1256
1257 return lruvec;
1258}
1259
925b7673 1260/**
fa9add64
HD
1261 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1262 * @lruvec: mem_cgroup per zone lru vector
1263 * @lru: index of lru list the page is sitting on
b4536f0c 1264 * @zid: zone id of the accounted pages
fa9add64 1265 * @nr_pages: positive when adding or negative when removing
925b7673 1266 *
ca707239 1267 * This function must be called under lru_lock, just before a page is added
07ca7606 1268 * to or just after a page is removed from an lru list.
3f58a829 1269 */
fa9add64 1270void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
b4536f0c 1271 int zid, int nr_pages)
3f58a829 1272{
ef8f2327 1273 struct mem_cgroup_per_node *mz;
fa9add64 1274 unsigned long *lru_size;
ca707239 1275 long size;
3f58a829
MK
1276
1277 if (mem_cgroup_disabled())
1278 return;
1279
ef8f2327 1280 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
b4536f0c 1281 lru_size = &mz->lru_zone_size[zid][lru];
ca707239
HD
1282
1283 if (nr_pages < 0)
1284 *lru_size += nr_pages;
1285
1286 size = *lru_size;
b4536f0c
MH
1287 if (WARN_ONCE(size < 0,
1288 "%s(%p, %d, %d): lru_size %ld\n",
1289 __func__, lruvec, lru, nr_pages, size)) {
ca707239
HD
1290 VM_BUG_ON(1);
1291 *lru_size = 0;
1292 }
1293
1294 if (nr_pages > 0)
1295 *lru_size += nr_pages;
08e552c6 1296}
544122e5 1297
19942822 1298/**
9d11ea9f 1299 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1300 * @memcg: the memory cgroup
19942822 1301 *
9d11ea9f 1302 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1303 * pages.
19942822 1304 */
c0ff4b85 1305static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1306{
3e32cb2e
JW
1307 unsigned long margin = 0;
1308 unsigned long count;
1309 unsigned long limit;
9d11ea9f 1310
3e32cb2e 1311 count = page_counter_read(&memcg->memory);
bbec2e15 1312 limit = READ_ONCE(memcg->memory.max);
3e32cb2e
JW
1313 if (count < limit)
1314 margin = limit - count;
1315
7941d214 1316 if (do_memsw_account()) {
3e32cb2e 1317 count = page_counter_read(&memcg->memsw);
bbec2e15 1318 limit = READ_ONCE(memcg->memsw.max);
1c4448ed 1319 if (count < limit)
3e32cb2e 1320 margin = min(margin, limit - count);
cbedbac3
LR
1321 else
1322 margin = 0;
3e32cb2e
JW
1323 }
1324
1325 return margin;
19942822
JW
1326}
1327
5f9a4f4a
MS
1328struct memory_stat {
1329 const char *name;
5f9a4f4a
MS
1330 unsigned int idx;
1331};
1332
57b2847d 1333static const struct memory_stat memory_stats[] = {
fff66b79
MS
1334 { "anon", NR_ANON_MAPPED },
1335 { "file", NR_FILE_PAGES },
a8c49af3 1336 { "kernel", MEMCG_KMEM },
fff66b79
MS
1337 { "kernel_stack", NR_KERNEL_STACK_KB },
1338 { "pagetables", NR_PAGETABLE },
ebc97a52 1339 { "sec_pagetables", NR_SECONDARY_PAGETABLE },
fff66b79
MS
1340 { "percpu", MEMCG_PERCPU_B },
1341 { "sock", MEMCG_SOCK },
4e5aa1f4 1342 { "vmalloc", MEMCG_VMALLOC },
fff66b79 1343 { "shmem", NR_SHMEM },
3a3b7fec 1344#ifdef CONFIG_ZSWAP
f4840ccf
JW
1345 { "zswap", MEMCG_ZSWAP_B },
1346 { "zswapped", MEMCG_ZSWAPPED },
1347#endif
fff66b79
MS
1348 { "file_mapped", NR_FILE_MAPPED },
1349 { "file_dirty", NR_FILE_DIRTY },
1350 { "file_writeback", NR_WRITEBACK },
b6038942
SB
1351#ifdef CONFIG_SWAP
1352 { "swapcached", NR_SWAPCACHE },
1353#endif
5f9a4f4a 1354#ifdef CONFIG_TRANSPARENT_HUGEPAGE
fff66b79
MS
1355 { "anon_thp", NR_ANON_THPS },
1356 { "file_thp", NR_FILE_THPS },
1357 { "shmem_thp", NR_SHMEM_THPS },
5f9a4f4a 1358#endif
fff66b79
MS
1359 { "inactive_anon", NR_INACTIVE_ANON },
1360 { "active_anon", NR_ACTIVE_ANON },
1361 { "inactive_file", NR_INACTIVE_FILE },
1362 { "active_file", NR_ACTIVE_FILE },
1363 { "unevictable", NR_UNEVICTABLE },
1364 { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
1365 { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
05d4532b
JH
1366#ifdef CONFIG_HUGETLB_PAGE
1367 { "hugetlb", NR_HUGETLB },
1368#endif
5f9a4f4a
MS
1369
1370 /* The memory events */
fff66b79
MS
1371 { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
1372 { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
1373 { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
1374 { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
1375 { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
1376 { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
1377 { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
f77f0c75
KZ
1378
1379 { "pgdemote_kswapd", PGDEMOTE_KSWAPD },
1380 { "pgdemote_direct", PGDEMOTE_DIRECT },
1381 { "pgdemote_khugepaged", PGDEMOTE_KHUGEPAGED },
e452872b 1382 { "pgdemote_proactive", PGDEMOTE_PROACTIVE },
f77f0c75
KZ
1383#ifdef CONFIG_NUMA_BALANCING
1384 { "pgpromote_success", PGPROMOTE_SUCCESS },
1385#endif
5f9a4f4a
MS
1386};
1387
ff841a06 1388/* The actual unit of the state item, not the same as the output unit */
fff66b79
MS
1389static int memcg_page_state_unit(int item)
1390{
1391 switch (item) {
1392 case MEMCG_PERCPU_B:
f4840ccf 1393 case MEMCG_ZSWAP_B:
fff66b79
MS
1394 case NR_SLAB_RECLAIMABLE_B:
1395 case NR_SLAB_UNRECLAIMABLE_B:
ff841a06
YA
1396 return 1;
1397 case NR_KERNEL_STACK_KB:
1398 return SZ_1K;
1399 default:
1400 return PAGE_SIZE;
1401 }
1402}
1403
1404/* Translate stat items to the correct unit for memory.stat output */
1405static int memcg_page_state_output_unit(int item)
1406{
1407 /*
1408 * Workingset state is actually in pages, but we export it to userspace
1409 * as a scalar count of events, so special case it here.
f77f0c75
KZ
1410 *
1411 * Demotion and promotion activities are exported in pages, consistent
1412 * with their global counterparts.
ff841a06
YA
1413 */
1414 switch (item) {
fff66b79
MS
1415 case WORKINGSET_REFAULT_ANON:
1416 case WORKINGSET_REFAULT_FILE:
1417 case WORKINGSET_ACTIVATE_ANON:
1418 case WORKINGSET_ACTIVATE_FILE:
1419 case WORKINGSET_RESTORE_ANON:
1420 case WORKINGSET_RESTORE_FILE:
1421 case WORKINGSET_NODERECLAIM:
f77f0c75
KZ
1422 case PGDEMOTE_KSWAPD:
1423 case PGDEMOTE_DIRECT:
1424 case PGDEMOTE_KHUGEPAGED:
e452872b 1425 case PGDEMOTE_PROACTIVE:
f77f0c75
KZ
1426#ifdef CONFIG_NUMA_BALANCING
1427 case PGPROMOTE_SUCCESS:
1428#endif
fff66b79 1429 return 1;
fff66b79 1430 default:
ff841a06 1431 return memcg_page_state_unit(item);
fff66b79
MS
1432 }
1433}
1434
ea1e8796 1435unsigned long memcg_page_state_output(struct mem_cgroup *memcg, int item)
fff66b79 1436{
ff841a06
YA
1437 return memcg_page_state(memcg, item) *
1438 memcg_page_state_output_unit(item);
1439}
1440
610dc18c 1441#ifdef CONFIG_MEMCG_V1
ea1e8796 1442unsigned long memcg_page_state_local_output(struct mem_cgroup *memcg, int item)
ff841a06
YA
1443{
1444 return memcg_page_state_local(memcg, item) *
1445 memcg_page_state_output_unit(item);
fff66b79 1446}
610dc18c 1447#endif
fff66b79 1448
4e97d64c
JH
1449#ifdef CONFIG_HUGETLB_PAGE
1450static bool memcg_accounts_hugetlb(void)
1451{
1452 return cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
1453}
1454#else /* CONFIG_HUGETLB_PAGE */
1455static bool memcg_accounts_hugetlb(void)
1456{
1457 return false;
1458}
1459#endif /* CONFIG_HUGETLB_PAGE */
1460
dddb44ff 1461static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
c8713d0b 1462{
c8713d0b 1463 int i;
71cd3113 1464
c8713d0b
JW
1465 /*
1466 * Provide statistics on the state of the memory subsystem as
1467 * well as cumulative event counters that show past behavior.
1468 *
1469 * This list is ordered following a combination of these gradients:
1470 * 1) generic big picture -> specifics and details
1471 * 2) reflecting userspace activity -> reflecting kernel heuristics
1472 *
1473 * Current memory state:
1474 */
7d7ef0a4 1475 mem_cgroup_flush_stats(memcg);
c8713d0b 1476
5f9a4f4a
MS
1477 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1478 u64 size;
c8713d0b 1479
05d4532b
JH
1480#ifdef CONFIG_HUGETLB_PAGE
1481 if (unlikely(memory_stats[i].idx == NR_HUGETLB) &&
4e97d64c 1482 !memcg_accounts_hugetlb())
05d4532b
JH
1483 continue;
1484#endif
fff66b79 1485 size = memcg_page_state_output(memcg, memory_stats[i].idx);
5b42360c 1486 seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
c8713d0b 1487
5f9a4f4a 1488 if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
fff66b79
MS
1489 size += memcg_page_state_output(memcg,
1490 NR_SLAB_RECLAIMABLE_B);
5b42360c 1491 seq_buf_printf(s, "slab %llu\n", size);
5f9a4f4a
MS
1492 }
1493 }
c8713d0b
JW
1494
1495 /* Accumulated memory events */
5b42360c 1496 seq_buf_printf(s, "pgscan %lu\n",
c8713d0b 1497 memcg_events(memcg, PGSCAN_KSWAPD) +
57e9cc50 1498 memcg_events(memcg, PGSCAN_DIRECT) +
e452872b 1499 memcg_events(memcg, PGSCAN_PROACTIVE) +
57e9cc50 1500 memcg_events(memcg, PGSCAN_KHUGEPAGED));
5b42360c 1501 seq_buf_printf(s, "pgsteal %lu\n",
c8713d0b 1502 memcg_events(memcg, PGSTEAL_KSWAPD) +
57e9cc50 1503 memcg_events(memcg, PGSTEAL_DIRECT) +
e452872b 1504 memcg_events(memcg, PGSTEAL_PROACTIVE) +
57e9cc50 1505 memcg_events(memcg, PGSTEAL_KHUGEPAGED));
c8713d0b 1506
8278f1c7 1507 for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
98455eef 1508#ifdef CONFIG_MEMCG_V1
8278f1c7
SB
1509 if (memcg_vm_event_stat[i] == PGPGIN ||
1510 memcg_vm_event_stat[i] == PGPGOUT)
1511 continue;
98455eef 1512#endif
5b42360c 1513 seq_buf_printf(s, "%s %lu\n",
673520f8
QZ
1514 vm_event_name(memcg_vm_event_stat[i]),
1515 memcg_events(memcg, memcg_vm_event_stat[i]));
8278f1c7 1516 }
c8713d0b 1517}
71cd3113 1518
dddb44ff
YA
1519static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1520{
1521 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1522 memcg_stat_format(memcg, s);
1523 else
1524 memcg1_stat_format(memcg, s);
c2fad56b
XJ
1525 if (seq_buf_has_overflowed(s))
1526 pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__);
dddb44ff
YA
1527}
1528
e222432b 1529/**
f0c867d9 1530 * mem_cgroup_print_oom_context: Print OOM information relevant to
1531 * memory controller.
e222432b
BS
1532 * @memcg: The memory cgroup that went over limit
1533 * @p: Task that is going to be killed
1534 *
1535 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1536 * enabled
1537 */
f0c867d9 1538void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
e222432b 1539{
e222432b
BS
1540 rcu_read_lock();
1541
f0c867d9 1542 if (memcg) {
1543 pr_cont(",oom_memcg=");
1544 pr_cont_cgroup_path(memcg->css.cgroup);
1545 } else
1546 pr_cont(",global_oom");
2415b9f5 1547 if (p) {
f0c867d9 1548 pr_cont(",task_memcg=");
2415b9f5 1549 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
2415b9f5 1550 }
e222432b 1551 rcu_read_unlock();
f0c867d9 1552}
1553
1554/**
1555 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1556 * memory controller.
1557 * @memcg: The memory cgroup that went over limit
1558 */
1559void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1560{
68aaee14 1561 /* Use static buffer, for the caller is holding oom_lock. */
8717734f 1562 static char buf[SEQ_BUF_SIZE];
5b42360c 1563 struct seq_buf s;
0e2759af 1564 unsigned long memory_failcnt;
68aaee14
TH
1565
1566 lockdep_assert_held(&oom_lock);
e222432b 1567
0e2759af
SB
1568 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1569 memory_failcnt = atomic_long_read(&memcg->memory_events[MEMCG_MAX]);
1570 else
1571 memory_failcnt = memcg->memory.failcnt;
1572
3e32cb2e
JW
1573 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1574 K((u64)page_counter_read(&memcg->memory)),
0e2759af 1575 K((u64)READ_ONCE(memcg->memory.max)), memory_failcnt);
c8713d0b
JW
1576 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1577 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1578 K((u64)page_counter_read(&memcg->swap)),
0e2759af
SB
1579 K((u64)READ_ONCE(memcg->swap.max)),
1580 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
47d2702b 1581#ifdef CONFIG_MEMCG_V1
c8713d0b
JW
1582 else {
1583 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1584 K((u64)page_counter_read(&memcg->memsw)),
1585 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1586 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1587 K((u64)page_counter_read(&memcg->kmem)),
1588 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
58cf188e 1589 }
47d2702b 1590#endif
c8713d0b
JW
1591
1592 pr_info("Memory cgroup stats for ");
1593 pr_cont_cgroup_path(memcg->css.cgroup);
1594 pr_cont(":");
8717734f 1595 seq_buf_init(&s, buf, SEQ_BUF_SIZE);
5b42360c
YA
1596 memory_stat_format(memcg, &s);
1597 seq_buf_do_printk(&s, KERN_INFO);
e222432b
BS
1598}
1599
a63d83f4
DR
1600/*
1601 * Return the memory (and swap, if configured) limit for a memcg.
1602 */
bbec2e15 1603unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
a63d83f4 1604{
8d387a5f
WL
1605 unsigned long max = READ_ONCE(memcg->memory.max);
1606
b94c4e94 1607 if (do_memsw_account()) {
8d387a5f
WL
1608 if (mem_cgroup_swappiness(memcg)) {
1609 /* Calculate swap excess capacity from memsw limit */
1610 unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1611
1612 max += min(swap, (unsigned long)total_swap_pages);
1613 }
b94c4e94
JW
1614 } else {
1615 if (mem_cgroup_swappiness(memcg))
1616 max += min(READ_ONCE(memcg->swap.max),
1617 (unsigned long)total_swap_pages);
9a5a8f19 1618 }
bbec2e15 1619 return max;
a63d83f4
DR
1620}
1621
9783aa99
CD
1622unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1623{
1624 return page_counter_read(&memcg->memory);
1625}
1626
b6e6edcf 1627static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
19965460 1628 int order)
9cbb78bb 1629{
6e0fc46d
DR
1630 struct oom_control oc = {
1631 .zonelist = NULL,
1632 .nodemask = NULL,
2a966b77 1633 .memcg = memcg,
6e0fc46d
DR
1634 .gfp_mask = gfp_mask,
1635 .order = order,
6e0fc46d 1636 };
1378b37d 1637 bool ret = true;
9cbb78bb 1638
7775face
TH
1639 if (mutex_lock_killable(&oom_lock))
1640 return true;
1378b37d
YS
1641
1642 if (mem_cgroup_margin(memcg) >= (1 << order))
1643 goto unlock;
1644
7775face
TH
1645 /*
1646 * A few threads which were not waiting at mutex_lock_killable() can
1647 * fail to bail out. Therefore, check again after holding oom_lock.
1648 */
a75ffa26 1649 ret = out_of_memory(&oc);
1378b37d
YS
1650
1651unlock:
dc56401f 1652 mutex_unlock(&oom_lock);
7c5f64f8 1653 return ret;
9cbb78bb
DR
1654}
1655
becdf89d
SB
1656/*
1657 * Returns true if successfully killed one or more processes. Though in some
1658 * corner cases it can return true even without killing any process.
1659 */
1660static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1661{
becdf89d 1662 bool locked, ret;
7056d3a3 1663
29ef680a 1664 if (order > PAGE_ALLOC_COSTLY_ORDER)
becdf89d 1665 return false;
29ef680a 1666
7a1adfdd
RG
1667 memcg_memory_event(memcg, MEMCG_OOM);
1668
292fc2e0 1669 if (!memcg1_oom_prepare(memcg, &locked))
becdf89d 1670 return false;
29ef680a 1671
becdf89d 1672 ret = mem_cgroup_out_of_memory(memcg, mask, order);
7056d3a3 1673
292fc2e0 1674 memcg1_oom_finish(memcg, locked);
29ef680a 1675
7056d3a3 1676 return ret;
3812c8c8
JW
1677}
1678
3d8b38eb
RG
1679/**
1680 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1681 * @victim: task to be killed by the OOM killer
1682 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1683 *
1684 * Returns a pointer to a memory cgroup, which has to be cleaned up
1685 * by killing all belonging OOM-killable tasks.
1686 *
1687 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1688 */
1689struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1690 struct mem_cgroup *oom_domain)
1691{
1692 struct mem_cgroup *oom_group = NULL;
1693 struct mem_cgroup *memcg;
1694
1695 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1696 return NULL;
1697
1698 if (!oom_domain)
1699 oom_domain = root_mem_cgroup;
1700
1701 rcu_read_lock();
1702
1703 memcg = mem_cgroup_from_task(victim);
7848ed62 1704 if (mem_cgroup_is_root(memcg))
3d8b38eb
RG
1705 goto out;
1706
48fe267c
RG
1707 /*
1708 * If the victim task has been asynchronously moved to a different
1709 * memory cgroup, we might end up killing tasks outside oom_domain.
1710 * In this case it's better to ignore memory.group.oom.
1711 */
1712 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1713 goto out;
1714
3d8b38eb
RG
1715 /*
1716 * Traverse the memory cgroup hierarchy from the victim task's
1717 * cgroup up to the OOMing cgroup (or root) to find the
1718 * highest-level memory cgroup with oom.group set.
1719 */
1720 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
eaf7b66b 1721 if (READ_ONCE(memcg->oom_group))
3d8b38eb
RG
1722 oom_group = memcg;
1723
1724 if (memcg == oom_domain)
1725 break;
1726 }
1727
1728 if (oom_group)
1729 css_get(&oom_group->css);
1730out:
1731 rcu_read_unlock();
1732
1733 return oom_group;
1734}
1735
1736void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1737{
1738 pr_info("Tasks in ");
1739 pr_cont_cgroup_path(memcg->css.cgroup);
1740 pr_cont(" are going to be killed due to memory.oom.group set\n");
1741}
1742
f735eebe
SB
1743/*
1744 * The value of NR_MEMCG_STOCK is selected to keep the cached memcgs and their
1745 * nr_pages in a single cacheline. This may change in future.
1746 */
1747#define NR_MEMCG_STOCK 7
c80509ef 1748#define FLUSHING_CACHED_CHARGE 0
fead2b86 1749struct memcg_stock_pcp {
c80509ef 1750 local_trylock_t lock;
f735eebe
SB
1751 uint8_t nr_pages[NR_MEMCG_STOCK];
1752 struct mem_cgroup *cached[NR_MEMCG_STOCK];
fead2b86 1753
c80509ef
SB
1754 struct work_struct work;
1755 unsigned long flags;
1756};
1757
1758static DEFINE_PER_CPU_ALIGNED(struct memcg_stock_pcp, memcg_stock) = {
1759 .lock = INIT_LOCAL_TRYLOCK(lock),
1760};
1761
1762struct obj_stock_pcp {
1763 local_trylock_t lock;
3523dd7a 1764 unsigned int nr_bytes;
bf4f0599 1765 struct obj_cgroup *cached_objcg;
68ac5b3c 1766 struct pglist_data *cached_pgdat;
68ac5b3c
WL
1767 int nr_slab_reclaimable_b;
1768 int nr_slab_unreclaimable_b;
bf4f0599 1769
cdec2e42 1770 struct work_struct work;
26fe6168 1771 unsigned long flags;
cdec2e42 1772};
c80509ef
SB
1773
1774static DEFINE_PER_CPU_ALIGNED(struct obj_stock_pcp, obj_stock) = {
1775 .lock = INIT_LOCAL_TRYLOCK(lock),
56751146 1776};
c80509ef 1777
9f50fad6 1778static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 1779
c80509ef
SB
1780static void drain_obj_stock(struct obj_stock_pcp *stock);
1781static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
bf4f0599
RG
1782 struct mem_cgroup *root_memcg);
1783
a0956d54
SS
1784/**
1785 * consume_stock: Try to consume stocked charge on this cpu.
1786 * @memcg: memcg to consume from.
1787 * @nr_pages: how many pages to charge.
1788 *
2fba5961
SB
1789 * Consume the cached charge if enough nr_pages are present otherwise return
1790 * failure. Also return failure for charge request larger than
1791 * MEMCG_CHARGE_BATCH or if the local lock is already taken.
a0956d54
SS
1792 *
1793 * returns true if successful, false otherwise.
cdec2e42 1794 */
2fba5961 1795static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
1796{
1797 struct memcg_stock_pcp *stock;
f735eebe 1798 uint8_t stock_pages;
3e32cb2e 1799 bool ret = false;
f735eebe 1800 int i;
cdec2e42 1801
2fba5961 1802 if (nr_pages > MEMCG_CHARGE_BATCH ||
9e619cd4 1803 !local_trylock(&memcg_stock.lock))
51339d99 1804 return ret;
db2ba40c
JW
1805
1806 stock = this_cpu_ptr(&memcg_stock);
f735eebe
SB
1807
1808 for (i = 0; i < NR_MEMCG_STOCK; ++i) {
1809 if (memcg != READ_ONCE(stock->cached[i]))
1810 continue;
1811
1812 stock_pages = READ_ONCE(stock->nr_pages[i]);
1813 if (stock_pages >= nr_pages) {
1814 WRITE_ONCE(stock->nr_pages[i], stock_pages - nr_pages);
1815 ret = true;
1816 }
1817 break;
3e32cb2e 1818 }
db2ba40c 1819
9e619cd4 1820 local_unlock(&memcg_stock.lock);
db2ba40c 1821
cdec2e42
KH
1822 return ret;
1823}
1824
89f342af
SB
1825static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
1826{
1827 page_counter_uncharge(&memcg->memory, nr_pages);
1828 if (do_memsw_account())
1829 page_counter_uncharge(&memcg->memsw, nr_pages);
1830}
1831
cdec2e42 1832/*
3e32cb2e 1833 * Returns stocks cached in percpu and reset cached information.
cdec2e42 1834 */
f735eebe 1835static void drain_stock(struct memcg_stock_pcp *stock, int i)
cdec2e42 1836{
f735eebe
SB
1837 struct mem_cgroup *old = READ_ONCE(stock->cached[i]);
1838 uint8_t stock_pages;
cdec2e42 1839
1a3e1f40
JW
1840 if (!old)
1841 return;
1842
f735eebe 1843 stock_pages = READ_ONCE(stock->nr_pages[i]);
1872b3bc 1844 if (stock_pages) {
89f342af 1845 memcg_uncharge(old, stock_pages);
f735eebe 1846 WRITE_ONCE(stock->nr_pages[i], 0);
cdec2e42 1847 }
1a3e1f40
JW
1848
1849 css_put(&old->css);
f735eebe 1850 WRITE_ONCE(stock->cached[i], NULL);
cdec2e42
KH
1851}
1852
f735eebe
SB
1853static void drain_stock_fully(struct memcg_stock_pcp *stock)
1854{
1855 int i;
1856
1857 for (i = 0; i < NR_MEMCG_STOCK; ++i)
1858 drain_stock(stock, i);
cdec2e42
KH
1859}
1860
c80509ef 1861static void drain_local_memcg_stock(struct work_struct *dummy)
cdec2e42 1862{
db2ba40c 1863 struct memcg_stock_pcp *stock;
db2ba40c 1864
3523dd7a
SB
1865 if (WARN_ONCE(!in_task(), "drain in non-task context"))
1866 return;
db2ba40c 1867
9e619cd4 1868 local_lock(&memcg_stock.lock);
db2ba40c
JW
1869
1870 stock = this_cpu_ptr(&memcg_stock);
f735eebe 1871 drain_stock_fully(stock);
26fe6168 1872 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
db2ba40c 1873
9e619cd4 1874 local_unlock(&memcg_stock.lock);
cdec2e42
KH
1875}
1876
c80509ef 1877static void drain_local_obj_stock(struct work_struct *dummy)
cdec2e42 1878{
c80509ef 1879 struct obj_stock_pcp *stock;
cdec2e42 1880
c80509ef
SB
1881 if (WARN_ONCE(!in_task(), "drain in non-task context"))
1882 return;
1883
200577f6 1884 local_lock(&obj_stock.lock);
c80509ef
SB
1885
1886 stock = this_cpu_ptr(&obj_stock);
1887 drain_obj_stock(stock);
1888 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
db2ba40c 1889
200577f6 1890 local_unlock(&obj_stock.lock);
af9a3b69
JW
1891}
1892
1893static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
1894{
db2ba40c 1895 struct memcg_stock_pcp *stock;
f735eebe
SB
1896 struct mem_cgroup *cached;
1897 uint8_t stock_pages;
f735eebe
SB
1898 bool success = false;
1899 int empty_slot = -1;
1900 int i;
1901
1902 /*
1903 * For now limit MEMCG_CHARGE_BATCH to 127 and less. In future if we
1904 * decide to increase it more than 127 then we will need more careful
1905 * handling of nr_pages[] in struct memcg_stock_pcp.
1906 */
1907 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S8_MAX);
475d0487 1908
cbc09144
SB
1909 VM_WARN_ON_ONCE(mem_cgroup_is_root(memcg));
1910
f735eebe 1911 if (nr_pages > MEMCG_CHARGE_BATCH ||
9e619cd4 1912 !local_trylock(&memcg_stock.lock)) {
01d37228 1913 /*
f735eebe 1914 * In case of larger than batch refill or unlikely failure to
c80509ef 1915 * lock the percpu memcg_stock.lock, uncharge memcg directly.
01d37228 1916 */
cbc09144 1917 memcg_uncharge(memcg, nr_pages);
01d37228
AS
1918 return;
1919 }
cdec2e42 1920
db2ba40c 1921 stock = this_cpu_ptr(&memcg_stock);
f735eebe
SB
1922 for (i = 0; i < NR_MEMCG_STOCK; ++i) {
1923 cached = READ_ONCE(stock->cached[i]);
1924 if (!cached && empty_slot == -1)
1925 empty_slot = i;
1926 if (memcg == READ_ONCE(stock->cached[i])) {
1927 stock_pages = READ_ONCE(stock->nr_pages[i]) + nr_pages;
1928 WRITE_ONCE(stock->nr_pages[i], stock_pages);
1929 if (stock_pages > MEMCG_CHARGE_BATCH)
1930 drain_stock(stock, i);
1931 success = true;
1932 break;
1933 }
cdec2e42 1934 }
db2ba40c 1935
f735eebe
SB
1936 if (!success) {
1937 i = empty_slot;
1938 if (i == -1) {
1939 i = get_random_u32_below(NR_MEMCG_STOCK);
1940 drain_stock(stock, i);
1941 }
1942 css_get(&memcg->css);
1943 WRITE_ONCE(stock->cached[i], memcg);
1944 WRITE_ONCE(stock->nr_pages[i], nr_pages);
1945 }
e56fa8f5 1946
9e619cd4 1947 local_unlock(&memcg_stock.lock);
cdec2e42
KH
1948}
1949
c80509ef
SB
1950static bool is_memcg_drain_needed(struct memcg_stock_pcp *stock,
1951 struct mem_cgroup *root_memcg)
f735eebe
SB
1952{
1953 struct mem_cgroup *memcg;
1954 bool flush = false;
1955 int i;
1956
1957 rcu_read_lock();
f735eebe
SB
1958 for (i = 0; i < NR_MEMCG_STOCK; ++i) {
1959 memcg = READ_ONCE(stock->cached[i]);
1960 if (!memcg)
1961 continue;
1962
1963 if (READ_ONCE(stock->nr_pages[i]) &&
1964 mem_cgroup_is_descendant(memcg, root_memcg)) {
1965 flush = true;
1966 break;
1967 }
1968 }
f735eebe
SB
1969 rcu_read_unlock();
1970 return flush;
cdec2e42
KH
1971}
1972
1973/*
c0ff4b85 1974 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 1975 * of the hierarchy under it.
cdec2e42 1976 */
ea1e8796 1977void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 1978{
26fe6168 1979 int cpu, curcpu;
d38144b7 1980
6d3d6aa2
JW
1981 /* If someone's already draining, avoid adding running more workers. */
1982 if (!mutex_trylock(&percpu_charge_mutex))
1983 return;
72f0184c
MH
1984 /*
1985 * Notify other cpus that system-wide "drain" is running
1986 * We do not care about races with the cpu hotplug because cpu down
1987 * as well as workers from this path always operate on the local
1988 * per-cpu data. CPU up doesn't touch memcg_stock at all.
1989 */
0790ed62
SAS
1990 migrate_disable();
1991 curcpu = smp_processor_id();
cdec2e42 1992 for_each_online_cpu(cpu) {
c80509ef
SB
1993 struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu);
1994 struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu);
26fe6168 1995
c80509ef
SB
1996 if (!test_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags) &&
1997 is_memcg_drain_needed(memcg_st, root_memcg) &&
1998 !test_and_set_bit(FLUSHING_CACHED_CHARGE,
1999 &memcg_st->flags)) {
d1a05b69 2000 if (cpu == curcpu)
c80509ef 2001 drain_local_memcg_stock(&memcg_st->work);
6a792697 2002 else if (!cpu_is_isolated(cpu))
c80509ef
SB
2003 schedule_work_on(cpu, &memcg_st->work);
2004 }
e1a366be 2005
c80509ef
SB
2006 if (!test_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags) &&
2007 obj_stock_flush_required(obj_st, root_memcg) &&
2008 !test_and_set_bit(FLUSHING_CACHED_CHARGE,
2009 &obj_st->flags)) {
d1a05b69 2010 if (cpu == curcpu)
c80509ef 2011 drain_local_obj_stock(&obj_st->work);
6a792697 2012 else if (!cpu_is_isolated(cpu))
c80509ef 2013 schedule_work_on(cpu, &obj_st->work);
d1a05b69 2014 }
cdec2e42 2015 }
0790ed62 2016 migrate_enable();
9f50fad6 2017 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2018}
2019
2cd21c89
JW
2020static int memcg_hotplug_cpu_dead(unsigned int cpu)
2021{
3523dd7a 2022 /* no need for the local lock */
0ccf1806 2023 drain_obj_stock(&per_cpu(obj_stock, cpu));
c80509ef 2024 drain_stock_fully(&per_cpu(memcg_stock, cpu));
a3d4c05a 2025
308167fc 2026 return 0;
cdec2e42
KH
2027}
2028
b3ff9291
CD
2029static unsigned long reclaim_high(struct mem_cgroup *memcg,
2030 unsigned int nr_pages,
2031 gfp_t gfp_mask)
f7e1cb6e 2032{
b3ff9291
CD
2033 unsigned long nr_reclaimed = 0;
2034
f7e1cb6e 2035 do {
e22c6ed9
JW
2036 unsigned long pflags;
2037
d1663a90
JK
2038 if (page_counter_read(&memcg->memory) <=
2039 READ_ONCE(memcg->memory.high))
f7e1cb6e 2040 continue;
e22c6ed9 2041
e27be240 2042 memcg_memory_event(memcg, MEMCG_HIGH);
e22c6ed9
JW
2043
2044 psi_memstall_enter(&pflags);
b3ff9291 2045 nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
73b73bac 2046 gfp_mask,
68cd9050
DS
2047 MEMCG_RECLAIM_MAY_SWAP,
2048 NULL);
e22c6ed9 2049 psi_memstall_leave(&pflags);
4bf17307
CD
2050 } while ((memcg = parent_mem_cgroup(memcg)) &&
2051 !mem_cgroup_is_root(memcg));
b3ff9291
CD
2052
2053 return nr_reclaimed;
f7e1cb6e
JW
2054}
2055
2056static void high_work_func(struct work_struct *work)
2057{
2058 struct mem_cgroup *memcg;
2059
2060 memcg = container_of(work, struct mem_cgroup, high_work);
a983b5eb 2061 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
f7e1cb6e
JW
2062}
2063
0e4b01df
CD
2064/*
2065 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2066 * enough to still cause a significant slowdown in most cases, while still
2067 * allowing diagnostics and tracing to proceed without becoming stuck.
2068 */
2069#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2070
2071/*
2072 * When calculating the delay, we use these either side of the exponentiation to
2073 * maintain precision and scale to a reasonable number of jiffies (see the table
2074 * below.
2075 *
2076 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2077 * overage ratio to a delay.
ac5ddd0f 2078 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
0e4b01df
CD
2079 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2080 * to produce a reasonable delay curve.
2081 *
2082 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2083 * reasonable delay curve compared to precision-adjusted overage, not
2084 * penalising heavily at first, but still making sure that growth beyond the
2085 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2086 * example, with a high of 100 megabytes:
2087 *
2088 * +-------+------------------------+
2089 * | usage | time to allocate in ms |
2090 * +-------+------------------------+
2091 * | 100M | 0 |
2092 * | 101M | 6 |
2093 * | 102M | 25 |
2094 * | 103M | 57 |
2095 * | 104M | 102 |
2096 * | 105M | 159 |
2097 * | 106M | 230 |
2098 * | 107M | 313 |
2099 * | 108M | 409 |
2100 * | 109M | 518 |
2101 * | 110M | 639 |
2102 * | 111M | 774 |
2103 * | 112M | 921 |
2104 * | 113M | 1081 |
2105 * | 114M | 1254 |
2106 * | 115M | 1439 |
2107 * | 116M | 1638 |
2108 * | 117M | 1849 |
2109 * | 118M | 2000 |
2110 * | 119M | 2000 |
2111 * | 120M | 2000 |
2112 * +-------+------------------------+
2113 */
2114 #define MEMCG_DELAY_PRECISION_SHIFT 20
2115 #define MEMCG_DELAY_SCALING_SHIFT 14
2116
8a5dbc65 2117static u64 calculate_overage(unsigned long usage, unsigned long high)
b23afb93 2118{
8a5dbc65 2119 u64 overage;
b23afb93 2120
8a5dbc65
JK
2121 if (usage <= high)
2122 return 0;
e26733e0 2123
8a5dbc65
JK
2124 /*
2125 * Prevent division by 0 in overage calculation by acting as if
2126 * it was a threshold of 1 page
2127 */
2128 high = max(high, 1UL);
9b8b1754 2129
8a5dbc65
JK
2130 overage = usage - high;
2131 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2132 return div64_u64(overage, high);
2133}
e26733e0 2134
8a5dbc65
JK
2135static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2136{
2137 u64 overage, max_overage = 0;
e26733e0 2138
8a5dbc65
JK
2139 do {
2140 overage = calculate_overage(page_counter_read(&memcg->memory),
d1663a90 2141 READ_ONCE(memcg->memory.high));
8a5dbc65 2142 max_overage = max(overage, max_overage);
e26733e0
CD
2143 } while ((memcg = parent_mem_cgroup(memcg)) &&
2144 !mem_cgroup_is_root(memcg));
2145
8a5dbc65
JK
2146 return max_overage;
2147}
2148
4b82ab4f
JK
2149static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2150{
2151 u64 overage, max_overage = 0;
2152
2153 do {
2154 overage = calculate_overage(page_counter_read(&memcg->swap),
2155 READ_ONCE(memcg->swap.high));
2156 if (overage)
2157 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2158 max_overage = max(overage, max_overage);
2159 } while ((memcg = parent_mem_cgroup(memcg)) &&
2160 !mem_cgroup_is_root(memcg));
2161
2162 return max_overage;
2163}
2164
8a5dbc65
JK
2165/*
2166 * Get the number of jiffies that we should penalise a mischievous cgroup which
2167 * is exceeding its memory.high by checking both it and its ancestors.
2168 */
2169static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2170 unsigned int nr_pages,
2171 u64 max_overage)
2172{
2173 unsigned long penalty_jiffies;
2174
e26733e0
CD
2175 if (!max_overage)
2176 return 0;
0e4b01df
CD
2177
2178 /*
0e4b01df
CD
2179 * We use overage compared to memory.high to calculate the number of
2180 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2181 * fairly lenient on small overages, and increasingly harsh when the
2182 * memcg in question makes it clear that it has no intention of stopping
2183 * its crazy behaviour, so we exponentially increase the delay based on
2184 * overage amount.
2185 */
e26733e0
CD
2186 penalty_jiffies = max_overage * max_overage * HZ;
2187 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2188 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
0e4b01df
CD
2189
2190 /*
2191 * Factor in the task's own contribution to the overage, such that four
2192 * N-sized allocations are throttled approximately the same as one
2193 * 4N-sized allocation.
2194 *
2195 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2196 * larger the current charge patch is than that.
2197 */
ff144e69 2198 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
e26733e0
CD
2199}
2200
2201/*
63fd3270
JW
2202 * Reclaims memory over the high limit. Called directly from
2203 * try_charge() (context permitting), as well as from the userland
2204 * return path where reclaim is always able to block.
e26733e0 2205 */
9ea9cb00 2206void mem_cgroup_handle_over_high(gfp_t gfp_mask)
e26733e0
CD
2207{
2208 unsigned long penalty_jiffies;
2209 unsigned long pflags;
b3ff9291 2210 unsigned long nr_reclaimed;
e26733e0 2211 unsigned int nr_pages = current->memcg_nr_pages_over_high;
d977aa93 2212 int nr_retries = MAX_RECLAIM_RETRIES;
e26733e0 2213 struct mem_cgroup *memcg;
b3ff9291 2214 bool in_retry = false;
e26733e0
CD
2215
2216 if (likely(!nr_pages))
2217 return;
2218
2219 memcg = get_mem_cgroup_from_mm(current->mm);
e26733e0
CD
2220 current->memcg_nr_pages_over_high = 0;
2221
b3ff9291 2222retry_reclaim:
63fd3270
JW
2223 /*
2224 * Bail if the task is already exiting. Unlike memory.max,
2225 * memory.high enforcement isn't as strict, and there is no
2226 * OOM killer involved, which means the excess could already
2227 * be much bigger (and still growing) than it could for
2228 * memory.max; the dying task could get stuck in fruitless
2229 * reclaim for a long time, which isn't desirable.
2230 */
2231 if (task_is_dying())
2232 goto out;
2233
b3ff9291
CD
2234 /*
2235 * The allocating task should reclaim at least the batch size, but for
2236 * subsequent retries we only want to do what's necessary to prevent oom
2237 * or breaching resource isolation.
2238 *
2239 * This is distinct from memory.max or page allocator behaviour because
2240 * memory.high is currently batched, whereas memory.max and the page
2241 * allocator run every time an allocation is made.
2242 */
2243 nr_reclaimed = reclaim_high(memcg,
2244 in_retry ? SWAP_CLUSTER_MAX : nr_pages,
9ea9cb00 2245 gfp_mask);
b3ff9291 2246
e26733e0
CD
2247 /*
2248 * memory.high is breached and reclaim is unable to keep up. Throttle
2249 * allocators proactively to slow down excessive growth.
2250 */
8a5dbc65
JK
2251 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2252 mem_find_max_overage(memcg));
0e4b01df 2253
4b82ab4f
JK
2254 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2255 swap_find_max_overage(memcg));
2256
ff144e69
JK
2257 /*
2258 * Clamp the max delay per usermode return so as to still keep the
2259 * application moving forwards and also permit diagnostics, albeit
2260 * extremely slowly.
2261 */
2262 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2263
0e4b01df
CD
2264 /*
2265 * Don't sleep if the amount of jiffies this memcg owes us is so low
2266 * that it's not even worth doing, in an attempt to be nice to those who
2267 * go only a small amount over their memory.high value and maybe haven't
2268 * been aggressively reclaimed enough yet.
2269 */
2270 if (penalty_jiffies <= HZ / 100)
2271 goto out;
2272
b3ff9291
CD
2273 /*
2274 * If reclaim is making forward progress but we're still over
2275 * memory.high, we want to encourage that rather than doing allocator
2276 * throttling.
2277 */
2278 if (nr_reclaimed || nr_retries--) {
2279 in_retry = true;
2280 goto retry_reclaim;
2281 }
2282
0e4b01df 2283 /*
63fd3270
JW
2284 * Reclaim didn't manage to push usage below the limit, slow
2285 * this allocating task down.
2286 *
0e4b01df
CD
2287 * If we exit early, we're guaranteed to die (since
2288 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2289 * need to account for any ill-begotten jiffies to pay them off later.
2290 */
2291 psi_memstall_enter(&pflags);
2292 schedule_timeout_killable(penalty_jiffies);
2293 psi_memstall_leave(&pflags);
2294
2295out:
2296 css_put(&memcg->css);
b23afb93
TH
2297}
2298
75fe8ec2
JW
2299static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2300 unsigned int nr_pages)
8a9f3ccd 2301{
a983b5eb 2302 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
d977aa93 2303 int nr_retries = MAX_RECLAIM_RETRIES;
6539cc05 2304 struct mem_cgroup *mem_over_limit;
3e32cb2e 2305 struct page_counter *counter;
6539cc05 2306 unsigned long nr_reclaimed;
a4ebf1b6 2307 bool passed_oom = false;
73b73bac 2308 unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
b70a2a21 2309 bool drained = false;
d6e103a7 2310 bool raised_max_event = false;
e22c6ed9 2311 unsigned long pflags;
a636b327 2312
6539cc05 2313retry:
2fba5961 2314 if (consume_stock(memcg, nr_pages))
10d53c74 2315 return 0;
8a9f3ccd 2316
01d37228
AS
2317 if (!gfpflags_allow_spinning(gfp_mask))
2318 /* Avoid the refill and flush of the older stock */
2319 batch = nr_pages;
2320
7941d214 2321 if (!do_memsw_account() ||
6071ca52
JW
2322 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2323 if (page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2324 goto done_restock;
7941d214 2325 if (do_memsw_account())
3e32cb2e
JW
2326 page_counter_uncharge(&memcg->memsw, batch);
2327 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2328 } else {
3e32cb2e 2329 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
73b73bac 2330 reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
3fbe7244 2331 }
7a81b88c 2332
6539cc05
JW
2333 if (batch > nr_pages) {
2334 batch = nr_pages;
2335 goto retry;
2336 }
6d61ef40 2337
89a28483
JW
2338 /*
2339 * Prevent unbounded recursion when reclaim operations need to
2340 * allocate memory. This might exceed the limits temporarily,
2341 * but we prefer facilitating memory reclaim and getting back
2342 * under the limit over triggering OOM kills in these cases.
2343 */
2344 if (unlikely(current->flags & PF_MEMALLOC))
2345 goto force;
2346
06b078fc
JW
2347 if (unlikely(task_in_memcg_oom(current)))
2348 goto nomem;
2349
d0164adc 2350 if (!gfpflags_allow_blocking(gfp_mask))
6539cc05 2351 goto nomem;
4b534334 2352
e27be240 2353 memcg_memory_event(mem_over_limit, MEMCG_MAX);
d6e103a7 2354 raised_max_event = true;
241994ed 2355
e22c6ed9 2356 psi_memstall_enter(&pflags);
b70a2a21 2357 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
68cd9050 2358 gfp_mask, reclaim_options, NULL);
e22c6ed9 2359 psi_memstall_leave(&pflags);
6539cc05 2360
61e02c74 2361 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2362 goto retry;
28c34c29 2363
b70a2a21 2364 if (!drained) {
6d3d6aa2 2365 drain_all_stock(mem_over_limit);
b70a2a21
JW
2366 drained = true;
2367 goto retry;
2368 }
2369
28c34c29
JW
2370 if (gfp_mask & __GFP_NORETRY)
2371 goto nomem;
6539cc05
JW
2372 /*
2373 * Even though the limit is exceeded at this point, reclaim
2374 * may have been able to free some pages. Retry the charge
2375 * before killing the task.
2376 *
2377 * Only for regular pages, though: huge pages are rather
2378 * unlikely to succeed so close to the limit, and we fall back
2379 * to regular pages anyway in case of failure.
2380 */
61e02c74 2381 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05 2382 goto retry;
6539cc05 2383
9b130619
JW
2384 if (nr_retries--)
2385 goto retry;
2386
38d38493 2387 if (gfp_mask & __GFP_RETRY_MAYFAIL)
29ef680a
MH
2388 goto nomem;
2389
a4ebf1b6
VA
2390 /* Avoid endless loop for tasks bypassed by the oom killer */
2391 if (passed_oom && task_is_dying())
2392 goto nomem;
6539cc05 2393
29ef680a
MH
2394 /*
2395 * keep retrying as long as the memcg oom killer is able to make
2396 * a forward progress or bypass the charge if the oom killer
2397 * couldn't make any progress.
2398 */
becdf89d
SB
2399 if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2400 get_order(nr_pages * PAGE_SIZE))) {
a4ebf1b6 2401 passed_oom = true;
d977aa93 2402 nr_retries = MAX_RECLAIM_RETRIES;
29ef680a 2403 goto retry;
29ef680a 2404 }
7a81b88c 2405nomem:
1461e8c2
SB
2406 /*
2407 * Memcg doesn't have a dedicated reserve for atomic
2408 * allocations. But like the global atomic pool, we need to
2409 * put the burden of reclaim on regular allocation requests
2410 * and let these go through as privileged allocations.
2411 */
2412 if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
3168ecbe 2413 return -ENOMEM;
10d53c74 2414force:
d6e103a7
RG
2415 /*
2416 * If the allocation has to be enforced, don't forget to raise
2417 * a MEMCG_MAX event.
2418 */
2419 if (!raised_max_event)
2420 memcg_memory_event(mem_over_limit, MEMCG_MAX);
2421
10d53c74
TH
2422 /*
2423 * The allocation either can't fail or will lead to more memory
2424 * being freed very soon. Allow memory usage go over the limit
2425 * temporarily by force charging it.
2426 */
2427 page_counter_charge(&memcg->memory, nr_pages);
7941d214 2428 if (do_memsw_account())
10d53c74 2429 page_counter_charge(&memcg->memsw, nr_pages);
10d53c74
TH
2430
2431 return 0;
6539cc05
JW
2432
2433done_restock:
2434 if (batch > nr_pages)
2435 refill_stock(memcg, batch - nr_pages);
b23afb93 2436
241994ed 2437 /*
b23afb93
TH
2438 * If the hierarchy is above the normal consumption range, schedule
2439 * reclaim on returning to userland. We can perform reclaim here
71baba4b 2440 * if __GFP_RECLAIM but let's always punt for simplicity and so that
b23afb93
TH
2441 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2442 * not recorded as it most likely matches current's and won't
2443 * change in the meantime. As high limit is checked again before
2444 * reclaim, the cost of mismatch is negligible.
241994ed
JW
2445 */
2446 do {
4b82ab4f
JK
2447 bool mem_high, swap_high;
2448
2449 mem_high = page_counter_read(&memcg->memory) >
2450 READ_ONCE(memcg->memory.high);
2451 swap_high = page_counter_read(&memcg->swap) >
2452 READ_ONCE(memcg->swap.high);
2453
2454 /* Don't bother a random interrupted task */
086f694a 2455 if (!in_task()) {
4b82ab4f 2456 if (mem_high) {
f7e1cb6e
JW
2457 schedule_work(&memcg->high_work);
2458 break;
2459 }
4b82ab4f
JK
2460 continue;
2461 }
2462
2463 if (mem_high || swap_high) {
2464 /*
2465 * The allocating tasks in this cgroup will need to do
2466 * reclaim or be throttled to prevent further growth
2467 * of the memory or swap footprints.
2468 *
2469 * Target some best-effort fairness between the tasks,
2470 * and distribute reclaim work and delay penalties
2471 * based on how much each task is actually allocating.
2472 */
9516a18a 2473 current->memcg_nr_pages_over_high += batch;
b23afb93
TH
2474 set_notify_resume(current);
2475 break;
2476 }
241994ed 2477 } while ((memcg = parent_mem_cgroup(memcg)));
10d53c74 2478
63fd3270
JW
2479 /*
2480 * Reclaim is set up above to be called from the userland
2481 * return path. But also attempt synchronous reclaim to avoid
2482 * excessive overrun while the task is still inside the
2483 * kernel. If this is successful, the return path will see it
2484 * when it rechecks the overage and simply bail out.
2485 */
c9afe31e
SB
2486 if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2487 !(current->flags & PF_MEMALLOC) &&
63fd3270 2488 gfpflags_allow_blocking(gfp_mask))
9ea9cb00 2489 mem_cgroup_handle_over_high(gfp_mask);
10d53c74 2490 return 0;
7a81b88c 2491}
8a9f3ccd 2492
75fe8ec2
JW
2493static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2494 unsigned int nr_pages)
2495{
2496 if (mem_cgroup_is_root(memcg))
2497 return 0;
2498
2499 return try_charge_memcg(memcg, gfp_mask, nr_pages);
2500}
2501
118f2875 2502static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
0a31bc97 2503{
02f4bbef 2504 VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
0a31bc97 2505 /*
a5eb011a 2506 * Any of the following ensures page's memcg stability:
0a31bc97 2507 *
a0b5b414
JW
2508 * - the page lock
2509 * - LRU isolation
a0b5b414 2510 * - exclusive reference
0a31bc97 2511 */
118f2875 2512 folio->memcg_data = (unsigned long)memcg;
7a81b88c 2513}
66e1707b 2514
15ca4fa9
SB
2515#ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
2516static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2517 struct pglist_data *pgdat,
2518 enum node_stat_item idx, int nr)
2519{
2520 struct lruvec *lruvec;
2521
2522 if (likely(!in_nmi())) {
2523 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2524 mod_memcg_lruvec_state(lruvec, idx, nr);
2525 } else {
2526 struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id];
2527
8dcb0ed8
SB
2528 /* preemption is disabled in_nmi(). */
2529 css_rstat_updated(&memcg->css, smp_processor_id());
15ca4fa9
SB
2530 if (idx == NR_SLAB_RECLAIMABLE_B)
2531 atomic_add(nr, &pn->slab_reclaimable);
2532 else
2533 atomic_add(nr, &pn->slab_unreclaimable);
2534 }
2535}
2536#else
2537static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2538 struct pglist_data *pgdat,
2539 enum node_stat_item idx, int nr)
2540{
2541 struct lruvec *lruvec;
2542
2543 lruvec = mem_cgroup_lruvec(memcg, pgdat);
2544 mod_memcg_lruvec_state(lruvec, idx, nr);
2545}
2546#endif
2547
eee8a177 2548static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
91882c16
SB
2549 struct pglist_data *pgdat,
2550 enum node_stat_item idx, int nr)
a7ebf564
WL
2551{
2552 struct mem_cgroup *memcg;
a7ebf564
WL
2553
2554 rcu_read_lock();
2555 memcg = obj_cgroup_memcg(objcg);
15ca4fa9 2556 account_slab_nmi_safe(memcg, pgdat, idx, nr);
a7ebf564
WL
2557 rcu_read_unlock();
2558}
2559
fc4db90f
RG
2560static __always_inline
2561struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
8380ce47 2562{
8380ce47 2563 /*
9855609b
RG
2564 * Slab objects are accounted individually, not per-page.
2565 * Memcg membership data for each individual object is saved in
21c690a3 2566 * slab->obj_exts.
8380ce47 2567 */
4b5f8d9a 2568 if (folio_test_slab(folio)) {
21c690a3 2569 struct slabobj_ext *obj_exts;
4b5f8d9a 2570 struct slab *slab;
9855609b
RG
2571 unsigned int off;
2572
4b5f8d9a 2573 slab = folio_slab(folio);
21c690a3
SB
2574 obj_exts = slab_obj_exts(slab);
2575 if (!obj_exts)
4b5f8d9a
VB
2576 return NULL;
2577
2578 off = obj_to_index(slab->slab_cache, slab, p);
21c690a3
SB
2579 if (obj_exts[off].objcg)
2580 return obj_cgroup_memcg(obj_exts[off].objcg);
10befea9
RG
2581
2582 return NULL;
9855609b 2583 }
8380ce47 2584
bcfe06bf 2585 /*
becacb04 2586 * folio_memcg_check() is used here, because in theory we can encounter
4b5f8d9a 2587 * a folio where the slab flag has been cleared already, but
21c690a3 2588 * slab->obj_exts has not been freed yet
becacb04 2589 * folio_memcg_check() will guarantee that a proper memory
bcfe06bf
RG
2590 * cgroup pointer or NULL will be returned.
2591 */
becacb04 2592 return folio_memcg_check(folio);
8380ce47
RG
2593}
2594
fc4db90f
RG
2595/*
2596 * Returns a pointer to the memory cgroup to which the kernel object is charged.
4fd568fa 2597 * It is not suitable for objects allocated using vmalloc().
fc4db90f
RG
2598 *
2599 * A passed kernel object must be a slab object or a generic kernel page.
2600 *
2601 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2602 * cgroup_mutex, etc.
2603 */
2604struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2605{
2606 if (mem_cgroup_disabled())
2607 return NULL;
2608
2609 return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
2610}
2611
f4840ccf
JW
2612static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2613{
2614 struct obj_cgroup *objcg = NULL;
2615
7848ed62 2616 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
f4840ccf 2617 objcg = rcu_dereference(memcg->objcg);
7d0715d0 2618 if (likely(objcg && obj_cgroup_tryget(objcg)))
f4840ccf
JW
2619 break;
2620 objcg = NULL;
2621 }
2622 return objcg;
2623}
2624
1aacbd35
RG
2625static struct obj_cgroup *current_objcg_update(void)
2626{
2627 struct mem_cgroup *memcg;
2628 struct obj_cgroup *old, *objcg = NULL;
2629
2630 do {
2631 /* Atomically drop the update bit. */
2632 old = xchg(&current->objcg, NULL);
2633 if (old) {
2634 old = (struct obj_cgroup *)
2635 ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
91b71e78 2636 obj_cgroup_put(old);
1aacbd35
RG
2637
2638 old = NULL;
2639 }
2640
2641 /* If new objcg is NULL, no reason for the second atomic update. */
2642 if (!current->mm || (current->flags & PF_KTHREAD))
2643 return NULL;
2644
2645 /*
2646 * Release the objcg pointer from the previous iteration,
2647 * if try_cmpxcg() below fails.
2648 */
2649 if (unlikely(objcg)) {
2650 obj_cgroup_put(objcg);
2651 objcg = NULL;
2652 }
2653
2654 /*
2655 * Obtain the new objcg pointer. The current task can be
2656 * asynchronously moved to another memcg and the previous
2657 * memcg can be offlined. So let's get the memcg pointer
2658 * and try get a reference to objcg under a rcu read lock.
2659 */
2660
2661 rcu_read_lock();
2662 memcg = mem_cgroup_from_task(current);
2663 objcg = __get_obj_cgroup_from_memcg(memcg);
2664 rcu_read_unlock();
2665
2666 /*
2667 * Try set up a new objcg pointer atomically. If it
2668 * fails, it means the update flag was set concurrently, so
2669 * the whole procedure should be repeated.
2670 */
2671 } while (!try_cmpxchg(&current->objcg, &old, objcg));
2672
2673 return objcg;
2674}
2675
e86828e5
RG
2676__always_inline struct obj_cgroup *current_obj_cgroup(void)
2677{
2678 struct mem_cgroup *memcg;
2679 struct obj_cgroup *objcg;
2680
25352d2f
SB
2681 if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi())
2682 return NULL;
2683
e86828e5
RG
2684 if (in_task()) {
2685 memcg = current->active_memcg;
2686 if (unlikely(memcg))
2687 goto from_memcg;
2688
2689 objcg = READ_ONCE(current->objcg);
2690 if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
2691 objcg = current_objcg_update();
2692 /*
2693 * Objcg reference is kept by the task, so it's safe
2694 * to use the objcg by the current task.
2695 */
2696 return objcg;
2697 }
2698
2699 memcg = this_cpu_read(int_active_memcg);
2700 if (unlikely(memcg))
2701 goto from_memcg;
2702
2703 return NULL;
2704
2705from_memcg:
5f79489a 2706 objcg = NULL;
e86828e5
RG
2707 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
2708 /*
2709 * Memcg pointer is protected by scope (see set_active_memcg())
2710 * and is pinning the corresponding objcg, so objcg can't go
2711 * away and can be used within the scope without any additional
2712 * protection.
2713 */
2714 objcg = rcu_dereference_check(memcg->objcg, 1);
2715 if (likely(objcg))
2716 break;
e86828e5
RG
2717 }
2718
2719 return objcg;
2720}
2721
074e3e26 2722struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
f4840ccf
JW
2723{
2724 struct obj_cgroup *objcg;
2725
f7a449f7 2726 if (!memcg_kmem_online())
f4840ccf
JW
2727 return NULL;
2728
074e3e26
MWO
2729 if (folio_memcg_kmem(folio)) {
2730 objcg = __folio_objcg(folio);
f4840ccf
JW
2731 obj_cgroup_get(objcg);
2732 } else {
2733 struct mem_cgroup *memcg;
bf4f0599 2734
f4840ccf 2735 rcu_read_lock();
074e3e26 2736 memcg = __folio_memcg(folio);
f4840ccf
JW
2737 if (memcg)
2738 objcg = __get_obj_cgroup_from_memcg(memcg);
2739 else
2740 objcg = NULL;
2741 rcu_read_unlock();
2742 }
bf4f0599
RG
2743 return objcg;
2744}
2745
9d3edf96
SB
2746#ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
2747static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
2748{
2749 if (likely(!in_nmi())) {
2750 mod_memcg_state(memcg, MEMCG_KMEM, val);
2751 } else {
8dcb0ed8
SB
2752 /* preemption is disabled in_nmi(). */
2753 css_rstat_updated(&memcg->css, smp_processor_id());
9d3edf96
SB
2754 atomic_add(val, &memcg->kmem_stat);
2755 }
2756}
2757#else
2758static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
2759{
2760 mod_memcg_state(memcg, MEMCG_KMEM, val);
2761}
2762#endif
2763
f1286fae
MS
2764/*
2765 * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2766 * @objcg: object cgroup to uncharge
2767 * @nr_pages: number of pages to uncharge
2768 */
e74d2259
MS
2769static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2770 unsigned int nr_pages)
2771{
2772 struct mem_cgroup *memcg;
2773
2774 memcg = get_mem_cgroup_from_objcg(objcg);
e74d2259 2775
9d3edf96 2776 account_kmem_nmi_safe(memcg, -nr_pages);
04fbe921 2777 memcg1_account_kmem(memcg, -nr_pages);
20d6c172
SB
2778 if (!mem_cgroup_is_root(memcg))
2779 refill_stock(memcg, nr_pages);
e74d2259 2780
e74d2259 2781 css_put(&memcg->css);
e74d2259
MS
2782}
2783
f1286fae
MS
2784/*
2785 * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2786 * @objcg: object cgroup to charge
45264778 2787 * @gfp: reclaim mode
92d0510c 2788 * @nr_pages: number of pages to charge
45264778
VD
2789 *
2790 * Returns 0 on success, an error code on failure.
2791 */
f1286fae
MS
2792static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2793 unsigned int nr_pages)
7ae1e1d0 2794{
f1286fae 2795 struct mem_cgroup *memcg;
7ae1e1d0
GC
2796 int ret;
2797
f1286fae
MS
2798 memcg = get_mem_cgroup_from_objcg(objcg);
2799
c5c8b16b 2800 ret = try_charge_memcg(memcg, gfp, nr_pages);
52c29b04 2801 if (ret)
f1286fae 2802 goto out;
52c29b04 2803
9d3edf96 2804 account_kmem_nmi_safe(memcg, nr_pages);
04fbe921 2805 memcg1_account_kmem(memcg, nr_pages);
f1286fae
MS
2806out:
2807 css_put(&memcg->css);
4b13f64d 2808
f1286fae 2809 return ret;
4b13f64d
RG
2810}
2811
7cc57eca
MWO
2812static struct obj_cgroup *page_objcg(const struct page *page)
2813{
2814 unsigned long memcg_data = page->memcg_data;
2815
2816 if (mem_cgroup_disabled() || !memcg_data)
2817 return NULL;
2818
2819 VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM,
2820 page);
2821 return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM);
2822}
2823
2824static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg)
2825{
2826 page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM;
2827}
2828
45264778 2829/**
f4b00eab 2830 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
45264778
VD
2831 * @page: page to charge
2832 * @gfp: reclaim mode
2833 * @order: allocation order
2834 *
2835 * Returns 0 on success, an error code on failure.
2836 */
f4b00eab 2837int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
7ae1e1d0 2838{
b4e0b68f 2839 struct obj_cgroup *objcg;
fcff7d7e 2840 int ret = 0;
7ae1e1d0 2841
e86828e5 2842 objcg = current_obj_cgroup();
b4e0b68f
MS
2843 if (objcg) {
2844 ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
4d96ba35 2845 if (!ret) {
e86828e5 2846 obj_cgroup_get(objcg);
7cc57eca 2847 page_set_objcg(page, objcg);
1a3e1f40 2848 return 0;
4d96ba35 2849 }
c4159a75 2850 }
d05e83a6 2851 return ret;
7ae1e1d0 2852}
49a18eae 2853
45264778 2854/**
f4b00eab 2855 * __memcg_kmem_uncharge_page: uncharge a kmem page
45264778
VD
2856 * @page: page to uncharge
2857 * @order: allocation order
2858 */
f4b00eab 2859void __memcg_kmem_uncharge_page(struct page *page, int order)
7ae1e1d0 2860{
0d2a2605 2861 struct obj_cgroup *objcg = page_objcg(page);
f3ccb2c4 2862 unsigned int nr_pages = 1 << order;
7ae1e1d0 2863
0d2a2605 2864 if (!objcg)
7ae1e1d0
GC
2865 return;
2866
b4e0b68f 2867 obj_cgroup_uncharge_pages(objcg, nr_pages);
0d2a2605 2868 page->memcg_data = 0;
b4e0b68f 2869 obj_cgroup_put(objcg);
60d3fd32 2870}
bf4f0599 2871
bc730030 2872static void __account_obj_stock(struct obj_cgroup *objcg,
c80509ef 2873 struct obj_stock_pcp *stock, int nr,
bc730030 2874 struct pglist_data *pgdat, enum node_stat_item idx)
68ac5b3c 2875{
68ac5b3c
WL
2876 int *bytes;
2877
68ac5b3c
WL
2878 /*
2879 * Save vmstat data in stock and skip vmstat array update unless
bc730030 2880 * accumulating over a page of vmstat data or when pgdat changes.
68ac5b3c 2881 */
bc730030 2882 if (stock->cached_pgdat != pgdat) {
68ac5b3c 2883 /* Flush the existing cached vmstat data */
7fa0dacb
WL
2884 struct pglist_data *oldpg = stock->cached_pgdat;
2885
68ac5b3c 2886 if (stock->nr_slab_reclaimable_b) {
eee8a177 2887 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
68ac5b3c
WL
2888 stock->nr_slab_reclaimable_b);
2889 stock->nr_slab_reclaimable_b = 0;
2890 }
2891 if (stock->nr_slab_unreclaimable_b) {
eee8a177 2892 mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
68ac5b3c
WL
2893 stock->nr_slab_unreclaimable_b);
2894 stock->nr_slab_unreclaimable_b = 0;
2895 }
2896 stock->cached_pgdat = pgdat;
2897 }
2898
2899 bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
2900 : &stock->nr_slab_unreclaimable_b;
2901 /*
2902 * Even for large object >= PAGE_SIZE, the vmstat data will still be
2903 * cached locally at least once before pushing it out.
2904 */
2905 if (!*bytes) {
2906 *bytes = nr;
2907 nr = 0;
2908 } else {
2909 *bytes += nr;
2910 if (abs(*bytes) > PAGE_SIZE) {
2911 nr = *bytes;
2912 *bytes = 0;
2913 } else {
2914 nr = 0;
2915 }
2916 }
2917 if (nr)
eee8a177 2918 mod_objcg_mlstate(objcg, pgdat, idx, nr);
68ac5b3c
WL
2919}
2920
bc730030
VB
2921static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
2922 struct pglist_data *pgdat, enum node_stat_item idx)
bf4f0599 2923{
c80509ef 2924 struct obj_stock_pcp *stock;
bf4f0599
RG
2925 bool ret = false;
2926
200577f6
SB
2927 if (!local_trylock(&obj_stock.lock))
2928 return ret;
fead2b86 2929
c80509ef 2930 stock = this_cpu_ptr(&obj_stock);
3b8abb32 2931 if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
bf4f0599
RG
2932 stock->nr_bytes -= nr_bytes;
2933 ret = true;
bc730030
VB
2934
2935 if (pgdat)
2936 __account_obj_stock(objcg, stock, nr_bytes, pgdat, idx);
bf4f0599
RG
2937 }
2938
200577f6 2939 local_unlock(&obj_stock.lock);
bf4f0599
RG
2940
2941 return ret;
2942}
2943
c80509ef 2944static void drain_obj_stock(struct obj_stock_pcp *stock)
bf4f0599 2945{
3b8abb32 2946 struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
bf4f0599
RG
2947
2948 if (!old)
ae51c775 2949 return;
bf4f0599
RG
2950
2951 if (stock->nr_bytes) {
2952 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
2953 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
2954
af9a3b69
JW
2955 if (nr_pages) {
2956 struct mem_cgroup *memcg;
2957
2958 memcg = get_mem_cgroup_from_objcg(old);
2959
04fbe921
RG
2960 mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
2961 memcg1_account_kmem(memcg, -nr_pages);
89f342af
SB
2962 if (!mem_cgroup_is_root(memcg))
2963 memcg_uncharge(memcg, nr_pages);
af9a3b69
JW
2964
2965 css_put(&memcg->css);
2966 }
bf4f0599
RG
2967
2968 /*
2969 * The leftover is flushed to the centralized per-memcg value.
2970 * On the next attempt to refill obj stock it will be moved
2971 * to a per-cpu stock (probably, on an other CPU), see
2972 * refill_obj_stock().
2973 *
2974 * How often it's flushed is a trade-off between the memory
2975 * limit enforcement accuracy and potential CPU contention,
2976 * so it might be changed in the future.
2977 */
2978 atomic_add(nr_bytes, &old->nr_charged_bytes);
2979 stock->nr_bytes = 0;
2980 }
2981
68ac5b3c
WL
2982 /*
2983 * Flush the vmstat data in current stock
2984 */
2985 if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
2986 if (stock->nr_slab_reclaimable_b) {
eee8a177 2987 mod_objcg_mlstate(old, stock->cached_pgdat,
68ac5b3c
WL
2988 NR_SLAB_RECLAIMABLE_B,
2989 stock->nr_slab_reclaimable_b);
2990 stock->nr_slab_reclaimable_b = 0;
2991 }
2992 if (stock->nr_slab_unreclaimable_b) {
eee8a177 2993 mod_objcg_mlstate(old, stock->cached_pgdat,
68ac5b3c
WL
2994 NR_SLAB_UNRECLAIMABLE_B,
2995 stock->nr_slab_unreclaimable_b);
2996 stock->nr_slab_unreclaimable_b = 0;
2997 }
2998 stock->cached_pgdat = NULL;
2999 }
3000
3b8abb32 3001 WRITE_ONCE(stock->cached_objcg, NULL);
ae51c775 3002 obj_cgroup_put(old);
bf4f0599
RG
3003}
3004
c80509ef 3005static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
bf4f0599
RG
3006 struct mem_cgroup *root_memcg)
3007{
3b8abb32 3008 struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
bf4f0599 3009 struct mem_cgroup *memcg;
c80509ef 3010 bool flush = false;
bf4f0599 3011
c80509ef 3012 rcu_read_lock();
3b8abb32
RG
3013 if (objcg) {
3014 memcg = obj_cgroup_memcg(objcg);
bf4f0599 3015 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
c80509ef 3016 flush = true;
bf4f0599 3017 }
c80509ef 3018 rcu_read_unlock();
bf4f0599 3019
c80509ef 3020 return flush;
bf4f0599
RG
3021}
3022
5387c904 3023static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
bc730030
VB
3024 bool allow_uncharge, int nr_acct, struct pglist_data *pgdat,
3025 enum node_stat_item idx)
bf4f0599 3026{
c80509ef 3027 struct obj_stock_pcp *stock;
5387c904 3028 unsigned int nr_pages = 0;
bf4f0599 3029
200577f6
SB
3030 if (!local_trylock(&obj_stock.lock)) {
3031 if (pgdat)
3032 mod_objcg_mlstate(objcg, pgdat, idx, nr_bytes);
3033 nr_pages = nr_bytes >> PAGE_SHIFT;
3034 nr_bytes = nr_bytes & (PAGE_SIZE - 1);
3035 atomic_add(nr_bytes, &objcg->nr_charged_bytes);
3036 goto out;
3037 }
fead2b86 3038
c80509ef 3039 stock = this_cpu_ptr(&obj_stock);
3b8abb32 3040 if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
ac26920d
SB
3041 drain_obj_stock(stock);
3042 obj_cgroup_get(objcg);
3043 stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3044 ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3045 WRITE_ONCE(stock->cached_objcg, objcg);
3046
5387c904 3047 allow_uncharge = true; /* Allow uncharge when objcg changes */
bf4f0599
RG
3048 }
3049 stock->nr_bytes += nr_bytes;
3050
bc730030
VB
3051 if (pgdat)
3052 __account_obj_stock(objcg, stock, nr_acct, pgdat, idx);
3053
5387c904
WL
3054 if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3055 nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3056 stock->nr_bytes &= (PAGE_SIZE - 1);
3057 }
bf4f0599 3058
200577f6
SB
3059 local_unlock(&obj_stock.lock);
3060out:
5387c904
WL
3061 if (nr_pages)
3062 obj_cgroup_uncharge_pages(objcg, nr_pages);
bf4f0599
RG
3063}
3064
bc730030
VB
3065static int obj_cgroup_charge_account(struct obj_cgroup *objcg, gfp_t gfp, size_t size,
3066 struct pglist_data *pgdat, enum node_stat_item idx)
bf4f0599 3067{
bf4f0599
RG
3068 unsigned int nr_pages, nr_bytes;
3069 int ret;
3070
bc730030 3071 if (likely(consume_obj_stock(objcg, size, pgdat, idx)))
bf4f0599
RG
3072 return 0;
3073
3074 /*
5387c904 3075 * In theory, objcg->nr_charged_bytes can have enough
bf4f0599 3076 * pre-charged bytes to satisfy the allocation. However,
5387c904
WL
3077 * flushing objcg->nr_charged_bytes requires two atomic
3078 * operations, and objcg->nr_charged_bytes can't be big.
3079 * The shared objcg->nr_charged_bytes can also become a
3080 * performance bottleneck if all tasks of the same memcg are
3081 * trying to update it. So it's better to ignore it and try
3082 * grab some new pages. The stock's nr_bytes will be flushed to
3083 * objcg->nr_charged_bytes later on when objcg changes.
3084 *
3085 * The stock's nr_bytes may contain enough pre-charged bytes
3086 * to allow one less page from being charged, but we can't rely
3087 * on the pre-charged bytes not being changed outside of
3088 * consume_obj_stock() or refill_obj_stock(). So ignore those
3089 * pre-charged bytes as well when charging pages. To avoid a
3090 * page uncharge right after a page charge, we set the
3091 * allow_uncharge flag to false when calling refill_obj_stock()
3092 * to temporarily allow the pre-charged bytes to exceed the page
3093 * size limit. The maximum reachable value of the pre-charged
3094 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3095 * race.
bf4f0599 3096 */
bf4f0599
RG
3097 nr_pages = size >> PAGE_SHIFT;
3098 nr_bytes = size & (PAGE_SIZE - 1);
3099
3100 if (nr_bytes)
3101 nr_pages += 1;
3102
e74d2259 3103 ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
bc730030
VB
3104 if (!ret && (nr_bytes || pgdat))
3105 refill_obj_stock(objcg, nr_bytes ? PAGE_SIZE - nr_bytes : 0,
3106 false, size, pgdat, idx);
bf4f0599 3107
bf4f0599
RG
3108 return ret;
3109}
3110
bc730030
VB
3111int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3112{
3113 return obj_cgroup_charge_account(objcg, gfp, size, NULL, 0);
3114}
3115
bf4f0599
RG
3116void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3117{
bc730030 3118 refill_obj_stock(objcg, size, true, 0, NULL, 0);
bf4f0599
RG
3119}
3120
e6100a45
VB
3121static inline size_t obj_full_size(struct kmem_cache *s)
3122{
3123 /*
3124 * For each accounted object there is an extra space which is used
3125 * to store obj_cgroup membership. Charge it too.
3126 */
3127 return s->size + sizeof(struct obj_cgroup *);
3128}
3129
3130bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3131 gfp_t flags, size_t size, void **p)
3132{
3133 struct obj_cgroup *objcg;
3134 struct slab *slab;
3135 unsigned long off;
3136 size_t i;
3137
3138 /*
3139 * The obtained objcg pointer is safe to use within the current scope,
3140 * defined by current task or set_active_memcg() pair.
3141 * obj_cgroup_get() is used to get a permanent reference.
3142 */
3143 objcg = current_obj_cgroup();
3144 if (!objcg)
3145 return true;
3146
3147 /*
3148 * slab_alloc_node() avoids the NULL check, so we might be called with a
3149 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3150 * the whole requested size.
3151 * return success as there's nothing to free back
3152 */
3153 if (unlikely(*p == NULL))
3154 return true;
3155
3156 flags &= gfp_allowed_mask;
3157
3158 if (lru) {
3159 int ret;
3160 struct mem_cgroup *memcg;
3161
3162 memcg = get_mem_cgroup_from_objcg(objcg);
3163 ret = memcg_list_lru_alloc(memcg, lru, flags);
3164 css_put(&memcg->css);
3165
3166 if (ret)
3167 return false;
3168 }
3169
e6100a45
VB
3170 for (i = 0; i < size; i++) {
3171 slab = virt_to_slab(p[i]);
3172
3173 if (!slab_obj_exts(slab) &&
3174 alloc_slab_obj_exts(slab, s, flags, false)) {
e6100a45
VB
3175 continue;
3176 }
3177
bc730030
VB
3178 /*
3179 * if we fail and size is 1, memcg_alloc_abort_single() will
3180 * just free the object, which is ok as we have not assigned
3181 * objcg to its obj_ext yet
3182 *
3183 * for larger sizes, kmem_cache_free_bulk() will uncharge
3184 * any objects that were already charged and obj_ext assigned
3185 *
3186 * TODO: we could batch this until slab_pgdat(slab) changes
3187 * between iterations, with a more complicated undo
3188 */
3189 if (obj_cgroup_charge_account(objcg, flags, obj_full_size(s),
3190 slab_pgdat(slab), cache_vmstat_idx(s)))
3191 return false;
3192
e6100a45
VB
3193 off = obj_to_index(s, slab, p[i]);
3194 obj_cgroup_get(objcg);
3195 slab_obj_exts(slab)[off].objcg = objcg;
e6100a45
VB
3196 }
3197
3198 return true;
3199}
3200
3201void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3202 void **p, int objects, struct slabobj_ext *obj_exts)
3203{
bc730030
VB
3204 size_t obj_size = obj_full_size(s);
3205
e6100a45
VB
3206 for (int i = 0; i < objects; i++) {
3207 struct obj_cgroup *objcg;
3208 unsigned int off;
3209
3210 off = obj_to_index(s, slab, p[i]);
3211 objcg = obj_exts[off].objcg;
3212 if (!objcg)
3213 continue;
3214
3215 obj_exts[off].objcg = NULL;
bc730030
VB
3216 refill_obj_stock(objcg, obj_size, true, -obj_size,
3217 slab_pgdat(slab), cache_vmstat_idx(s));
e6100a45
VB
3218 obj_cgroup_put(objcg);
3219 }
3220}
7ae1e1d0 3221
ca3e0214 3222/*
1506c255
MWO
3223 * The objcg is only set on the first page, so transfer it to all the
3224 * other pages.
ca3e0214 3225 */
7cc57eca 3226void split_page_memcg(struct page *page, unsigned order)
ca3e0214 3227{
7cc57eca 3228 struct obj_cgroup *objcg = page_objcg(page);
1506c255 3229 unsigned int i, nr = 1 << order;
ca3e0214 3230
7cc57eca 3231 if (!objcg)
3d37c4a9 3232 return;
b070e65c 3233
1506c255 3234 for (i = 1; i < nr; i++)
7cc57eca 3235 page_set_objcg(&page[i], objcg);
b4e0b68f 3236
7cc57eca 3237 obj_cgroup_get_many(objcg, nr - 1);
fa23a338
MWO
3238}
3239
3240void folio_split_memcg_refs(struct folio *folio, unsigned old_order,
3241 unsigned new_order)
3242{
3243 unsigned new_refs;
3244
3245 if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
3246 return;
3247
3248 new_refs = (1 << (old_order - new_order)) - 1;
3249 css_get_many(&__folio_memcg(folio)->css, new_refs);
ca3e0214 3250}
ca3e0214 3251
66d60c42 3252unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
ce00a967 3253{
42a30035 3254 unsigned long val;
ce00a967 3255
3e32cb2e 3256 if (mem_cgroup_is_root(memcg)) {
a2174e95 3257 /*
f82a7a86
YA
3258 * Approximate root's usage from global state. This isn't
3259 * perfect, but the root usage was always an approximation.
a2174e95 3260 */
f82a7a86
YA
3261 val = global_node_page_state(NR_FILE_PAGES) +
3262 global_node_page_state(NR_ANON_MAPPED);
42a30035 3263 if (swap)
f82a7a86 3264 val += total_swap_pages - get_nr_swap_pages();
3e32cb2e 3265 } else {
ce00a967 3266 if (!swap)
3e32cb2e 3267 val = page_counter_read(&memcg->memory);
ce00a967 3268 else
3e32cb2e 3269 val = page_counter_read(&memcg->memsw);
ce00a967 3270 }
c12176d3 3271 return val;
ce00a967
JW
3272}
3273
567e9ab2 3274static int memcg_online_kmem(struct mem_cgroup *memcg)
d6441637 3275{
bf4f0599 3276 struct obj_cgroup *objcg;
d6441637 3277
9c94bef9 3278 if (mem_cgroup_kmem_disabled())
b313aeee
VD
3279 return 0;
3280
da0efe30
MS
3281 if (unlikely(mem_cgroup_is_root(memcg)))
3282 return 0;
d6441637 3283
bf4f0599 3284 objcg = obj_cgroup_alloc();
f9c69d63 3285 if (!objcg)
bf4f0599 3286 return -ENOMEM;
f9c69d63 3287
bf4f0599
RG
3288 objcg->memcg = memcg;
3289 rcu_assign_pointer(memcg->objcg, objcg);
675d6c9b
RG
3290 obj_cgroup_get(objcg);
3291 memcg->orig_objcg = objcg;
bf4f0599 3292
f7a449f7 3293 static_branch_enable(&memcg_kmem_online_key);
d648bcc7 3294
f9c69d63 3295 memcg->kmemcg_id = memcg->id.id;
0b8f73e1
JW
3296
3297 return 0;
d6441637
VD
3298}
3299
8e0a8912
JW
3300static void memcg_offline_kmem(struct mem_cgroup *memcg)
3301{
64268868 3302 struct mem_cgroup *parent;
8e0a8912 3303
9c94bef9 3304 if (mem_cgroup_kmem_disabled())
da0efe30
MS
3305 return;
3306
3307 if (unlikely(mem_cgroup_is_root(memcg)))
8e0a8912 3308 return;
9855609b 3309
8e0a8912
JW
3310 parent = parent_mem_cgroup(memcg);
3311 if (!parent)
3312 parent = root_mem_cgroup;
3313
1f391eb2 3314 memcg_reparent_list_lrus(memcg, parent);
fb56fdf8
KS
3315
3316 /*
3317 * Objcg's reparenting must be after list_lru's, make sure list_lru
3318 * helpers won't use parent's list_lru until child is drained.
3319 */
3320 memcg_reparent_objcgs(memcg, parent);
8e0a8912 3321}
127424c8 3322
52ebea74
TH
3323#ifdef CONFIG_CGROUP_WRITEBACK
3324
3a8e9ac8
TH
3325#include <trace/events/writeback.h>
3326
841710aa
TH
3327static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3328{
3329 return wb_domain_init(&memcg->cgwb_domain, gfp);
3330}
3331
3332static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3333{
3334 wb_domain_exit(&memcg->cgwb_domain);
3335}
3336
2529bb3a
TH
3337static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3338{
3339 wb_domain_size_changed(&memcg->cgwb_domain);
3340}
3341
841710aa
TH
3342struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3343{
3344 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3345
3346 if (!memcg->css.parent)
3347 return NULL;
3348
3349 return &memcg->cgwb_domain;
3350}
3351
c2aa723a
TH
3352/**
3353 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3354 * @wb: bdi_writeback in question
c5edf9cd
TH
3355 * @pfilepages: out parameter for number of file pages
3356 * @pheadroom: out parameter for number of allocatable pages according to memcg
c2aa723a
TH
3357 * @pdirty: out parameter for number of dirty pages
3358 * @pwriteback: out parameter for number of pages under writeback
3359 *
c5edf9cd
TH
3360 * Determine the numbers of file, headroom, dirty, and writeback pages in
3361 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
3362 * is a bit more involved.
c2aa723a 3363 *
c5edf9cd
TH
3364 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
3365 * headroom is calculated as the lowest headroom of itself and the
3366 * ancestors. Note that this doesn't consider the actual amount of
3367 * available memory in the system. The caller should further cap
3368 * *@pheadroom accordingly.
c2aa723a 3369 */
c5edf9cd
TH
3370void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3371 unsigned long *pheadroom, unsigned long *pdirty,
3372 unsigned long *pwriteback)
c2aa723a
TH
3373{
3374 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3375 struct mem_cgroup *parent;
c2aa723a 3376
d9b3ce87 3377 mem_cgroup_flush_stats_ratelimited(memcg);
c2aa723a 3378
2d146aa3
JW
3379 *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
3380 *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
3381 *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
3382 memcg_page_state(memcg, NR_ACTIVE_FILE);
c2aa723a 3383
2d146aa3 3384 *pheadroom = PAGE_COUNTER_MAX;
c2aa723a 3385 while ((parent = parent_mem_cgroup(memcg))) {
15b42562 3386 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
d1663a90 3387 READ_ONCE(memcg->memory.high));
c2aa723a
TH
3388 unsigned long used = page_counter_read(&memcg->memory);
3389
c5edf9cd 3390 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
c2aa723a
TH
3391 memcg = parent;
3392 }
c2aa723a
TH
3393}
3394
97b27821
TH
3395/*
3396 * Foreign dirty flushing
3397 *
3398 * There's an inherent mismatch between memcg and writeback. The former
f0953a1b 3399 * tracks ownership per-page while the latter per-inode. This was a
97b27821
TH
3400 * deliberate design decision because honoring per-page ownership in the
3401 * writeback path is complicated, may lead to higher CPU and IO overheads
3402 * and deemed unnecessary given that write-sharing an inode across
3403 * different cgroups isn't a common use-case.
3404 *
3405 * Combined with inode majority-writer ownership switching, this works well
3406 * enough in most cases but there are some pathological cases. For
3407 * example, let's say there are two cgroups A and B which keep writing to
3408 * different but confined parts of the same inode. B owns the inode and
3409 * A's memory is limited far below B's. A's dirty ratio can rise enough to
3410 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
3411 * triggering background writeback. A will be slowed down without a way to
3412 * make writeback of the dirty pages happen.
3413 *
f0953a1b 3414 * Conditions like the above can lead to a cgroup getting repeatedly and
97b27821 3415 * severely throttled after making some progress after each
f0953a1b 3416 * dirty_expire_interval while the underlying IO device is almost
97b27821
TH
3417 * completely idle.
3418 *
3419 * Solving this problem completely requires matching the ownership tracking
3420 * granularities between memcg and writeback in either direction. However,
3421 * the more egregious behaviors can be avoided by simply remembering the
3422 * most recent foreign dirtying events and initiating remote flushes on
3423 * them when local writeback isn't enough to keep the memory clean enough.
3424 *
3425 * The following two functions implement such mechanism. When a foreign
3426 * page - a page whose memcg and writeback ownerships don't match - is
3427 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
3428 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
3429 * decides that the memcg needs to sleep due to high dirty ratio, it calls
3430 * mem_cgroup_flush_foreign() which queues writeback on the recorded
3431 * foreign bdi_writebacks which haven't expired. Both the numbers of
3432 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
3433 * limited to MEMCG_CGWB_FRN_CNT.
3434 *
3435 * The mechanism only remembers IDs and doesn't hold any object references.
3436 * As being wrong occasionally doesn't matter, updates and accesses to the
3437 * records are lockless and racy.
3438 */
9d8053fc 3439void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
97b27821
TH
3440 struct bdi_writeback *wb)
3441{
9d8053fc 3442 struct mem_cgroup *memcg = folio_memcg(folio);
97b27821
TH
3443 struct memcg_cgwb_frn *frn;
3444 u64 now = get_jiffies_64();
3445 u64 oldest_at = now;
3446 int oldest = -1;
3447 int i;
3448
9d8053fc 3449 trace_track_foreign_dirty(folio, wb);
3a8e9ac8 3450
97b27821
TH
3451 /*
3452 * Pick the slot to use. If there is already a slot for @wb, keep
3453 * using it. If not replace the oldest one which isn't being
3454 * written out.
3455 */
3456 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3457 frn = &memcg->cgwb_frn[i];
3458 if (frn->bdi_id == wb->bdi->id &&
3459 frn->memcg_id == wb->memcg_css->id)
3460 break;
3461 if (time_before64(frn->at, oldest_at) &&
3462 atomic_read(&frn->done.cnt) == 1) {
3463 oldest = i;
3464 oldest_at = frn->at;
3465 }
3466 }
3467
3468 if (i < MEMCG_CGWB_FRN_CNT) {
3469 /*
3470 * Re-using an existing one. Update timestamp lazily to
3471 * avoid making the cacheline hot. We want them to be
3472 * reasonably up-to-date and significantly shorter than
3473 * dirty_expire_interval as that's what expires the record.
3474 * Use the shorter of 1s and dirty_expire_interval / 8.
3475 */
3476 unsigned long update_intv =
3477 min_t(unsigned long, HZ,
3478 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
3479
3480 if (time_before64(frn->at, now - update_intv))
3481 frn->at = now;
3482 } else if (oldest >= 0) {
3483 /* replace the oldest free one */
3484 frn = &memcg->cgwb_frn[oldest];
3485 frn->bdi_id = wb->bdi->id;
3486 frn->memcg_id = wb->memcg_css->id;
3487 frn->at = now;
3488 }
3489}
3490
3491/* issue foreign writeback flushes for recorded foreign dirtying events */
3492void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
3493{
3494 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3495 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
3496 u64 now = jiffies_64;
3497 int i;
3498
3499 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3500 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
3501
3502 /*
3503 * If the record is older than dirty_expire_interval,
3504 * writeback on it has already started. No need to kick it
3505 * off again. Also, don't start a new one if there's
3506 * already one in flight.
3507 */
3508 if (time_after64(frn->at, now - intv) &&
3509 atomic_read(&frn->done.cnt) == 1) {
3510 frn->at = 0;
3a8e9ac8 3511 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
7490a2d2 3512 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
97b27821
TH
3513 WB_REASON_FOREIGN_FLUSH,
3514 &frn->done);
3515 }
3516 }
3517}
3518
841710aa
TH
3519#else /* CONFIG_CGROUP_WRITEBACK */
3520
3521static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3522{
3523 return 0;
3524}
3525
3526static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3527{
3528}
3529
2529bb3a
TH
3530static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3531{
3532}
3533
52ebea74
TH
3534#endif /* CONFIG_CGROUP_WRITEBACK */
3535
73f576c0
JW
3536/*
3537 * Private memory cgroup IDR
3538 *
3539 * Swap-out records and page cache shadow entries need to store memcg
3540 * references in constrained space, so we maintain an ID space that is
3541 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
3542 * memory-controlled cgroups to 64k.
3543 *
b8f2935f 3544 * However, there usually are many references to the offline CSS after
73f576c0
JW
3545 * the cgroup has been destroyed, such as page cache or reclaimable
3546 * slab objects, that don't need to hang on to the ID. We want to keep
3547 * those dead CSS from occupying IDs, or we might quickly exhaust the
3548 * relatively small ID space and prevent the creation of new cgroups
3549 * even when there are much fewer than 64k cgroups - possibly none.
3550 *
3551 * Maintain a private 16-bit ID space for memcg, and allow the ID to
3552 * be freed and recycled when it's no longer needed, which is usually
3553 * when the CSS is offlined.
3554 *
3555 * The only exception to that are records of swapped out tmpfs/shmem
3556 * pages that need to be attributed to live ancestors on swapin. But
3557 * those references are manageable from userspace.
3558 */
3559
60b1e24c 3560#define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
07222371 3561static DEFINE_XARRAY_ALLOC1(mem_cgroup_ids);
73f576c0 3562
7e97de0b
KT
3563static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
3564{
3565 if (memcg->id.id > 0) {
07222371 3566 xa_erase(&mem_cgroup_ids, memcg->id.id);
7e97de0b
KT
3567 memcg->id.id = 0;
3568 }
3569}
3570
e548ad4a
RG
3571void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
3572 unsigned int n)
73f576c0 3573{
1c2d479a 3574 refcount_add(n, &memcg->id.ref);
73f576c0
JW
3575}
3576
75fe8ec2 3577static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
73f576c0 3578{
1c2d479a 3579 if (refcount_sub_and_test(n, &memcg->id.ref)) {
7e97de0b 3580 mem_cgroup_id_remove(memcg);
73f576c0
JW
3581
3582 /* Memcg ID pins CSS */
3583 css_put(&memcg->css);
3584 }
3585}
3586
615d66c3
VD
3587static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
3588{
3589 mem_cgroup_id_put_many(memcg, 1);
3590}
3591
89ce924f
JW
3592struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
3593{
3594 while (!refcount_inc_not_zero(&memcg->id.ref)) {
3595 /*
3596 * The root cgroup cannot be destroyed, so it's refcount must
3597 * always be >= 1.
3598 */
3599 if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
3600 VM_BUG_ON(1);
3601 break;
3602 }
3603 memcg = parent_mem_cgroup(memcg);
3604 if (!memcg)
3605 memcg = root_mem_cgroup;
3606 }
3607 return memcg;
3608}
3609
73f576c0
JW
3610/**
3611 * mem_cgroup_from_id - look up a memcg from a memcg id
3612 * @id: the memcg id to look up
3613 *
3614 * Caller must hold rcu_read_lock().
3615 */
3616struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
3617{
3618 WARN_ON_ONCE(!rcu_read_lock_held());
07222371 3619 return xa_load(&mem_cgroup_ids, id);
73f576c0
JW
3620}
3621
c15187a4
RG
3622#ifdef CONFIG_SHRINKER_DEBUG
3623struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
3624{
3625 struct cgroup *cgrp;
3626 struct cgroup_subsys_state *css;
3627 struct mem_cgroup *memcg;
3628
3629 cgrp = cgroup_get_from_id(ino);
fa7e439c 3630 if (IS_ERR(cgrp))
c0f2df49 3631 return ERR_CAST(cgrp);
c15187a4
RG
3632
3633 css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
3634 if (css)
3635 memcg = container_of(css, struct mem_cgroup, css);
3636 else
3637 memcg = ERR_PTR(-ENOENT);
3638
3639 cgroup_put(cgrp);
3640
3641 return memcg;
3642}
3643#endif
3644
2059c8e3
CR
3645static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn)
3646{
3647 if (!pn)
3648 return;
3649
3650 free_percpu(pn->lruvec_stats_percpu);
3651 kfree(pn->lruvec_stats);
3652 kfree(pn);
3653}
3654
a8248bb7 3655static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
3656{
3657 struct mem_cgroup_per_node *pn;
8c9bb398 3658
1b6a58e2
HY
3659 pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
3660 node);
6d12e2d8 3661 if (!pn)
a8248bb7 3662 return false;
1ecaab2b 3663
aab6103b
RG
3664 pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
3665 GFP_KERNEL_ACCOUNT, node);
70a64b79
SB
3666 if (!pn->lruvec_stats)
3667 goto fail;
3668
7e1c0d6f
SB
3669 pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
3670 GFP_KERNEL_ACCOUNT);
70a64b79
SB
3671 if (!pn->lruvec_stats_percpu)
3672 goto fail;
00f3ca2c 3673
ef8f2327 3674 lruvec_init(&pn->lruvec);
ef8f2327
MG
3675 pn->memcg = memcg;
3676
54f72fe0 3677 memcg->nodeinfo[node] = pn;
a8248bb7 3678 return true;
70a64b79 3679fail:
2059c8e3 3680 free_mem_cgroup_per_node_info(pn);
a8248bb7 3681 return false;
6d12e2d8
KH
3682}
3683
40e952f9 3684static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 3685{
c8b2a36f 3686 int node;
59927fb9 3687
91b71e78 3688 obj_cgroup_put(memcg->orig_objcg);
675d6c9b 3689
c8b2a36f 3690 for_each_node(node)
2059c8e3 3691 free_mem_cgroup_per_node_info(memcg->nodeinfo[node]);
5d383b69 3692 memcg1_free_events(memcg);
410f8e82 3693 kfree(memcg->vmstats);
871789d4 3694 free_percpu(memcg->vmstats_percpu);
8ff69e2c 3695 kfree(memcg);
59927fb9 3696}
3afe36b1 3697
40e952f9
TE
3698static void mem_cgroup_free(struct mem_cgroup *memcg)
3699{
ec1c86b2 3700 lru_gen_exit_memcg(memcg);
40e952f9
TE
3701 memcg_wb_domain_exit(memcg);
3702 __mem_cgroup_free(memcg);
3703}
3704
9cee7e8e 3705static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
8cdea7c0 3706{
8a4b42b9
SB
3707 struct memcg_vmstats_percpu *statc;
3708 struct memcg_vmstats_percpu __percpu *pstatc_pcpu;
d142e3e6 3709 struct mem_cgroup *memcg;
9cee7e8e 3710 int node, cpu;
97b27821 3711 int __maybe_unused i;
07222371 3712 long error;
8cdea7c0 3713
97e4fc4b 3714 memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
c0ff4b85 3715 if (!memcg)
07222371 3716 return ERR_PTR(-ENOMEM);
0b8f73e1 3717
07222371
SB
3718 error = xa_alloc(&mem_cgroup_ids, &memcg->id.id, NULL,
3719 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
3720 if (error)
73f576c0 3721 goto fail;
07222371 3722 error = -ENOMEM;
73f576c0 3723
aab6103b
RG
3724 memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
3725 GFP_KERNEL_ACCOUNT);
410f8e82
SB
3726 if (!memcg->vmstats)
3727 goto fail;
3728
3e38e0aa
RG
3729 memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
3730 GFP_KERNEL_ACCOUNT);
871789d4 3731 if (!memcg->vmstats_percpu)
0b8f73e1 3732 goto fail;
78fb7466 3733
5d383b69
SB
3734 if (!memcg1_alloc_events(memcg))
3735 goto fail;
3736
9cee7e8e
YA
3737 for_each_possible_cpu(cpu) {
3738 if (parent)
8a4b42b9 3739 pstatc_pcpu = parent->vmstats_percpu;
9cee7e8e 3740 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
8a4b42b9 3741 statc->parent_pcpu = parent ? pstatc_pcpu : NULL;
9cee7e8e
YA
3742 statc->vmstats = memcg->vmstats;
3743 }
3744
3ed28fa1 3745 for_each_node(node)
a8248bb7 3746 if (!alloc_mem_cgroup_per_node_info(memcg, node))
0b8f73e1 3747 goto fail;
f64c3f54 3748
0b8f73e1
JW
3749 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
3750 goto fail;
28dbc4b6 3751
f7e1cb6e 3752 INIT_WORK(&memcg->high_work, high_work_func);
70ddf637 3753 vmpressure_init(&memcg->vmpressure);
c6f53ed8
DF
3754 INIT_LIST_HEAD(&memcg->memory_peaks);
3755 INIT_LIST_HEAD(&memcg->swap_peaks);
3756 spin_lock_init(&memcg->peaks_lock);
378bdb97
KI
3757 memcg->socket_pressure = get_jiffies_64();
3758#if BITS_PER_LONG < 64
3759 seqlock_init(&memcg->socket_pressure_seqlock);
3760#endif
b5855a26 3761 memcg1_memcg_init(memcg);
900a38f0 3762 memcg->kmemcg_id = -1;
bf4f0599 3763 INIT_LIST_HEAD(&memcg->objcg_list);
52ebea74
TH
3764#ifdef CONFIG_CGROUP_WRITEBACK
3765 INIT_LIST_HEAD(&memcg->cgwb_list);
97b27821
TH
3766 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3767 memcg->cgwb_frn[i].done =
3768 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
87eaceb3
YS
3769#endif
3770#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3771 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
3772 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
3773 memcg->deferred_split_queue.split_queue_len = 0;
52ebea74 3774#endif
ec1c86b2 3775 lru_gen_init_memcg(memcg);
0b8f73e1
JW
3776 return memcg;
3777fail:
7e97de0b 3778 mem_cgroup_id_remove(memcg);
40e952f9 3779 __mem_cgroup_free(memcg);
11d67612 3780 return ERR_PTR(error);
d142e3e6
GC
3781}
3782
0b8f73e1
JW
3783static struct cgroup_subsys_state * __ref
3784mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
d142e3e6 3785{
0b8f73e1 3786 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
b87d8cef 3787 struct mem_cgroup *memcg, *old_memcg;
645207a6 3788 bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys);
d142e3e6 3789
b87d8cef 3790 old_memcg = set_active_memcg(parent);
9cee7e8e 3791 memcg = mem_cgroup_alloc(parent);
b87d8cef 3792 set_active_memcg(old_memcg);
11d67612
YS
3793 if (IS_ERR(memcg))
3794 return ERR_CAST(memcg);
d142e3e6 3795
d1663a90 3796 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
d12f6d22 3797 memcg1_soft_limit_reset(memcg);
3a3b7fec 3798#ifdef CONFIG_ZSWAP
f4840ccf 3799 memcg->zswap_max = PAGE_COUNTER_MAX;
e3992573 3800 WRITE_ONCE(memcg->zswap_writeback, true);
f4840ccf 3801#endif
4b82ab4f 3802 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
0b8f73e1 3803 if (parent) {
82b3aa26 3804 WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
bef8620c 3805
645207a6 3806 page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl);
f77bd4b1 3807 page_counter_init(&memcg->swap, &parent->swap, false);
05dfec12 3808#ifdef CONFIG_MEMCG_V1
0e2759af 3809 memcg->memory.track_failcnt = !memcg_on_dfl;
05dfec12 3810 WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
f77bd4b1
RG
3811 page_counter_init(&memcg->kmem, &parent->kmem, false);
3812 page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
05dfec12 3813#endif
18f59ea7 3814 } else {
ff48c71c 3815 init_memcg_stats();
8278f1c7 3816 init_memcg_events();
f77bd4b1
RG
3817 page_counter_init(&memcg->memory, NULL, true);
3818 page_counter_init(&memcg->swap, NULL, false);
05dfec12 3819#ifdef CONFIG_MEMCG_V1
f77bd4b1
RG
3820 page_counter_init(&memcg->kmem, NULL, false);
3821 page_counter_init(&memcg->tcpmem, NULL, false);
05dfec12 3822#endif
0b8f73e1
JW
3823 root_mem_cgroup = memcg;
3824 return &memcg->css;
3825 }
3826
645207a6 3827 if (memcg_on_dfl && !cgroup_memory_nosocket)
ef12947c 3828 static_branch_inc(&memcg_sockets_enabled_key);
f7e1cb6e 3829
b6c1a8af
YS
3830 if (!cgroup_memory_nobpf)
3831 static_branch_inc(&memcg_bpf_enabled_key);
b6c1a8af 3832
0b8f73e1 3833 return &memcg->css;
0b8f73e1
JW
3834}
3835
73f576c0 3836static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
0b8f73e1 3837{
58fa2a55
VD
3838 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3839
da0efe30
MS
3840 if (memcg_online_kmem(memcg))
3841 goto remove_id;
3842
0a4465d3 3843 /*
e4262c4f 3844 * A memcg must be visible for expand_shrinker_info()
0a4465d3
KT
3845 * by the time the maps are allocated. So, we allocate maps
3846 * here, when for_each_mem_cgroup() can't skip it.
3847 */
da0efe30
MS
3848 if (alloc_shrinker_info(memcg))
3849 goto offline_kmem;
0a4465d3 3850
13ef7424 3851 if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
aa48e47e 3852 queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
396faf88 3853 FLUSH_TIME);
e4dde56c 3854 lru_gen_online_memcg(memcg);
6f0df8e1
JW
3855
3856 /* Online state pins memcg ID, memcg ID pins CSS */
3857 refcount_set(&memcg->id.ref, 1);
3858 css_get(css);
3859
3860 /*
3861 * Ensure mem_cgroup_from_id() works once we're fully online.
3862 *
3863 * We could do this earlier and require callers to filter with
3864 * css_tryget_online(). But right now there are no users that
3865 * need earlier access, and the workingset code relies on the
3866 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
3867 * publish it here at the end of onlining. This matches the
3868 * regular ID destruction during offlining.
3869 */
07222371 3870 xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
6f0df8e1 3871
2f7dd7a4 3872 return 0;
da0efe30
MS
3873offline_kmem:
3874 memcg_offline_kmem(memcg);
3875remove_id:
3876 mem_cgroup_id_remove(memcg);
3877 return -ENOMEM;
8cdea7c0
BS
3878}
3879
eb95419b 3880static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 3881{
eb95419b 3882 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
79bd9814 3883
66d60c42 3884 memcg1_css_offline(memcg);
ec64f515 3885
bf8d5d52 3886 page_counter_set_min(&memcg->memory, 0);
23067153 3887 page_counter_set_low(&memcg->memory, 0);
63677c74 3888
a65b0e76
DC
3889 zswap_memcg_offline_cleanup(memcg);
3890
567e9ab2 3891 memcg_offline_kmem(memcg);
a178015c 3892 reparent_shrinker_deferred(memcg);
52ebea74 3893 wb_memcg_offline(memcg);
e4dde56c 3894 lru_gen_offline_memcg(memcg);
73f576c0 3895
591edfb1
RG
3896 drain_all_stock(memcg);
3897
73f576c0 3898 mem_cgroup_id_put(memcg);
df878fb0
KH
3899}
3900
6df38689
VD
3901static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
3902{
3903 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3904
3905 invalidate_reclaim_iterators(memcg);
e4dde56c 3906 lru_gen_release_memcg(memcg);
6df38689
VD
3907}
3908
eb95419b 3909static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 3910{
eb95419b 3911 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
97b27821 3912 int __maybe_unused i;
c268e994 3913
97b27821
TH
3914#ifdef CONFIG_CGROUP_WRITEBACK
3915 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3916 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
3917#endif
f7e1cb6e 3918 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 3919 static_branch_dec(&memcg_sockets_enabled_key);
127424c8 3920
773e9ae7 3921 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
d55f90bf 3922 static_branch_dec(&memcg_sockets_enabled_key);
3893e302 3923
b6c1a8af
YS
3924 if (!cgroup_memory_nobpf)
3925 static_branch_dec(&memcg_bpf_enabled_key);
b6c1a8af 3926
0b8f73e1
JW
3927 vmpressure_cleanup(&memcg->vmpressure);
3928 cancel_work_sync(&memcg->high_work);
87024f58 3929 memcg1_remove_from_trees(memcg);
e4262c4f 3930 free_shrinker_info(memcg);
0b8f73e1 3931 mem_cgroup_free(memcg);
8cdea7c0
BS
3932}
3933
1ced953b
TH
3934/**
3935 * mem_cgroup_css_reset - reset the states of a mem_cgroup
3936 * @css: the target css
3937 *
3938 * Reset the states of the mem_cgroup associated with @css. This is
3939 * invoked when the userland requests disabling on the default hierarchy
3940 * but the memcg is pinned through dependency. The memcg should stop
3941 * applying policies and should revert to the vanilla state as it may be
3942 * made visible again.
3943 *
3944 * The current implementation only resets the essential configurations.
3945 * This needs to be expanded to cover all the visible parts.
3946 */
3947static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
3948{
3949 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3950
bbec2e15
RG
3951 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
3952 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
05dfec12 3953#ifdef CONFIG_MEMCG_V1
bbec2e15
RG
3954 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
3955 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
05dfec12 3956#endif
bf8d5d52 3957 page_counter_set_min(&memcg->memory, 0);
23067153 3958 page_counter_set_low(&memcg->memory, 0);
d1663a90 3959 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
d12f6d22 3960 memcg1_soft_limit_reset(memcg);
4b82ab4f 3961 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
2529bb3a 3962 memcg_wb_domain_size_changed(memcg);
1ced953b
TH
3963}
3964
2b1d5549
XJ
3965struct aggregate_control {
3966 /* pointer to the aggregated (CPU and subtree aggregated) counters */
3967 long *aggregate;
3968 /* pointer to the non-hierarchichal (CPU aggregated) counters */
3969 long *local;
3970 /* pointer to the pending child counters during tree propagation */
3971 long *pending;
3972 /* pointer to the parent's pending counters, could be NULL */
3973 long *ppending;
3974 /* pointer to the percpu counters to be aggregated */
3975 long *cstat;
3976 /* pointer to the percpu counters of the last aggregation*/
3977 long *cstat_prev;
3978 /* size of the above counters */
3979 int size;
3980};
3981
3982static void mem_cgroup_stat_aggregate(struct aggregate_control *ac)
2d146aa3 3983{
2b1d5549 3984 int i;
f82e6bf9 3985 long delta, delta_cpu, v;
2d146aa3 3986
2b1d5549 3987 for (i = 0; i < ac->size; i++) {
2d146aa3
JW
3988 /*
3989 * Collect the aggregated propagation counts of groups
3990 * below us. We're in a per-cpu loop here and this is
3991 * a global counter, so the first cycle will get them.
3992 */
2b1d5549 3993 delta = ac->pending[i];
2d146aa3 3994 if (delta)
2b1d5549 3995 ac->pending[i] = 0;
2d146aa3
JW
3996
3997 /* Add CPU changes on this level since the last flush */
f82e6bf9 3998 delta_cpu = 0;
2b1d5549
XJ
3999 v = READ_ONCE(ac->cstat[i]);
4000 if (v != ac->cstat_prev[i]) {
4001 delta_cpu = v - ac->cstat_prev[i];
f82e6bf9 4002 delta += delta_cpu;
2b1d5549 4003 ac->cstat_prev[i] = v;
2d146aa3
JW
4004 }
4005
2d146aa3 4006 /* Aggregate counts on this level and propagate upwards */
f82e6bf9 4007 if (delta_cpu)
2b1d5549 4008 ac->local[i] += delta_cpu;
f82e6bf9
YA
4009
4010 if (delta) {
2b1d5549
XJ
4011 ac->aggregate[i] += delta;
4012 if (ac->ppending)
4013 ac->ppending[i] += delta;
f82e6bf9 4014 }
2d146aa3 4015 }
2b1d5549 4016}
2d146aa3 4017
940b01fc
SB
4018#ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
4019static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4020 int cpu)
4021{
4022 int nid;
4023
4024 if (atomic_read(&memcg->kmem_stat)) {
4025 int kmem = atomic_xchg(&memcg->kmem_stat, 0);
4026 int index = memcg_stats_index(MEMCG_KMEM);
4027
4028 memcg->vmstats->state[index] += kmem;
4029 if (parent)
4030 parent->vmstats->state_pending[index] += kmem;
4031 }
4032
4033 for_each_node_state(nid, N_MEMORY) {
4034 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4035 struct lruvec_stats *lstats = pn->lruvec_stats;
4036 struct lruvec_stats *plstats = NULL;
4037
4038 if (parent)
4039 plstats = parent->nodeinfo[nid]->lruvec_stats;
4040
4041 if (atomic_read(&pn->slab_reclaimable)) {
4042 int slab = atomic_xchg(&pn->slab_reclaimable, 0);
4043 int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B);
4044
4045 lstats->state[index] += slab;
4046 if (plstats)
4047 plstats->state_pending[index] += slab;
4048 }
4049 if (atomic_read(&pn->slab_unreclaimable)) {
4050 int slab = atomic_xchg(&pn->slab_unreclaimable, 0);
4051 int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B);
4052
4053 lstats->state[index] += slab;
4054 if (plstats)
4055 plstats->state_pending[index] += slab;
4056 }
4057 }
4058}
4059#else
4060static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4061 int cpu)
4062{}
4063#endif
4064
2b1d5549
XJ
4065static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
4066{
4067 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4068 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4069 struct memcg_vmstats_percpu *statc;
4070 struct aggregate_control ac;
4071 int nid;
2d146aa3 4072
940b01fc
SB
4073 flush_nmi_stats(memcg, parent, cpu);
4074
2b1d5549 4075 statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
2d146aa3 4076
2b1d5549
XJ
4077 ac = (struct aggregate_control) {
4078 .aggregate = memcg->vmstats->state,
4079 .local = memcg->vmstats->state_local,
4080 .pending = memcg->vmstats->state_pending,
4081 .ppending = parent ? parent->vmstats->state_pending : NULL,
4082 .cstat = statc->state,
4083 .cstat_prev = statc->state_prev,
4084 .size = MEMCG_VMSTAT_SIZE,
4085 };
4086 mem_cgroup_stat_aggregate(&ac);
4087
4088 ac = (struct aggregate_control) {
4089 .aggregate = memcg->vmstats->events,
4090 .local = memcg->vmstats->events_local,
4091 .pending = memcg->vmstats->events_pending,
4092 .ppending = parent ? parent->vmstats->events_pending : NULL,
4093 .cstat = statc->events,
4094 .cstat_prev = statc->events_prev,
4095 .size = NR_MEMCG_EVENTS,
4096 };
4097 mem_cgroup_stat_aggregate(&ac);
7e1c0d6f
SB
4098
4099 for_each_node_state(nid, N_MEMORY) {
4100 struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
70a64b79
SB
4101 struct lruvec_stats *lstats = pn->lruvec_stats;
4102 struct lruvec_stats *plstats = NULL;
7e1c0d6f
SB
4103 struct lruvec_stats_percpu *lstatc;
4104
4105 if (parent)
70a64b79 4106 plstats = parent->nodeinfo[nid]->lruvec_stats;
7e1c0d6f
SB
4107
4108 lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
4109
2b1d5549
XJ
4110 ac = (struct aggregate_control) {
4111 .aggregate = lstats->state,
4112 .local = lstats->state_local,
4113 .pending = lstats->state_pending,
4114 .ppending = plstats ? plstats->state_pending : NULL,
4115 .cstat = lstatc->state,
4116 .cstat_prev = lstatc->state_prev,
4117 .size = NR_MEMCG_NODE_STAT_ITEMS,
4118 };
4119 mem_cgroup_stat_aggregate(&ac);
7e1c0d6f 4120
7e1c0d6f 4121 }
78ec6f9d 4122 WRITE_ONCE(statc->stats_updates, 0);
8d59d221 4123 /* We are in a per-cpu loop here, only do the atomic write once */
3ac4638a
SB
4124 if (atomic_read(&memcg->vmstats->stats_updates))
4125 atomic_set(&memcg->vmstats->stats_updates, 0);
2d146aa3
JW
4126}
4127
1aacbd35
RG
4128static void mem_cgroup_fork(struct task_struct *task)
4129{
4130 /*
4131 * Set the update flag to cause task->objcg to be initialized lazily
4132 * on the first allocation. It can be done without any synchronization
4133 * because it's always performed on the current task, so does
4134 * current_objcg_update().
4135 */
4136 task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
4137}
4138
4139static void mem_cgroup_exit(struct task_struct *task)
4140{
4141 struct obj_cgroup *objcg = task->objcg;
4142
4143 objcg = (struct obj_cgroup *)
4144 ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
91b71e78 4145 obj_cgroup_put(objcg);
1aacbd35
RG
4146
4147 /*
4148 * Some kernel allocations can happen after this point,
4149 * but let's ignore them. It can be done without any synchronization
4150 * because it's always performed on the current task, so does
4151 * current_objcg_update().
4152 */
4153 task->objcg = NULL;
4154}
1aacbd35 4155
bd74fdae 4156#ifdef CONFIG_LRU_GEN
1aacbd35 4157static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
bd74fdae
YZ
4158{
4159 struct task_struct *task;
4160 struct cgroup_subsys_state *css;
4161
4162 /* find the first leader if there is any */
4163 cgroup_taskset_for_each_leader(task, css, tset)
4164 break;
4165
4166 if (!task)
4167 return;
4168
4169 task_lock(task);
4170 if (task->mm && READ_ONCE(task->mm->owner) == task)
4171 lru_gen_migrate_mm(task->mm);
4172 task_unlock(task);
4173}
4174#else
1aacbd35
RG
4175static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
4176#endif /* CONFIG_LRU_GEN */
4177
1aacbd35
RG
4178static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
4179{
4180 struct task_struct *task;
4181 struct cgroup_subsys_state *css;
4182
4183 cgroup_taskset_for_each(task, css, tset) {
4184 /* atomically set the update bit */
4185 set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
4186 }
4187}
1aacbd35 4188
bd74fdae
YZ
4189static void mem_cgroup_attach(struct cgroup_taskset *tset)
4190{
1aacbd35
RG
4191 mem_cgroup_lru_gen_attach(tset);
4192 mem_cgroup_kmem_attach(tset);
bd74fdae 4193}
bd74fdae 4194
677dc973
CD
4195static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
4196{
4197 if (value == PAGE_COUNTER_MAX)
4198 seq_puts(m, "max\n");
4199 else
4200 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
4201
4202 return 0;
4203}
4204
241994ed
JW
4205static u64 memory_current_read(struct cgroup_subsys_state *css,
4206 struct cftype *cft)
4207{
f5fc3c5d
JW
4208 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4209
4210 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
241994ed
JW
4211}
4212
c6f53ed8
DF
4213#define OFP_PEAK_UNSET (((-1UL)))
4214
4215static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
8e20d4b3 4216{
c6f53ed8
DF
4217 struct cgroup_of_peak *ofp = of_peak(sf->private);
4218 u64 fd_peak = READ_ONCE(ofp->value), peak;
4219
4220 /* User wants global or local peak? */
4221 if (fd_peak == OFP_PEAK_UNSET)
4222 peak = pc->watermark;
4223 else
4224 peak = max(fd_peak, READ_ONCE(pc->local_watermark));
4225
4226 seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
4227 return 0;
4228}
4229
4230static int memory_peak_show(struct seq_file *sf, void *v)
4231{
4232 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
8e20d4b3 4233
c6f53ed8 4234 return peak_show(sf, v, &memcg->memory);
8e20d4b3
GR
4235}
4236
c6f53ed8
DF
4237static int peak_open(struct kernfs_open_file *of)
4238{
4239 struct cgroup_of_peak *ofp = of_peak(of);
4240
4241 ofp->value = OFP_PEAK_UNSET;
4242 return 0;
4243}
4244
4245static void peak_release(struct kernfs_open_file *of)
4246{
4247 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4248 struct cgroup_of_peak *ofp = of_peak(of);
4249
4250 if (ofp->value == OFP_PEAK_UNSET) {
4251 /* fast path (no writes on this fd) */
4252 return;
4253 }
4254 spin_lock(&memcg->peaks_lock);
4255 list_del(&ofp->list);
4256 spin_unlock(&memcg->peaks_lock);
4257}
4258
4259static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
4260 loff_t off, struct page_counter *pc,
4261 struct list_head *watchers)
4262{
4263 unsigned long usage;
4264 struct cgroup_of_peak *peer_ctx;
4265 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4266 struct cgroup_of_peak *ofp = of_peak(of);
4267
4268 spin_lock(&memcg->peaks_lock);
4269
4270 usage = page_counter_read(pc);
4271 WRITE_ONCE(pc->local_watermark, usage);
4272
4273 list_for_each_entry(peer_ctx, watchers, list)
4274 if (usage > peer_ctx->value)
4275 WRITE_ONCE(peer_ctx->value, usage);
4276
4277 /* initial write, register watcher */
1c81f1a6 4278 if (ofp->value == OFP_PEAK_UNSET)
c6f53ed8
DF
4279 list_add(&ofp->list, watchers);
4280
4281 WRITE_ONCE(ofp->value, usage);
4282 spin_unlock(&memcg->peaks_lock);
4283
4284 return nbytes;
4285}
4286
4287static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
4288 size_t nbytes, loff_t off)
4289{
4290 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
8e20d4b3 4291
c6f53ed8
DF
4292 return peak_write(of, buf, nbytes, off, &memcg->memory,
4293 &memcg->memory_peaks);
8e20d4b3
GR
4294}
4295
c6f53ed8
DF
4296#undef OFP_PEAK_UNSET
4297
bf8d5d52
RG
4298static int memory_min_show(struct seq_file *m, void *v)
4299{
677dc973
CD
4300 return seq_puts_memcg_tunable(m,
4301 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
bf8d5d52
RG
4302}
4303
4304static ssize_t memory_min_write(struct kernfs_open_file *of,
4305 char *buf, size_t nbytes, loff_t off)
4306{
4307 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4308 unsigned long min;
4309 int err;
4310
4311 buf = strstrip(buf);
4312 err = page_counter_memparse(buf, "max", &min);
4313 if (err)
4314 return err;
4315
4316 page_counter_set_min(&memcg->memory, min);
4317
4318 return nbytes;
4319}
4320
241994ed
JW
4321static int memory_low_show(struct seq_file *m, void *v)
4322{
677dc973
CD
4323 return seq_puts_memcg_tunable(m,
4324 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
241994ed
JW
4325}
4326
4327static ssize_t memory_low_write(struct kernfs_open_file *of,
4328 char *buf, size_t nbytes, loff_t off)
4329{
4330 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4331 unsigned long low;
4332 int err;
4333
4334 buf = strstrip(buf);
d2973697 4335 err = page_counter_memparse(buf, "max", &low);
241994ed
JW
4336 if (err)
4337 return err;
4338
23067153 4339 page_counter_set_low(&memcg->memory, low);
241994ed
JW
4340
4341 return nbytes;
4342}
4343
4344static int memory_high_show(struct seq_file *m, void *v)
4345{
d1663a90
JK
4346 return seq_puts_memcg_tunable(m,
4347 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
241994ed
JW
4348}
4349
4350static ssize_t memory_high_write(struct kernfs_open_file *of,
4351 char *buf, size_t nbytes, loff_t off)
4352{
4353 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
d977aa93 4354 unsigned int nr_retries = MAX_RECLAIM_RETRIES;
8c8c383c 4355 bool drained = false;
241994ed
JW
4356 unsigned long high;
4357 int err;
4358
4359 buf = strstrip(buf);
d2973697 4360 err = page_counter_memparse(buf, "max", &high);
241994ed
JW
4361 if (err)
4362 return err;
4363
e82553c1
JW
4364 page_counter_set_high(&memcg->memory, high);
4365
c8e6002b
SB
4366 if (of->file->f_flags & O_NONBLOCK)
4367 goto out;
4368
8c8c383c
JW
4369 for (;;) {
4370 unsigned long nr_pages = page_counter_read(&memcg->memory);
4371 unsigned long reclaimed;
4372
4373 if (nr_pages <= high)
4374 break;
4375
4376 if (signal_pending(current))
4377 break;
4378
4379 if (!drained) {
4380 drain_all_stock(memcg);
4381 drained = true;
4382 continue;
4383 }
4384
4385 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
68cd9050 4386 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
8c8c383c
JW
4387
4388 if (!reclaimed && !nr_retries--)
4389 break;
4390 }
c8e6002b 4391out:
19ce33ac 4392 memcg_wb_domain_size_changed(memcg);
241994ed
JW
4393 return nbytes;
4394}
4395
4396static int memory_max_show(struct seq_file *m, void *v)
4397{
677dc973
CD
4398 return seq_puts_memcg_tunable(m,
4399 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
241994ed
JW
4400}
4401
4402static ssize_t memory_max_write(struct kernfs_open_file *of,
4403 char *buf, size_t nbytes, loff_t off)
4404{
4405 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
d977aa93 4406 unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
b6e6edcf 4407 bool drained = false;
241994ed
JW
4408 unsigned long max;
4409 int err;
4410
4411 buf = strstrip(buf);
d2973697 4412 err = page_counter_memparse(buf, "max", &max);
241994ed
JW
4413 if (err)
4414 return err;
4415
bbec2e15 4416 xchg(&memcg->memory.max, max);
b6e6edcf 4417
c8e6002b
SB
4418 if (of->file->f_flags & O_NONBLOCK)
4419 goto out;
4420
b6e6edcf
JW
4421 for (;;) {
4422 unsigned long nr_pages = page_counter_read(&memcg->memory);
4423
4424 if (nr_pages <= max)
4425 break;
4426
7249c9f0 4427 if (signal_pending(current))
b6e6edcf 4428 break;
b6e6edcf
JW
4429
4430 if (!drained) {
4431 drain_all_stock(memcg);
4432 drained = true;
4433 continue;
4434 }
4435
4436 if (nr_reclaims) {
4437 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
68cd9050 4438 GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
b6e6edcf
JW
4439 nr_reclaims--;
4440 continue;
4441 }
4442
e27be240 4443 memcg_memory_event(memcg, MEMCG_OOM);
b6e6edcf
JW
4444 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
4445 break;
99333229 4446 cond_resched();
b6e6edcf 4447 }
c8e6002b 4448out:
2529bb3a 4449 memcg_wb_domain_size_changed(memcg);
241994ed
JW
4450 return nbytes;
4451}
4452
664dc218
DR
4453/*
4454 * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
4455 * if any new events become available.
4456 */
1e577f97
SB
4457static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
4458{
4459 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
4460 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
4461 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
4462 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
4463 seq_printf(m, "oom_kill %lu\n",
4464 atomic_long_read(&events[MEMCG_OOM_KILL]));
b6bf9abb
DS
4465 seq_printf(m, "oom_group_kill %lu\n",
4466 atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
1e577f97
SB
4467}
4468
241994ed
JW
4469static int memory_events_show(struct seq_file *m, void *v)
4470{
aa9694bb 4471 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 4472
1e577f97
SB
4473 __memory_events_show(m, memcg->memory_events);
4474 return 0;
4475}
4476
4477static int memory_events_local_show(struct seq_file *m, void *v)
4478{
4479 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 4480
1e577f97 4481 __memory_events_show(m, memcg->memory_events_local);
241994ed
JW
4482 return 0;
4483}
4484
ea1e8796 4485int memory_stat_show(struct seq_file *m, void *v)
587d9f72 4486{
aa9694bb 4487 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
8717734f 4488 char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
5b42360c 4489 struct seq_buf s;
1ff9e6e1 4490
c8713d0b
JW
4491 if (!buf)
4492 return -ENOMEM;
8717734f 4493 seq_buf_init(&s, buf, SEQ_BUF_SIZE);
5b42360c 4494 memory_stat_format(memcg, &s);
c8713d0b
JW
4495 seq_puts(m, buf);
4496 kfree(buf);
587d9f72
JW
4497 return 0;
4498}
4499
5f9a4f4a 4500#ifdef CONFIG_NUMA
fff66b79
MS
4501static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
4502 int item)
4503{
ff841a06
YA
4504 return lruvec_page_state(lruvec, item) *
4505 memcg_page_state_output_unit(item);
fff66b79
MS
4506}
4507
5f9a4f4a
MS
4508static int memory_numa_stat_show(struct seq_file *m, void *v)
4509{
4510 int i;
4511 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4512
7d7ef0a4 4513 mem_cgroup_flush_stats(memcg);
7e1c0d6f 4514
5f9a4f4a
MS
4515 for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
4516 int nid;
4517
4518 if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
4519 continue;
4520
4521 seq_printf(m, "%s", memory_stats[i].name);
4522 for_each_node_state(nid, N_MEMORY) {
4523 u64 size;
4524 struct lruvec *lruvec;
4525
4526 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
fff66b79
MS
4527 size = lruvec_page_state_output(lruvec,
4528 memory_stats[i].idx);
5f9a4f4a
MS
4529 seq_printf(m, " N%d=%llu", nid, size);
4530 }
4531 seq_putc(m, '\n');
4532 }
4533
4534 return 0;
4535}
4536#endif
4537
3d8b38eb
RG
4538static int memory_oom_group_show(struct seq_file *m, void *v)
4539{
aa9694bb 4540 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3d8b38eb 4541
eaf7b66b 4542 seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
3d8b38eb
RG
4543
4544 return 0;
4545}
4546
4547static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
4548 char *buf, size_t nbytes, loff_t off)
4549{
4550 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4551 int ret, oom_group;
4552
4553 buf = strstrip(buf);
4554 if (!buf)
4555 return -EINVAL;
4556
4557 ret = kstrtoint(buf, 0, &oom_group);
4558 if (ret)
4559 return ret;
4560
4561 if (oom_group != 0 && oom_group != 1)
4562 return -EINVAL;
4563
eaf7b66b 4564 WRITE_ONCE(memcg->oom_group, oom_group);
3d8b38eb
RG
4565
4566 return nbytes;
4567}
4568
94968384
SB
4569static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
4570 size_t nbytes, loff_t off)
4571{
4572 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
2b7226af 4573 int ret;
94968384 4574
2b7226af
DB
4575 ret = user_proactive_reclaim(buf, memcg, NULL);
4576 if (ret)
4577 return ret;
94968384
SB
4578
4579 return nbytes;
4580}
4581
241994ed
JW
4582static struct cftype memory_files[] = {
4583 {
4584 .name = "current",
f5fc3c5d 4585 .flags = CFTYPE_NOT_ON_ROOT,
241994ed
JW
4586 .read_u64 = memory_current_read,
4587 },
8e20d4b3
GR
4588 {
4589 .name = "peak",
4590 .flags = CFTYPE_NOT_ON_ROOT,
c6f53ed8
DF
4591 .open = peak_open,
4592 .release = peak_release,
4593 .seq_show = memory_peak_show,
4594 .write = memory_peak_write,
8e20d4b3 4595 },
bf8d5d52
RG
4596 {
4597 .name = "min",
4598 .flags = CFTYPE_NOT_ON_ROOT,
4599 .seq_show = memory_min_show,
4600 .write = memory_min_write,
4601 },
241994ed
JW
4602 {
4603 .name = "low",
4604 .flags = CFTYPE_NOT_ON_ROOT,
4605 .seq_show = memory_low_show,
4606 .write = memory_low_write,
4607 },
4608 {
4609 .name = "high",
4610 .flags = CFTYPE_NOT_ON_ROOT,
4611 .seq_show = memory_high_show,
4612 .write = memory_high_write,
4613 },
4614 {
4615 .name = "max",
4616 .flags = CFTYPE_NOT_ON_ROOT,
4617 .seq_show = memory_max_show,
4618 .write = memory_max_write,
4619 },
4620 {
4621 .name = "events",
4622 .flags = CFTYPE_NOT_ON_ROOT,
472912a2 4623 .file_offset = offsetof(struct mem_cgroup, events_file),
241994ed
JW
4624 .seq_show = memory_events_show,
4625 },
1e577f97
SB
4626 {
4627 .name = "events.local",
4628 .flags = CFTYPE_NOT_ON_ROOT,
4629 .file_offset = offsetof(struct mem_cgroup, events_local_file),
4630 .seq_show = memory_events_local_show,
4631 },
587d9f72
JW
4632 {
4633 .name = "stat",
587d9f72
JW
4634 .seq_show = memory_stat_show,
4635 },
5f9a4f4a
MS
4636#ifdef CONFIG_NUMA
4637 {
4638 .name = "numa_stat",
4639 .seq_show = memory_numa_stat_show,
4640 },
4641#endif
3d8b38eb
RG
4642 {
4643 .name = "oom.group",
4644 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
4645 .seq_show = memory_oom_group_show,
4646 .write = memory_oom_group_write,
4647 },
94968384
SB
4648 {
4649 .name = "reclaim",
4650 .flags = CFTYPE_NS_DELEGATABLE,
4651 .write = memory_reclaim,
4652 },
241994ed
JW
4653 { } /* terminate */
4654};
4655
073219e9 4656struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 4657 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 4658 .css_online = mem_cgroup_css_online,
92fb9748 4659 .css_offline = mem_cgroup_css_offline,
6df38689 4660 .css_released = mem_cgroup_css_released,
92fb9748 4661 .css_free = mem_cgroup_css_free,
1ced953b 4662 .css_reset = mem_cgroup_css_reset,
2d146aa3 4663 .css_rstat_flush = mem_cgroup_css_rstat_flush,
bd74fdae 4664 .attach = mem_cgroup_attach,
1aacbd35
RG
4665 .fork = mem_cgroup_fork,
4666 .exit = mem_cgroup_exit,
241994ed 4667 .dfl_cftypes = memory_files,
e93d4166 4668#ifdef CONFIG_MEMCG_V1
241994ed 4669 .legacy_cftypes = mem_cgroup_legacy_files,
e93d4166 4670#endif
6d12e2d8 4671 .early_init = 0,
8cdea7c0 4672};
c077719b 4673
241994ed 4674/**
05395718 4675 * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
34c81057 4676 * @root: the top ancestor of the sub-tree being checked
241994ed
JW
4677 * @memcg: the memory cgroup to check
4678 *
23067153
RG
4679 * WARNING: This function is not stateless! It can only be used as part
4680 * of a top-down tree iteration, not for isolated queries.
241994ed 4681 */
45c7f7e1
CD
4682void mem_cgroup_calculate_protection(struct mem_cgroup *root,
4683 struct mem_cgroup *memcg)
241994ed 4684{
a8585ac6
ML
4685 bool recursive_protection =
4686 cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
23067153 4687
241994ed 4688 if (mem_cgroup_disabled())
45c7f7e1 4689 return;
241994ed 4690
34c81057
SC
4691 if (!root)
4692 root = root_mem_cgroup;
22f7496f 4693
a8585ac6 4694 page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
241994ed
JW
4695}
4696
8f425e4e
MWO
4697static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
4698 gfp_t gfp)
0add0c77 4699{
0add0c77
SB
4700 int ret;
4701
4b569387 4702 ret = try_charge(memcg, gfp, folio_nr_pages(folio));
0add0c77
SB
4703 if (ret)
4704 goto out;
4705
1d8f136a
JH
4706 css_get(&memcg->css);
4707 commit_charge(folio, memcg);
4708 memcg1_commit_charge(folio, memcg);
0add0c77
SB
4709out:
4710 return ret;
4711}
4712
8f425e4e 4713int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
00501b53 4714{
0add0c77
SB
4715 struct mem_cgroup *memcg;
4716 int ret;
00501b53 4717
0add0c77 4718 memcg = get_mem_cgroup_from_mm(mm);
8f425e4e 4719 ret = charge_memcg(folio, memcg, gfp);
0add0c77 4720 css_put(&memcg->css);
2d1c4980 4721
0add0c77
SB
4722 return ret;
4723}
e993d905 4724
99113577
JH
4725/**
4726 * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
4727 * @folio: folio being charged
4728 * @gfp: reclaim mode
4729 *
4730 * This function is called when allocating a huge page folio, after the page has
4731 * already been obtained and charged to the appropriate hugetlb cgroup
4732 * controller (if it is enabled).
4733 *
4734 * Returns ENOMEM if the memcg is already full.
4735 * Returns 0 if either the charge was successful, or if we skip the charging.
4736 */
4737int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
4738{
4739 struct mem_cgroup *memcg = get_mem_cgroup_from_current();
4740 int ret = 0;
4741
4742 /*
4743 * Even memcg does not account for hugetlb, we still want to update
4744 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip
4745 * charging the memcg.
4746 */
4747 if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() ||
4748 !memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
4749 goto out;
4750
4751 if (charge_memcg(folio, memcg, gfp))
4752 ret = -ENOMEM;
4753
4754out:
4755 mem_cgroup_put(memcg);
4756 return ret;
4757}
4758
0add0c77 4759/**
65995918
MWO
4760 * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
4761 * @folio: folio to charge.
0add0c77
SB
4762 * @mm: mm context of the victim
4763 * @gfp: reclaim mode
65995918 4764 * @entry: swap entry for which the folio is allocated
0add0c77 4765 *
65995918
MWO
4766 * This function charges a folio allocated for swapin. Please call this before
4767 * adding the folio to the swapcache.
0add0c77
SB
4768 *
4769 * Returns 0 on success. Otherwise, an error code is returned.
4770 */
65995918 4771int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
0add0c77
SB
4772 gfp_t gfp, swp_entry_t entry)
4773{
4774 struct mem_cgroup *memcg;
4775 unsigned short id;
4776 int ret;
00501b53 4777
0add0c77
SB
4778 if (mem_cgroup_disabled())
4779 return 0;
00501b53 4780
0add0c77
SB
4781 id = lookup_swap_cgroup_id(entry);
4782 rcu_read_lock();
4783 memcg = mem_cgroup_from_id(id);
4784 if (!memcg || !css_tryget_online(&memcg->css))
4785 memcg = get_mem_cgroup_from_mm(mm);
4786 rcu_read_unlock();
00501b53 4787
8f425e4e 4788 ret = charge_memcg(folio, memcg, gfp);
6abb5a86 4789
0add0c77
SB
4790 css_put(&memcg->css);
4791 return ret;
4792}
00501b53 4793
a9d5adee
JG
4794struct uncharge_gather {
4795 struct mem_cgroup *memcg;
b4e0b68f 4796 unsigned long nr_memory;
a9d5adee 4797 unsigned long pgpgout;
a9d5adee 4798 unsigned long nr_kmem;
8e88bd2d 4799 int nid;
a9d5adee
JG
4800};
4801
4802static inline void uncharge_gather_clear(struct uncharge_gather *ug)
747db954 4803{
a9d5adee
JG
4804 memset(ug, 0, sizeof(*ug));
4805}
4806
4807static void uncharge_batch(const struct uncharge_gather *ug)
4808{
b4e0b68f 4809 if (ug->nr_memory) {
89f342af 4810 memcg_uncharge(ug->memcg, ug->nr_memory);
04fbe921
RG
4811 if (ug->nr_kmem) {
4812 mod_memcg_state(ug->memcg, MEMCG_KMEM, -ug->nr_kmem);
4813 memcg1_account_kmem(ug->memcg, -ug->nr_kmem);
4814 }
8d49b699 4815 memcg1_oom_recover(ug->memcg);
ce00a967 4816 }
747db954 4817
f7d49ba0 4818 memcg1_uncharge_batch(ug->memcg, ug->pgpgout, ug->nr_memory, ug->nid);
f1796544 4819
c4ed6ebf 4820 /* drop reference from uncharge_folio */
f1796544 4821 css_put(&ug->memcg->css);
a9d5adee
JG
4822}
4823
c4ed6ebf 4824static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
a9d5adee 4825{
c4ed6ebf 4826 long nr_pages;
b4e0b68f
MS
4827 struct mem_cgroup *memcg;
4828 struct obj_cgroup *objcg;
9f762dbe 4829
c4ed6ebf 4830 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
a9d5adee 4831
a9d5adee
JG
4832 /*
4833 * Nobody should be changing or seriously looking at
c4ed6ebf
MWO
4834 * folio memcg or objcg at this point, we have fully
4835 * exclusive access to the folio.
a9d5adee 4836 */
fead2b86 4837 if (folio_memcg_kmem(folio)) {
1b7e4464 4838 objcg = __folio_objcg(folio);
b4e0b68f
MS
4839 /*
4840 * This get matches the put at the end of the function and
4841 * kmem pages do not hold memcg references anymore.
4842 */
4843 memcg = get_mem_cgroup_from_objcg(objcg);
4844 } else {
1b7e4464 4845 memcg = __folio_memcg(folio);
b4e0b68f 4846 }
a9d5adee 4847
b4e0b68f
MS
4848 if (!memcg)
4849 return;
4850
4851 if (ug->memcg != memcg) {
a9d5adee
JG
4852 if (ug->memcg) {
4853 uncharge_batch(ug);
4854 uncharge_gather_clear(ug);
4855 }
b4e0b68f 4856 ug->memcg = memcg;
c4ed6ebf 4857 ug->nid = folio_nid(folio);
f1796544
MH
4858
4859 /* pairs with css_put in uncharge_batch */
b4e0b68f 4860 css_get(&memcg->css);
a9d5adee
JG
4861 }
4862
c4ed6ebf 4863 nr_pages = folio_nr_pages(folio);
a9d5adee 4864
fead2b86 4865 if (folio_memcg_kmem(folio)) {
b4e0b68f 4866 ug->nr_memory += nr_pages;
9f762dbe 4867 ug->nr_kmem += nr_pages;
b4e0b68f 4868
c4ed6ebf 4869 folio->memcg_data = 0;
b4e0b68f
MS
4870 obj_cgroup_put(objcg);
4871 } else {
4872 /* LRU pages aren't accounted at the root level */
4873 if (!mem_cgroup_is_root(memcg))
4874 ug->nr_memory += nr_pages;
18b2db3b 4875 ug->pgpgout++;
a9d5adee 4876
f8f931bb 4877 WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
c4ed6ebf 4878 folio->memcg_data = 0;
b4e0b68f
MS
4879 }
4880
4881 css_put(&memcg->css);
747db954
JW
4882}
4883
bbc6b703 4884void __mem_cgroup_uncharge(struct folio *folio)
0a31bc97 4885{
a9d5adee
JG
4886 struct uncharge_gather ug;
4887
bbc6b703 4888 /* Don't touch folio->lru of any random page, pre-check: */
02f4bbef 4889 if (!folio_memcg_charged(folio))
0a31bc97
JW
4890 return;
4891
a9d5adee 4892 uncharge_gather_clear(&ug);
bbc6b703 4893 uncharge_folio(folio, &ug);
a9d5adee 4894 uncharge_batch(&ug);
747db954 4895}
0a31bc97 4896
4882c809
MWO
4897void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
4898{
4899 struct uncharge_gather ug;
4900 unsigned int i;
4901
4902 uncharge_gather_clear(&ug);
4903 for (i = 0; i < folios->nr; i++)
4904 uncharge_folio(folios->folios[i], &ug);
4905 if (ug.memcg)
4906 uncharge_batch(&ug);
0a31bc97
JW
4907}
4908
4909/**
85ce2c51 4910 * mem_cgroup_replace_folio - Charge a folio's replacement.
d21bba2b
MWO
4911 * @old: Currently circulating folio.
4912 * @new: Replacement folio.
0a31bc97 4913 *
d21bba2b 4914 * Charge @new as a replacement folio for @old. @old will
9094b4a1 4915 * be uncharged upon free.
0a31bc97 4916 *
d21bba2b 4917 * Both folios must be locked, @new->mapping must be set up.
0a31bc97 4918 */
85ce2c51 4919void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
0a31bc97 4920{
29833315 4921 struct mem_cgroup *memcg;
d21bba2b 4922 long nr_pages = folio_nr_pages(new);
0a31bc97 4923
d21bba2b
MWO
4924 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
4925 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
4926 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
4927 VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
0a31bc97
JW
4928
4929 if (mem_cgroup_disabled())
4930 return;
4931
d21bba2b 4932 /* Page cache replacement: new folio already charged? */
02f4bbef 4933 if (folio_memcg_charged(new))
0a31bc97
JW
4934 return;
4935
d21bba2b
MWO
4936 memcg = folio_memcg(old);
4937 VM_WARN_ON_ONCE_FOLIO(!memcg, old);
29833315 4938 if (!memcg)
0a31bc97
JW
4939 return;
4940
44b7a8d3 4941 /* Force-charge the new page. The old one will be freed soon */
8dc87c7d
MS
4942 if (!mem_cgroup_is_root(memcg)) {
4943 page_counter_charge(&memcg->memory, nr_pages);
4944 if (do_memsw_account())
4945 page_counter_charge(&memcg->memsw, nr_pages);
4946 }
0a31bc97 4947
1a3e1f40 4948 css_get(&memcg->css);
d21bba2b 4949 commit_charge(new, memcg);
f7d49ba0 4950 memcg1_commit_charge(new, memcg);
0a31bc97
JW
4951}
4952
85ce2c51
NP
4953/**
4954 * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
4955 * @old: Currently circulating folio.
4956 * @new: Replacement folio.
4957 *
4958 * Transfer the memcg data from the old folio to the new folio for migration.
4959 * The old folio's data info will be cleared. Note that the memory counters
4960 * will remain unchanged throughout the process.
4961 *
4962 * Both folios must be locked, @new->mapping must be set up.
4963 */
4964void mem_cgroup_migrate(struct folio *old, struct folio *new)
4965{
4966 struct mem_cgroup *memcg;
4967
4968 VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
4969 VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
4970 VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
4971 VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
a6ab9c82 4972 VM_BUG_ON_FOLIO(folio_test_lru(old), old);
85ce2c51
NP
4973
4974 if (mem_cgroup_disabled())
4975 return;
4976
4977 memcg = folio_memcg(old);
8cba9576
NP
4978 /*
4979 * Note that it is normal to see !memcg for a hugetlb folio.
4980 * For e.g, itt could have been allocated when memory_hugetlb_accounting
4981 * was not selected.
4982 */
4983 VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
85ce2c51
NP
4984 if (!memcg)
4985 return;
4986
4987 /* Transfer the charge and the css ref */
4988 commit_charge(new, memcg);
f8f931bb
HD
4989
4990 /* Warning should never happen, so don't worry about refcount non-0 */
4991 WARN_ON_ONCE(folio_unqueue_deferred_split(old));
85ce2c51
NP
4992 old->memcg_data = 0;
4993}
4994
ef12947c 4995DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
11092087
JW
4996EXPORT_SYMBOL(memcg_sockets_enabled_key);
4997
2d758073 4998void mem_cgroup_sk_alloc(struct sock *sk)
11092087
JW
4999{
5000 struct mem_cgroup *memcg;
5001
2d758073
JW
5002 if (!mem_cgroup_sockets_enabled)
5003 return;
5004
e876ecc6 5005 /* Do not associate the sock with unrelated interrupted task's memcg. */
086f694a 5006 if (!in_task())
e876ecc6
SB
5007 return;
5008
11092087
JW
5009 rcu_read_lock();
5010 memcg = mem_cgroup_from_task(current);
7848ed62 5011 if (mem_cgroup_is_root(memcg))
f7e1cb6e 5012 goto out;
773e9ae7 5013 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
f7e1cb6e 5014 goto out;
8965aa28 5015 if (css_tryget(&memcg->css))
11092087 5016 sk->sk_memcg = memcg;
f7e1cb6e 5017out:
11092087
JW
5018 rcu_read_unlock();
5019}
11092087 5020
2d758073 5021void mem_cgroup_sk_free(struct sock *sk)
11092087 5022{
2d758073
JW
5023 if (sk->sk_memcg)
5024 css_put(&sk->sk_memcg->css);
11092087
JW
5025}
5026
5027/**
5028 * mem_cgroup_charge_skmem - charge socket memory
5029 * @memcg: memcg to charge
5030 * @nr_pages: number of pages to charge
4b1327be 5031 * @gfp_mask: reclaim mode
11092087
JW
5032 *
5033 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
4b1327be 5034 * @memcg's configured limit, %false if it doesn't.
11092087 5035 */
4b1327be
WW
5036bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
5037 gfp_t gfp_mask)
11092087 5038{
773e9ae7
RG
5039 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5040 return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
d886f4e4 5041
3dc30ef6 5042 if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) {
4b1327be 5043 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
f7e1cb6e 5044 return true;
4b1327be 5045 }
f7e1cb6e 5046
11092087
JW
5047 return false;
5048}
5049
5050/**
5051 * mem_cgroup_uncharge_skmem - uncharge socket memory
b7701a5f
MR
5052 * @memcg: memcg to uncharge
5053 * @nr_pages: number of pages to uncharge
11092087
JW
5054 */
5055void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
5056{
f7e1cb6e 5057 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
773e9ae7 5058 memcg1_uncharge_skmem(memcg, nr_pages);
f7e1cb6e
JW
5059 return;
5060 }
d886f4e4 5061
c9019e9b 5062 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
b2807f07 5063
475d0487 5064 refill_stock(memcg, nr_pages);
11092087
JW
5065}
5066
f7e1cb6e
JW
5067static int __init cgroup_memory(char *s)
5068{
5069 char *token;
5070
5071 while ((token = strsep(&s, ",")) != NULL) {
5072 if (!*token)
5073 continue;
5074 if (!strcmp(token, "nosocket"))
5075 cgroup_memory_nosocket = true;
04823c83
VD
5076 if (!strcmp(token, "nokmem"))
5077 cgroup_memory_nokmem = true;
b6c1a8af
YS
5078 if (!strcmp(token, "nobpf"))
5079 cgroup_memory_nobpf = true;
f7e1cb6e 5080 }
460a79e1 5081 return 1;
f7e1cb6e
JW
5082}
5083__setup("cgroup.memory=", cgroup_memory);
11092087 5084
2d11085e 5085/*
bc9817bb 5086 * Memory controller init before cgroup_init() initialize root_mem_cgroup.
1081312f 5087 *
308167fc
SAS
5088 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
5089 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
5090 * basically everything that doesn't depend on a specific mem_cgroup structure
5091 * should be initialized from here.
2d11085e 5092 */
bc9817bb 5093int __init mem_cgroup_init(void)
2d11085e 5094{
97e4fc4b 5095 unsigned int memcg_size;
d12f6d22 5096 int cpu;
95a045f6 5097
f3344adf
MS
5098 /*
5099 * Currently s32 type (can refer to struct batched_lruvec_stat) is
5100 * used for per-memcg-per-cpu caching of per-node statistics. In order
5101 * to work fine, we should make sure that the overfill threshold can't
5102 * exceed S32_MAX / PAGE_SIZE.
5103 */
5104 BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
5105
308167fc
SAS
5106 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
5107 memcg_hotplug_cpu_dead);
95a045f6 5108
c80509ef 5109 for_each_possible_cpu(cpu) {
95a045f6 5110 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
c80509ef
SB
5111 drain_local_memcg_stock);
5112 INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work,
5113 drain_local_obj_stock);
5114 }
95a045f6 5115
97e4fc4b
HY
5116 memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
5117 memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
5118 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
5119
1b6a58e2
HY
5120 memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
5121 SLAB_PANIC | SLAB_HWCACHE_ALIGN);
95a045f6 5122
2d11085e
MH
5123 return 0;
5124}
21afa38e 5125
e55b9f96 5126#ifdef CONFIG_SWAP
38d8b4e6 5127/**
e2e3fdc7
MWO
5128 * __mem_cgroup_try_charge_swap - try charging swap space for a folio
5129 * @folio: folio being added to swap
37e84351
VD
5130 * @entry: swap entry to charge
5131 *
e2e3fdc7 5132 * Try to charge @folio's memcg for the swap space at @entry.
37e84351
VD
5133 *
5134 * Returns 0 on success, -ENOMEM on failure.
5135 */
e2e3fdc7 5136int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
37e84351 5137{
e2e3fdc7 5138 unsigned int nr_pages = folio_nr_pages(folio);
37e84351 5139 struct page_counter *counter;
38d8b4e6 5140 struct mem_cgroup *memcg;
37e84351 5141
b94c4e94 5142 if (do_memsw_account())
37e84351
VD
5143 return 0;
5144
e2e3fdc7 5145 memcg = folio_memcg(folio);
37e84351 5146
e2e3fdc7 5147 VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
37e84351
VD
5148 if (!memcg)
5149 return 0;
5150
f3a53a3a
TH
5151 if (!entry.val) {
5152 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
bb98f2c5 5153 return 0;
f3a53a3a 5154 }
bb98f2c5 5155
1f47b61f
VD
5156 memcg = mem_cgroup_id_get_online(memcg);
5157
b25806dc 5158 if (!mem_cgroup_is_root(memcg) &&
38d8b4e6 5159 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
f3a53a3a
TH
5160 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
5161 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
1f47b61f 5162 mem_cgroup_id_put(memcg);
37e84351 5163 return -ENOMEM;
1f47b61f 5164 }
37e84351 5165
38d8b4e6
HY
5166 /* Get references for the tail pages, too */
5167 if (nr_pages > 1)
5168 mem_cgroup_id_get_many(memcg, nr_pages - 1);
c9019e9b 5169 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
37e84351 5170
73f839b6 5171 swap_cgroup_record(folio, mem_cgroup_id(memcg), entry);
67691831 5172
37e84351
VD
5173 return 0;
5174}
5175
21afa38e 5176/**
01c4b28c 5177 * __mem_cgroup_uncharge_swap - uncharge swap space
21afa38e 5178 * @entry: swap entry to uncharge
38d8b4e6 5179 * @nr_pages: the amount of swap space to uncharge
21afa38e 5180 */
01c4b28c 5181void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
21afa38e
JW
5182{
5183 struct mem_cgroup *memcg;
5184 unsigned short id;
5185
67691831 5186 id = swap_cgroup_clear(entry, nr_pages);
21afa38e 5187 rcu_read_lock();
adbe427b 5188 memcg = mem_cgroup_from_id(id);
21afa38e 5189 if (memcg) {
b25806dc 5190 if (!mem_cgroup_is_root(memcg)) {
b94c4e94 5191 if (do_memsw_account())
38d8b4e6 5192 page_counter_uncharge(&memcg->memsw, nr_pages);
b94c4e94
JW
5193 else
5194 page_counter_uncharge(&memcg->swap, nr_pages);
37e84351 5195 }
c9019e9b 5196 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
38d8b4e6 5197 mem_cgroup_id_put_many(memcg, nr_pages);
21afa38e
JW
5198 }
5199 rcu_read_unlock();
5200}
5201
d8b38438
VD
5202long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
5203{
5204 long nr_swap_pages = get_nr_swap_pages();
5205
b25806dc 5206 if (mem_cgroup_disabled() || do_memsw_account())
d8b38438 5207 return nr_swap_pages;
7848ed62 5208 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
d8b38438 5209 nr_swap_pages = min_t(long, nr_swap_pages,
bbec2e15 5210 READ_ONCE(memcg->swap.max) -
d8b38438
VD
5211 page_counter_read(&memcg->swap));
5212 return nr_swap_pages;
5213}
5214
9202d527 5215bool mem_cgroup_swap_full(struct folio *folio)
5ccc5aba
VD
5216{
5217 struct mem_cgroup *memcg;
5218
9202d527 5219 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5ccc5aba
VD
5220
5221 if (vm_swap_full())
5222 return true;
b25806dc 5223 if (do_memsw_account())
5ccc5aba
VD
5224 return false;
5225
9202d527 5226 memcg = folio_memcg(folio);
5ccc5aba
VD
5227 if (!memcg)
5228 return false;
5229
7848ed62 5230 for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
4b82ab4f
JK
5231 unsigned long usage = page_counter_read(&memcg->swap);
5232
5233 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
5234 usage * 2 >= READ_ONCE(memcg->swap.max))
5ccc5aba 5235 return true;
4b82ab4f 5236 }
5ccc5aba
VD
5237
5238 return false;
5239}
5240
eccb52e7 5241static int __init setup_swap_account(char *s)
21afa38e 5242{
118642d7
JW
5243 bool res;
5244
5245 if (!kstrtobool(s, &res) && !res)
5246 pr_warn_once("The swapaccount=0 commandline option is deprecated "
5247 "in favor of configuring swap control via cgroupfs. "
5248 "Please report your usecase to linux-mm@kvack.org if you "
5249 "depend on this functionality.\n");
21afa38e
JW
5250 return 1;
5251}
eccb52e7 5252__setup("swapaccount=", setup_swap_account);
21afa38e 5253
37e84351
VD
5254static u64 swap_current_read(struct cgroup_subsys_state *css,
5255 struct cftype *cft)
5256{
5257 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5258
5259 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
5260}
5261
c6f53ed8 5262static int swap_peak_show(struct seq_file *sf, void *v)
e0e0b412 5263{
c6f53ed8
DF
5264 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
5265
5266 return peak_show(sf, v, &memcg->swap);
5267}
5268
5269static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
5270 size_t nbytes, loff_t off)
5271{
5272 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
e0e0b412 5273
c6f53ed8
DF
5274 return peak_write(of, buf, nbytes, off, &memcg->swap,
5275 &memcg->swap_peaks);
e0e0b412
LD
5276}
5277
4b82ab4f
JK
5278static int swap_high_show(struct seq_file *m, void *v)
5279{
5280 return seq_puts_memcg_tunable(m,
5281 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
5282}
5283
5284static ssize_t swap_high_write(struct kernfs_open_file *of,
5285 char *buf, size_t nbytes, loff_t off)
5286{
5287 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5288 unsigned long high;
5289 int err;
5290
5291 buf = strstrip(buf);
5292 err = page_counter_memparse(buf, "max", &high);
5293 if (err)
5294 return err;
5295
5296 page_counter_set_high(&memcg->swap, high);
5297
5298 return nbytes;
5299}
5300
37e84351
VD
5301static int swap_max_show(struct seq_file *m, void *v)
5302{
677dc973
CD
5303 return seq_puts_memcg_tunable(m,
5304 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
37e84351
VD
5305}
5306
5307static ssize_t swap_max_write(struct kernfs_open_file *of,
5308 char *buf, size_t nbytes, loff_t off)
5309{
5310 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5311 unsigned long max;
5312 int err;
5313
5314 buf = strstrip(buf);
5315 err = page_counter_memparse(buf, "max", &max);
5316 if (err)
5317 return err;
5318
be09102b 5319 xchg(&memcg->swap.max, max);
37e84351
VD
5320
5321 return nbytes;
5322}
5323
f3a53a3a
TH
5324static int swap_events_show(struct seq_file *m, void *v)
5325{
aa9694bb 5326 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
f3a53a3a 5327
4b82ab4f
JK
5328 seq_printf(m, "high %lu\n",
5329 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
f3a53a3a
TH
5330 seq_printf(m, "max %lu\n",
5331 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
5332 seq_printf(m, "fail %lu\n",
5333 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
5334
5335 return 0;
5336}
5337
37e84351
VD
5338static struct cftype swap_files[] = {
5339 {
5340 .name = "swap.current",
5341 .flags = CFTYPE_NOT_ON_ROOT,
5342 .read_u64 = swap_current_read,
5343 },
4b82ab4f
JK
5344 {
5345 .name = "swap.high",
5346 .flags = CFTYPE_NOT_ON_ROOT,
5347 .seq_show = swap_high_show,
5348 .write = swap_high_write,
5349 },
37e84351
VD
5350 {
5351 .name = "swap.max",
5352 .flags = CFTYPE_NOT_ON_ROOT,
5353 .seq_show = swap_max_show,
5354 .write = swap_max_write,
5355 },
e0e0b412
LD
5356 {
5357 .name = "swap.peak",
5358 .flags = CFTYPE_NOT_ON_ROOT,
c6f53ed8
DF
5359 .open = peak_open,
5360 .release = peak_release,
5361 .seq_show = swap_peak_show,
5362 .write = swap_peak_write,
e0e0b412 5363 },
f3a53a3a
TH
5364 {
5365 .name = "swap.events",
5366 .flags = CFTYPE_NOT_ON_ROOT,
5367 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
5368 .seq_show = swap_events_show,
5369 },
37e84351
VD
5370 { } /* terminate */
5371};
5372
3a3b7fec 5373#ifdef CONFIG_ZSWAP
f4840ccf
JW
5374/**
5375 * obj_cgroup_may_zswap - check if this cgroup can zswap
5376 * @objcg: the object cgroup
5377 *
5378 * Check if the hierarchical zswap limit has been reached.
5379 *
5380 * This doesn't check for specific headroom, and it is not atomic
5381 * either. But with zswap, the size of the allocation is only known
be16dd76 5382 * once compression has occurred, and this optimistic pre-check avoids
f4840ccf
JW
5383 * spending cycles on compression when there is already no room left
5384 * or zswap is disabled altogether somewhere in the hierarchy.
5385 */
5386bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
5387{
5388 struct mem_cgroup *memcg, *original_memcg;
5389 bool ret = true;
5390
5391 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5392 return true;
5393
5394 original_memcg = get_mem_cgroup_from_objcg(objcg);
7848ed62 5395 for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
f4840ccf
JW
5396 memcg = parent_mem_cgroup(memcg)) {
5397 unsigned long max = READ_ONCE(memcg->zswap_max);
5398 unsigned long pages;
5399
5400 if (max == PAGE_COUNTER_MAX)
5401 continue;
5402 if (max == 0) {
5403 ret = false;
5404 break;
5405 }
5406
e1479b88
JK
5407 /* Force flush to get accurate stats for charging */
5408 __mem_cgroup_flush_stats(memcg, true);
f4840ccf
JW
5409 pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
5410 if (pages < max)
5411 continue;
5412 ret = false;
5413 break;
5414 }
5415 mem_cgroup_put(original_memcg);
5416 return ret;
5417}
5418
5419/**
5420 * obj_cgroup_charge_zswap - charge compression backend memory
5421 * @objcg: the object cgroup
5422 * @size: size of compressed object
5423 *
3a1060c2 5424 * This forces the charge after obj_cgroup_may_zswap() allowed
f4840ccf
JW
5425 * compression and storage in zwap for this cgroup to go ahead.
5426 */
5427void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
5428{
5429 struct mem_cgroup *memcg;
5430
5431 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5432 return;
5433
5434 VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
5435
5436 /* PF_MEMALLOC context, charging must succeed */
5437 if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
5438 VM_WARN_ON_ONCE(1);
5439
5440 rcu_read_lock();
5441 memcg = obj_cgroup_memcg(objcg);
5442 mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
5443 mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
5444 rcu_read_unlock();
5445}
5446
5447/**
5448 * obj_cgroup_uncharge_zswap - uncharge compression backend memory
5449 * @objcg: the object cgroup
5450 * @size: size of compressed object
5451 *
5452 * Uncharges zswap memory on page in.
5453 */
5454void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
5455{
5456 struct mem_cgroup *memcg;
5457
5458 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5459 return;
5460
5461 obj_cgroup_uncharge(objcg, size);
5462
5463 rcu_read_lock();
5464 memcg = obj_cgroup_memcg(objcg);
5465 mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
5466 mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
5467 rcu_read_unlock();
5468}
5469
501a06fe
NP
5470bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
5471{
5472 /* if zswap is disabled, do not block pages going to the swapping device */
e3992573
MY
5473 if (!zswap_is_enabled())
5474 return true;
5475
5476 for (; memcg; memcg = parent_mem_cgroup(memcg))
5477 if (!READ_ONCE(memcg->zswap_writeback))
5478 return false;
5479
5480 return true;
501a06fe
NP
5481}
5482
f4840ccf
JW
5483static u64 zswap_current_read(struct cgroup_subsys_state *css,
5484 struct cftype *cft)
5485{
7d7ef0a4
YA
5486 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5487
5488 mem_cgroup_flush_stats(memcg);
5489 return memcg_page_state(memcg, MEMCG_ZSWAP_B);
f4840ccf
JW
5490}
5491
5492static int zswap_max_show(struct seq_file *m, void *v)
5493{
5494 return seq_puts_memcg_tunable(m,
5495 READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
5496}
5497
5498static ssize_t zswap_max_write(struct kernfs_open_file *of,
5499 char *buf, size_t nbytes, loff_t off)
5500{
5501 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5502 unsigned long max;
5503 int err;
5504
5505 buf = strstrip(buf);
5506 err = page_counter_memparse(buf, "max", &max);
5507 if (err)
5508 return err;
5509
5510 xchg(&memcg->zswap_max, max);
5511
5512 return nbytes;
5513}
5514
501a06fe
NP
5515static int zswap_writeback_show(struct seq_file *m, void *v)
5516{
5517 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5518
5519 seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
5520 return 0;
5521}
5522
5523static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
5524 char *buf, size_t nbytes, loff_t off)
5525{
5526 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5527 int zswap_writeback;
5528 ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
5529
5530 if (parse_ret)
5531 return parse_ret;
5532
5533 if (zswap_writeback != 0 && zswap_writeback != 1)
5534 return -EINVAL;
5535
5536 WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
5537 return nbytes;
5538}
5539
f4840ccf
JW
5540static struct cftype zswap_files[] = {
5541 {
5542 .name = "zswap.current",
5543 .flags = CFTYPE_NOT_ON_ROOT,
5544 .read_u64 = zswap_current_read,
5545 },
5546 {
5547 .name = "zswap.max",
5548 .flags = CFTYPE_NOT_ON_ROOT,
5549 .seq_show = zswap_max_show,
5550 .write = zswap_max_write,
5551 },
501a06fe
NP
5552 {
5553 .name = "zswap.writeback",
5554 .seq_show = zswap_writeback_show,
5555 .write = zswap_writeback_write,
5556 },
f4840ccf
JW
5557 { } /* terminate */
5558};
3a3b7fec 5559#endif /* CONFIG_ZSWAP */
f4840ccf 5560
21afa38e
JW
5561static int __init mem_cgroup_swap_init(void)
5562{
2d1c4980 5563 if (mem_cgroup_disabled())
eccb52e7
JW
5564 return 0;
5565
5566 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
e93d4166 5567#ifdef CONFIG_MEMCG_V1
eccb52e7 5568 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
e93d4166 5569#endif
3a3b7fec 5570#ifdef CONFIG_ZSWAP
f4840ccf
JW
5571 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
5572#endif
21afa38e
JW
5573 return 0;
5574}
b25806dc 5575subsys_initcall(mem_cgroup_swap_init);
21afa38e 5576
e55b9f96 5577#endif /* CONFIG_SWAP */
7d709f49
GP
5578
5579bool mem_cgroup_node_allowed(struct mem_cgroup *memcg, int nid)
5580{
5581 return memcg ? cpuset_node_allowed(memcg->css.cgroup, nid) : true;
5582}