xref: /linux/mm/memcontrol.c (revision de6be06f4a2dc88066e6227ec6864e7903985549)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
3  *
4  * Copyright IBM Corporation, 2007
5  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6  *
7  * Copyright 2007 OpenVZ SWsoft Inc
8  * Author: Pavel Emelianov <xemul@openvz.org>
9  *
10  * Memory thresholds
11  * Copyright (C) 2009 Nokia Corporation
12  * Author: Kirill A. Shutemov
13  *
14  * Kernel Memory Controller
15  * Copyright (C) 2012 Parallels Inc. and Google Inc.
16  * Authors: Glauber Costa and Suleiman Souhlal
17  *
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
23  *
24  * Per memcg lru locking
25  * Copyright (C) 2020 Alibaba, Inc, Alex Shi
26  */
27 
28 #include <linux/cgroup-defs.h>
29 #include <linux/page_counter.h>
30 #include <linux/memcontrol.h>
31 #include <linux/cgroup.h>
32 #include <linux/cpuset.h>
33 #include <linux/sched/mm.h>
34 #include <linux/shmem_fs.h>
35 #include <linux/hugetlb.h>
36 #include <linux/pagemap.h>
37 #include <linux/folio_batch.h>
38 #include <linux/vm_event_item.h>
39 #include <linux/smp.h>
40 #include <linux/page-flags.h>
41 #include <linux/backing-dev.h>
42 #include <linux/bit_spinlock.h>
43 #include <linux/rcupdate.h>
44 #include <linux/limits.h>
45 #include <linux/export.h>
46 #include <linux/list.h>
47 #include <linux/mutex.h>
48 #include <linux/rbtree.h>
49 #include <linux/slab.h>
50 #include <linux/swapops.h>
51 #include <linux/spinlock.h>
52 #include <linux/fs.h>
53 #include <linux/seq_file.h>
54 #include <linux/vmpressure.h>
55 #include <linux/memremap.h>
56 #include <linux/mm_inline.h>
57 #include <linux/cpu.h>
58 #include <linux/oom.h>
59 #include <linux/lockdep.h>
60 #include <linux/resume_user_mode.h>
61 #include <linux/psi.h>
62 #include <linux/seq_buf.h>
63 #include <linux/sched/isolation.h>
64 #include <linux/kmemleak.h>
65 #include <linux/irq_work.h>
66 #include "internal.h"
67 #include "swap.h"
68 #include "swap_table.h"
69 #include <net/sock.h>
70 #include <net/ip.h>
71 #include "slab.h"
72 #include "memcontrol-v1.h"
73 
74 #include <linux/uaccess.h>
75 
76 #define CREATE_TRACE_POINTS
77 #include <trace/events/memcg.h>
78 #undef CREATE_TRACE_POINTS
79 
80 #include <trace/events/vmscan.h>
81 
82 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
83 EXPORT_SYMBOL(memory_cgrp_subsys);
84 
85 struct mem_cgroup *root_mem_cgroup __read_mostly;
86 EXPORT_SYMBOL(root_mem_cgroup);
87 
88 /* Active memory cgroup to use from an interrupt context */
89 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
90 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
91 
92 /* Socket memory accounting disabled? */
93 static bool cgroup_memory_nosocket __ro_after_init;
94 
95 /* Kernel memory accounting disabled? */
96 static bool cgroup_memory_nokmem __ro_after_init;
97 
98 /* BPF memory accounting disabled? */
99 static bool cgroup_memory_nobpf __ro_after_init;
100 
101 static struct workqueue_struct *memcg_wq __ro_after_init;
102 
103 static struct kmem_cache *memcg_cachep;
104 static struct kmem_cache *memcg_pn_cachep;
105 
106 #ifdef CONFIG_CGROUP_WRITEBACK
107 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
108 #endif
109 
110 static inline bool task_is_dying(void)
111 {
112 	return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
113 		(current->flags & PF_EXITING);
114 }
115 
116 /* Some nice accessors for the vmpressure. */
117 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
118 {
119 	if (!memcg)
120 		memcg = root_mem_cgroup;
121 	return &memcg->vmpressure;
122 }
123 
124 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
125 {
126 	return container_of(vmpr, struct mem_cgroup, vmpressure);
127 }
128 
129 #define SEQ_BUF_SIZE SZ_4K
130 #define CURRENT_OBJCG_UPDATE_BIT 0
131 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
132 
133 static DEFINE_SPINLOCK(objcg_lock);
134 
135 bool mem_cgroup_kmem_disabled(void)
136 {
137 	return cgroup_memory_nokmem;
138 }
139 
140 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages);
141 
142 static void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned int nr_pages)
143 {
144 	mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
145 	memcg1_account_kmem(memcg, -nr_pages);
146 	if (!mem_cgroup_is_root(memcg))
147 		memcg_uncharge(memcg, nr_pages);
148 }
149 
150 static void obj_cgroup_release(struct percpu_ref *ref)
151 {
152 	struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
153 	unsigned int nr_bytes;
154 	unsigned int nr_pages;
155 	unsigned long flags;
156 
157 	/*
158 	 * At this point all allocated objects are freed, and
159 	 * objcg->nr_charged_bytes can't have an arbitrary byte value.
160 	 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
161 	 *
162 	 * The following sequence can lead to it:
163 	 * 1) CPU0: objcg cached in one of stock->cached[i]
164 	 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
165 	 *          PAGE_SIZE bytes are charged
166 	 * 3) CPU1: a process from another memcg is allocating something,
167 	 *          the stock if flushed,
168 	 *          objcg->nr_charged_bytes = PAGE_SIZE - 92
169 	 * 4) CPU0: we do release this object,
170 	 *          92 bytes are added to stock->nr_bytes[i]
171 	 * 5) CPU0: stock is flushed,
172 	 *          92 bytes are added to objcg->nr_charged_bytes
173 	 *
174 	 * In the result, nr_charged_bytes == PAGE_SIZE.
175 	 * This page will be uncharged in obj_cgroup_release().
176 	 */
177 	nr_bytes = atomic_read(&objcg->nr_charged_bytes);
178 	WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
179 	nr_pages = nr_bytes >> PAGE_SHIFT;
180 
181 	if (nr_pages) {
182 		struct mem_cgroup *memcg;
183 
184 		memcg = get_mem_cgroup_from_objcg(objcg);
185 		memcg_uncharge_kmem(memcg, nr_pages);
186 		mem_cgroup_put(memcg);
187 	}
188 
189 	spin_lock_irqsave(&objcg_lock, flags);
190 	list_del(&objcg->list);
191 	spin_unlock_irqrestore(&objcg_lock, flags);
192 
193 	percpu_ref_exit(ref);
194 	kfree_rcu(objcg, rcu);
195 }
196 
197 static struct obj_cgroup *obj_cgroup_alloc(void)
198 {
199 	struct obj_cgroup *objcg;
200 	int ret;
201 
202 	objcg = kzalloc_obj(struct obj_cgroup);
203 	if (!objcg)
204 		return NULL;
205 
206 	ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
207 			      GFP_KERNEL);
208 	if (ret) {
209 		kfree(objcg);
210 		return NULL;
211 	}
212 	INIT_LIST_HEAD(&objcg->list);
213 	return objcg;
214 }
215 
216 static inline struct obj_cgroup *__memcg_reparent_objcgs(struct mem_cgroup *memcg,
217 							 struct mem_cgroup *parent,
218 							 int nid)
219 {
220 	struct obj_cgroup *objcg, *iter;
221 	struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
222 	struct mem_cgroup_per_node *parent_pn = parent->nodeinfo[nid];
223 
224 	objcg = rcu_replace_pointer(pn->objcg, NULL, true);
225 	/* 1) Ready to reparent active objcg. */
226 	list_add(&objcg->list, &pn->objcg_list);
227 	/* 2) Reparent active objcg and already reparented objcgs to parent. */
228 	list_for_each_entry(iter, &pn->objcg_list, list)
229 		WRITE_ONCE(iter->memcg, parent);
230 	/* 3) Move already reparented objcgs to the parent's list */
231 	list_splice(&pn->objcg_list, &parent_pn->objcg_list);
232 
233 	return objcg;
234 }
235 
236 static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force);
237 
238 /*
239  * Reparent the non-hierarchical lruvec stats that count_shadow_nodes() reads
240  * to approximate the shadow node budget.  They are not exposed to userspace
241  * on cgroup v2, but they must follow the reparented folios; otherwise the
242  * ancestor would only receive the negative deltas when the folios are freed
243  * without ever having received the positive base, and its local stats would
244  * permanently underflow.
245  */
246 static void reparent_v2_lruvec_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent)
247 {
248 	int i;
249 
250 	for (i = 0; i < NR_LRU_LISTS; i++)
251 		reparent_memcg_lruvec_state_local(memcg, parent, NR_LRU_BASE + i);
252 
253 	reparent_memcg_lruvec_state_local(memcg, parent, NR_SLAB_RECLAIMABLE_B);
254 	reparent_memcg_lruvec_state_local(memcg, parent, NR_SLAB_UNRECLAIMABLE_B);
255 }
256 
257 static inline void reparent_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent)
258 {
259 	/*
260 	 * Reparent stats exposed non-hierarchically. Flush @memcg's stats first
261 	 * to read its stats accurately , and conservatively flush @parent's
262 	 * stats after reparenting to avoid hiding a potentially large stat
263 	 * update (e.g. from callers of mem_cgroup_flush_stats_ratelimited()).
264 	 */
265 	__mem_cgroup_flush_stats(memcg, true);
266 
267 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
268 		reparent_v2_lruvec_state_local(memcg, parent);
269 	} else {
270 #ifdef CONFIG_MEMCG_V1
271 		/* The following counts are all non-hierarchical and need to be reparented. */
272 		reparent_memcg1_state_local(memcg, parent);
273 		reparent_memcg1_lruvec_state_local(memcg, parent);
274 #endif
275 	}
276 
277 	__mem_cgroup_flush_stats(parent, true);
278 }
279 
280 static inline void reparent_locks(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid)
281 {
282 	spin_lock_irq(&objcg_lock);
283 	spin_lock_nested(&mem_cgroup_lruvec(memcg, NODE_DATA(nid))->lru_lock, 1);
284 	spin_lock_nested(&mem_cgroup_lruvec(parent, NODE_DATA(nid))->lru_lock, 2);
285 }
286 
287 static inline void reparent_unlocks(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid)
288 {
289 	spin_unlock(&mem_cgroup_lruvec(parent, NODE_DATA(nid))->lru_lock);
290 	spin_unlock(&mem_cgroup_lruvec(memcg, NODE_DATA(nid))->lru_lock);
291 	spin_unlock_irq(&objcg_lock);
292 }
293 
294 static void memcg_reparent_objcgs(struct mem_cgroup *memcg)
295 {
296 	struct obj_cgroup *objcg;
297 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
298 	int nid;
299 
300 	for_each_node(nid) {
301 retry:
302 		if (lru_gen_enabled())
303 			max_lru_gen_memcg(parent, nid);
304 
305 		reparent_locks(memcg, parent, nid);
306 
307 		if (lru_gen_enabled()) {
308 			if (!recheck_lru_gen_max_memcg(parent, nid)) {
309 				reparent_unlocks(memcg, parent, nid);
310 				cond_resched();
311 				goto retry;
312 			}
313 			lru_gen_reparent_memcg(memcg, parent, nid);
314 		} else {
315 			lru_reparent_memcg(memcg, parent, nid);
316 		}
317 
318 		objcg = __memcg_reparent_objcgs(memcg, parent, nid);
319 
320 		reparent_unlocks(memcg, parent, nid);
321 
322 		percpu_ref_kill(&objcg->refcnt);
323 	}
324 
325 	reparent_state_local(memcg, parent);
326 }
327 
328 /*
329  * A lot of the calls to the cache allocation functions are expected to be
330  * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
331  * conditional to this static branch, we'll have to allow modules that does
332  * kmem_cache_alloc and the such to see this symbol as well
333  */
334 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
335 EXPORT_SYMBOL(memcg_kmem_online_key);
336 
337 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
338 EXPORT_SYMBOL(memcg_bpf_enabled_key);
339 
340 /**
341  * get_mem_cgroup_css_from_folio - acquire a css of the memcg associated with a folio
342  * @folio: folio of interest
343  *
344  * If memcg is bound to the default hierarchy, css of the memcg associated
345  * with @folio is returned.  The returned css remains associated with @folio
346  * until it is released.
347  *
348  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
349  * is returned.
350  */
351 struct cgroup_subsys_state *get_mem_cgroup_css_from_folio(const struct folio *folio)
352 {
353 	struct mem_cgroup *memcg;
354 
355 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
356 		return &root_mem_cgroup->css;
357 
358 	memcg = get_mem_cgroup_from_folio(folio);
359 
360 	return memcg ? &memcg->css : &root_mem_cgroup->css;
361 }
362 
363 /**
364  * page_cgroup_ino - return inode number of the memcg a page is charged to
365  * @page: the page
366  *
367  * Look up the closest online ancestor of the memory cgroup @page is charged to
368  * and return its inode number or 0 if @page is not charged to any cgroup. It
369  * is safe to call this function without holding a reference to @page.
370  *
371  * Note, this function is inherently racy, because there is nothing to prevent
372  * the cgroup inode from getting torn down and potentially reallocated a moment
373  * after page_cgroup_ino() returns, so it only should be used by callers that
374  * do not care (such as procfs interfaces).
375  */
376 ino_t page_cgroup_ino(const struct page *page)
377 {
378 	struct mem_cgroup *memcg;
379 	unsigned long ino = 0;
380 
381 	rcu_read_lock();
382 	/* page_folio() is racy here, but the entire function is racy anyway */
383 	memcg = folio_memcg_check(page_folio(page));
384 
385 	while (memcg && !css_is_online(&memcg->css))
386 		memcg = parent_mem_cgroup(memcg);
387 	if (memcg)
388 		ino = cgroup_ino(memcg->css.cgroup);
389 	rcu_read_unlock();
390 	return ino;
391 }
392 EXPORT_SYMBOL_GPL(page_cgroup_ino);
393 
394 /* Subset of node_stat_item for memcg stats */
395 static const unsigned int memcg_node_stat_items[] = {
396 	NR_INACTIVE_ANON,
397 	NR_ACTIVE_ANON,
398 	NR_INACTIVE_FILE,
399 	NR_ACTIVE_FILE,
400 	NR_UNEVICTABLE,
401 	NR_SLAB_RECLAIMABLE_B,
402 	NR_SLAB_UNRECLAIMABLE_B,
403 	WORKINGSET_REFAULT_ANON,
404 	WORKINGSET_REFAULT_FILE,
405 	WORKINGSET_ACTIVATE_ANON,
406 	WORKINGSET_ACTIVATE_FILE,
407 	WORKINGSET_RESTORE_ANON,
408 	WORKINGSET_RESTORE_FILE,
409 	WORKINGSET_NODERECLAIM,
410 	NR_ANON_MAPPED,
411 	NR_FILE_MAPPED,
412 	NR_FILE_PAGES,
413 	NR_FILE_DIRTY,
414 	NR_WRITEBACK,
415 	NR_SHMEM,
416 	NR_SHMEM_THPS,
417 	NR_FILE_THPS,
418 	NR_ANON_THPS,
419 	NR_VMSCAN_WRITE,
420 	NR_VMALLOC,
421 	NR_KERNEL_STACK_KB,
422 	NR_PAGETABLE,
423 	NR_SECONDARY_PAGETABLE,
424 #ifdef CONFIG_SWAP
425 	NR_SWAPCACHE,
426 #endif
427 #ifdef CONFIG_NUMA_BALANCING
428 	PGPROMOTE_SUCCESS,
429 #endif
430 	PGDEMOTE_KSWAPD,
431 	PGDEMOTE_DIRECT,
432 	PGDEMOTE_KHUGEPAGED,
433 	PGDEMOTE_PROACTIVE,
434 	PGSTEAL_KSWAPD,
435 	PGSTEAL_DIRECT,
436 	PGSTEAL_KHUGEPAGED,
437 	PGSTEAL_PROACTIVE,
438 	PGSTEAL_ANON,
439 	PGSTEAL_FILE,
440 	PGSCAN_KSWAPD,
441 	PGSCAN_DIRECT,
442 	PGSCAN_KHUGEPAGED,
443 	PGSCAN_PROACTIVE,
444 	PGSCAN_ANON,
445 	PGSCAN_FILE,
446 	PGROTATE_ANON,
447 	PGROTATE_FILE,
448 	PGREFILL,
449 #ifdef CONFIG_HUGETLB_PAGE
450 	NR_HUGETLB,
451 #endif
452 };
453 
454 static const unsigned int memcg_stat_items[] = {
455 	MEMCG_SWAP,
456 	MEMCG_SOCK,
457 	MEMCG_PERCPU_B,
458 	MEMCG_KMEM,
459 	MEMCG_ZSWAP_B,
460 	MEMCG_ZSWAPPED,
461 	MEMCG_ZSWAP_INCOMP,
462 };
463 
464 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
465 #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
466 			   ARRAY_SIZE(memcg_stat_items))
467 #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
468 static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
469 
470 static void init_memcg_stats(void)
471 {
472 	u8 i, j = 0;
473 
474 	BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
475 
476 	memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
477 
478 	for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
479 		mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
480 
481 	for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
482 		mem_cgroup_stats_index[memcg_stat_items[i]] = j;
483 }
484 
485 static inline int memcg_stats_index(int idx)
486 {
487 	return mem_cgroup_stats_index[idx];
488 }
489 
490 struct lruvec_stats_percpu {
491 	/* Local (CPU and cgroup) state */
492 	long state[NR_MEMCG_NODE_STAT_ITEMS];
493 
494 	/* Delta calculation for lockless upward propagation */
495 	long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
496 };
497 
498 struct lruvec_stats {
499 	/* Aggregated (CPU and subtree) state */
500 	long state[NR_MEMCG_NODE_STAT_ITEMS];
501 
502 	/* Non-hierarchical (CPU aggregated) state */
503 	long state_local[NR_MEMCG_NODE_STAT_ITEMS];
504 
505 	/* Pending child counts during tree propagation */
506 	long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
507 };
508 
509 unsigned long lruvec_page_state(const struct lruvec *lruvec, enum node_stat_item idx)
510 {
511 	const struct mem_cgroup_per_node *pn;
512 	long x;
513 	int i;
514 
515 	if (mem_cgroup_disabled())
516 		return node_page_state(lruvec_pgdat(lruvec), idx);
517 
518 	i = memcg_stats_index(idx);
519 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
520 		return 0;
521 
522 	pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec);
523 	x = READ_ONCE(pn->lruvec_stats->state[i]);
524 #ifdef CONFIG_SMP
525 	if (x < 0)
526 		x = 0;
527 #endif
528 	return x;
529 }
530 
531 /**
532  * lruvec_page_state_monotonic - non-clamping lruvec stat read for delta sampling
533  * @lruvec: the LRU vector to read from
534  * @idx: the node_stat_item to read
535  *
536  * Returns the raw state[idx] value cast to unsigned long, skipping the
537  * clamp-negative-to-zero step in lruvec_page_state(). Intended for callers
538  * that snapshot a monotonically-incremented counter and subtract two
539  * samples: unsigned modular arithmetic then yields the correct delta across
540  * a signed-long wraparound (a real hazard on 32-bit) that the clamp would
541  * otherwise turn into a huge spurious delta.
542  *
543  * Do NOT use for non-monotonic page-count reads where a transient negative
544  * reading from per-CPU delta skew must present as zero.
545  *
546  * XXX: This helper (and its node/global peers) exists because some
547  * monotonically-incremented event counters are stored in
548  * enum node_stat_item.
549  */
550 unsigned long lruvec_page_state_monotonic(const struct lruvec *lruvec,
551 					  enum node_stat_item idx)
552 {
553 	const struct mem_cgroup_per_node *pn;
554 	int i;
555 
556 	if (mem_cgroup_disabled())
557 		return node_page_state_monotonic(lruvec_pgdat(lruvec), idx);
558 
559 	i = memcg_stats_index(idx);
560 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
561 		return 0;
562 
563 	pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec);
564 	return (unsigned long)READ_ONCE(pn->lruvec_stats->state[i]);
565 }
566 
567 unsigned long lruvec_page_state_local(const struct lruvec *lruvec,
568 				      enum node_stat_item idx)
569 {
570 	const struct mem_cgroup_per_node *pn;
571 	long x;
572 	int i;
573 
574 	if (mem_cgroup_disabled())
575 		return node_page_state(lruvec_pgdat(lruvec), idx);
576 
577 	i = memcg_stats_index(idx);
578 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
579 		return 0;
580 
581 	pn = container_of_const(lruvec, struct mem_cgroup_per_node, lruvec);
582 	x = READ_ONCE(pn->lruvec_stats->state_local[i]);
583 #ifdef CONFIG_SMP
584 	if (x < 0)
585 		x = 0;
586 #endif
587 	return x;
588 }
589 
590 static void __mod_memcg_lruvec_state(struct mem_cgroup_per_node *pn,
591 				     enum node_stat_item idx, long val);
592 
593 void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg,
594 				       struct mem_cgroup *parent, int idx)
595 {
596 	int nid;
597 
598 	for_each_node(nid) {
599 		struct lruvec *child_lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
600 		struct lruvec *parent_lruvec = mem_cgroup_lruvec(parent, NODE_DATA(nid));
601 		unsigned long value = lruvec_page_state_local(child_lruvec, idx);
602 		struct mem_cgroup_per_node *child_pn, *parent_pn;
603 
604 		child_pn = container_of(child_lruvec, struct mem_cgroup_per_node, lruvec);
605 		parent_pn = container_of(parent_lruvec, struct mem_cgroup_per_node, lruvec);
606 
607 		__mod_memcg_lruvec_state(child_pn, idx, -value);
608 		__mod_memcg_lruvec_state(parent_pn, idx, value);
609 	}
610 }
611 
612 /* Subset of vm_event_item to report for memcg event stats */
613 static const unsigned int memcg_vm_event_stat[] = {
614 #ifdef CONFIG_MEMCG_V1
615 	PGPGIN,
616 	PGPGOUT,
617 #endif
618 	PSWPIN,
619 	PSWPOUT,
620 	PGFAULT,
621 	PGMAJFAULT,
622 	PGACTIVATE,
623 	PGDEACTIVATE,
624 	PGLAZYFREE,
625 	PGLAZYFREED,
626 #ifdef CONFIG_SWAP
627 	SWPIN_ZERO,
628 	SWPOUT_ZERO,
629 #endif
630 #ifdef CONFIG_ZSWAP
631 	ZSWPIN,
632 	ZSWPOUT,
633 	ZSWPWB,
634 #endif
635 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
636 	THP_FAULT_ALLOC,
637 	THP_COLLAPSE_ALLOC,
638 	THP_SWPOUT,
639 	THP_SWPOUT_FALLBACK,
640 #endif
641 #ifdef CONFIG_NUMA_BALANCING
642 	NUMA_PAGE_MIGRATE,
643 	NUMA_PTE_UPDATES,
644 	NUMA_HINT_FAULTS,
645 #endif
646 };
647 
648 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
649 static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
650 
651 static void init_memcg_events(void)
652 {
653 	u8 i;
654 
655 	BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
656 
657 	memset(mem_cgroup_events_index, U8_MAX,
658 	       sizeof(mem_cgroup_events_index));
659 
660 	for (i = 0; i < NR_MEMCG_EVENTS; ++i)
661 		mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
662 }
663 
664 static inline int memcg_events_index(enum vm_event_item idx)
665 {
666 	return mem_cgroup_events_index[idx];
667 }
668 
669 struct memcg_vmstats_percpu {
670 	/* Stats updates since the last flush */
671 	unsigned long			stats_updates;
672 
673 	/* Cached pointers for fast iteration in memcg_rstat_updated() */
674 	struct memcg_vmstats_percpu __percpu	*parent_pcpu;
675 	struct memcg_vmstats			*vmstats;
676 
677 	/* The above should fit a single cacheline for memcg_rstat_updated() */
678 
679 	/* Local (CPU and cgroup) page state & events */
680 	long			state[MEMCG_VMSTAT_SIZE];
681 	unsigned long		events[NR_MEMCG_EVENTS];
682 
683 	/* Delta calculation for lockless upward propagation */
684 	long			state_prev[MEMCG_VMSTAT_SIZE];
685 	unsigned long		events_prev[NR_MEMCG_EVENTS];
686 } ____cacheline_aligned;
687 
688 struct memcg_vmstats {
689 	/* Aggregated (CPU and subtree) page state & events */
690 	long			state[MEMCG_VMSTAT_SIZE];
691 	unsigned long		events[NR_MEMCG_EVENTS];
692 
693 #ifdef CONFIG_MEMCG_V1
694 	/* Non-hierarchical (CPU aggregated) page state & events */
695 	long			state_local[MEMCG_VMSTAT_SIZE];
696 	unsigned long		events_local[NR_MEMCG_EVENTS];
697 #endif
698 
699 	/* Pending child counts during tree propagation */
700 	long			state_pending[MEMCG_VMSTAT_SIZE];
701 	unsigned long		events_pending[NR_MEMCG_EVENTS];
702 
703 	/* Stats updates since the last flush */
704 	atomic_long_t		stats_updates;
705 };
706 
707 /*
708  * The non-hierarchical memcg-wide counters are read back only by the legacy
709  * memory.stat and memory.numa_stat, and by reparenting on offline, all of which
710  * are v1-only. If the kernel is built without CONFIG_MEMCG_V1, or if the boot
711  * param cgroup_no_v1= has blocked the memory controller from v1 hierarchies,
712  * then nothing reads them and writers can skip the updates.
713  */
714 static long *memcg_state_local_array(struct mem_cgroup *memcg)
715 {
716 #ifdef CONFIG_MEMCG_V1
717 	if (!cgroup1_ssid_disabled(memory_cgrp_id))
718 		return memcg->vmstats->state_local;
719 #endif
720 	return NULL;
721 }
722 
723 static unsigned long *memcg_events_local_array(struct mem_cgroup *memcg)
724 {
725 #ifdef CONFIG_MEMCG_V1
726 	if (!cgroup1_ssid_disabled(memory_cgrp_id))
727 		return memcg->vmstats->events_local;
728 #endif
729 	return NULL;
730 }
731 
732 /*
733  * memcg and lruvec stats flushing
734  *
735  * Many codepaths leading to stats update or read are performance sensitive and
736  * adding stats flushing in such codepaths is not desirable. So, to optimize the
737  * flushing the kernel does:
738  *
739  * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
740  *    rstat update tree grow unbounded.
741  *
742  * 2) Flush the stats synchronously on reader side only when there are more than
743  *    (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
744  *    will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
745  *    only for 2 seconds due to (1).
746  */
747 static void flush_memcg_stats_dwork(struct work_struct *w);
748 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
749 static u64 flush_last_time;
750 
751 #define FLUSH_TIME (2UL*HZ)
752 
753 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
754 {
755 	return atomic_long_read(&vmstats->stats_updates) >
756 		MEMCG_CHARGE_BATCH * num_online_cpus();
757 }
758 
759 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, long val,
760 				       int cpu)
761 {
762 	struct memcg_vmstats_percpu __percpu *statc_pcpu;
763 	struct memcg_vmstats_percpu *statc;
764 	unsigned long stats_updates;
765 
766 	if (!val)
767 		return;
768 
769 	__css_rstat_updated(&memcg->css, cpu);
770 	statc_pcpu = memcg->vmstats_percpu;
771 	for (; statc_pcpu; statc_pcpu = statc->parent_pcpu) {
772 		statc = this_cpu_ptr(statc_pcpu);
773 		/*
774 		 * If @memcg is already flushable then all its ancestors are
775 		 * flushable as well and also there is no need to increase
776 		 * stats_updates.
777 		 */
778 		if (memcg_vmstats_needs_flush(statc->vmstats))
779 			break;
780 
781 		stats_updates = this_cpu_add_return(statc_pcpu->stats_updates,
782 						    abs(val));
783 		if (stats_updates < MEMCG_CHARGE_BATCH)
784 			continue;
785 
786 		stats_updates = this_cpu_xchg(statc_pcpu->stats_updates, 0);
787 		atomic_long_add(stats_updates, &statc->vmstats->stats_updates);
788 	}
789 }
790 
791 static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force)
792 {
793 	bool needs_flush = memcg_vmstats_needs_flush(memcg->vmstats);
794 
795 	trace_memcg_flush_stats(memcg, atomic_long_read(&memcg->vmstats->stats_updates),
796 		force, needs_flush);
797 
798 	if (!force && !needs_flush)
799 		return;
800 
801 	if (mem_cgroup_is_root(memcg))
802 		WRITE_ONCE(flush_last_time, get_jiffies_64());
803 
804 	css_rstat_flush(&memcg->css);
805 }
806 
807 /*
808  * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
809  * @memcg: root of the subtree to flush
810  *
811  * Flushing is serialized by the underlying global rstat lock. There is also a
812  * minimum amount of work to be done even if there are no stat updates to flush.
813  * Hence, we only flush the stats if the updates delta exceeds a threshold. This
814  * avoids unnecessary work and contention on the underlying lock.
815  */
816 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
817 {
818 	if (mem_cgroup_disabled())
819 		return;
820 
821 	if (!memcg)
822 		memcg = root_mem_cgroup;
823 
824 	__mem_cgroup_flush_stats(memcg, false);
825 }
826 
827 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
828 {
829 	/* Only flush if the periodic flusher is one full cycle late */
830 	if (time_after64(get_jiffies_64(), READ_ONCE(flush_last_time) + 2 * FLUSH_TIME))
831 		mem_cgroup_flush_stats(memcg);
832 }
833 
834 static void flush_memcg_stats_dwork(struct work_struct *w)
835 {
836 	/*
837 	 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
838 	 * in latency-sensitive paths is as cheap as possible.
839 	 */
840 	__mem_cgroup_flush_stats(root_mem_cgroup, true);
841 	queue_delayed_work(system_dfl_wq, &stats_flush_dwork, FLUSH_TIME);
842 }
843 
844 unsigned long memcg_page_state(const struct mem_cgroup *memcg, int idx)
845 {
846 	long x;
847 	int i = memcg_stats_index(idx);
848 
849 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
850 		return 0;
851 
852 	x = READ_ONCE(memcg->vmstats->state[i]);
853 #ifdef CONFIG_SMP
854 	if (x < 0)
855 		x = 0;
856 #endif
857 	return x;
858 }
859 
860 bool memcg_stat_item_valid(int idx)
861 {
862 	if ((u32)idx >= MEMCG_NR_STAT)
863 		return false;
864 
865 	return !BAD_STAT_IDX(memcg_stats_index(idx));
866 }
867 
868 static int memcg_page_state_unit(int item);
869 
870 /*
871  * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
872  * up non-zero sub-page updates to 1 page as zero page updates are ignored.
873  */
874 static long memcg_state_val_in_pages(int idx, long val)
875 {
876 	int unit = memcg_page_state_unit(idx);
877 	long res;
878 
879 	if (!val || unit == PAGE_SIZE)
880 		return val;
881 
882 	/* Get the absolute value of (val * unit / PAGE_SIZE). */
883 	res = mult_frac(abs(val), unit, PAGE_SIZE);
884 	/* Round up zero values. */
885 	res = res ? : 1;
886 
887 	return val < 0 ? -res : res;
888 }
889 
890 /*
891  * Used in mod_memcg_state() and mod_memcg_lruvec_state() to avoid race
892  * with reparenting of non-hierarchical state_locals.  Offlining a
893  * memcg is rare, so do the redirection for all cgroup hierarchies.
894  */
895 static inline struct mem_cgroup *
896 get_non_dying_memcg_start(struct mem_cgroup *memcg, bool *rcu_locked)
897 {
898 	/*
899 	 * Fast path: the caller holds a reference to @memcg, so reading
900 	 * its CSS_DYING flag without the RCU lock is safe.  The RCU lock
901 	 * is only needed to walk up to a non-dying ancestor, which
902 	 * happens only while a memcg is actually being offlined.
903 	 */
904 	if (!memcg_is_dying(memcg)) {
905 		*rcu_locked = false;
906 		return memcg;
907 	}
908 
909 	rcu_read_lock();
910 	*rcu_locked = true;
911 
912 	while (memcg_is_dying(memcg))
913 		memcg = parent_mem_cgroup(memcg);
914 
915 	return memcg;
916 }
917 
918 static inline void get_non_dying_memcg_end(bool rcu_locked)
919 {
920 	if (!rcu_locked)
921 		return;
922 
923 	rcu_read_unlock();
924 }
925 
926 static void __mod_memcg_state(struct mem_cgroup *memcg,
927 			      enum memcg_stat_item idx, long val)
928 {
929 	int i = memcg_stats_index(idx);
930 	int cpu;
931 
932 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
933 		return;
934 
935 	cpu = get_cpu();
936 
937 	this_cpu_add(memcg->vmstats_percpu->state[i], val);
938 	val = memcg_state_val_in_pages(idx, val);
939 	memcg_rstat_updated(memcg, val, cpu);
940 
941 	trace_mod_memcg_state(memcg, idx, val);
942 
943 	put_cpu();
944 }
945 
946 /**
947  * mod_memcg_state - update cgroup memory statistics
948  * @memcg: the memory cgroup
949  * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
950  * @val: delta to add to the counter, can be negative
951  */
952 void mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
953 		       int val)
954 {
955 	bool rcu_locked = false;
956 
957 	if (mem_cgroup_disabled())
958 		return;
959 
960 	memcg = get_non_dying_memcg_start(memcg, &rcu_locked);
961 	__mod_memcg_state(memcg, idx, val);
962 	get_non_dying_memcg_end(rcu_locked);
963 }
964 
965 #ifdef CONFIG_MEMCG_V1
966 /* idx can be of type enum memcg_stat_item or node_stat_item. */
967 unsigned long memcg_page_state_local(const struct mem_cgroup *memcg, int idx)
968 {
969 	long x;
970 	int i = memcg_stats_index(idx);
971 
972 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
973 		return 0;
974 
975 	x = READ_ONCE(memcg->vmstats->state_local[i]);
976 #ifdef CONFIG_SMP
977 	if (x < 0)
978 		x = 0;
979 #endif
980 	return x;
981 }
982 
983 void reparent_memcg_state_local(struct mem_cgroup *memcg,
984 				struct mem_cgroup *parent, int idx)
985 {
986 	unsigned long value = memcg_page_state_local(memcg, idx);
987 
988 	__mod_memcg_state(memcg, idx, -value);
989 	__mod_memcg_state(parent, idx, value);
990 }
991 #endif
992 
993 static void __mod_memcg_lruvec_state(struct mem_cgroup_per_node *pn,
994 				     enum node_stat_item idx, long val)
995 {
996 	struct mem_cgroup *memcg = pn->memcg;
997 	int i = memcg_stats_index(idx);
998 	int cpu;
999 
1000 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
1001 		return;
1002 
1003 	cpu = get_cpu();
1004 
1005 	/* Update memcg */
1006 	this_cpu_add(memcg->vmstats_percpu->state[i], val);
1007 
1008 	/* Update lruvec */
1009 	this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
1010 
1011 	val = memcg_state_val_in_pages(idx, val);
1012 	memcg_rstat_updated(memcg, val, cpu);
1013 	trace_mod_memcg_lruvec_state(memcg, idx, val);
1014 
1015 	put_cpu();
1016 }
1017 
1018 static void mod_memcg_lruvec_state(struct lruvec *lruvec,
1019 				     enum node_stat_item idx,
1020 				     int val)
1021 {
1022 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1023 	struct mem_cgroup_per_node *pn;
1024 	struct mem_cgroup *memcg;
1025 	bool rcu_locked = false;
1026 
1027 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1028 	memcg = get_non_dying_memcg_start(pn->memcg, &rcu_locked);
1029 	pn = memcg->nodeinfo[pgdat->node_id];
1030 
1031 	__mod_memcg_lruvec_state(pn, idx, val);
1032 
1033 	get_non_dying_memcg_end(rcu_locked);
1034 }
1035 
1036 /**
1037  * mod_lruvec_state - update lruvec memory statistics
1038  * @lruvec: the lruvec
1039  * @idx: the stat item
1040  * @val: delta to add to the counter, can be negative
1041  *
1042  * The lruvec is the intersection of the NUMA node and a cgroup. This
1043  * function updates the all three counters that are affected by a
1044  * change of state at this level: per-node, per-cgroup, per-lruvec.
1045  */
1046 void mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
1047 			int val)
1048 {
1049 	/* Update node */
1050 	mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
1051 
1052 	/* Update memcg and lruvec */
1053 	if (!mem_cgroup_disabled())
1054 		mod_memcg_lruvec_state(lruvec, idx, val);
1055 }
1056 
1057 void lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
1058 			     int val)
1059 {
1060 	struct mem_cgroup *memcg;
1061 	pg_data_t *pgdat = folio_pgdat(folio);
1062 	struct lruvec *lruvec;
1063 
1064 	rcu_read_lock();
1065 	memcg = folio_memcg(folio);
1066 	/* Untracked pages have no memcg, no lruvec. Update only the node */
1067 	if (!memcg) {
1068 		rcu_read_unlock();
1069 		mod_node_page_state(pgdat, idx, val);
1070 		return;
1071 	}
1072 
1073 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
1074 	mod_lruvec_state(lruvec, idx, val);
1075 	rcu_read_unlock();
1076 }
1077 EXPORT_SYMBOL(lruvec_stat_mod_folio);
1078 
1079 void mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
1080 {
1081 	pg_data_t *pgdat = page_pgdat(virt_to_page(p));
1082 	struct mem_cgroup *memcg;
1083 	struct lruvec *lruvec;
1084 
1085 	rcu_read_lock();
1086 	memcg = mem_cgroup_from_virt(p);
1087 
1088 	/*
1089 	 * Untracked pages have no memcg, no lruvec. Update only the
1090 	 * node. If we reparent the slab objects to the root memcg,
1091 	 * when we free the slab object, we need to update the per-memcg
1092 	 * vmstats to keep it correct for the root memcg.
1093 	 */
1094 	if (!memcg) {
1095 		mod_node_page_state(pgdat, idx, val);
1096 	} else {
1097 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
1098 		mod_lruvec_state(lruvec, idx, val);
1099 	}
1100 	rcu_read_unlock();
1101 }
1102 
1103 /**
1104  * count_memcg_events - account VM events in a cgroup
1105  * @memcg: the memory cgroup
1106  * @idx: the event item
1107  * @count: the number of events that occurred
1108  */
1109 void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
1110 			  unsigned long count)
1111 {
1112 	int i = memcg_events_index(idx);
1113 	int cpu;
1114 
1115 	if (mem_cgroup_disabled())
1116 		return;
1117 
1118 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
1119 		return;
1120 
1121 	cpu = get_cpu();
1122 
1123 	this_cpu_add(memcg->vmstats_percpu->events[i], count);
1124 	memcg_rstat_updated(memcg, count, cpu);
1125 	trace_count_memcg_events(memcg, idx, count);
1126 
1127 	put_cpu();
1128 }
1129 
1130 unsigned long memcg_events(const struct mem_cgroup *memcg, int event)
1131 {
1132 	int i = memcg_events_index(event);
1133 
1134 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
1135 		return 0;
1136 
1137 	return READ_ONCE(memcg->vmstats->events[i]);
1138 }
1139 
1140 bool memcg_vm_event_item_valid(enum vm_event_item idx)
1141 {
1142 	if (idx >= NR_VM_EVENT_ITEMS)
1143 		return false;
1144 
1145 	return !BAD_STAT_IDX(memcg_events_index(idx));
1146 }
1147 
1148 #ifdef CONFIG_MEMCG_V1
1149 unsigned long memcg_events_local(const struct mem_cgroup *memcg, int event)
1150 {
1151 	int i = memcg_events_index(event);
1152 
1153 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
1154 		return 0;
1155 
1156 	return READ_ONCE(memcg->vmstats->events_local[i]);
1157 }
1158 #endif
1159 
1160 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1161 {
1162 	/*
1163 	 * mm_update_next_owner() may clear mm->owner to NULL
1164 	 * if it races with swapoff, page migration, etc.
1165 	 * So this can be called with p == NULL.
1166 	 */
1167 	if (unlikely(!p))
1168 		return NULL;
1169 
1170 	return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
1171 }
1172 EXPORT_SYMBOL(mem_cgroup_from_task);
1173 
1174 static __always_inline struct mem_cgroup *active_memcg(void)
1175 {
1176 	if (!in_task())
1177 		return this_cpu_read(int_active_memcg);
1178 	else
1179 		return current->active_memcg;
1180 }
1181 
1182 /**
1183  * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1184  * @mm: mm from which memcg should be extracted. It can be NULL.
1185  *
1186  * Obtain a reference on mm->memcg and returns it if successful. If mm
1187  * is NULL, then the memcg is chosen as follows:
1188  * 1) The active memcg, if set.
1189  * 2) current->mm->memcg, if available
1190  * 3) root memcg
1191  * If mem_cgroup is disabled, NULL is returned.
1192  */
1193 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
1194 {
1195 	struct mem_cgroup *memcg;
1196 
1197 	if (mem_cgroup_disabled())
1198 		return NULL;
1199 
1200 	/*
1201 	 * Page cache insertions can happen without an
1202 	 * actual mm context, e.g. during disk probing
1203 	 * on boot, loopback IO, acct() writes etc.
1204 	 *
1205 	 * No need to css_get on root memcg as the reference
1206 	 * counting is disabled on the root level in the
1207 	 * cgroup core. See CSS_NO_REF.
1208 	 */
1209 	if (unlikely(!mm)) {
1210 		memcg = active_memcg();
1211 		if (unlikely(memcg)) {
1212 			/* remote memcg must hold a ref */
1213 			css_get(&memcg->css);
1214 			return memcg;
1215 		}
1216 		mm = current->mm;
1217 		if (unlikely(!mm))
1218 			return root_mem_cgroup;
1219 	}
1220 
1221 	rcu_read_lock();
1222 	do {
1223 		memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1224 		if (unlikely(!memcg))
1225 			memcg = root_mem_cgroup;
1226 	} while (!css_tryget(&memcg->css));
1227 	rcu_read_unlock();
1228 	return memcg;
1229 }
1230 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1231 
1232 /**
1233  * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
1234  */
1235 struct mem_cgroup *get_mem_cgroup_from_current(void)
1236 {
1237 	struct mem_cgroup *memcg;
1238 
1239 	if (mem_cgroup_disabled())
1240 		return NULL;
1241 
1242 again:
1243 	rcu_read_lock();
1244 	memcg = mem_cgroup_from_task(current);
1245 	if (!css_tryget(&memcg->css)) {
1246 		rcu_read_unlock();
1247 		goto again;
1248 	}
1249 	rcu_read_unlock();
1250 	return memcg;
1251 }
1252 
1253 /**
1254  * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg.
1255  * @folio: folio from which memcg should be extracted.
1256  *
1257  * See folio_memcg() for folio->objcg/memcg binding rules.
1258  */
1259 struct mem_cgroup *get_mem_cgroup_from_folio(const struct folio *folio)
1260 {
1261 	struct mem_cgroup *memcg;
1262 
1263 	if (mem_cgroup_disabled())
1264 		return NULL;
1265 
1266 	if (!folio_memcg_charged(folio))
1267 		return root_mem_cgroup;
1268 
1269 	rcu_read_lock();
1270 	do {
1271 		memcg = folio_memcg(folio);
1272 	} while (unlikely(!css_tryget(&memcg->css)));
1273 	rcu_read_unlock();
1274 	return memcg;
1275 }
1276 
1277 /**
1278  * mem_cgroup_iter - iterate over memory cgroup hierarchy
1279  * @root: hierarchy root
1280  * @prev: previously returned memcg, NULL on first invocation
1281  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1282  *
1283  * Returns references to children of the hierarchy below @root, or
1284  * @root itself, or %NULL after a full round-trip.
1285  *
1286  * Caller must pass the return value in @prev on subsequent
1287  * invocations for reference counting, or use mem_cgroup_iter_break()
1288  * to cancel a hierarchy walk before the round-trip is complete.
1289  *
1290  * Reclaimers can specify a node in @reclaim to divide up the memcgs
1291  * in the hierarchy among all concurrent reclaimers operating on the
1292  * same node.
1293  */
1294 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1295 				   struct mem_cgroup *prev,
1296 				   struct mem_cgroup_reclaim_cookie *reclaim)
1297 {
1298 	struct mem_cgroup_reclaim_iter *iter;
1299 	struct cgroup_subsys_state *css;
1300 	struct mem_cgroup *pos;
1301 	struct mem_cgroup *next;
1302 
1303 	if (mem_cgroup_disabled())
1304 		return NULL;
1305 
1306 	if (!root)
1307 		root = root_mem_cgroup;
1308 
1309 	rcu_read_lock();
1310 restart:
1311 	next = NULL;
1312 
1313 	if (reclaim) {
1314 		int gen;
1315 		int nid = reclaim->pgdat->node_id;
1316 
1317 		iter = &root->nodeinfo[nid]->iter;
1318 		gen = atomic_read(&iter->generation);
1319 
1320 		/*
1321 		 * On start, join the current reclaim iteration cycle.
1322 		 * Exit when a concurrent walker completes it.
1323 		 */
1324 		if (!prev)
1325 			reclaim->generation = gen;
1326 		else if (reclaim->generation != gen)
1327 			goto out_unlock;
1328 
1329 		pos = READ_ONCE(iter->position);
1330 	} else
1331 		pos = prev;
1332 
1333 	css = pos ? &pos->css : NULL;
1334 
1335 	while ((css = css_next_descendant_pre(css, &root->css))) {
1336 		/*
1337 		 * Verify the css and acquire a reference.  The root
1338 		 * is provided by the caller, so we know it's alive
1339 		 * and kicking, and don't take an extra reference.
1340 		 */
1341 		if (css == &root->css || css_tryget(css))
1342 			break;
1343 	}
1344 
1345 	next = mem_cgroup_from_css(css);
1346 
1347 	if (reclaim) {
1348 		/*
1349 		 * The position could have already been updated by a competing
1350 		 * thread, so check that the value hasn't changed since we read
1351 		 * it to avoid reclaiming from the same cgroup twice.
1352 		 */
1353 		if (cmpxchg(&iter->position, pos, next) != pos) {
1354 			if (css && css != &root->css)
1355 				css_put(css);
1356 			goto restart;
1357 		}
1358 
1359 		if (!next) {
1360 			atomic_inc(&iter->generation);
1361 
1362 			/*
1363 			 * Reclaimers share the hierarchy walk, and a
1364 			 * new one might jump in right at the end of
1365 			 * the hierarchy - make sure they see at least
1366 			 * one group and restart from the beginning.
1367 			 */
1368 			if (!prev)
1369 				goto restart;
1370 		}
1371 	}
1372 
1373 out_unlock:
1374 	rcu_read_unlock();
1375 	if (prev && prev != root)
1376 		css_put(&prev->css);
1377 
1378 	return next;
1379 }
1380 
1381 /**
1382  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1383  * @root: hierarchy root
1384  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1385  */
1386 void mem_cgroup_iter_break(struct mem_cgroup *root,
1387 			   struct mem_cgroup *prev)
1388 {
1389 	if (!root)
1390 		root = root_mem_cgroup;
1391 	if (prev && prev != root)
1392 		css_put(&prev->css);
1393 }
1394 
1395 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1396 					struct mem_cgroup *dead_memcg)
1397 {
1398 	struct mem_cgroup_reclaim_iter *iter;
1399 	struct mem_cgroup_per_node *mz;
1400 	int nid;
1401 
1402 	for_each_node(nid) {
1403 		mz = from->nodeinfo[nid];
1404 		iter = &mz->iter;
1405 		cmpxchg(&iter->position, dead_memcg, NULL);
1406 	}
1407 }
1408 
1409 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1410 {
1411 	struct mem_cgroup *memcg = dead_memcg;
1412 	struct mem_cgroup *last;
1413 
1414 	do {
1415 		__invalidate_reclaim_iterators(memcg, dead_memcg);
1416 		last = memcg;
1417 	} while ((memcg = parent_mem_cgroup(memcg)));
1418 
1419 	/*
1420 	 * When cgroup1 non-hierarchy mode is used,
1421 	 * parent_mem_cgroup() does not walk all the way up to the
1422 	 * cgroup root (root_mem_cgroup). So we have to handle
1423 	 * dead_memcg from cgroup root separately.
1424 	 */
1425 	if (!mem_cgroup_is_root(last))
1426 		__invalidate_reclaim_iterators(root_mem_cgroup,
1427 						dead_memcg);
1428 }
1429 
1430 /**
1431  * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1432  * @memcg: hierarchy root
1433  * @fn: function to call for each task
1434  * @arg: argument passed to @fn
1435  *
1436  * This function iterates over tasks attached to @memcg or to any of its
1437  * descendants and calls @fn for each task. If @fn returns a non-zero
1438  * value, the function breaks the iteration loop. Otherwise, it will iterate
1439  * over all tasks and return 0.
1440  *
1441  * This function must not be called for the root memory cgroup.
1442  */
1443 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1444 			   int (*fn)(struct task_struct *, void *), void *arg)
1445 {
1446 	struct mem_cgroup *iter;
1447 	int ret = 0;
1448 
1449 	BUG_ON(mem_cgroup_is_root(memcg));
1450 
1451 	for_each_mem_cgroup_tree(iter, memcg) {
1452 		struct css_task_iter it;
1453 		struct task_struct *task;
1454 
1455 		css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1456 		while (!ret && (task = css_task_iter_next(&it))) {
1457 			ret = fn(task, arg);
1458 			/* Avoid potential softlockup warning */
1459 			cond_resched();
1460 		}
1461 		css_task_iter_end(&it);
1462 		if (ret) {
1463 			mem_cgroup_iter_break(memcg, iter);
1464 			break;
1465 		}
1466 	}
1467 }
1468 
1469 /**
1470  * folio_lruvec_lock - Lock the lruvec for a folio.
1471  * @folio: Pointer to the folio.
1472  *
1473  * These functions are safe to use under any of the following conditions:
1474  * - folio locked
1475  * - folio_test_lru false
1476  * - folio frozen (refcount of 0)
1477  *
1478  * Return: The lruvec this folio is on with its lock held and rcu read lock held.
1479  */
1480 struct lruvec *folio_lruvec_lock(const struct folio *folio)
1481 {
1482 	struct lruvec *lruvec;
1483 
1484 	rcu_read_lock();
1485 retry:
1486 	lruvec = folio_lruvec(folio);
1487 	spin_lock(&lruvec->lru_lock);
1488 	if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
1489 		spin_unlock(&lruvec->lru_lock);
1490 		goto retry;
1491 	}
1492 
1493 	return lruvec;
1494 }
1495 
1496 /**
1497  * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1498  * @folio: Pointer to the folio.
1499  *
1500  * These functions are safe to use under any of the following conditions:
1501  * - folio locked
1502  * - folio_test_lru false
1503  * - folio frozen (refcount of 0)
1504  *
1505  * Return: The lruvec this folio is on with its lock held and interrupts
1506  * disabled and rcu read lock held.
1507  */
1508 struct lruvec *folio_lruvec_lock_irq(const struct folio *folio)
1509 {
1510 	struct lruvec *lruvec;
1511 
1512 	rcu_read_lock();
1513 retry:
1514 	lruvec = folio_lruvec(folio);
1515 	spin_lock_irq(&lruvec->lru_lock);
1516 	if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
1517 		spin_unlock_irq(&lruvec->lru_lock);
1518 		goto retry;
1519 	}
1520 
1521 	return lruvec;
1522 }
1523 
1524 /**
1525  * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1526  * @folio: Pointer to the folio.
1527  * @flags: Pointer to irqsave flags.
1528  *
1529  * These functions are safe to use under any of the following conditions:
1530  * - folio locked
1531  * - folio_test_lru false
1532  * - folio frozen (refcount of 0)
1533  *
1534  * Return: The lruvec this folio is on with its lock held and interrupts
1535  * disabled and rcu read lock held.
1536  */
1537 struct lruvec *folio_lruvec_lock_irqsave(const struct folio *folio,
1538 		unsigned long *flags)
1539 {
1540 	struct lruvec *lruvec;
1541 
1542 	rcu_read_lock();
1543 retry:
1544 	lruvec = folio_lruvec(folio);
1545 	spin_lock_irqsave(&lruvec->lru_lock, *flags);
1546 	if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
1547 		spin_unlock_irqrestore(&lruvec->lru_lock, *flags);
1548 		goto retry;
1549 	}
1550 
1551 	return lruvec;
1552 }
1553 
1554 /**
1555  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1556  * @lruvec: mem_cgroup per zone lru vector
1557  * @lru: index of lru list the page is sitting on
1558  * @zid: zone id of the accounted pages
1559  * @nr_pages: positive when adding or negative when removing
1560  *
1561  * This function must be called under lru_lock, just before a page is added
1562  * to or just after a page is removed from an lru list.
1563  */
1564 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1565 				int zid, long nr_pages)
1566 {
1567 	struct mem_cgroup_per_node *mz;
1568 
1569 	if (mem_cgroup_disabled())
1570 		return;
1571 
1572 	mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1573 	mz->lru_zone_size[zid][lru] += nr_pages;
1574 }
1575 
1576 /**
1577  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1578  * @memcg: the memory cgroup
1579  *
1580  * Returns the maximum amount of memory @mem can be charged with, in
1581  * pages.
1582  */
1583 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1584 {
1585 	unsigned long margin = 0;
1586 	unsigned long count;
1587 	unsigned long limit;
1588 
1589 	count = page_counter_read(&memcg->memory);
1590 	limit = READ_ONCE(memcg->memory.max);
1591 	if (count < limit)
1592 		margin = limit - count;
1593 
1594 	if (do_memsw_account()) {
1595 		count = page_counter_read(&memcg->memsw);
1596 		limit = READ_ONCE(memcg->memsw.max);
1597 		if (count < limit)
1598 			margin = min(margin, limit - count);
1599 		else
1600 			margin = 0;
1601 	}
1602 
1603 	return margin;
1604 }
1605 
1606 struct memory_stat {
1607 	const char *name;
1608 	unsigned int idx;
1609 };
1610 
1611 static const struct memory_stat memory_stats[] = {
1612 	{ "anon",			NR_ANON_MAPPED			},
1613 	{ "file",			NR_FILE_PAGES			},
1614 	{ "kernel",			MEMCG_KMEM			},
1615 	{ "kernel_stack",		NR_KERNEL_STACK_KB		},
1616 	{ "pagetables",			NR_PAGETABLE			},
1617 	{ "sec_pagetables",		NR_SECONDARY_PAGETABLE		},
1618 	{ "percpu",			MEMCG_PERCPU_B			},
1619 	{ "sock",			MEMCG_SOCK			},
1620 	{ "vmalloc",			NR_VMALLOC			},
1621 	{ "shmem",			NR_SHMEM			},
1622 #ifdef CONFIG_ZSWAP
1623 	{ "zswap",			MEMCG_ZSWAP_B			},
1624 	{ "zswapped",			MEMCG_ZSWAPPED			},
1625 	{ "zswap_incomp",		MEMCG_ZSWAP_INCOMP		},
1626 #endif
1627 	{ "file_mapped",		NR_FILE_MAPPED			},
1628 	{ "file_dirty",			NR_FILE_DIRTY			},
1629 	{ "file_writeback",		NR_WRITEBACK			},
1630 #ifdef CONFIG_SWAP
1631 	{ "swapcached",			NR_SWAPCACHE			},
1632 #endif
1633 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1634 	{ "anon_thp",			NR_ANON_THPS			},
1635 	{ "file_thp",			NR_FILE_THPS			},
1636 	{ "shmem_thp",			NR_SHMEM_THPS			},
1637 #endif
1638 	{ "inactive_anon",		NR_INACTIVE_ANON		},
1639 	{ "active_anon",		NR_ACTIVE_ANON			},
1640 	{ "inactive_file",		NR_INACTIVE_FILE		},
1641 	{ "active_file",		NR_ACTIVE_FILE			},
1642 	{ "unevictable",		NR_UNEVICTABLE			},
1643 	{ "slab_reclaimable",		NR_SLAB_RECLAIMABLE_B		},
1644 	{ "slab_unreclaimable",		NR_SLAB_UNRECLAIMABLE_B		},
1645 #ifdef CONFIG_HUGETLB_PAGE
1646 	{ "hugetlb",			NR_HUGETLB			},
1647 #endif
1648 
1649 	/* The memory events */
1650 	{ "workingset_refault_anon",	WORKINGSET_REFAULT_ANON		},
1651 	{ "workingset_refault_file",	WORKINGSET_REFAULT_FILE		},
1652 	{ "workingset_activate_anon",	WORKINGSET_ACTIVATE_ANON	},
1653 	{ "workingset_activate_file",	WORKINGSET_ACTIVATE_FILE	},
1654 	{ "workingset_restore_anon",	WORKINGSET_RESTORE_ANON		},
1655 	{ "workingset_restore_file",	WORKINGSET_RESTORE_FILE		},
1656 	{ "workingset_nodereclaim",	WORKINGSET_NODERECLAIM		},
1657 
1658 	{ "pgdemote_kswapd",		PGDEMOTE_KSWAPD		},
1659 	{ "pgdemote_direct",		PGDEMOTE_DIRECT		},
1660 	{ "pgdemote_khugepaged",	PGDEMOTE_KHUGEPAGED	},
1661 	{ "pgdemote_proactive",		PGDEMOTE_PROACTIVE	},
1662 	{ "pgsteal_kswapd",		PGSTEAL_KSWAPD		},
1663 	{ "pgsteal_direct",		PGSTEAL_DIRECT		},
1664 	{ "pgsteal_khugepaged",		PGSTEAL_KHUGEPAGED	},
1665 	{ "pgsteal_proactive",		PGSTEAL_PROACTIVE	},
1666 	{ "pgscan_kswapd",		PGSCAN_KSWAPD		},
1667 	{ "pgscan_direct",		PGSCAN_DIRECT		},
1668 	{ "pgscan_khugepaged",		PGSCAN_KHUGEPAGED	},
1669 	{ "pgscan_proactive",		PGSCAN_PROACTIVE	},
1670 	{ "pgrefill",			PGREFILL		},
1671 #ifdef CONFIG_NUMA_BALANCING
1672 	{ "pgpromote_success",		PGPROMOTE_SUCCESS	},
1673 #endif
1674 };
1675 
1676 /* The actual unit of the state item, not the same as the output unit */
1677 static int memcg_page_state_unit(int item)
1678 {
1679 	switch (item) {
1680 	case MEMCG_PERCPU_B:
1681 	case MEMCG_ZSWAP_B:
1682 	case NR_SLAB_RECLAIMABLE_B:
1683 	case NR_SLAB_UNRECLAIMABLE_B:
1684 		return 1;
1685 	case NR_KERNEL_STACK_KB:
1686 		return SZ_1K;
1687 	default:
1688 		return PAGE_SIZE;
1689 	}
1690 }
1691 
1692 /* Translate stat items to the correct unit for memory.stat output */
1693 static int memcg_page_state_output_unit(int item)
1694 {
1695 	/*
1696 	 * Workingset state is actually in pages, but we export it to userspace
1697 	 * as a scalar count of events, so special case it here.
1698 	 *
1699 	 * Demotion and promotion activities are exported in pages, consistent
1700 	 * with their global counterparts.
1701 	 */
1702 	switch (item) {
1703 	case WORKINGSET_REFAULT_ANON:
1704 	case WORKINGSET_REFAULT_FILE:
1705 	case WORKINGSET_ACTIVATE_ANON:
1706 	case WORKINGSET_ACTIVATE_FILE:
1707 	case WORKINGSET_RESTORE_ANON:
1708 	case WORKINGSET_RESTORE_FILE:
1709 	case WORKINGSET_NODERECLAIM:
1710 	case PGDEMOTE_KSWAPD:
1711 	case PGDEMOTE_DIRECT:
1712 	case PGDEMOTE_KHUGEPAGED:
1713 	case PGDEMOTE_PROACTIVE:
1714 	case PGSTEAL_KSWAPD:
1715 	case PGSTEAL_DIRECT:
1716 	case PGSTEAL_KHUGEPAGED:
1717 	case PGSTEAL_PROACTIVE:
1718 	case PGSCAN_KSWAPD:
1719 	case PGSCAN_DIRECT:
1720 	case PGSCAN_KHUGEPAGED:
1721 	case PGSCAN_PROACTIVE:
1722 	case PGREFILL:
1723 #ifdef CONFIG_NUMA_BALANCING
1724 	case PGPROMOTE_SUCCESS:
1725 #endif
1726 		return 1;
1727 	default:
1728 		return memcg_page_state_unit(item);
1729 	}
1730 }
1731 
1732 unsigned long memcg_page_state_output(const struct mem_cgroup *memcg, int item)
1733 {
1734 	return memcg_page_state(memcg, item) *
1735 		memcg_page_state_output_unit(item);
1736 }
1737 
1738 #ifdef CONFIG_MEMCG_V1
1739 unsigned long memcg_page_state_local_output(const struct mem_cgroup *memcg, int item)
1740 {
1741 	return memcg_page_state_local(memcg, item) *
1742 		memcg_page_state_output_unit(item);
1743 }
1744 #endif
1745 
1746 #ifdef CONFIG_HUGETLB_PAGE
1747 static bool memcg_accounts_hugetlb(void)
1748 {
1749 	return cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
1750 }
1751 #else /* CONFIG_HUGETLB_PAGE */
1752 static bool memcg_accounts_hugetlb(void)
1753 {
1754 	return false;
1755 }
1756 #endif /* CONFIG_HUGETLB_PAGE */
1757 
1758 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1759 {
1760 	int i;
1761 
1762 	/*
1763 	 * Provide statistics on the state of the memory subsystem as
1764 	 * well as cumulative event counters that show past behavior.
1765 	 *
1766 	 * This list is ordered following a combination of these gradients:
1767 	 * 1) generic big picture -> specifics and details
1768 	 * 2) reflecting userspace activity -> reflecting kernel heuristics
1769 	 *
1770 	 * Current memory state:
1771 	 */
1772 	mem_cgroup_flush_stats(memcg);
1773 
1774 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1775 		u64 size;
1776 
1777 #ifdef CONFIG_HUGETLB_PAGE
1778 		if (unlikely(memory_stats[i].idx == NR_HUGETLB) &&
1779 			!memcg_accounts_hugetlb())
1780 			continue;
1781 #endif
1782 		size = memcg_page_state_output(memcg, memory_stats[i].idx);
1783 		seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1784 
1785 		if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1786 			size += memcg_page_state_output(memcg,
1787 							NR_SLAB_RECLAIMABLE_B);
1788 			seq_buf_printf(s, "slab %llu\n", size);
1789 		}
1790 	}
1791 
1792 	/* Accumulated memory events */
1793 	seq_buf_printf(s, "pgscan %lu\n",
1794 		       memcg_page_state(memcg, PGSCAN_KSWAPD) +
1795 		       memcg_page_state(memcg, PGSCAN_DIRECT) +
1796 		       memcg_page_state(memcg, PGSCAN_PROACTIVE) +
1797 		       memcg_page_state(memcg, PGSCAN_KHUGEPAGED));
1798 	seq_buf_printf(s, "pgsteal %lu\n",
1799 		       memcg_page_state(memcg, PGSTEAL_KSWAPD) +
1800 		       memcg_page_state(memcg, PGSTEAL_DIRECT) +
1801 		       memcg_page_state(memcg, PGSTEAL_PROACTIVE) +
1802 		       memcg_page_state(memcg, PGSTEAL_KHUGEPAGED));
1803 
1804 	for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1805 #ifdef CONFIG_MEMCG_V1
1806 		if (memcg_vm_event_stat[i] == PGPGIN ||
1807 		    memcg_vm_event_stat[i] == PGPGOUT)
1808 			continue;
1809 #endif
1810 		seq_buf_printf(s, "%s %lu\n",
1811 			       vm_event_name(memcg_vm_event_stat[i]),
1812 			       memcg_events(memcg, memcg_vm_event_stat[i]));
1813 	}
1814 }
1815 
1816 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1817 {
1818 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1819 		memcg_stat_format(memcg, s);
1820 	else
1821 		memcg1_stat_format(memcg, s);
1822 	if (seq_buf_has_overflowed(s))
1823 		pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__);
1824 }
1825 
1826 /**
1827  * mem_cgroup_print_oom_context: Print OOM information relevant to
1828  * memory controller.
1829  * @memcg: The memory cgroup that went over limit
1830  * @p: Task that is going to be killed
1831  *
1832  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1833  * enabled
1834  */
1835 void mem_cgroup_print_oom_context(const struct mem_cgroup *memcg,
1836 				  struct task_struct *p)
1837 {
1838 	rcu_read_lock();
1839 
1840 	if (memcg) {
1841 		pr_cont(",oom_memcg=");
1842 		pr_cont_cgroup_path(memcg->css.cgroup);
1843 	} else
1844 		pr_cont(",global_oom");
1845 	if (p) {
1846 		pr_cont(",task_memcg=");
1847 		pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1848 	}
1849 	rcu_read_unlock();
1850 }
1851 
1852 /**
1853  * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1854  * memory controller.
1855  * @memcg: The memory cgroup that went over limit
1856  */
1857 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1858 {
1859 	/* Use static buffer, for the caller is holding oom_lock. */
1860 	static char buf[SEQ_BUF_SIZE];
1861 	struct seq_buf s;
1862 	unsigned long memory_failcnt;
1863 
1864 	lockdep_assert_held(&oom_lock);
1865 
1866 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1867 		memory_failcnt = atomic_long_read(&memcg->memory_events[MEMCG_MAX]);
1868 	else
1869 		memory_failcnt = memcg->memory.failcnt;
1870 
1871 	pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1872 		K((u64)page_counter_read(&memcg->memory)),
1873 		K((u64)READ_ONCE(memcg->memory.max)), memory_failcnt);
1874 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1875 		pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1876 			K((u64)page_counter_read(&memcg->swap)),
1877 			K((u64)READ_ONCE(memcg->swap.max)),
1878 			atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
1879 #ifdef CONFIG_MEMCG_V1
1880 	else {
1881 		pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1882 			K((u64)page_counter_read(&memcg->memsw)),
1883 			K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1884 		pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1885 			K((u64)page_counter_read(&memcg->kmem)),
1886 			K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1887 	}
1888 #endif
1889 
1890 	pr_info("Memory cgroup stats for ");
1891 	pr_cont_cgroup_path(memcg->css.cgroup);
1892 	pr_cont(":");
1893 	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
1894 	memory_stat_format(memcg, &s);
1895 	seq_buf_do_printk(&s, KERN_INFO);
1896 }
1897 
1898 /*
1899  * Return the memory (and swap, if configured) limit for a memcg.
1900  */
1901 unsigned long mem_cgroup_get_max(const struct mem_cgroup *memcg)
1902 {
1903 	unsigned long max = READ_ONCE(memcg->memory.max);
1904 
1905 	if (do_memsw_account()) {
1906 		if (mem_cgroup_swappiness(memcg)) {
1907 			/* Calculate swap excess capacity from memsw limit */
1908 			unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1909 
1910 			max += min(swap, (unsigned long)total_swap_pages);
1911 		}
1912 	} else {
1913 		if (mem_cgroup_swappiness(memcg))
1914 			max += min(READ_ONCE(memcg->swap.max),
1915 				   (unsigned long)total_swap_pages);
1916 	}
1917 	return max;
1918 }
1919 
1920 void __memcg_memory_event(struct mem_cgroup *memcg,
1921 			  enum memcg_memory_event event, bool allow_spinning)
1922 {
1923 	bool swap_event = event == MEMCG_SWAP_HIGH || event == MEMCG_SWAP_MAX ||
1924 			  event == MEMCG_SWAP_FAIL;
1925 
1926 	/* For now only MEMCG_MAX can happen with !allow_spinning context. */
1927 	VM_WARN_ON_ONCE(!allow_spinning && event != MEMCG_MAX);
1928 
1929 	atomic_long_inc(&memcg->memory_events_local[event]);
1930 	if (!swap_event && allow_spinning)
1931 		cgroup_file_notify(&memcg->events_local_file);
1932 
1933 	do {
1934 		atomic_long_inc(&memcg->memory_events[event]);
1935 		if (allow_spinning) {
1936 			if (swap_event)
1937 				cgroup_file_notify(&memcg->swap_events_file);
1938 			else
1939 				cgroup_file_notify(&memcg->events_file);
1940 		}
1941 
1942 		if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1943 			break;
1944 		if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1945 			break;
1946 	} while ((memcg = parent_mem_cgroup(memcg)) &&
1947 		 !mem_cgroup_is_root(memcg));
1948 }
1949 EXPORT_SYMBOL_GPL(__memcg_memory_event);
1950 
1951 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1952 				     int order)
1953 {
1954 	struct oom_control oc = {
1955 		.zonelist = NULL,
1956 		.nodemask = NULL,
1957 		.memcg = memcg,
1958 		.gfp_mask = gfp_mask,
1959 		.order = order,
1960 	};
1961 	bool ret = true;
1962 
1963 	if (mutex_lock_killable(&oom_lock))
1964 		return true;
1965 
1966 	if (mem_cgroup_margin(memcg) >= (1 << order))
1967 		goto unlock;
1968 
1969 	/*
1970 	 * A few threads which were not waiting at mutex_lock_killable() can
1971 	 * fail to bail out. Therefore, check again after holding oom_lock.
1972 	 */
1973 	ret = out_of_memory(&oc);
1974 
1975 unlock:
1976 	mutex_unlock(&oom_lock);
1977 	return ret;
1978 }
1979 
1980 /*
1981  * Returns true if successfully killed one or more processes. Though in some
1982  * corner cases it can return true even without killing any process.
1983  */
1984 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1985 {
1986 	bool locked, ret;
1987 
1988 	if (order > PAGE_ALLOC_COSTLY_ORDER)
1989 		return false;
1990 
1991 	memcg_memory_event(memcg, MEMCG_OOM);
1992 
1993 	if (!memcg1_oom_prepare(memcg, &locked))
1994 		return false;
1995 
1996 	ret = mem_cgroup_out_of_memory(memcg, mask, order);
1997 
1998 	memcg1_oom_finish(memcg, locked);
1999 
2000 	return ret;
2001 }
2002 
2003 /**
2004  * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2005  * @victim: task to be killed by the OOM killer
2006  * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2007  *
2008  * Returns a pointer to a memory cgroup, which has to be cleaned up
2009  * by killing all belonging OOM-killable tasks.
2010  *
2011  * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2012  */
2013 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2014 					    struct mem_cgroup *oom_domain)
2015 {
2016 	struct mem_cgroup *oom_group = NULL;
2017 	struct mem_cgroup *memcg;
2018 
2019 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2020 		return NULL;
2021 
2022 	if (!oom_domain)
2023 		oom_domain = root_mem_cgroup;
2024 
2025 	rcu_read_lock();
2026 
2027 	memcg = mem_cgroup_from_task(victim);
2028 	if (mem_cgroup_is_root(memcg))
2029 		goto out;
2030 
2031 	/*
2032 	 * If the victim task has been asynchronously moved to a different
2033 	 * memory cgroup, we might end up killing tasks outside oom_domain.
2034 	 * In this case it's better to ignore memory.group.oom.
2035 	 */
2036 	if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2037 		goto out;
2038 
2039 	/*
2040 	 * Traverse the memory cgroup hierarchy from the victim task's
2041 	 * cgroup up to the OOMing cgroup (or root) to find the
2042 	 * highest-level memory cgroup with oom.group set.
2043 	 */
2044 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2045 		if (READ_ONCE(memcg->oom_group))
2046 			oom_group = memcg;
2047 
2048 		if (memcg == oom_domain)
2049 			break;
2050 	}
2051 
2052 	if (oom_group)
2053 		css_get(&oom_group->css);
2054 out:
2055 	rcu_read_unlock();
2056 
2057 	return oom_group;
2058 }
2059 
2060 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2061 {
2062 	pr_info("Tasks in ");
2063 	pr_cont_cgroup_path(memcg->css.cgroup);
2064 	pr_cont(" are going to be killed due to memory.oom.group set\n");
2065 }
2066 
2067 /*
2068  * The value of NR_MEMCG_STOCK is selected to keep the cached memcgs and their
2069  * nr_pages in a single cacheline. This may change in future.
2070  */
2071 #define NR_MEMCG_STOCK 7
2072 
2073 /*
2074  * Watermarks for a charge stock slot, in the spirit of pcp->high and
2075  * pcp->batch: MEMCG_STOCK_HIGH is the high watermark at which a slot is
2076  * trimmed, and it is trimmed down to MEMCG_STOCK_LOW rather than emptied.
2077  */
2078 #define MEMCG_STOCK_LOW		(MEMCG_CHARGE_BATCH / 2)
2079 #define MEMCG_STOCK_HIGH	(MEMCG_CHARGE_BATCH)
2080 
2081 #define FLUSHING_CACHED_CHARGE	0
2082 struct memcg_stock_pcp {
2083 	local_trylock_t lock;
2084 	uint8_t nr_pages[NR_MEMCG_STOCK];
2085 	struct mem_cgroup *cached[NR_MEMCG_STOCK];
2086 
2087 	struct work_struct work;
2088 	unsigned long flags;
2089 	uint8_t drain_idx;
2090 };
2091 
2092 static DEFINE_PER_CPU_ALIGNED(struct memcg_stock_pcp, memcg_stock) = {
2093 	.lock = INIT_LOCAL_TRYLOCK(lock),
2094 };
2095 
2096 /*
2097  * NR_OBJ_STOCK is sized so the entire hot path of obj_stock_pcp
2098  * (lock, accounting metadata, nr_bytes[] and cached[]) fits within a
2099  * single 64-byte cache line on non-debug 64-bit builds. With 5 slots:
2100  *   lock(1) + index(1) + node_id(2) + slab stats(4) + nr_bytes(10)
2101  *   + pad(6) + cached(40) == 64 bytes.
2102  * A CPU can thus consume/refill/account against five different objcgs
2103  * (typically per-node variants of the same memcg) while incurring at
2104  * most one cache miss on the stock.
2105  */
2106 #define NR_OBJ_STOCK 5
2107 struct obj_stock_pcp {
2108 	local_trylock_t lock;
2109 	int8_t index;
2110 	int16_t node_id;
2111 	int16_t nr_slab_reclaimable_b;
2112 	int16_t nr_slab_unreclaimable_b;
2113 #if PAGE_SHIFT > 16
2114 	/*
2115 	 * On rare archs with 256KiB base page size (hexagon and powerpc 44x)
2116 	 * keep nr_bytes to unsigned int as uint16_t cannot represent the full
2117 	 * sub-page remainder. Such archs are not cacheline optimization targets.
2118 	 */
2119 	unsigned int nr_bytes[NR_OBJ_STOCK];
2120 #else
2121 	uint16_t nr_bytes[NR_OBJ_STOCK];
2122 #endif
2123 	struct obj_cgroup *cached[NR_OBJ_STOCK];
2124 
2125 	struct work_struct work;
2126 	unsigned long flags;
2127 	uint8_t drain_idx;
2128 };
2129 
2130 static DEFINE_PER_CPU_ALIGNED(struct obj_stock_pcp, obj_stock) = {
2131 	.lock = INIT_LOCAL_TRYLOCK(lock),
2132 	.index = -1,
2133 	.node_id = NUMA_NO_NODE,
2134 };
2135 
2136 static DEFINE_MUTEX(percpu_charge_mutex);
2137 
2138 static void drain_obj_stock_slot(struct obj_stock_pcp *stock, int i);
2139 static void drain_obj_stock(struct obj_stock_pcp *stock);
2140 static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
2141 				     struct mem_cgroup *root_memcg);
2142 
2143 /**
2144  * consume_stock: Try to consume stocked charge on this cpu.
2145  * @memcg: memcg to consume from.
2146  * @nr_pages: how many pages to charge.
2147  *
2148  * Consume the cached charge if enough nr_pages are present otherwise return
2149  * failure. Also return failure for charge request larger than
2150  * MEMCG_CHARGE_BATCH or if the local lock is already taken.
2151  *
2152  * returns true if successful, false otherwise.
2153  */
2154 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2155 {
2156 	struct memcg_stock_pcp *stock;
2157 	uint8_t stock_pages;
2158 	bool ret = false;
2159 	int i;
2160 
2161 	if (nr_pages > MEMCG_CHARGE_BATCH ||
2162 	    !local_trylock(&memcg_stock.lock))
2163 		return ret;
2164 
2165 	stock = this_cpu_ptr(&memcg_stock);
2166 
2167 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2168 		if (memcg != READ_ONCE(stock->cached[i]))
2169 			continue;
2170 
2171 		stock_pages = READ_ONCE(stock->nr_pages[i]);
2172 		if (stock_pages >= nr_pages) {
2173 			stock_pages -= nr_pages;
2174 			WRITE_ONCE(stock->nr_pages[i], stock_pages);
2175 			if (!stock_pages) {
2176 				css_put(&memcg->css);
2177 				WRITE_ONCE(stock->cached[i], NULL);
2178 			}
2179 			ret = true;
2180 		}
2181 		break;
2182 	}
2183 
2184 	local_unlock(&memcg_stock.lock);
2185 
2186 	return ret;
2187 }
2188 
2189 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
2190 {
2191 	page_counter_uncharge(&memcg->memory, nr_pages);
2192 	if (do_memsw_account())
2193 		page_counter_uncharge(&memcg->memsw, nr_pages);
2194 }
2195 
2196 /*
2197  * Returns stocks cached in percpu and reset cached information.
2198  */
2199 static void drain_stock(struct memcg_stock_pcp *stock, int i)
2200 {
2201 	struct mem_cgroup *old = READ_ONCE(stock->cached[i]);
2202 	uint8_t stock_pages;
2203 
2204 	if (!old)
2205 		return;
2206 
2207 	stock_pages = READ_ONCE(stock->nr_pages[i]);
2208 	if (stock_pages) {
2209 		memcg_uncharge(old, stock_pages);
2210 		WRITE_ONCE(stock->nr_pages[i], 0);
2211 	}
2212 
2213 	css_put(&old->css);
2214 	WRITE_ONCE(stock->cached[i], NULL);
2215 }
2216 
2217 static void drain_stock_fully(struct memcg_stock_pcp *stock)
2218 {
2219 	int i;
2220 
2221 	for (i = 0; i < NR_MEMCG_STOCK; ++i)
2222 		drain_stock(stock, i);
2223 }
2224 
2225 static void drain_local_memcg_stock(struct work_struct *dummy)
2226 {
2227 	struct memcg_stock_pcp *stock;
2228 
2229 	if (WARN_ONCE(!in_task(), "drain in non-task context"))
2230 		return;
2231 
2232 	local_lock(&memcg_stock.lock);
2233 
2234 	stock = this_cpu_ptr(&memcg_stock);
2235 	drain_stock_fully(stock);
2236 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2237 
2238 	local_unlock(&memcg_stock.lock);
2239 }
2240 
2241 static void drain_local_obj_stock(struct work_struct *dummy)
2242 {
2243 	struct obj_stock_pcp *stock;
2244 
2245 	if (WARN_ONCE(!in_task(), "drain in non-task context"))
2246 		return;
2247 
2248 	local_lock(&obj_stock.lock);
2249 
2250 	stock = this_cpu_ptr(&obj_stock);
2251 	drain_obj_stock(stock);
2252 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2253 
2254 	local_unlock(&obj_stock.lock);
2255 }
2256 
2257 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2258 {
2259 	struct memcg_stock_pcp *stock;
2260 	struct mem_cgroup *cached;
2261 	unsigned int stock_pages;
2262 	bool success = false;
2263 	int empty_slot = -1;
2264 	int i;
2265 
2266 	/*
2267 	 * nr_pages[] is a uint8_t and a slot's count is capped at
2268 	 * MEMCG_STOCK_HIGH. Raising MEMCG_CHARGE_BATCH beyond 127 would need
2269 	 * more careful handling of nr_pages[] in struct memcg_stock_pcp.
2270 	 */
2271 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S8_MAX);
2272 	BUILD_BUG_ON(MEMCG_STOCK_HIGH > U8_MAX);
2273 
2274 	VM_WARN_ON_ONCE(mem_cgroup_is_root(memcg));
2275 
2276 	if (nr_pages > MEMCG_CHARGE_BATCH ||
2277 	    !local_trylock(&memcg_stock.lock)) {
2278 		/*
2279 		 * In case of larger than batch refill or unlikely failure to
2280 		 * lock the percpu memcg_stock.lock, uncharge memcg directly.
2281 		 */
2282 		memcg_uncharge(memcg, nr_pages);
2283 		return;
2284 	}
2285 
2286 	stock = this_cpu_ptr(&memcg_stock);
2287 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2288 		cached = READ_ONCE(stock->cached[i]);
2289 		if (!cached && empty_slot == -1)
2290 			empty_slot = i;
2291 		if (memcg == READ_ONCE(stock->cached[i])) {
2292 			stock_pages = READ_ONCE(stock->nr_pages[i]) + nr_pages;
2293 			if (stock_pages > MEMCG_STOCK_HIGH) {
2294 				memcg_uncharge(memcg,
2295 					       stock_pages - MEMCG_STOCK_LOW);
2296 				stock_pages = MEMCG_STOCK_LOW;
2297 			}
2298 			WRITE_ONCE(stock->nr_pages[i], stock_pages);
2299 			success = true;
2300 			break;
2301 		}
2302 	}
2303 
2304 	if (!success) {
2305 		i = empty_slot;
2306 		if (i == -1) {
2307 			i = stock->drain_idx++;
2308 			if (stock->drain_idx == NR_MEMCG_STOCK)
2309 				stock->drain_idx = 0;
2310 			drain_stock(stock, i);
2311 		}
2312 		css_get(&memcg->css);
2313 		WRITE_ONCE(stock->cached[i], memcg);
2314 		WRITE_ONCE(stock->nr_pages[i], nr_pages);
2315 	}
2316 
2317 	local_unlock(&memcg_stock.lock);
2318 }
2319 
2320 static bool is_memcg_drain_needed(struct memcg_stock_pcp *stock,
2321 				  struct mem_cgroup *root_memcg)
2322 {
2323 	struct mem_cgroup *memcg;
2324 	bool flush = false;
2325 	int i;
2326 
2327 	rcu_read_lock();
2328 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2329 		memcg = READ_ONCE(stock->cached[i]);
2330 		if (!memcg)
2331 			continue;
2332 
2333 		if (READ_ONCE(stock->nr_pages[i]) &&
2334 		    mem_cgroup_is_descendant(memcg, root_memcg)) {
2335 			flush = true;
2336 			break;
2337 		}
2338 	}
2339 	rcu_read_unlock();
2340 	return flush;
2341 }
2342 
2343 static bool schedule_drain_work(int cpu, struct work_struct *work)
2344 {
2345 	/*
2346 	 * Protect housekeeping cpumask read and work enqueue together
2347 	 * in the same RCU critical section so that later cpuset isolated
2348 	 * partition update only need to wait for an RCU GP and flush the
2349 	 * pending work on newly isolated CPUs.
2350 	 */
2351 	guard(rcu)();
2352 	if (cpu_is_isolated(cpu))
2353 		return false;
2354 
2355 	queue_work_on(cpu, memcg_wq, work);
2356 	return true;
2357 }
2358 
2359 /*
2360  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2361  * of the hierarchy under it.
2362  */
2363 void drain_all_stock(struct mem_cgroup *root_memcg)
2364 {
2365 	int cpu, curcpu;
2366 
2367 	/* If someone's already draining, avoid adding running more workers. */
2368 	if (!mutex_trylock(&percpu_charge_mutex))
2369 		return;
2370 	/*
2371 	 * Notify other cpus that system-wide "drain" is running
2372 	 * We do not care about races with the cpu hotplug because cpu down
2373 	 * as well as workers from this path always operate on the local
2374 	 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2375 	 */
2376 	migrate_disable();
2377 	curcpu = smp_processor_id();
2378 	for_each_online_cpu(cpu) {
2379 		struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu);
2380 		struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu);
2381 
2382 		if (!test_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags) &&
2383 		    is_memcg_drain_needed(memcg_st, root_memcg) &&
2384 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE,
2385 				      &memcg_st->flags)) {
2386 			if (cpu == curcpu)
2387 				drain_local_memcg_stock(&memcg_st->work);
2388 			else if (!schedule_drain_work(cpu, &memcg_st->work))
2389 				clear_bit(FLUSHING_CACHED_CHARGE,
2390 					  &memcg_st->flags);
2391 		}
2392 
2393 		if (!test_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags) &&
2394 		    obj_stock_flush_required(obj_st, root_memcg) &&
2395 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE,
2396 				      &obj_st->flags)) {
2397 			if (cpu == curcpu)
2398 				drain_local_obj_stock(&obj_st->work);
2399 			else if (!schedule_drain_work(cpu, &obj_st->work))
2400 				clear_bit(FLUSHING_CACHED_CHARGE,
2401 					  &obj_st->flags);
2402 		}
2403 	}
2404 	migrate_enable();
2405 	mutex_unlock(&percpu_charge_mutex);
2406 }
2407 
2408 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2409 {
2410 	struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu);
2411 	struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu);
2412 
2413 	/* no need for the local lock */
2414 	drain_obj_stock(obj_st);
2415 	drain_stock_fully(memcg_st);
2416 
2417 	/*
2418 	 * A drain work queued before the CPU went away is executed by an
2419 	 * unbound worker on some other CPU and clears that CPU's flag, so
2420 	 * clear the flags here to make these stocks drainable again once
2421 	 * the CPU comes back online.
2422 	 */
2423 	clear_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags);
2424 	clear_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags);
2425 
2426 	return 0;
2427 }
2428 
2429 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2430 				  unsigned int nr_pages,
2431 				  gfp_t gfp_mask)
2432 {
2433 	unsigned long nr_reclaimed = 0;
2434 
2435 	do {
2436 		unsigned long pflags;
2437 
2438 		if (page_counter_read(&memcg->memory) <=
2439 		    READ_ONCE(memcg->memory.high))
2440 			continue;
2441 
2442 		memcg_memory_event(memcg, MEMCG_HIGH);
2443 
2444 		psi_memstall_enter(&pflags);
2445 		nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2446 							gfp_mask,
2447 							MEMCG_RECLAIM_MAY_SWAP,
2448 							NULL);
2449 		psi_memstall_leave(&pflags);
2450 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2451 		 !mem_cgroup_is_root(memcg));
2452 
2453 	return nr_reclaimed;
2454 }
2455 
2456 static void high_work_func(struct work_struct *work)
2457 {
2458 	struct mem_cgroup *memcg;
2459 
2460 	memcg = container_of(work, struct mem_cgroup, high_work);
2461 	reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2462 }
2463 
2464 static void high_irq_work_func(struct irq_work *work)
2465 {
2466 	schedule_work(&container_of(work, struct mem_cgroup, high_irq_work)->high_work);
2467 }
2468 
2469 /*
2470  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2471  * enough to still cause a significant slowdown in most cases, while still
2472  * allowing diagnostics and tracing to proceed without becoming stuck.
2473  */
2474 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2475 
2476 /*
2477  * When calculating the delay, we use these either side of the exponentiation to
2478  * maintain precision and scale to a reasonable number of jiffies (see the table
2479  * below.
2480  *
2481  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2482  *   overage ratio to a delay.
2483  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2484  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2485  *   to produce a reasonable delay curve.
2486  *
2487  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2488  * reasonable delay curve compared to precision-adjusted overage, not
2489  * penalising heavily at first, but still making sure that growth beyond the
2490  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2491  * example, with a high of 100 megabytes:
2492  *
2493  *  +-------+------------------------+
2494  *  | usage | time to allocate in ms |
2495  *  +-------+------------------------+
2496  *  | 100M  |                      0 |
2497  *  | 101M  |                      6 |
2498  *  | 102M  |                     25 |
2499  *  | 103M  |                     57 |
2500  *  | 104M  |                    102 |
2501  *  | 105M  |                    159 |
2502  *  | 106M  |                    230 |
2503  *  | 107M  |                    313 |
2504  *  | 108M  |                    409 |
2505  *  | 109M  |                    518 |
2506  *  | 110M  |                    639 |
2507  *  | 111M  |                    774 |
2508  *  | 112M  |                    921 |
2509  *  | 113M  |                   1081 |
2510  *  | 114M  |                   1254 |
2511  *  | 115M  |                   1439 |
2512  *  | 116M  |                   1638 |
2513  *  | 117M  |                   1849 |
2514  *  | 118M  |                   2000 |
2515  *  | 119M  |                   2000 |
2516  *  | 120M  |                   2000 |
2517  *  +-------+------------------------+
2518  */
2519  #define MEMCG_DELAY_PRECISION_SHIFT 20
2520  #define MEMCG_DELAY_SCALING_SHIFT 14
2521 
2522 static u64 calculate_overage(unsigned long usage, unsigned long high)
2523 {
2524 	u64 overage;
2525 
2526 	if (usage <= high)
2527 		return 0;
2528 
2529 	/*
2530 	 * Prevent division by 0 in overage calculation by acting as if
2531 	 * it was a threshold of 1 page
2532 	 */
2533 	high = max(high, 1UL);
2534 
2535 	overage = usage - high;
2536 	overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2537 	return div64_u64(overage, high);
2538 }
2539 
2540 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2541 {
2542 	u64 overage, max_overage = 0;
2543 
2544 	do {
2545 		overage = calculate_overage(page_counter_read(&memcg->memory),
2546 					    READ_ONCE(memcg->memory.high));
2547 		max_overage = max(overage, max_overage);
2548 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2549 		 !mem_cgroup_is_root(memcg));
2550 
2551 	return max_overage;
2552 }
2553 
2554 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2555 {
2556 	u64 overage, max_overage = 0;
2557 
2558 	do {
2559 		overage = calculate_overage(page_counter_read(&memcg->swap),
2560 					    READ_ONCE(memcg->swap.high));
2561 		if (overage)
2562 			memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2563 		max_overage = max(overage, max_overage);
2564 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2565 		 !mem_cgroup_is_root(memcg));
2566 
2567 	return max_overage;
2568 }
2569 
2570 /*
2571  * Get the number of jiffies that we should penalise a mischievous cgroup which
2572  * is exceeding its memory.high by checking both it and its ancestors.
2573  */
2574 static unsigned long calculate_high_delay(unsigned int nr_pages,
2575 					  u64 max_overage)
2576 {
2577 	unsigned long penalty_jiffies;
2578 
2579 	if (!max_overage)
2580 		return 0;
2581 
2582 	/*
2583 	 * We use overage compared to memory.high to calculate the number of
2584 	 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2585 	 * fairly lenient on small overages, and increasingly harsh when the
2586 	 * memcg in question makes it clear that it has no intention of stopping
2587 	 * its crazy behaviour, so we exponentially increase the delay based on
2588 	 * overage amount.
2589 	 */
2590 	penalty_jiffies = max_overage * max_overage * HZ;
2591 	penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2592 	penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2593 
2594 	/*
2595 	 * Factor in the task's own contribution to the overage, such that four
2596 	 * N-sized allocations are throttled approximately the same as one
2597 	 * 4N-sized allocation.
2598 	 *
2599 	 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2600 	 * larger the current charge patch is than that.
2601 	 */
2602 	return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2603 }
2604 
2605 /*
2606  * Reclaims memory over the high limit. Called directly from
2607  * try_charge() (context permitting), as well as from the userland
2608  * return path where reclaim is always able to block.
2609  */
2610 void __mem_cgroup_handle_over_high(gfp_t gfp_mask)
2611 {
2612 	unsigned long penalty_jiffies;
2613 	unsigned long pflags;
2614 	unsigned long nr_reclaimed;
2615 	unsigned int nr_pages = current->memcg_nr_pages_over_high;
2616 	int nr_retries = MAX_RECLAIM_RETRIES;
2617 	struct mem_cgroup *memcg;
2618 	bool in_retry = false;
2619 
2620 	memcg = get_mem_cgroup_from_mm(current->mm);
2621 	current->memcg_nr_pages_over_high = 0;
2622 
2623 retry_reclaim:
2624 	/*
2625 	 * Bail if the task is already exiting. Unlike memory.max,
2626 	 * memory.high enforcement isn't as strict, and there is no
2627 	 * OOM killer involved, which means the excess could already
2628 	 * be much bigger (and still growing) than it could for
2629 	 * memory.max; the dying task could get stuck in fruitless
2630 	 * reclaim for a long time, which isn't desirable.
2631 	 */
2632 	if (task_is_dying())
2633 		goto out;
2634 
2635 	/*
2636 	 * The allocating task should reclaim at least the batch size, but for
2637 	 * subsequent retries we only want to do what's necessary to prevent oom
2638 	 * or breaching resource isolation.
2639 	 *
2640 	 * This is distinct from memory.max or page allocator behaviour because
2641 	 * memory.high is currently batched, whereas memory.max and the page
2642 	 * allocator run every time an allocation is made.
2643 	 */
2644 	nr_reclaimed = reclaim_high(memcg,
2645 				    in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2646 				    gfp_mask);
2647 
2648 	/*
2649 	 * memory.high is breached and reclaim is unable to keep up. Throttle
2650 	 * allocators proactively to slow down excessive growth.
2651 	 */
2652 	penalty_jiffies = calculate_high_delay(nr_pages,
2653 					       mem_find_max_overage(memcg));
2654 
2655 	penalty_jiffies += calculate_high_delay(nr_pages,
2656 						swap_find_max_overage(memcg));
2657 
2658 	/*
2659 	 * Clamp the max delay per usermode return so as to still keep the
2660 	 * application moving forwards and also permit diagnostics, albeit
2661 	 * extremely slowly.
2662 	 */
2663 	penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2664 
2665 	/*
2666 	 * Don't sleep if the amount of jiffies this memcg owes us is so low
2667 	 * that it's not even worth doing, in an attempt to be nice to those who
2668 	 * go only a small amount over their memory.high value and maybe haven't
2669 	 * been aggressively reclaimed enough yet.
2670 	 */
2671 	if (penalty_jiffies <= HZ / 100)
2672 		goto out;
2673 
2674 	/*
2675 	 * If reclaim is making forward progress but we're still over
2676 	 * memory.high, we want to encourage that rather than doing allocator
2677 	 * throttling.
2678 	 */
2679 	if (nr_reclaimed || nr_retries--) {
2680 		in_retry = true;
2681 		goto retry_reclaim;
2682 	}
2683 
2684 	/*
2685 	 * Reclaim didn't manage to push usage below the limit, slow
2686 	 * this allocating task down.
2687 	 *
2688 	 * If we exit early, we're guaranteed to die (since
2689 	 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2690 	 * need to account for any ill-begotten jiffies to pay them off later.
2691 	 */
2692 	psi_memstall_enter(&pflags);
2693 	schedule_timeout_killable(penalty_jiffies);
2694 	psi_memstall_leave(&pflags);
2695 
2696 out:
2697 	css_put(&memcg->css);
2698 }
2699 
2700 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2701 			    unsigned int nr_pages)
2702 {
2703 	unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2704 	int nr_retries = MAX_RECLAIM_RETRIES;
2705 	struct mem_cgroup *mem_over_limit;
2706 	struct page_counter *counter;
2707 	unsigned long nr_reclaimed;
2708 	bool passed_oom = false;
2709 	unsigned int reclaim_options;
2710 	bool drained = false;
2711 	bool raised_max_event = false;
2712 	unsigned long pflags;
2713 	bool allow_spinning = gfpflags_allow_spinning(gfp_mask);
2714 	int ret = 0;
2715 
2716 retry:
2717 	if (consume_stock(memcg, nr_pages))
2718 		return ret;
2719 
2720 	if (!allow_spinning)
2721 		/* Avoid the refill and flush of the older stock */
2722 		batch = nr_pages;
2723 
2724 	reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2725 	if (!do_memsw_account() ||
2726 	    page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2727 		if (page_counter_try_charge(&memcg->memory, batch, &counter))
2728 			goto done_restock;
2729 		if (do_memsw_account())
2730 			page_counter_uncharge(&memcg->memsw, batch);
2731 		mem_over_limit = mem_cgroup_from_counter(counter, memory);
2732 	} else {
2733 		mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2734 		reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2735 	}
2736 
2737 	if (batch > nr_pages) {
2738 		batch = nr_pages;
2739 		goto retry;
2740 	}
2741 
2742 	/*
2743 	 * Prevent unbounded recursion when reclaim operations need to
2744 	 * allocate memory. This might exceed the limits temporarily,
2745 	 * but we prefer facilitating memory reclaim and getting back
2746 	 * under the limit over triggering OOM kills in these cases.
2747 	 */
2748 	if (unlikely(current->flags & PF_MEMALLOC))
2749 		goto force;
2750 
2751 	if (unlikely(task_in_memcg_oom(current)))
2752 		goto nomem;
2753 
2754 	if (!gfpflags_allow_blocking(gfp_mask))
2755 		goto nomem;
2756 
2757 	/*
2758 	 * OOM victim still needs to charge memory to exit. OOM reaper should
2759 	 * help but it might fail on mmap_lock contention. If the victim is a
2760 	 * large thread group then all exiting threads might compete on oom_lock
2761 	 * just to learn that there is nothing really killable anymore. Bail
2762 	 * out early and fail the charge to expedite their exit. They are
2763 	 * considered fully reclaimed by the oom reaper and they shouldn't
2764 	 * contribute further charges.
2765 	 */
2766 	if (tsk_is_oom_victim(current) &&
2767 	    mm_flags_test(MMF_OOM_SKIP, current->signal->oom_mm))
2768 		goto nomem;
2769 
2770 	__memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
2771 	raised_max_event = true;
2772 
2773 	psi_memstall_enter(&pflags);
2774 	nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2775 						    gfp_mask, reclaim_options, NULL);
2776 	psi_memstall_leave(&pflags);
2777 
2778 	if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2779 		goto retry;
2780 
2781 	if (!drained) {
2782 		drain_all_stock(mem_over_limit);
2783 		drained = true;
2784 		goto retry;
2785 	}
2786 
2787 	if (gfp_mask & __GFP_NORETRY)
2788 		goto nomem;
2789 	/*
2790 	 * Even though the limit is exceeded at this point, reclaim
2791 	 * may have been able to free some pages.  Retry the charge
2792 	 * before killing the task.
2793 	 *
2794 	 * Only for regular pages, though: huge pages are rather
2795 	 * unlikely to succeed so close to the limit, and we fall back
2796 	 * to regular pages anyway in case of failure.
2797 	 */
2798 	if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2799 		goto retry;
2800 
2801 	if (nr_retries--)
2802 		goto retry;
2803 
2804 	if (gfp_mask & __GFP_RETRY_MAYFAIL)
2805 		goto nomem;
2806 
2807 	/* Avoid endless loop for tasks bypassed by the oom killer */
2808 	if (passed_oom && task_is_dying())
2809 		goto nomem;
2810 
2811 	/*
2812 	 * keep retrying as long as the memcg oom killer is able to make
2813 	 * a forward progress or bypass the charge if the oom killer
2814 	 * couldn't make any progress.
2815 	 */
2816 	if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2817 			   get_order(nr_pages * PAGE_SIZE))) {
2818 		passed_oom = true;
2819 		nr_retries = MAX_RECLAIM_RETRIES;
2820 		goto retry;
2821 	}
2822 nomem:
2823 	/*
2824 	 * Memcg doesn't have a dedicated reserve for atomic
2825 	 * allocations. But like the global atomic pool, we need to
2826 	 * put the burden of reclaim on regular allocation requests
2827 	 * and let these go through as privileged allocations.
2828 	 */
2829 	if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH))) {
2830 		ret = -ENOMEM;
2831 		goto out;
2832 	}
2833 force:
2834 	/*
2835 	 * The allocation either can't fail or will lead to more memory
2836 	 * being freed very soon.  Allow memory usage go over the limit
2837 	 * temporarily by force charging it.
2838 	 */
2839 	page_counter_charge(&memcg->memory, nr_pages);
2840 	if (do_memsw_account())
2841 		page_counter_charge(&memcg->memsw, nr_pages);
2842 
2843 out:
2844 	/*
2845 	 * Don't forget to raise a MEMCG_MAX event for forced or rejected
2846 	 * requests.
2847 	 */
2848 	if (!raised_max_event)
2849 		__memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
2850 
2851 	return ret;
2852 
2853 done_restock:
2854 	if (batch > nr_pages)
2855 		refill_stock(memcg, batch - nr_pages);
2856 
2857 	/*
2858 	 * If the hierarchy is above the normal consumption range, schedule
2859 	 * reclaim on returning to userland.  We can perform reclaim here
2860 	 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2861 	 * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2862 	 * not recorded as it most likely matches current's and won't
2863 	 * change in the meantime.  As high limit is checked again before
2864 	 * reclaim, the cost of mismatch is negligible.
2865 	 */
2866 	do {
2867 		bool mem_high, swap_high;
2868 
2869 		mem_high = page_counter_read(&memcg->memory) >
2870 			READ_ONCE(memcg->memory.high);
2871 		swap_high = page_counter_read(&memcg->swap) >
2872 			READ_ONCE(memcg->swap.high);
2873 
2874 		/* Don't bother a random interrupted task */
2875 		if (!in_task()) {
2876 			if (mem_high) {
2877 				if (allow_spinning)
2878 					schedule_work(&memcg->high_work);
2879 				else
2880 					irq_work_queue(&memcg->high_irq_work);
2881 				break;
2882 			}
2883 			continue;
2884 		}
2885 
2886 		if (mem_high || swap_high) {
2887 			/*
2888 			 * The allocating tasks in this cgroup will need to do
2889 			 * reclaim or be throttled to prevent further growth
2890 			 * of the memory or swap footprints.
2891 			 *
2892 			 * Target some best-effort fairness between the tasks,
2893 			 * and distribute reclaim work and delay penalties
2894 			 * based on how much each task is actually allocating.
2895 			 */
2896 			current->memcg_nr_pages_over_high += batch;
2897 			set_notify_resume(current);
2898 			break;
2899 		}
2900 	} while ((memcg = parent_mem_cgroup(memcg)));
2901 
2902 	/*
2903 	 * Reclaim is set up above to be called from the userland
2904 	 * return path. But also attempt synchronous reclaim to avoid
2905 	 * excessive overrun while the task is still inside the
2906 	 * kernel. If this is successful, the return path will see it
2907 	 * when it rechecks the overage and simply bail out.
2908 	 */
2909 	if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2910 	    !(current->flags & PF_MEMALLOC) &&
2911 	    gfpflags_allow_blocking(gfp_mask))
2912 		__mem_cgroup_handle_over_high(gfp_mask);
2913 	return ret;
2914 }
2915 
2916 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2917 			     unsigned int nr_pages)
2918 {
2919 	if (mem_cgroup_is_root(memcg))
2920 		return 0;
2921 
2922 	return try_charge_memcg(memcg, gfp_mask, nr_pages);
2923 }
2924 
2925 static void commit_charge(struct folio *folio, struct obj_cgroup *objcg)
2926 {
2927 	VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
2928 	/*
2929 	 * Any of the following ensures folio's objcg stability:
2930 	 *
2931 	 * - the page lock
2932 	 * - LRU isolation
2933 	 * - exclusive reference
2934 	 */
2935 	folio->memcg_data = (unsigned long)objcg;
2936 }
2937 
2938 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
2939 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2940 					 struct pglist_data *pgdat,
2941 					 enum node_stat_item idx, int nr)
2942 {
2943 	struct lruvec *lruvec;
2944 
2945 	if (likely(!in_nmi())) {
2946 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
2947 		mod_memcg_lruvec_state(lruvec, idx, nr);
2948 	} else {
2949 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id];
2950 
2951 		/* preemption is disabled in_nmi(). */
2952 		__css_rstat_updated(&memcg->css, smp_processor_id());
2953 		if (idx == NR_SLAB_RECLAIMABLE_B)
2954 			atomic_add(nr, &pn->slab_reclaimable);
2955 		else
2956 			atomic_add(nr, &pn->slab_unreclaimable);
2957 	}
2958 }
2959 #else
2960 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2961 					 struct pglist_data *pgdat,
2962 					 enum node_stat_item idx, int nr)
2963 {
2964 	struct lruvec *lruvec;
2965 
2966 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
2967 	mod_memcg_lruvec_state(lruvec, idx, nr);
2968 }
2969 #endif
2970 
2971 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2972 				       struct pglist_data *pgdat,
2973 				       enum node_stat_item idx, int nr)
2974 {
2975 	struct mem_cgroup *memcg;
2976 
2977 	rcu_read_lock();
2978 	memcg = obj_cgroup_memcg(objcg);
2979 	account_slab_nmi_safe(memcg, pgdat, idx, nr);
2980 	rcu_read_unlock();
2981 }
2982 
2983 static __always_inline
2984 struct mem_cgroup *mem_cgroup_from_obj_slab(struct slab *slab, void *p)
2985 {
2986 	/*
2987 	 * Slab objects are accounted individually, not per-page.
2988 	 * Memcg membership data for each individual object is saved in
2989 	 * slab->obj_exts.
2990 	 */
2991 	unsigned long obj_exts;
2992 	struct slabobj_ext *obj_ext;
2993 	struct obj_cgroup *objcg;
2994 
2995 	obj_exts = slab_obj_exts(slab);
2996 	if (!obj_exts)
2997 		return NULL;
2998 
2999 	if (!slab_needs_objcg(slab))
3000 		return NULL;
3001 
3002 	get_slab_obj_exts(obj_exts);
3003 	obj_ext = slab_obj_ext(slab->slab_cache, slab, obj_exts, p);
3004 	objcg = slab_obj_ext_objcg(slab, obj_ext);
3005 	if (objcg) {
3006 		put_slab_obj_exts(obj_exts);
3007 		return obj_cgroup_memcg(objcg);
3008 	}
3009 	put_slab_obj_exts(obj_exts);
3010 
3011 	return NULL;
3012 }
3013 
3014 /*
3015  * Returns a pointer to the memory cgroup to which the kernel object is charged.
3016  * It is not suitable for objects allocated using vmalloc().
3017  *
3018  * A passed kernel object must be a slab object or a generic kernel page.
3019  *
3020  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
3021  * cgroup_mutex, etc.
3022  */
3023 struct mem_cgroup *mem_cgroup_from_virt(void *p)
3024 {
3025 	struct slab *slab;
3026 
3027 	if (mem_cgroup_disabled())
3028 		return NULL;
3029 
3030 	slab = virt_to_slab(p);
3031 	if (slab)
3032 		return mem_cgroup_from_obj_slab(slab, p);
3033 	return folio_memcg_check(virt_to_folio(p));
3034 }
3035 
3036 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg,
3037 						      int nid)
3038 {
3039 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
3040 		struct obj_cgroup *objcg = rcu_dereference(memcg->nodeinfo[nid]->objcg);
3041 
3042 		if (likely(objcg && obj_cgroup_tryget(objcg)))
3043 			return objcg;
3044 	}
3045 
3046 	return NULL;
3047 }
3048 
3049 static inline struct obj_cgroup *get_obj_cgroup_from_memcg(struct mem_cgroup *memcg,
3050 							   int nid)
3051 {
3052 	struct obj_cgroup *objcg;
3053 
3054 	rcu_read_lock();
3055 	objcg = __get_obj_cgroup_from_memcg(memcg, nid);
3056 	rcu_read_unlock();
3057 
3058 	return objcg;
3059 }
3060 
3061 static struct obj_cgroup *current_objcg_update(void)
3062 {
3063 	struct mem_cgroup *memcg;
3064 	struct obj_cgroup *old, *objcg = NULL;
3065 
3066 	do {
3067 		/* Atomically drop the update bit. */
3068 		old = xchg(&current->objcg, NULL);
3069 		if (old) {
3070 			old = (struct obj_cgroup *)
3071 				((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
3072 			obj_cgroup_put(old);
3073 
3074 			old = NULL;
3075 		}
3076 
3077 		/* If new objcg is NULL, no reason for the second atomic update. */
3078 		if (!current->mm || (current->flags & PF_KTHREAD))
3079 			return NULL;
3080 
3081 		/*
3082 		 * Release the objcg pointer from the previous iteration,
3083 		 * if try_cmpxcg() below fails.
3084 		 */
3085 		if (unlikely(objcg)) {
3086 			obj_cgroup_put(objcg);
3087 			objcg = NULL;
3088 		}
3089 
3090 		/*
3091 		 * Obtain the new objcg pointer. The current task can be
3092 		 * asynchronously moved to another memcg and the previous
3093 		 * memcg can be offlined. So let's get the memcg pointer
3094 		 * and try get a reference to objcg under a rcu read lock.
3095 		 */
3096 
3097 		rcu_read_lock();
3098 		memcg = mem_cgroup_from_task(current);
3099 		objcg = __get_obj_cgroup_from_memcg(memcg, numa_node_id());
3100 		rcu_read_unlock();
3101 
3102 		/*
3103 		 * Try set up a new objcg pointer atomically. If it
3104 		 * fails, it means the update flag was set concurrently, so
3105 		 * the whole procedure should be repeated.
3106 		 */
3107 	} while (!try_cmpxchg(&current->objcg, &old, objcg));
3108 
3109 	return objcg;
3110 }
3111 
3112 __always_inline struct obj_cgroup *current_obj_cgroup(void)
3113 {
3114 	struct mem_cgroup *memcg;
3115 	struct obj_cgroup *objcg;
3116 	int nid = numa_node_id();
3117 
3118 	if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi())
3119 		return NULL;
3120 
3121 	if (in_task()) {
3122 		memcg = current->active_memcg;
3123 		if (unlikely(memcg))
3124 			goto from_memcg;
3125 
3126 		objcg = READ_ONCE(current->objcg);
3127 		if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
3128 			objcg = current_objcg_update();
3129 		/*
3130 		 * Objcg reference is kept by the task, so it's safe
3131 		 * to use the objcg by the current task.
3132 		 */
3133 		return objcg ? : rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
3134 	}
3135 
3136 	memcg = this_cpu_read(int_active_memcg);
3137 	if (unlikely(memcg))
3138 		goto from_memcg;
3139 
3140 	return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
3141 
3142 from_memcg:
3143 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
3144 		/*
3145 		 * Memcg pointer is protected by scope (see set_active_memcg())
3146 		 * and is pinning the corresponding objcg, so objcg can't go
3147 		 * away and can be used within the scope without any additional
3148 		 * protection.
3149 		 */
3150 		objcg = rcu_dereference_check(memcg->nodeinfo[nid]->objcg, 1);
3151 		if (likely(objcg))
3152 			return objcg;
3153 	}
3154 
3155 	return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
3156 }
3157 
3158 struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio)
3159 {
3160 	struct obj_cgroup *objcg;
3161 
3162 	objcg = folio_objcg(folio);
3163 	if (objcg)
3164 		obj_cgroup_get(objcg);
3165 
3166 	return objcg;
3167 }
3168 
3169 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
3170 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
3171 {
3172 	if (likely(!in_nmi())) {
3173 		mod_memcg_state(memcg, MEMCG_KMEM, val);
3174 	} else {
3175 		/* preemption is disabled in_nmi(). */
3176 		__css_rstat_updated(&memcg->css, smp_processor_id());
3177 		atomic_add(val, &memcg->kmem_stat);
3178 	}
3179 }
3180 #else
3181 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
3182 {
3183 	mod_memcg_state(memcg, MEMCG_KMEM, val);
3184 }
3185 #endif
3186 
3187 /*
3188  * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3189  * @objcg: object cgroup to uncharge
3190  * @nr_pages: number of pages to uncharge
3191  */
3192 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3193 				      unsigned int nr_pages)
3194 {
3195 	struct mem_cgroup *memcg;
3196 
3197 	memcg = get_mem_cgroup_from_objcg(objcg);
3198 
3199 	account_kmem_nmi_safe(memcg, -nr_pages);
3200 	memcg1_account_kmem(memcg, -nr_pages);
3201 	if (!mem_cgroup_is_root(memcg))
3202 		refill_stock(memcg, nr_pages);
3203 
3204 	css_put(&memcg->css);
3205 }
3206 
3207 /*
3208  * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3209  * @objcg: object cgroup to charge
3210  * @gfp: reclaim mode
3211  * @nr_pages: number of pages to charge
3212  *
3213  * Returns 0 on success, an error code on failure.
3214  */
3215 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3216 				   unsigned int nr_pages)
3217 {
3218 	struct mem_cgroup *memcg;
3219 	int ret;
3220 
3221 	memcg = get_mem_cgroup_from_objcg(objcg);
3222 
3223 	ret = try_charge(memcg, gfp, nr_pages);
3224 	if (ret)
3225 		goto out;
3226 
3227 	account_kmem_nmi_safe(memcg, nr_pages);
3228 	memcg1_account_kmem(memcg, nr_pages);
3229 out:
3230 	css_put(&memcg->css);
3231 
3232 	return ret;
3233 }
3234 
3235 static struct obj_cgroup *page_objcg(const struct page *page)
3236 {
3237 	unsigned long memcg_data = page->memcg_data;
3238 
3239 	if (mem_cgroup_disabled() || !memcg_data)
3240 		return NULL;
3241 
3242 	VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM,
3243 			page);
3244 	return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM);
3245 }
3246 
3247 static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg)
3248 {
3249 	page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM;
3250 }
3251 
3252 /**
3253  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3254  * @page: page to charge
3255  * @gfp: reclaim mode
3256  * @order: allocation order
3257  *
3258  * Returns 0 on success, an error code on failure.
3259  */
3260 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3261 {
3262 	struct obj_cgroup *objcg;
3263 	int ret = 0;
3264 
3265 	objcg = current_obj_cgroup();
3266 	if (objcg && !obj_cgroup_is_root(objcg)) {
3267 		ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3268 		if (!ret) {
3269 			obj_cgroup_get(objcg);
3270 			page_set_objcg(page, objcg);
3271 			return 0;
3272 		}
3273 	}
3274 	return ret;
3275 }
3276 
3277 /**
3278  * __memcg_kmem_uncharge_page: uncharge a kmem page
3279  * @page: page to uncharge
3280  * @order: allocation order
3281  */
3282 void __memcg_kmem_uncharge_page(struct page *page, int order)
3283 {
3284 	struct obj_cgroup *objcg = page_objcg(page);
3285 	unsigned int nr_pages = 1 << order;
3286 
3287 	if (!objcg)
3288 		return;
3289 
3290 	obj_cgroup_uncharge_pages(objcg, nr_pages);
3291 	page->memcg_data = 0;
3292 	obj_cgroup_put(objcg);
3293 }
3294 
3295 static struct obj_stock_pcp *trylock_stock(void)
3296 {
3297 	if (local_trylock(&obj_stock.lock))
3298 		return this_cpu_ptr(&obj_stock);
3299 
3300 	return NULL;
3301 }
3302 
3303 static void unlock_stock(struct obj_stock_pcp *stock)
3304 {
3305 	if (stock)
3306 		local_unlock(&obj_stock.lock);
3307 }
3308 
3309 /* Call after __refill_obj_stock() so a slot for objcg exists in the stock */
3310 static void __account_obj_stock(struct obj_cgroup *objcg,
3311 				struct obj_stock_pcp *stock, int nr,
3312 				struct pglist_data *pgdat, enum node_stat_item idx)
3313 {
3314 	int16_t *bytes;
3315 	int i;
3316 
3317 	/*
3318 	 * Though at the moment MAX_NUMNODES <= 1024 in all archs but let's make
3319 	 * sure it does not exceed S16_MAX otherwise we need to fix node_id type
3320 	 * in struct obj_stock_pcp.
3321 	 */
3322 	BUILD_BUG_ON(MAX_NUMNODES >= S16_MAX);
3323 
3324 	if (!stock)
3325 		goto direct;
3326 
3327 	for (i = 0; i < NR_OBJ_STOCK; ++i) {
3328 		if (READ_ONCE(stock->cached[i]) == objcg)
3329 			break;
3330 	}
3331 	if (i == NR_OBJ_STOCK)
3332 		goto direct;
3333 
3334 	/*
3335 	 * Save vmstat data in stock and skip vmstat array update unless
3336 	 * accumulating over a page of vmstat data or when the objcg slot or
3337 	 * pgdat the stats belong to changes.
3338 	 */
3339 	if (stock->index < 0) {
3340 		stock->index = i;
3341 		stock->node_id = pgdat->node_id;
3342 	} else if (stock->index != i || stock->node_id != pgdat->node_id) {
3343 		struct obj_cgroup *old = READ_ONCE(stock->cached[stock->index]);
3344 		struct pglist_data *oldpg = NODE_DATA(stock->node_id);
3345 
3346 		if (stock->nr_slab_reclaimable_b) {
3347 			mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B,
3348 					  stock->nr_slab_reclaimable_b);
3349 			stock->nr_slab_reclaimable_b = 0;
3350 		}
3351 		if (stock->nr_slab_unreclaimable_b) {
3352 			mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3353 					  stock->nr_slab_unreclaimable_b);
3354 			stock->nr_slab_unreclaimable_b = 0;
3355 		}
3356 		stock->index = i;
3357 		stock->node_id = pgdat->node_id;
3358 	}
3359 
3360 	bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3361 					       : &stock->nr_slab_unreclaimable_b;
3362 
3363 	/*
3364 	 * Fold @nr into the cached value and decide whether to keep it cached
3365 	 * or flush it directly. Cache the combined value when it fits in the
3366 	 * int16_t storage and either the cache was empty (so even a value
3367 	 * above PAGE_SIZE gets a chance to be canceled by a paired delta) or
3368 	 * the combined value is within the PAGE_SIZE flush threshold.
3369 	 */
3370 	nr += *bytes;
3371 	if (abs(nr) <= S16_MAX && (!*bytes || abs(nr) <= PAGE_SIZE)) {
3372 		*bytes = nr;
3373 		nr = 0;
3374 	} else {
3375 		*bytes = 0;
3376 	}
3377 direct:
3378 	if (nr)
3379 		mod_objcg_mlstate(objcg, pgdat, idx, nr);
3380 }
3381 
3382 static bool __consume_obj_stock(struct obj_cgroup *objcg,
3383 				struct obj_stock_pcp *stock,
3384 				unsigned int nr_bytes)
3385 {
3386 	int i;
3387 
3388 	for (i = 0; i < NR_OBJ_STOCK; ++i) {
3389 		if (READ_ONCE(stock->cached[i]) != objcg)
3390 			continue;
3391 		if (stock->nr_bytes[i] >= nr_bytes) {
3392 			stock->nr_bytes[i] -= nr_bytes;
3393 			return true;
3394 		}
3395 		return false;
3396 	}
3397 
3398 	return false;
3399 }
3400 
3401 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3402 {
3403 	struct obj_stock_pcp *stock;
3404 	bool ret = false;
3405 
3406 	stock = trylock_stock();
3407 	if (!stock)
3408 		return ret;
3409 
3410 	ret = __consume_obj_stock(objcg, stock, nr_bytes);
3411 	unlock_stock(stock);
3412 
3413 	return ret;
3414 }
3415 
3416 /* Flush the cached slab stats (if any) back to their owning objcg/pgdat. */
3417 static void drain_obj_stock_stats(struct obj_stock_pcp *stock)
3418 {
3419 	struct obj_cgroup *old;
3420 	struct pglist_data *oldpg;
3421 
3422 	if (stock->index < 0)
3423 		return;
3424 
3425 	old = READ_ONCE(stock->cached[stock->index]);
3426 	oldpg = NODE_DATA(stock->node_id);
3427 
3428 	if (stock->nr_slab_reclaimable_b) {
3429 		mod_objcg_mlstate(old, oldpg, NR_SLAB_RECLAIMABLE_B,
3430 				  stock->nr_slab_reclaimable_b);
3431 		stock->nr_slab_reclaimable_b = 0;
3432 	}
3433 	if (stock->nr_slab_unreclaimable_b) {
3434 		mod_objcg_mlstate(old, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3435 				  stock->nr_slab_unreclaimable_b);
3436 		stock->nr_slab_unreclaimable_b = 0;
3437 	}
3438 	stock->index = -1;
3439 	stock->node_id = NUMA_NO_NODE;
3440 }
3441 
3442 static void drain_obj_stock_slot(struct obj_stock_pcp *stock, int i)
3443 {
3444 	struct obj_cgroup *old = READ_ONCE(stock->cached[i]);
3445 
3446 	if (!old)
3447 		return;
3448 
3449 	if (stock->nr_bytes[i]) {
3450 		unsigned int nr_pages = stock->nr_bytes[i] >> PAGE_SHIFT;
3451 		unsigned int nr_bytes = stock->nr_bytes[i] & (PAGE_SIZE - 1);
3452 
3453 		if (nr_pages) {
3454 			struct mem_cgroup *memcg;
3455 
3456 			memcg = get_mem_cgroup_from_objcg(old);
3457 
3458 			memcg_uncharge_kmem(memcg, nr_pages);
3459 
3460 			css_put(&memcg->css);
3461 		}
3462 
3463 		/*
3464 		 * The leftover is flushed to the centralized per-memcg value.
3465 		 * On the next attempt to refill obj stock it will be moved
3466 		 * to a per-cpu stock (probably, on an other CPU), see
3467 		 * refill_obj_stock().
3468 		 *
3469 		 * How often it's flushed is a trade-off between the memory
3470 		 * limit enforcement accuracy and potential CPU contention,
3471 		 * so it might be changed in the future.
3472 		 */
3473 		atomic_add(nr_bytes, &old->nr_charged_bytes);
3474 		stock->nr_bytes[i] = 0;
3475 	}
3476 
3477 	/* Flush vmstat data when its owning slot is being drained. */
3478 	if (stock->index == i)
3479 		drain_obj_stock_stats(stock);
3480 
3481 	WRITE_ONCE(stock->cached[i], NULL);
3482 	obj_cgroup_put(old);
3483 }
3484 
3485 static void drain_obj_stock(struct obj_stock_pcp *stock)
3486 {
3487 	int i;
3488 
3489 	for (i = 0; i < NR_OBJ_STOCK; ++i)
3490 		drain_obj_stock_slot(stock, i);
3491 }
3492 
3493 static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
3494 				     struct mem_cgroup *root_memcg)
3495 {
3496 	struct obj_cgroup *objcg;
3497 	struct mem_cgroup *memcg;
3498 	bool flush = false;
3499 	int i;
3500 
3501 	rcu_read_lock();
3502 	for (i = 0; i < NR_OBJ_STOCK; ++i) {
3503 		objcg = READ_ONCE(stock->cached[i]);
3504 		if (!objcg)
3505 			continue;
3506 		memcg = obj_cgroup_memcg(objcg);
3507 		if (memcg && mem_cgroup_is_descendant(memcg, root_memcg)) {
3508 			flush = true;
3509 			break;
3510 		}
3511 	}
3512 	rcu_read_unlock();
3513 
3514 	return flush;
3515 }
3516 
3517 static void __refill_obj_stock(struct obj_cgroup *objcg,
3518 			       struct obj_stock_pcp *stock,
3519 			       unsigned int nr_bytes,
3520 			       bool allow_uncharge)
3521 {
3522 	unsigned int nr_pages = 0;
3523 	unsigned int stock_nr_bytes;
3524 	int i, slot = -1, empty_slot = -1;
3525 
3526 	if (!stock) {
3527 		nr_pages = nr_bytes >> PAGE_SHIFT;
3528 		nr_bytes = nr_bytes & (PAGE_SIZE - 1);
3529 		atomic_add(nr_bytes, &objcg->nr_charged_bytes);
3530 		goto out;
3531 	}
3532 
3533 	for (i = 0; i < NR_OBJ_STOCK; ++i) {
3534 		struct obj_cgroup *cached = READ_ONCE(stock->cached[i]);
3535 
3536 		if (!cached) {
3537 			if (empty_slot == -1)
3538 				empty_slot = i;
3539 			continue;
3540 		}
3541 		if (cached == objcg) {
3542 			slot = i;
3543 			break;
3544 		}
3545 	}
3546 
3547 	if (slot == -1) {
3548 		slot = empty_slot;
3549 		if (slot == -1) {
3550 			slot = stock->drain_idx++;
3551 			if (stock->drain_idx == NR_OBJ_STOCK)
3552 				stock->drain_idx = 0;
3553 			drain_obj_stock_slot(stock, slot);
3554 		}
3555 		obj_cgroup_get(objcg);
3556 		/*
3557 		 * Keep the xchg result in the unsigned int local; storing
3558 		 * it directly into stock->nr_bytes[slot] (uint16_t) would
3559 		 * silently truncate values >= U16_MAX and bypass the flush
3560 		 * guard below, leaking page-counter charges.
3561 		 */
3562 		stock_nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3563 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3564 		WRITE_ONCE(stock->cached[slot], objcg);
3565 
3566 		allow_uncharge = true;	/* Allow uncharge when objcg changes */
3567 	} else {
3568 		stock_nr_bytes = stock->nr_bytes[slot];
3569 	}
3570 
3571 	stock_nr_bytes += nr_bytes;
3572 
3573 	if ((allow_uncharge && (stock_nr_bytes > PAGE_SIZE)) ||
3574 	    stock_nr_bytes > U16_MAX) {
3575 		nr_pages = stock_nr_bytes >> PAGE_SHIFT;
3576 		stock_nr_bytes &= (PAGE_SIZE - 1);
3577 	}
3578 	stock->nr_bytes[slot] = stock_nr_bytes;
3579 
3580 out:
3581 	if (nr_pages)
3582 		obj_cgroup_uncharge_pages(objcg, nr_pages);
3583 }
3584 
3585 static void refill_obj_stock(struct obj_cgroup *objcg,
3586 			     unsigned int nr_bytes,
3587 			     bool allow_uncharge)
3588 {
3589 	struct obj_stock_pcp *stock = trylock_stock();
3590 	__refill_obj_stock(objcg, stock, nr_bytes, allow_uncharge);
3591 	unlock_stock(stock);
3592 }
3593 
3594 static int __obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp,
3595 			       size_t size, size_t *remainder)
3596 {
3597 	size_t charge_size;
3598 	int ret;
3599 
3600 	charge_size = PAGE_ALIGN(size);
3601 	ret = obj_cgroup_charge_pages(objcg, gfp, charge_size >> PAGE_SHIFT);
3602 	if (!ret)
3603 		*remainder = charge_size - size;
3604 
3605 	return ret;
3606 }
3607 
3608 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3609 {
3610 	size_t remainder;
3611 	int ret;
3612 
3613 	if (likely(consume_obj_stock(objcg, size)))
3614 		return 0;
3615 
3616 	/*
3617 	 * In theory, objcg->nr_charged_bytes can have enough
3618 	 * pre-charged bytes to satisfy the allocation. However,
3619 	 * flushing objcg->nr_charged_bytes requires two atomic
3620 	 * operations, and objcg->nr_charged_bytes can't be big.
3621 	 * The shared objcg->nr_charged_bytes can also become a
3622 	 * performance bottleneck if all tasks of the same memcg are
3623 	 * trying to update it. So it's better to ignore it and try
3624 	 * grab some new pages. The stock's nr_bytes will be flushed to
3625 	 * objcg->nr_charged_bytes later on when objcg changes.
3626 	 *
3627 	 * The stock's nr_bytes may contain enough pre-charged bytes
3628 	 * to allow one less page from being charged, but we can't rely
3629 	 * on the pre-charged bytes not being changed outside of
3630 	 * consume_obj_stock() or refill_obj_stock(). So ignore those
3631 	 * pre-charged bytes as well when charging pages. To avoid a
3632 	 * page uncharge right after a page charge, we set the
3633 	 * allow_uncharge flag to false when calling refill_obj_stock()
3634 	 * to temporarily allow the pre-charged bytes to exceed the page
3635 	 * size limit. The maximum reachable value of the pre-charged
3636 	 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3637 	 * race.
3638 	 */
3639 	ret = __obj_cgroup_charge(objcg, gfp, size, &remainder);
3640 	if (!ret && remainder)
3641 		refill_obj_stock(objcg, remainder, false);
3642 
3643 	return ret;
3644 }
3645 
3646 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3647 {
3648 	refill_obj_stock(objcg, size, true);
3649 }
3650 
3651 static inline size_t obj_full_size(struct kmem_cache *s)
3652 {
3653 	/*
3654 	 * For each accounted object there is an extra space which is used
3655 	 * to store obj_cgroup membership. Charge it too.
3656 	 */
3657 	return s->size + sizeof(struct obj_cgroup *);
3658 }
3659 
3660 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3661 				  gfp_t flags, unsigned int slab_alloc_flags,
3662 				  size_t size, void **p)
3663 {
3664 	size_t obj_size = obj_full_size(s);
3665 	struct obj_cgroup *objcg;
3666 	struct slab *slab;
3667 	size_t i;
3668 
3669 	/*
3670 	 * The obtained objcg pointer is safe to use within the current scope,
3671 	 * defined by current task or set_active_memcg() pair.
3672 	 * obj_cgroup_get() is used to get a permanent reference.
3673 	 */
3674 	objcg = current_obj_cgroup();
3675 	if (!objcg || obj_cgroup_is_root(objcg))
3676 		return true;
3677 
3678 	/*
3679 	 * slab_alloc_node() avoids the NULL check, so we might be called with a
3680 	 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3681 	 * the whole requested size.
3682 	 * return success as there's nothing to free back
3683 	 */
3684 	if (unlikely(*p == NULL))
3685 		return true;
3686 
3687 	flags &= gfp_allowed_mask;
3688 
3689 	if (lru) {
3690 		int ret;
3691 		struct mem_cgroup *memcg;
3692 
3693 		memcg = get_mem_cgroup_from_objcg(objcg);
3694 		ret = memcg_list_lru_alloc(memcg, lru, flags);
3695 		css_put(&memcg->css);
3696 
3697 		if (ret)
3698 			return false;
3699 	}
3700 
3701 	for (i = 0; i < size; i++) {
3702 		unsigned long obj_exts;
3703 		struct slabobj_ext *obj_ext;
3704 		struct obj_stock_pcp *stock;
3705 
3706 		slab = virt_to_slab(p[i]);
3707 
3708 		if (!slab_obj_exts(slab)) {
3709 			if (is_kfence_address(p[i]))
3710 				continue;
3711 			if (alloc_slab_obj_exts(slab, s, flags, slab_alloc_flags))
3712 				continue;
3713 		}
3714 
3715 		/*
3716 		 * if we fail and size is 1, memcg_alloc_abort_single() will
3717 		 * just free the object, which is ok as we have not assigned
3718 		 * objcg to its obj_ext yet
3719 		 *
3720 		 * for larger sizes, kmem_cache_free_bulk() will uncharge
3721 		 * any objects that were already charged and obj_ext assigned
3722 		 *
3723 		 * TODO: we could batch this until slab_pgdat(slab) changes
3724 		 * between iterations, with a more complicated undo
3725 		 */
3726 		stock = trylock_stock();
3727 		if (!stock || !__consume_obj_stock(objcg, stock, obj_size)) {
3728 			size_t remainder;
3729 
3730 			unlock_stock(stock);
3731 			if (__obj_cgroup_charge(objcg, flags, obj_size, &remainder))
3732 				return false;
3733 			stock = trylock_stock();
3734 			if (remainder)
3735 				__refill_obj_stock(objcg, stock, remainder, false);
3736 		}
3737 		__account_obj_stock(objcg, stock, obj_size,
3738 				    slab_pgdat(slab), cache_vmstat_idx(s));
3739 		unlock_stock(stock);
3740 
3741 		obj_exts = slab_obj_exts(slab);
3742 		get_slab_obj_exts(obj_exts);
3743 		obj_ext = slab_obj_ext(s, slab, obj_exts, p[i]);
3744 
3745 		obj_cgroup_get(objcg);
3746 		slab_obj_ext_set_objcg(slab, obj_ext, objcg);
3747 
3748 		put_slab_obj_exts(obj_exts);
3749 	}
3750 
3751 	return true;
3752 }
3753 
3754 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3755 			    void **p, int objects, unsigned long obj_exts)
3756 {
3757 	size_t obj_size = obj_full_size(s);
3758 
3759 	for (int i = 0; i < objects; i++) {
3760 		struct obj_cgroup *objcg;
3761 		struct slabobj_ext *obj_ext;
3762 		struct obj_stock_pcp *stock;
3763 
3764 		obj_ext = slab_obj_ext(s, slab, obj_exts, p[i]);
3765 		objcg = slab_obj_ext_objcg(slab, obj_ext);
3766 		if (!objcg)
3767 			continue;
3768 
3769 		slab_obj_ext_set_objcg(slab, obj_ext, NULL);
3770 
3771 		stock = trylock_stock();
3772 		__refill_obj_stock(objcg, stock, obj_size, true);
3773 		__account_obj_stock(objcg, stock, -obj_size,
3774 				    slab_pgdat(slab), cache_vmstat_idx(s));
3775 		unlock_stock(stock);
3776 
3777 		obj_cgroup_put(objcg);
3778 	}
3779 }
3780 
3781 /*
3782  * The objcg is only set on the first page, so transfer it to all the
3783  * other pages.
3784  */
3785 void split_page_memcg(struct page *page, unsigned order)
3786 {
3787 	struct obj_cgroup *objcg = page_objcg(page);
3788 	unsigned int i, nr = 1 << order;
3789 
3790 	if (!objcg)
3791 		return;
3792 
3793 	for (i = 1; i < nr; i++)
3794 		page_set_objcg(&page[i], objcg);
3795 
3796 	obj_cgroup_get_many(objcg, nr - 1);
3797 }
3798 
3799 void folio_split_memcg_refs(struct folio *folio, unsigned old_order,
3800 		unsigned new_order)
3801 {
3802 	unsigned new_refs;
3803 
3804 	if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
3805 		return;
3806 
3807 	new_refs = (1 << (old_order - new_order)) - 1;
3808 	obj_cgroup_get_many(folio_objcg(folio), new_refs);
3809 }
3810 
3811 static void memcg_online_kmem(struct mem_cgroup *memcg)
3812 {
3813 	if (mem_cgroup_kmem_disabled())
3814 		return;
3815 
3816 	if (unlikely(mem_cgroup_is_root(memcg)))
3817 		return;
3818 
3819 	static_branch_enable(&memcg_kmem_online_key);
3820 
3821 	memcg->kmemcg_id = memcg->private_id;
3822 }
3823 
3824 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3825 {
3826 	struct mem_cgroup *parent;
3827 
3828 	if (mem_cgroup_kmem_disabled())
3829 		return;
3830 
3831 	if (unlikely(mem_cgroup_is_root(memcg)))
3832 		return;
3833 
3834 	parent = parent_mem_cgroup(memcg);
3835 	memcg_reparent_list_lrus(memcg, parent);
3836 }
3837 
3838 #ifdef CONFIG_CGROUP_WRITEBACK
3839 
3840 #include <trace/events/writeback.h>
3841 
3842 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3843 {
3844 	return wb_domain_init(&memcg->cgwb_domain, gfp);
3845 }
3846 
3847 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3848 {
3849 	wb_domain_exit(&memcg->cgwb_domain);
3850 }
3851 
3852 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3853 {
3854 	wb_domain_size_changed(&memcg->cgwb_domain);
3855 }
3856 
3857 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3858 {
3859 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3860 
3861 	if (!memcg->css.parent)
3862 		return NULL;
3863 
3864 	return &memcg->cgwb_domain;
3865 }
3866 
3867 /**
3868  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3869  * @wb: bdi_writeback in question
3870  * @pfilepages: out parameter for number of file pages
3871  * @pheadroom: out parameter for number of allocatable pages according to memcg
3872  * @pdirty: out parameter for number of dirty pages
3873  * @pwriteback: out parameter for number of pages under writeback
3874  *
3875  * Determine the numbers of file, headroom, dirty, and writeback pages in
3876  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
3877  * is a bit more involved.
3878  *
3879  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
3880  * headroom is calculated as the lowest headroom of itself and the
3881  * ancestors.  Note that this doesn't consider the actual amount of
3882  * available memory in the system.  The caller should further cap
3883  * *@pheadroom accordingly.
3884  */
3885 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3886 			 unsigned long *pheadroom, unsigned long *pdirty,
3887 			 unsigned long *pwriteback)
3888 {
3889 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3890 	struct mem_cgroup *parent;
3891 
3892 	mem_cgroup_flush_stats_ratelimited(memcg);
3893 
3894 	*pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
3895 	*pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
3896 	*pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
3897 			memcg_page_state(memcg, NR_ACTIVE_FILE);
3898 
3899 	*pheadroom = PAGE_COUNTER_MAX;
3900 	while ((parent = parent_mem_cgroup(memcg))) {
3901 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
3902 					    READ_ONCE(memcg->memory.high));
3903 		unsigned long used = page_counter_read(&memcg->memory);
3904 
3905 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
3906 		memcg = parent;
3907 	}
3908 }
3909 
3910 /*
3911  * Foreign dirty flushing
3912  *
3913  * There's an inherent mismatch between memcg and writeback.  The former
3914  * tracks ownership per-page while the latter per-inode.  This was a
3915  * deliberate design decision because honoring per-page ownership in the
3916  * writeback path is complicated, may lead to higher CPU and IO overheads
3917  * and deemed unnecessary given that write-sharing an inode across
3918  * different cgroups isn't a common use-case.
3919  *
3920  * Combined with inode majority-writer ownership switching, this works well
3921  * enough in most cases but there are some pathological cases.  For
3922  * example, let's say there are two cgroups A and B which keep writing to
3923  * different but confined parts of the same inode.  B owns the inode and
3924  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
3925  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
3926  * triggering background writeback.  A will be slowed down without a way to
3927  * make writeback of the dirty pages happen.
3928  *
3929  * Conditions like the above can lead to a cgroup getting repeatedly and
3930  * severely throttled after making some progress after each
3931  * dirty_expire_interval while the underlying IO device is almost
3932  * completely idle.
3933  *
3934  * Solving this problem completely requires matching the ownership tracking
3935  * granularities between memcg and writeback in either direction.  However,
3936  * the more egregious behaviors can be avoided by simply remembering the
3937  * most recent foreign dirtying events and initiating remote flushes on
3938  * them when local writeback isn't enough to keep the memory clean enough.
3939  *
3940  * The following two functions implement such mechanism.  When a foreign
3941  * page - a page whose memcg and writeback ownerships don't match - is
3942  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
3943  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
3944  * decides that the memcg needs to sleep due to high dirty ratio, it calls
3945  * mem_cgroup_flush_foreign() which queues writeback on the recorded
3946  * foreign bdi_writebacks which haven't expired.  Both the numbers of
3947  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
3948  * limited to MEMCG_CGWB_FRN_CNT.
3949  *
3950  * The mechanism only remembers IDs and doesn't hold any object references.
3951  * As being wrong occasionally doesn't matter, updates and accesses to the
3952  * records are lockless and racy.
3953  */
3954 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
3955 					     struct bdi_writeback *wb)
3956 {
3957 	struct mem_cgroup *memcg = folio_memcg(folio);
3958 	struct memcg_cgwb_frn *frn;
3959 	u64 now = get_jiffies_64();
3960 	u64 oldest_at = now;
3961 	int oldest = -1;
3962 	int i;
3963 
3964 	trace_track_foreign_dirty(folio, wb);
3965 
3966 	/*
3967 	 * Pick the slot to use.  If there is already a slot for @wb, keep
3968 	 * using it.  If not replace the oldest one which isn't being
3969 	 * written out.
3970 	 */
3971 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3972 		frn = &memcg->cgwb_frn[i];
3973 		if (frn->bdi_id == wb->bdi->id &&
3974 		    frn->memcg_id == wb->memcg_css->id)
3975 			break;
3976 		if (time_before64(frn->at, oldest_at) &&
3977 		    atomic_read(&frn->done.cnt) == 1) {
3978 			oldest = i;
3979 			oldest_at = frn->at;
3980 		}
3981 	}
3982 
3983 	if (i < MEMCG_CGWB_FRN_CNT) {
3984 		/*
3985 		 * Re-using an existing one.  Update timestamp lazily to
3986 		 * avoid making the cacheline hot.  We want them to be
3987 		 * reasonably up-to-date and significantly shorter than
3988 		 * dirty_expire_interval as that's what expires the record.
3989 		 * Use the shorter of 1s and dirty_expire_interval / 8.
3990 		 */
3991 		unsigned long update_intv =
3992 			min_t(unsigned long, HZ,
3993 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
3994 
3995 		if (time_before64(frn->at, now - update_intv))
3996 			frn->at = now;
3997 	} else if (oldest >= 0) {
3998 		/* replace the oldest free one */
3999 		frn = &memcg->cgwb_frn[oldest];
4000 		frn->bdi_id = wb->bdi->id;
4001 		frn->memcg_id = wb->memcg_css->id;
4002 		frn->at = now;
4003 	}
4004 }
4005 
4006 /* issue foreign writeback flushes for recorded foreign dirtying events */
4007 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4008 {
4009 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4010 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4011 	u64 now = get_jiffies_64();
4012 	int i;
4013 
4014 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4015 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4016 
4017 		/*
4018 		 * If the record is older than dirty_expire_interval,
4019 		 * writeback on it has already started.  No need to kick it
4020 		 * off again.  Also, don't start a new one if there's
4021 		 * already one in flight.
4022 		 */
4023 		if (time_after64(frn->at, now - intv) &&
4024 		    atomic_read(&frn->done.cnt) == 1) {
4025 			frn->at = 0;
4026 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4027 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
4028 					       WB_REASON_FOREIGN_FLUSH,
4029 					       &frn->done);
4030 		}
4031 	}
4032 }
4033 
4034 #else	/* CONFIG_CGROUP_WRITEBACK */
4035 
4036 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4037 {
4038 	return 0;
4039 }
4040 
4041 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4042 {
4043 }
4044 
4045 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4046 {
4047 }
4048 
4049 #endif	/* CONFIG_CGROUP_WRITEBACK */
4050 
4051 /*
4052  * Private memory cgroup IDR
4053  *
4054  * Swap-out records and page cache shadow entries need to store memcg
4055  * references in constrained space, so we maintain an ID space that is
4056  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4057  * memory-controlled cgroups to 64k.
4058  *
4059  * However, there usually are many references to the offline CSS after
4060  * the cgroup has been destroyed, such as page cache or reclaimable
4061  * slab objects, that don't need to hang on to the ID. We want to keep
4062  * those dead CSS from occupying IDs, or we might quickly exhaust the
4063  * relatively small ID space and prevent the creation of new cgroups
4064  * even when there are much fewer than 64k cgroups - possibly none.
4065  *
4066  * Maintain a private 16-bit ID space for memcg, and allow the ID to
4067  * be freed and recycled when it's no longer needed, which is usually
4068  * when the CSS is offlined.
4069  *
4070  * The only exception to that are records of swapped out tmpfs/shmem
4071  * pages that need to be attributed to live ancestors on swapin. But
4072  * those references are manageable from userspace.
4073  */
4074 
4075 #define MEM_CGROUP_ID_MAX	((1UL << MEM_CGROUP_ID_SHIFT) - 1)
4076 static DEFINE_XARRAY_ALLOC1(mem_cgroup_private_ids);
4077 
4078 static void mem_cgroup_private_id_remove(struct mem_cgroup *memcg)
4079 {
4080 	if (memcg->private_id > 0) {
4081 		xa_erase(&mem_cgroup_private_ids, memcg->private_id);
4082 		memcg->private_id = 0;
4083 	}
4084 }
4085 
4086 static inline void mem_cgroup_private_id_put(struct mem_cgroup *memcg, unsigned int n)
4087 {
4088 	if (refcount_sub_and_test(n, &memcg->private_id_ref)) {
4089 		mem_cgroup_private_id_remove(memcg);
4090 
4091 		/* Memcg ID pins CSS */
4092 		css_put(&memcg->css);
4093 	}
4094 }
4095 
4096 struct mem_cgroup *mem_cgroup_private_id_get_online(struct mem_cgroup *memcg, unsigned int n)
4097 {
4098 	while (!refcount_add_not_zero(n, &memcg->private_id_ref)) {
4099 		/*
4100 		 * The root cgroup cannot be destroyed, so it's refcount must
4101 		 * always be >= 1.
4102 		 */
4103 		if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
4104 			VM_BUG_ON(1);
4105 			break;
4106 		}
4107 		memcg = parent_mem_cgroup(memcg);
4108 	}
4109 	return memcg;
4110 }
4111 
4112 /**
4113  * mem_cgroup_from_private_id - look up a memcg from a memcg id
4114  * @id: the memcg id to look up
4115  *
4116  * Caller must hold rcu_read_lock().
4117  */
4118 struct mem_cgroup *mem_cgroup_from_private_id(unsigned short id)
4119 {
4120 	WARN_ON_ONCE(!rcu_read_lock_held());
4121 	return xa_load(&mem_cgroup_private_ids, id);
4122 }
4123 
4124 struct mem_cgroup *mem_cgroup_get_from_id(u64 id)
4125 {
4126 	struct cgroup *cgrp;
4127 	struct cgroup_subsys_state *css;
4128 	struct mem_cgroup *memcg = NULL;
4129 
4130 	cgrp = cgroup_get_from_id(id);
4131 	if (IS_ERR(cgrp))
4132 		return NULL;
4133 
4134 	css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
4135 	if (css)
4136 		memcg = container_of(css, struct mem_cgroup, css);
4137 
4138 	cgroup_put(cgrp);
4139 
4140 	return memcg;
4141 }
4142 
4143 static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn)
4144 {
4145 	if (!pn)
4146 		return;
4147 
4148 	free_percpu(pn->lruvec_stats_percpu);
4149 	kfree(pn->lruvec_stats);
4150 	kfree(pn);
4151 }
4152 
4153 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
4154 {
4155 	struct mem_cgroup_per_node *pn;
4156 
4157 	pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
4158 				   node);
4159 	if (!pn)
4160 		return false;
4161 
4162 	pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
4163 					GFP_KERNEL_ACCOUNT, node);
4164 	if (!pn->lruvec_stats)
4165 		goto fail;
4166 
4167 	pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
4168 						   GFP_KERNEL_ACCOUNT);
4169 	if (!pn->lruvec_stats_percpu)
4170 		goto fail;
4171 
4172 	INIT_LIST_HEAD(&pn->objcg_list);
4173 
4174 	lruvec_init(&pn->lruvec);
4175 	pn->memcg = memcg;
4176 
4177 	memcg->nodeinfo[node] = pn;
4178 	return true;
4179 fail:
4180 	free_mem_cgroup_per_node_info(pn);
4181 	return false;
4182 }
4183 
4184 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4185 {
4186 	int node;
4187 
4188 	for_each_node(node) {
4189 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
4190 		if (!pn)
4191 			continue;
4192 
4193 		obj_cgroup_put(pn->orig_objcg);
4194 		free_mem_cgroup_per_node_info(pn);
4195 	}
4196 	memcg1_free_events(memcg);
4197 	kfree(memcg->vmstats);
4198 	free_percpu(memcg->vmstats_percpu);
4199 	kfree(memcg);
4200 }
4201 
4202 static void mem_cgroup_free(struct mem_cgroup *memcg)
4203 {
4204 	lru_gen_exit_memcg(memcg);
4205 	memcg_wb_domain_exit(memcg);
4206 	__mem_cgroup_free(memcg);
4207 }
4208 
4209 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
4210 {
4211 	struct memcg_vmstats_percpu *statc;
4212 	struct memcg_vmstats_percpu __percpu *pstatc_pcpu;
4213 	struct mem_cgroup *memcg;
4214 	int node, cpu;
4215 	int __maybe_unused i;
4216 	long error;
4217 
4218 	memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
4219 	if (!memcg)
4220 		return ERR_PTR(-ENOMEM);
4221 
4222 	error = xa_alloc(&mem_cgroup_private_ids, &memcg->private_id, NULL,
4223 			 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
4224 	if (error)
4225 		goto fail;
4226 	error = -ENOMEM;
4227 
4228 	memcg->vmstats = kzalloc_obj(struct memcg_vmstats, GFP_KERNEL_ACCOUNT);
4229 	if (!memcg->vmstats)
4230 		goto fail;
4231 
4232 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
4233 						 GFP_KERNEL_ACCOUNT);
4234 	if (!memcg->vmstats_percpu)
4235 		goto fail;
4236 
4237 	if (!memcg1_alloc_events(memcg))
4238 		goto fail;
4239 
4240 	pstatc_pcpu = parent ? parent->vmstats_percpu : NULL;
4241 	for_each_possible_cpu(cpu) {
4242 		statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
4243 		statc->parent_pcpu = pstatc_pcpu;
4244 		statc->vmstats = memcg->vmstats;
4245 	}
4246 
4247 	for_each_node(node)
4248 		if (!alloc_mem_cgroup_per_node_info(memcg, node))
4249 			goto fail;
4250 
4251 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
4252 		goto fail;
4253 
4254 	INIT_WORK(&memcg->high_work, high_work_func);
4255 	init_irq_work(&memcg->high_irq_work, high_irq_work_func);
4256 	vmpressure_init(&memcg->vmpressure);
4257 	INIT_LIST_HEAD(&memcg->memory_peaks);
4258 	INIT_LIST_HEAD(&memcg->swap_peaks);
4259 	spin_lock_init(&memcg->peaks_lock);
4260 	memcg->socket_pressure = get_jiffies_64();
4261 #if BITS_PER_LONG < 64
4262 	seqlock_init(&memcg->socket_pressure_seqlock);
4263 #endif
4264 	memcg1_memcg_init(memcg);
4265 	memcg->kmemcg_id = -1;
4266 #ifdef CONFIG_CGROUP_WRITEBACK
4267 	INIT_LIST_HEAD(&memcg->cgwb_list);
4268 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
4269 		memcg->cgwb_frn[i].done =
4270 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
4271 #endif
4272 	lru_gen_init_memcg(memcg);
4273 	return memcg;
4274 fail:
4275 	mem_cgroup_private_id_remove(memcg);
4276 	__mem_cgroup_free(memcg);
4277 	return ERR_PTR(error);
4278 }
4279 
4280 static struct cgroup_subsys_state * __ref
4281 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
4282 {
4283 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
4284 	struct mem_cgroup *memcg, *old_memcg;
4285 	bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys);
4286 
4287 	old_memcg = set_active_memcg(parent);
4288 	memcg = mem_cgroup_alloc(parent);
4289 	set_active_memcg(old_memcg);
4290 	if (IS_ERR(memcg))
4291 		return ERR_CAST(memcg);
4292 
4293 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
4294 #ifdef CONFIG_ZSWAP
4295 	memcg->zswap_max = PAGE_COUNTER_MAX;
4296 	WRITE_ONCE(memcg->zswap_writeback, true);
4297 #endif
4298 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
4299 	if (parent) {
4300 		page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl);
4301 		page_counter_init(&memcg->swap, &parent->swap, false);
4302 #ifdef CONFIG_MEMCG_V1
4303 		WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
4304 		memcg->memory.track_failcnt = !memcg_on_dfl;
4305 		memcg->memsw.track_failcnt = !memcg_on_dfl;
4306 		WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
4307 		page_counter_init(&memcg->kmem, &parent->kmem, false);
4308 		page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
4309 		memcg->tcpmem.track_failcnt = !memcg_on_dfl;
4310 #endif
4311 	} else {
4312 		init_memcg_stats();
4313 		init_memcg_events();
4314 		page_counter_init(&memcg->memory, NULL, true);
4315 		page_counter_init(&memcg->swap, NULL, false);
4316 #ifdef CONFIG_MEMCG_V1
4317 		page_counter_init(&memcg->kmem, NULL, false);
4318 		page_counter_init(&memcg->tcpmem, NULL, false);
4319 #endif
4320 		root_mem_cgroup = memcg;
4321 		return &memcg->css;
4322 	}
4323 
4324 	if (memcg_on_dfl && !cgroup_memory_nosocket)
4325 		static_branch_inc(&memcg_sockets_enabled_key);
4326 
4327 	if (!cgroup_memory_nobpf)
4328 		static_branch_inc(&memcg_bpf_enabled_key);
4329 
4330 	return &memcg->css;
4331 }
4332 
4333 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
4334 {
4335 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4336 	struct obj_cgroup *objcg;
4337 	int nid;
4338 
4339 	memcg_online_kmem(memcg);
4340 
4341 	/*
4342 	 * A memcg must be visible for expand_shrinker_info()
4343 	 * by the time the maps are allocated. So, we allocate maps
4344 	 * here, when mem_cgroup_iter() can't skip it.
4345 	 */
4346 	if (alloc_shrinker_info(memcg))
4347 		goto offline_kmem;
4348 
4349 	for_each_node(nid) {
4350 		objcg = obj_cgroup_alloc();
4351 		if (!objcg)
4352 			goto free_objcg;
4353 
4354 		if (unlikely(mem_cgroup_is_root(memcg)))
4355 			objcg->is_root = true;
4356 
4357 		objcg->memcg = memcg;
4358 		rcu_assign_pointer(memcg->nodeinfo[nid]->objcg, objcg);
4359 		obj_cgroup_get(objcg);
4360 		memcg->nodeinfo[nid]->orig_objcg = objcg;
4361 	}
4362 
4363 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
4364 		queue_delayed_work(system_dfl_wq, &stats_flush_dwork,
4365 				   FLUSH_TIME);
4366 	lru_gen_online_memcg(memcg);
4367 
4368 	/* Online state pins memcg ID, memcg ID pins CSS */
4369 	refcount_set(&memcg->private_id_ref, 1);
4370 	css_get(css);
4371 
4372 	/*
4373 	 * Ensure mem_cgroup_from_private_id() works once we're fully online.
4374 	 *
4375 	 * We could do this earlier and require callers to filter with
4376 	 * css_tryget_online(). But right now there are no users that
4377 	 * need earlier access, and the workingset code relies on the
4378 	 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
4379 	 * publish it here at the end of onlining. This matches the
4380 	 * regular ID destruction during offlining.
4381 	 */
4382 	xa_store(&mem_cgroup_private_ids, memcg->private_id, memcg, GFP_KERNEL);
4383 
4384 	return 0;
4385 free_objcg:
4386 	for_each_node(nid) {
4387 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4388 
4389 		objcg = rcu_replace_pointer(pn->objcg, NULL, true);
4390 		if (objcg)
4391 			percpu_ref_kill(&objcg->refcnt);
4392 
4393 		if (pn->orig_objcg) {
4394 			obj_cgroup_put(pn->orig_objcg);
4395 			/*
4396 			 * Reset pn->orig_objcg to NULL to prevent
4397 			 * obj_cgroup_put() from being called again in
4398 			 * __mem_cgroup_free().
4399 			 */
4400 			pn->orig_objcg = NULL;
4401 		}
4402 	}
4403 	free_shrinker_info(memcg);
4404 offline_kmem:
4405 	memcg_offline_kmem(memcg);
4406 	mem_cgroup_private_id_remove(memcg);
4407 	return -ENOMEM;
4408 }
4409 
4410 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
4411 {
4412 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4413 
4414 	memcg1_css_offline(memcg);
4415 
4416 	page_counter_set_min(&memcg->memory, 0);
4417 	page_counter_set_low(&memcg->memory, 0);
4418 
4419 	zswap_memcg_offline_cleanup(memcg);
4420 
4421 	memcg_offline_kmem(memcg);
4422 	/*
4423 	 * The reparenting of objcg must be after the reparenting of
4424 	 * the list_lru in memcg_offline_kmem(), which ensures that
4425 	 * they will not mistakenly get the parent list_lru.
4426 	 */
4427 	memcg_reparent_objcgs(memcg);
4428 	reparent_shrinker_deferred(memcg);
4429 	wb_memcg_offline(memcg);
4430 	lru_gen_offline_memcg(memcg);
4431 
4432 	drain_all_stock(memcg);
4433 
4434 	mem_cgroup_private_id_put(memcg, 1);
4435 }
4436 
4437 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
4438 {
4439 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4440 
4441 	invalidate_reclaim_iterators(memcg);
4442 	lru_gen_release_memcg(memcg);
4443 }
4444 
4445 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
4446 {
4447 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4448 	int __maybe_unused i;
4449 
4450 #ifdef CONFIG_CGROUP_WRITEBACK
4451 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
4452 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
4453 #endif
4454 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
4455 		static_branch_dec(&memcg_sockets_enabled_key);
4456 
4457 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
4458 		static_branch_dec(&memcg_sockets_enabled_key);
4459 
4460 	if (!cgroup_memory_nobpf)
4461 		static_branch_dec(&memcg_bpf_enabled_key);
4462 
4463 	vmpressure_cleanup(&memcg->vmpressure);
4464 	irq_work_sync(&memcg->high_irq_work);
4465 	cancel_work_sync(&memcg->high_work);
4466 	free_shrinker_info(memcg);
4467 	mem_cgroup_free(memcg);
4468 }
4469 
4470 /**
4471  * mem_cgroup_css_reset - reset the states of a mem_cgroup
4472  * @css: the target css
4473  *
4474  * Reset the states of the mem_cgroup associated with @css.  This is
4475  * invoked when the userland requests disabling on the default hierarchy
4476  * but the memcg is pinned through dependency.  The memcg should stop
4477  * applying policies and should revert to the vanilla state as it may be
4478  * made visible again.
4479  *
4480  * The current implementation only resets the essential configurations.
4481  * This needs to be expanded to cover all the visible parts.
4482  */
4483 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4484 {
4485 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4486 
4487 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
4488 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
4489 	WRITE_ONCE(memcg->oom_group, false);
4490 #ifdef CONFIG_ZSWAP
4491 	WRITE_ONCE(memcg->zswap_max, PAGE_COUNTER_MAX);
4492 	WRITE_ONCE(memcg->zswap_writeback, true);
4493 #endif
4494 #ifdef CONFIG_MEMCG_V1
4495 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
4496 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
4497 #endif
4498 	page_counter_set_min(&memcg->memory, 0);
4499 	page_counter_set_low(&memcg->memory, 0);
4500 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
4501 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
4502 	memcg_wb_domain_size_changed(memcg);
4503 }
4504 
4505 struct aggregate_control {
4506 	/* pointer to the aggregated (CPU and subtree aggregated) counters */
4507 	long *aggregate;
4508 	/*
4509 	 * pointer to the non-hierarchical (CPU aggregated) counters or NULL to
4510 	 * skip updating them (see memcg_state_local_array())
4511 	 */
4512 	long *local;
4513 	/* pointer to the pending child counters during tree propagation */
4514 	long *pending;
4515 	/* pointer to the parent's pending counters, could be NULL */
4516 	long *ppending;
4517 	/* pointer to the percpu counters to be aggregated */
4518 	long *cstat;
4519 	/* pointer to the percpu counters of the last aggregation*/
4520 	long *cstat_prev;
4521 	/* size of the above counters */
4522 	int size;
4523 };
4524 
4525 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac)
4526 {
4527 	int i;
4528 	long delta, delta_cpu, v;
4529 
4530 	for (i = 0; i < ac->size; i++) {
4531 		/*
4532 		 * Collect the aggregated propagation counts of groups
4533 		 * below us. We're in a per-cpu loop here and this is
4534 		 * a global counter, so the first cycle will get them.
4535 		 */
4536 		delta = ac->pending[i];
4537 		if (delta)
4538 			ac->pending[i] = 0;
4539 
4540 		/* Add CPU changes on this level since the last flush */
4541 		delta_cpu = 0;
4542 		v = READ_ONCE(ac->cstat[i]);
4543 		if (v != ac->cstat_prev[i]) {
4544 			delta_cpu = v - ac->cstat_prev[i];
4545 			delta += delta_cpu;
4546 			ac->cstat_prev[i] = v;
4547 		}
4548 
4549 		/* Aggregate counts on this level and propagate upwards */
4550 		if (delta_cpu && ac->local)
4551 			ac->local[i] += delta_cpu;
4552 
4553 		if (delta) {
4554 			ac->aggregate[i] += delta;
4555 			if (ac->ppending)
4556 				ac->ppending[i] += delta;
4557 		}
4558 	}
4559 }
4560 
4561 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
4562 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent)
4563 {
4564 	long *state_local = memcg_state_local_array(memcg);
4565 	int nid;
4566 
4567 	if (atomic_read(&memcg->kmem_stat)) {
4568 		int kmem = atomic_xchg(&memcg->kmem_stat, 0);
4569 		int index = memcg_stats_index(MEMCG_KMEM);
4570 
4571 		memcg->vmstats->state[index] += kmem;
4572 		if (state_local)
4573 			state_local[index] += kmem;
4574 		if (parent)
4575 			parent->vmstats->state_pending[index] += kmem;
4576 	}
4577 
4578 	for_each_node_state(nid, N_MEMORY) {
4579 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4580 		struct lruvec_stats *lstats = pn->lruvec_stats;
4581 		struct lruvec_stats *plstats = NULL;
4582 
4583 		if (parent)
4584 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4585 
4586 		if (atomic_read(&pn->slab_reclaimable)) {
4587 			int slab = atomic_xchg(&pn->slab_reclaimable, 0);
4588 			int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B);
4589 
4590 			lstats->state[index] += slab;
4591 			lstats->state_local[index] += slab;
4592 			if (plstats)
4593 				plstats->state_pending[index] += slab;
4594 			memcg->vmstats->state[index] += slab;
4595 			if (state_local)
4596 				state_local[index] += slab;
4597 			if (parent)
4598 				parent->vmstats->state_pending[index] += slab;
4599 		}
4600 		if (atomic_read(&pn->slab_unreclaimable)) {
4601 			int slab = atomic_xchg(&pn->slab_unreclaimable, 0);
4602 			int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B);
4603 
4604 			lstats->state[index] += slab;
4605 			lstats->state_local[index] += slab;
4606 			if (plstats)
4607 				plstats->state_pending[index] += slab;
4608 			memcg->vmstats->state[index] += slab;
4609 			if (state_local)
4610 				state_local[index] += slab;
4611 			if (parent)
4612 				parent->vmstats->state_pending[index] += slab;
4613 		}
4614 	}
4615 }
4616 #else
4617 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent)
4618 {}
4619 #endif
4620 
4621 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
4622 {
4623 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4624 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4625 	struct memcg_vmstats_percpu *statc;
4626 	struct aggregate_control ac;
4627 	int nid;
4628 
4629 	flush_nmi_stats(memcg, parent);
4630 
4631 	statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
4632 
4633 	ac = (struct aggregate_control) {
4634 		.aggregate = memcg->vmstats->state,
4635 		.local = memcg_state_local_array(memcg),
4636 		.pending = memcg->vmstats->state_pending,
4637 		.ppending = parent ? parent->vmstats->state_pending : NULL,
4638 		.cstat = statc->state,
4639 		.cstat_prev = statc->state_prev,
4640 		.size = MEMCG_VMSTAT_SIZE,
4641 	};
4642 	mem_cgroup_stat_aggregate(&ac);
4643 
4644 	ac = (struct aggregate_control) {
4645 		.aggregate = memcg->vmstats->events,
4646 		.local = memcg_events_local_array(memcg),
4647 		.pending = memcg->vmstats->events_pending,
4648 		.ppending = parent ? parent->vmstats->events_pending : NULL,
4649 		.cstat = statc->events,
4650 		.cstat_prev = statc->events_prev,
4651 		.size = NR_MEMCG_EVENTS,
4652 	};
4653 	mem_cgroup_stat_aggregate(&ac);
4654 
4655 	for_each_node_state(nid, N_MEMORY) {
4656 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4657 		struct lruvec_stats *lstats = pn->lruvec_stats;
4658 		struct lruvec_stats *plstats = NULL;
4659 		struct lruvec_stats_percpu *lstatc;
4660 
4661 		if (parent)
4662 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4663 
4664 		lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
4665 
4666 		ac = (struct aggregate_control) {
4667 			.aggregate = lstats->state,
4668 			.local = lstats->state_local,
4669 			.pending = lstats->state_pending,
4670 			.ppending = plstats ? plstats->state_pending : NULL,
4671 			.cstat = lstatc->state,
4672 			.cstat_prev = lstatc->state_prev,
4673 			.size = NR_MEMCG_NODE_STAT_ITEMS,
4674 		};
4675 		mem_cgroup_stat_aggregate(&ac);
4676 
4677 	}
4678 	WRITE_ONCE(statc->stats_updates, 0);
4679 	/* We are in a per-cpu loop here, only do the atomic write once */
4680 	if (atomic_long_read(&memcg->vmstats->stats_updates))
4681 		atomic_long_set(&memcg->vmstats->stats_updates, 0);
4682 }
4683 
4684 static void mem_cgroup_fork(struct task_struct *task)
4685 {
4686 	/*
4687 	 * Set the update flag to cause task->objcg to be initialized lazily
4688 	 * on the first allocation. It can be done without any synchronization
4689 	 * because it's always performed on the current task, so does
4690 	 * current_objcg_update().
4691 	 */
4692 	task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
4693 }
4694 
4695 static void mem_cgroup_exit(struct task_struct *task)
4696 {
4697 	struct obj_cgroup *objcg = task->objcg;
4698 
4699 	objcg = (struct obj_cgroup *)
4700 		((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
4701 	obj_cgroup_put(objcg);
4702 
4703 	/*
4704 	 * Some kernel allocations can happen after this point,
4705 	 * but let's ignore them. It can be done without any synchronization
4706 	 * because it's always performed on the current task, so does
4707 	 * current_objcg_update().
4708 	 */
4709 	task->objcg = NULL;
4710 }
4711 
4712 #ifdef CONFIG_LRU_GEN
4713 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
4714 {
4715 	struct task_struct *task;
4716 	struct cgroup_subsys_state *css;
4717 
4718 	/* find the first leader if there is any */
4719 	cgroup_taskset_for_each_leader(task, css, tset)
4720 		break;
4721 
4722 	if (!task)
4723 		return;
4724 
4725 	task_lock(task);
4726 	if (task->mm && READ_ONCE(task->mm->owner) == task)
4727 		lru_gen_migrate_mm(task->mm);
4728 	task_unlock(task);
4729 }
4730 #else
4731 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
4732 #endif /* CONFIG_LRU_GEN */
4733 
4734 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
4735 {
4736 	struct task_struct *task;
4737 	struct cgroup_subsys_state *css;
4738 
4739 	cgroup_taskset_for_each(task, css, tset) {
4740 		/* atomically set the update bit */
4741 		set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
4742 	}
4743 }
4744 
4745 static void mem_cgroup_attach(struct cgroup_taskset *tset)
4746 {
4747 	mem_cgroup_lru_gen_attach(tset);
4748 	mem_cgroup_kmem_attach(tset);
4749 }
4750 
4751 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
4752 {
4753 	if (value == PAGE_COUNTER_MAX)
4754 		seq_puts(m, "max\n");
4755 	else
4756 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
4757 
4758 	return 0;
4759 }
4760 
4761 static u64 memory_current_read(struct cgroup_subsys_state *css,
4762 			       struct cftype *cft)
4763 {
4764 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4765 
4766 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
4767 }
4768 
4769 #define OFP_PEAK_UNSET (((-1UL)))
4770 
4771 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
4772 {
4773 	struct cgroup_of_peak *ofp = of_peak(sf->private);
4774 	u64 fd_peak = READ_ONCE(ofp->value), peak;
4775 
4776 	/* User wants global or local peak? */
4777 	if (fd_peak == OFP_PEAK_UNSET)
4778 		peak = pc->watermark;
4779 	else
4780 		peak = max(fd_peak, READ_ONCE(pc->local_watermark));
4781 
4782 	seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
4783 	return 0;
4784 }
4785 
4786 static int memory_peak_show(struct seq_file *sf, void *v)
4787 {
4788 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
4789 
4790 	guard(spinlock)(&memcg->peaks_lock);
4791 	return peak_show(sf, v, &memcg->memory);
4792 }
4793 
4794 static int peak_open(struct kernfs_open_file *of)
4795 {
4796 	struct cgroup_of_peak *ofp = of_peak(of);
4797 
4798 	ofp->value = OFP_PEAK_UNSET;
4799 	return 0;
4800 }
4801 
4802 static void peak_release(struct kernfs_open_file *of)
4803 {
4804 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4805 	struct cgroup_of_peak *ofp = of_peak(of);
4806 
4807 	if (ofp->value == OFP_PEAK_UNSET) {
4808 		/* fast path (no writes on this fd) */
4809 		return;
4810 	}
4811 	spin_lock(&memcg->peaks_lock);
4812 	list_del(&ofp->list);
4813 	spin_unlock(&memcg->peaks_lock);
4814 }
4815 
4816 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
4817 			  loff_t off, struct page_counter *pc,
4818 			  struct list_head *watchers)
4819 {
4820 	unsigned long usage, old_watermark;
4821 	struct cgroup_of_peak *peer_ctx;
4822 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4823 	struct cgroup_of_peak *ofp = of_peak(of);
4824 
4825 	spin_lock(&memcg->peaks_lock);
4826 
4827 	usage = page_counter_read(pc);
4828 	old_watermark = READ_ONCE(pc->local_watermark);
4829 	WRITE_ONCE(pc->local_watermark, usage);
4830 
4831 	list_for_each_entry(peer_ctx, watchers, list)
4832 		if (peer_ctx != ofp && old_watermark > peer_ctx->value)
4833 			WRITE_ONCE(peer_ctx->value, old_watermark);
4834 
4835 	/* initial write, register watcher */
4836 	if (ofp->value == OFP_PEAK_UNSET)
4837 		list_add(&ofp->list, watchers);
4838 
4839 	WRITE_ONCE(ofp->value, usage);
4840 	spin_unlock(&memcg->peaks_lock);
4841 
4842 	return nbytes;
4843 }
4844 
4845 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
4846 				 size_t nbytes, loff_t off)
4847 {
4848 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4849 
4850 	return peak_write(of, buf, nbytes, off, &memcg->memory,
4851 			  &memcg->memory_peaks);
4852 }
4853 
4854 #undef OFP_PEAK_UNSET
4855 
4856 static int memory_min_show(struct seq_file *m, void *v)
4857 {
4858 	return seq_puts_memcg_tunable(m,
4859 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
4860 }
4861 
4862 static ssize_t memory_min_write(struct kernfs_open_file *of,
4863 				char *buf, size_t nbytes, loff_t off)
4864 {
4865 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4866 	unsigned long min;
4867 	int err;
4868 
4869 	buf = strstrip(buf);
4870 	err = page_counter_memparse(buf, "max", &min);
4871 	if (err)
4872 		return err;
4873 
4874 	page_counter_set_min(&memcg->memory, min);
4875 
4876 	return nbytes;
4877 }
4878 
4879 static int memory_low_show(struct seq_file *m, void *v)
4880 {
4881 	return seq_puts_memcg_tunable(m,
4882 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
4883 }
4884 
4885 static ssize_t memory_low_write(struct kernfs_open_file *of,
4886 				char *buf, size_t nbytes, loff_t off)
4887 {
4888 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4889 	unsigned long low;
4890 	int err;
4891 
4892 	buf = strstrip(buf);
4893 	err = page_counter_memparse(buf, "max", &low);
4894 	if (err)
4895 		return err;
4896 
4897 	page_counter_set_low(&memcg->memory, low);
4898 
4899 	return nbytes;
4900 }
4901 
4902 static int memory_high_show(struct seq_file *m, void *v)
4903 {
4904 	return seq_puts_memcg_tunable(m,
4905 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
4906 }
4907 
4908 static ssize_t memory_high_write(struct kernfs_open_file *of,
4909 				 char *buf, size_t nbytes, loff_t off)
4910 {
4911 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4912 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
4913 	bool drained = false;
4914 	unsigned long high;
4915 	int err;
4916 
4917 	buf = strstrip(buf);
4918 	err = page_counter_memparse(buf, "max", &high);
4919 	if (err)
4920 		return err;
4921 
4922 	page_counter_set_high(&memcg->memory, high);
4923 
4924 	if (of->file->f_flags & O_NONBLOCK)
4925 		goto out;
4926 
4927 	for (;;) {
4928 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4929 		unsigned long reclaimed;
4930 
4931 		if (high != READ_ONCE(memcg->memory.high))
4932 			break;
4933 
4934 		if (nr_pages <= high)
4935 			break;
4936 
4937 		if (signal_pending(current))
4938 			break;
4939 
4940 		/* cgroup_rmdir() waits for us with cgroup_mutex held. */
4941 		if (memcg_is_dying(memcg))
4942 			break;
4943 
4944 		if (!drained) {
4945 			drain_all_stock(memcg);
4946 			drained = true;
4947 			continue;
4948 		}
4949 
4950 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
4951 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
4952 
4953 		if (!reclaimed && !nr_retries--)
4954 			break;
4955 	}
4956 out:
4957 	memcg_wb_domain_size_changed(memcg);
4958 	return nbytes;
4959 }
4960 
4961 static int memory_max_show(struct seq_file *m, void *v)
4962 {
4963 	return seq_puts_memcg_tunable(m,
4964 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
4965 }
4966 
4967 static ssize_t memory_max_write(struct kernfs_open_file *of,
4968 				char *buf, size_t nbytes, loff_t off)
4969 {
4970 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4971 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
4972 	bool drained = false;
4973 	unsigned long max;
4974 	int err;
4975 
4976 	buf = strstrip(buf);
4977 	err = page_counter_memparse(buf, "max", &max);
4978 	if (err)
4979 		return err;
4980 
4981 	xchg(&memcg->memory.max, max);
4982 
4983 	if (of->file->f_flags & O_NONBLOCK)
4984 		goto out;
4985 
4986 	for (;;) {
4987 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4988 
4989 		if (max != READ_ONCE(memcg->memory.max))
4990 			break;
4991 
4992 		if (nr_pages <= max)
4993 			break;
4994 
4995 		if (signal_pending(current))
4996 			break;
4997 
4998 		/* cgroup_rmdir() waits for us with cgroup_mutex held. */
4999 		if (memcg_is_dying(memcg))
5000 			break;
5001 
5002 		if (!drained) {
5003 			drain_all_stock(memcg);
5004 			drained = true;
5005 			continue;
5006 		}
5007 
5008 		if (nr_reclaims) {
5009 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
5010 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
5011 				nr_reclaims--;
5012 			continue;
5013 		}
5014 
5015 		memcg_memory_event(memcg, MEMCG_OOM);
5016 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
5017 			break;
5018 		cond_resched();
5019 	}
5020 out:
5021 	memcg_wb_domain_size_changed(memcg);
5022 	return nbytes;
5023 }
5024 
5025 /*
5026  * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
5027  * if any new events become available.
5028  */
5029 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
5030 {
5031 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
5032 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
5033 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
5034 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
5035 	seq_printf(m, "oom_kill %lu\n",
5036 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
5037 	seq_printf(m, "oom_group_kill %lu\n",
5038 		   atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
5039 	seq_printf(m, "sock_throttled %lu\n",
5040 		   atomic_long_read(&events[MEMCG_SOCK_THROTTLED]));
5041 }
5042 
5043 static int memory_events_show(struct seq_file *m, void *v)
5044 {
5045 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5046 
5047 	__memory_events_show(m, memcg->memory_events);
5048 	return 0;
5049 }
5050 
5051 static int memory_events_local_show(struct seq_file *m, void *v)
5052 {
5053 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5054 
5055 	__memory_events_show(m, memcg->memory_events_local);
5056 	return 0;
5057 }
5058 
5059 int memory_stat_show(struct seq_file *m, void *v)
5060 {
5061 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5062 	char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
5063 	struct seq_buf s;
5064 
5065 	if (!buf)
5066 		return -ENOMEM;
5067 	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
5068 	memory_stat_format(memcg, &s);
5069 	seq_puts(m, buf);
5070 	kfree(buf);
5071 	return 0;
5072 }
5073 
5074 #ifdef CONFIG_NUMA
5075 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
5076 						     int item)
5077 {
5078 	return lruvec_page_state(lruvec, item) *
5079 		memcg_page_state_output_unit(item);
5080 }
5081 
5082 static int memory_numa_stat_show(struct seq_file *m, void *v)
5083 {
5084 	int i;
5085 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5086 
5087 	mem_cgroup_flush_stats(memcg);
5088 
5089 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
5090 		int nid;
5091 
5092 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
5093 			continue;
5094 
5095 		seq_printf(m, "%s", memory_stats[i].name);
5096 		for_each_node_state(nid, N_MEMORY) {
5097 			u64 size;
5098 			struct lruvec *lruvec;
5099 
5100 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
5101 			size = lruvec_page_state_output(lruvec,
5102 							memory_stats[i].idx);
5103 			seq_printf(m, " N%d=%llu", nid, size);
5104 		}
5105 		seq_putc(m, '\n');
5106 	}
5107 
5108 	return 0;
5109 }
5110 #endif
5111 
5112 static int memory_oom_group_show(struct seq_file *m, void *v)
5113 {
5114 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5115 
5116 	seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
5117 
5118 	return 0;
5119 }
5120 
5121 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
5122 				      char *buf, size_t nbytes, loff_t off)
5123 {
5124 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5125 	int ret, oom_group;
5126 
5127 	buf = strstrip(buf);
5128 	if (!buf)
5129 		return -EINVAL;
5130 
5131 	ret = kstrtoint(buf, 0, &oom_group);
5132 	if (ret)
5133 		return ret;
5134 
5135 	if (oom_group != 0 && oom_group != 1)
5136 		return -EINVAL;
5137 
5138 	WRITE_ONCE(memcg->oom_group, oom_group);
5139 
5140 	return nbytes;
5141 }
5142 
5143 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
5144 			      size_t nbytes, loff_t off)
5145 {
5146 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5147 	int ret;
5148 
5149 	ret = user_proactive_reclaim(buf, memcg, NULL);
5150 	if (ret)
5151 		return ret;
5152 
5153 	return nbytes;
5154 }
5155 
5156 static struct cftype memory_files[] = {
5157 	{
5158 		.name = "current",
5159 		.flags = CFTYPE_NOT_ON_ROOT,
5160 		.read_u64 = memory_current_read,
5161 	},
5162 	{
5163 		.name = "peak",
5164 		.flags = CFTYPE_NOT_ON_ROOT,
5165 		.open = peak_open,
5166 		.release = peak_release,
5167 		.seq_show = memory_peak_show,
5168 		.write = memory_peak_write,
5169 	},
5170 	{
5171 		.name = "min",
5172 		.flags = CFTYPE_NOT_ON_ROOT,
5173 		.seq_show = memory_min_show,
5174 		.write = memory_min_write,
5175 	},
5176 	{
5177 		.name = "low",
5178 		.flags = CFTYPE_NOT_ON_ROOT,
5179 		.seq_show = memory_low_show,
5180 		.write = memory_low_write,
5181 	},
5182 	{
5183 		.name = "high",
5184 		.flags = CFTYPE_NOT_ON_ROOT,
5185 		.seq_show = memory_high_show,
5186 		.write = memory_high_write,
5187 	},
5188 	{
5189 		.name = "max",
5190 		.flags = CFTYPE_NOT_ON_ROOT,
5191 		.seq_show = memory_max_show,
5192 		.write = memory_max_write,
5193 	},
5194 	{
5195 		.name = "events",
5196 		.flags = CFTYPE_NOT_ON_ROOT,
5197 		.file_offset = offsetof(struct mem_cgroup, events_file),
5198 		.seq_show = memory_events_show,
5199 	},
5200 	{
5201 		.name = "events.local",
5202 		.flags = CFTYPE_NOT_ON_ROOT,
5203 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
5204 		.seq_show = memory_events_local_show,
5205 	},
5206 	{
5207 		.name = "stat",
5208 		.seq_show = memory_stat_show,
5209 	},
5210 #ifdef CONFIG_NUMA
5211 	{
5212 		.name = "numa_stat",
5213 		.seq_show = memory_numa_stat_show,
5214 	},
5215 #endif
5216 	{
5217 		.name = "oom.group",
5218 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
5219 		.seq_show = memory_oom_group_show,
5220 		.write = memory_oom_group_write,
5221 	},
5222 	{
5223 		.name = "reclaim",
5224 		.flags = CFTYPE_NS_DELEGATABLE,
5225 		.write = memory_reclaim,
5226 	},
5227 	{ }	/* terminate */
5228 };
5229 
5230 struct cgroup_subsys memory_cgrp_subsys = {
5231 	.css_alloc = mem_cgroup_css_alloc,
5232 	.css_online = mem_cgroup_css_online,
5233 	.css_offline = mem_cgroup_css_offline,
5234 	.css_released = mem_cgroup_css_released,
5235 	.css_free = mem_cgroup_css_free,
5236 	.css_reset = mem_cgroup_css_reset,
5237 	.css_rstat_flush = mem_cgroup_css_rstat_flush,
5238 	.attach = mem_cgroup_attach,
5239 	.fork = mem_cgroup_fork,
5240 	.exit = mem_cgroup_exit,
5241 	.dfl_cftypes = memory_files,
5242 #ifdef CONFIG_MEMCG_V1
5243 	.legacy_cftypes = mem_cgroup_legacy_files,
5244 #endif
5245 	.early_init = 0,
5246 };
5247 
5248 /**
5249  * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
5250  * @root: the top ancestor of the sub-tree being checked
5251  * @memcg: the memory cgroup to check
5252  *
5253  * WARNING: This function is not stateless! It can only be used as part
5254  *          of a top-down tree iteration, not for isolated queries.
5255  */
5256 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
5257 				     struct mem_cgroup *memcg)
5258 {
5259 	bool recursive_protection =
5260 		cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
5261 
5262 	if (mem_cgroup_disabled())
5263 		return;
5264 
5265 	if (!root)
5266 		root = root_mem_cgroup;
5267 
5268 	page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
5269 }
5270 
5271 #ifdef CONFIG_LRU_GEN
5272 /**
5273  * mem_cgroup_calculate_protection_path - compute protection along a path
5274  * @root: the top ancestor of the sub-tree being checked (NULL for root_mem_cgroup)
5275  * @memcg: the target memory cgroup
5276  *
5277  * Walk the ancestor path from @root down to @memcg and compute the effective
5278  * protection at each level.  This is safe for isolated queries because it
5279  * ensures parents are computed before children.
5280  */
5281 void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
5282 					  struct mem_cgroup *memcg)
5283 {
5284 	bool recursive_protection =
5285 		cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
5286 	struct cgroup *cg;
5287 	int root_level, i;
5288 
5289 	if (mem_cgroup_disabled())
5290 		return;
5291 
5292 	if (!root)
5293 		root = root_mem_cgroup;
5294 
5295 	if (memcg == root)
5296 		return;
5297 
5298 	root_level = root->css.cgroup->level;
5299 	cg = memcg->css.cgroup;
5300 
5301 	rcu_read_lock();
5302 	for (i = root_level + 1; i <= cg->level; i++) {
5303 		struct mem_cgroup *cur;
5304 
5305 		cur = mem_cgroup_from_css(cgroup_css(cg->ancestors[i],
5306 						     &memory_cgrp_subsys));
5307 		if (cur)
5308 			page_counter_calculate_protection(&root->memory,
5309 							  &cur->memory,
5310 							  recursive_protection);
5311 	}
5312 	rcu_read_unlock();
5313 }
5314 #endif /* CONFIG_LRU_GEN */
5315 
5316 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
5317 			gfp_t gfp)
5318 {
5319 	int ret = 0;
5320 	struct obj_cgroup *objcg;
5321 
5322 	objcg = get_obj_cgroup_from_memcg(memcg, folio_nid(folio));
5323 	/* Do not account at the root objcg level. */
5324 	if (!obj_cgroup_is_root(objcg))
5325 		ret = try_charge_memcg(memcg, gfp, folio_nr_pages(folio));
5326 	if (ret) {
5327 		obj_cgroup_put(objcg);
5328 		return ret;
5329 	}
5330 	commit_charge(folio, objcg);
5331 	memcg1_commit_charge(folio, memcg);
5332 
5333 	return ret;
5334 }
5335 
5336 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
5337 {
5338 	struct mem_cgroup *memcg;
5339 	int ret;
5340 
5341 	memcg = get_mem_cgroup_from_mm(mm);
5342 	ret = charge_memcg(folio, memcg, gfp);
5343 	css_put(&memcg->css);
5344 
5345 	return ret;
5346 }
5347 
5348 /**
5349  * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
5350  * @folio: folio being charged
5351  * @mm: mm context of the allocation target
5352  * @gfp: reclaim mode
5353  *
5354  * This function is called when allocating a huge page folio, after the page has
5355  * already been obtained and charged to the appropriate hugetlb cgroup
5356  * controller (if it is enabled).
5357  *
5358  * Returns ENOMEM if the memcg is already full.
5359  * Returns 0 if either the charge was successful, or if we skip the charging.
5360  */
5361 int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,
5362 			      gfp_t gfp)
5363 {
5364 	struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
5365 	int ret = 0;
5366 
5367 	/*
5368 	 * Even memcg does not account for hugetlb, we still want to update
5369 	 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip
5370 	 * charging the memcg.
5371 	 */
5372 	if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() ||
5373 		!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5374 		goto out;
5375 
5376 	if (charge_memcg(folio, memcg, gfp))
5377 		ret = -ENOMEM;
5378 
5379 out:
5380 	mem_cgroup_put(memcg);
5381 	return ret;
5382 }
5383 
5384 /**
5385  * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
5386  * @folio: the folio to charge
5387  * @id: memory cgroup id
5388  * @mm: mm context of the victim
5389  * @gfp: reclaim mode
5390  *
5391  * This function charges a folio allocated for swapin. Please call this before
5392  * adding the folio to the swapcache.
5393  *
5394  * Returns 0 on success. Otherwise, an error code is returned.
5395  */
5396 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id,
5397 				   struct mm_struct *mm, gfp_t gfp)
5398 {
5399 	struct mem_cgroup *memcg;
5400 	int ret;
5401 
5402 	if (mem_cgroup_disabled())
5403 		return 0;
5404 
5405 	rcu_read_lock();
5406 	memcg = mem_cgroup_from_private_id(id);
5407 	if (!memcg || !css_tryget_online(&memcg->css))
5408 		memcg = get_mem_cgroup_from_mm(mm);
5409 	rcu_read_unlock();
5410 
5411 	ret = charge_memcg(folio, memcg, gfp);
5412 
5413 	css_put(&memcg->css);
5414 	return ret;
5415 }
5416 
5417 struct uncharge_gather {
5418 	struct obj_cgroup *objcg;
5419 	unsigned long nr_memory;
5420 	unsigned long pgpgout;
5421 	unsigned long nr_kmem;
5422 };
5423 
5424 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
5425 {
5426 	memset(ug, 0, sizeof(*ug));
5427 }
5428 
5429 static void uncharge_batch(const struct uncharge_gather *ug)
5430 {
5431 	struct mem_cgroup *memcg;
5432 
5433 	rcu_read_lock();
5434 	memcg = obj_cgroup_memcg(ug->objcg);
5435 	if (ug->nr_memory) {
5436 		memcg_uncharge(memcg, ug->nr_memory);
5437 		if (ug->nr_kmem) {
5438 			mod_memcg_state(memcg, MEMCG_KMEM, -ug->nr_kmem);
5439 			memcg1_account_kmem(memcg, -ug->nr_kmem);
5440 		}
5441 		memcg1_oom_recover(memcg);
5442 	}
5443 
5444 	memcg1_uncharge_batch(memcg, ug->pgpgout, ug->nr_memory);
5445 	rcu_read_unlock();
5446 
5447 	/* drop reference from uncharge_folio */
5448 	obj_cgroup_put(ug->objcg);
5449 }
5450 
5451 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
5452 {
5453 	long nr_pages;
5454 	struct obj_cgroup *objcg;
5455 
5456 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5457 
5458 	/*
5459 	 * Nobody should be changing or seriously looking at
5460 	 * folio objcg at this point, we have fully exclusive
5461 	 * access to the folio.
5462 	 */
5463 	objcg = folio_objcg(folio);
5464 	if (!objcg)
5465 		return;
5466 
5467 	if (ug->objcg != objcg) {
5468 		if (ug->objcg) {
5469 			uncharge_batch(ug);
5470 			uncharge_gather_clear(ug);
5471 		}
5472 		ug->objcg = objcg;
5473 
5474 		/* pairs with obj_cgroup_put in uncharge_batch */
5475 		obj_cgroup_get(objcg);
5476 	}
5477 
5478 	nr_pages = folio_nr_pages(folio);
5479 
5480 	if (folio_memcg_kmem(folio)) {
5481 		ug->nr_memory += nr_pages;
5482 		ug->nr_kmem += nr_pages;
5483 	} else {
5484 		/* LRU pages aren't accounted at the root level */
5485 		if (!obj_cgroup_is_root(objcg))
5486 			ug->nr_memory += nr_pages;
5487 		ug->pgpgout++;
5488 
5489 		WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
5490 	}
5491 
5492 	folio->memcg_data = 0;
5493 	obj_cgroup_put(objcg);
5494 }
5495 
5496 void __mem_cgroup_uncharge(struct folio *folio)
5497 {
5498 	struct uncharge_gather ug;
5499 
5500 	/* Don't touch folio->lru of any random page, pre-check: */
5501 	if (!folio_memcg_charged(folio))
5502 		return;
5503 
5504 	uncharge_gather_clear(&ug);
5505 	uncharge_folio(folio, &ug);
5506 	uncharge_batch(&ug);
5507 }
5508 
5509 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
5510 {
5511 	struct uncharge_gather ug;
5512 	unsigned int i;
5513 
5514 	uncharge_gather_clear(&ug);
5515 	for (i = 0; i < folios->nr; i++)
5516 		uncharge_folio(folios->folios[i], &ug);
5517 	if (ug.objcg)
5518 		uncharge_batch(&ug);
5519 }
5520 
5521 /*
5522  * An LRU folio must hold the objcg belonging to its own node.
5523  *
5524  * memcg_reparent_objcgs() reparents a dying cgroup one node at a time: the
5525  * folios on that node's LRU lists move to the parent and that node's objcg is
5526  * redirected to the parent, atomically under the node's lru_lock.
5527  * folio_lruvec_lock() relies on this to provide a stable folio<->lruvec
5528  * binding. If a folio holds another node's objcg, its list membership and its
5529  * lruvec resolution change in separate lock sections, and an LRU operation in
5530  * between can re-add the folio to, and strand it on, the LRU list of a dead
5531  * memcg.
5532  *
5533  * So when migration transfers the memcg state to a folio on another node,
5534  * re-derive the objcg for the destination node. If the memcg is dying and the
5535  * destination node has already been reparented, the lookup walks up to the
5536  * nearest live ancestor - which is also where that node's LRU lists went.
5537  *
5538  * Returns the objcg to commit to @new, with a reference for the caller.
5539  */
5540 static struct obj_cgroup *get_migration_objcg(struct folio *old,
5541 					      struct folio *new)
5542 {
5543 	struct obj_cgroup *old_objcg, *new_objcg;
5544 	int new_nid = folio_nid(new);
5545 
5546 	old_objcg = get_obj_cgroup_from_folio(old);
5547 
5548 	if (folio_nid(old) == new_nid)
5549 		return old_objcg;
5550 
5551 	rcu_read_lock();
5552 	new_objcg = __get_obj_cgroup_from_memcg(obj_cgroup_memcg(old_objcg),
5553 						new_nid);
5554 	rcu_read_unlock();
5555 
5556 	obj_cgroup_put(old_objcg);
5557 
5558 	return new_objcg;
5559 }
5560 
5561 /**
5562  * mem_cgroup_replace_folio - Charge a folio's replacement.
5563  * @old: Currently circulating folio.
5564  * @new: Replacement folio.
5565  *
5566  * Charge @new as a replacement folio for @old. @old will
5567  * be uncharged upon free.
5568  *
5569  * Both folios must be locked, @new->mapping must be set up.
5570  */
5571 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
5572 {
5573 	struct mem_cgroup *memcg;
5574 	struct obj_cgroup *objcg;
5575 	long nr_pages = folio_nr_pages(new);
5576 
5577 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
5578 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5579 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5580 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
5581 
5582 	if (mem_cgroup_disabled())
5583 		return;
5584 
5585 	/* Page cache replacement: new folio already charged? */
5586 	if (folio_memcg_charged(new))
5587 		return;
5588 
5589 	VM_WARN_ON_ONCE_FOLIO(!folio_objcg(old), old);
5590 	if (!folio_objcg(old))
5591 		return;
5592 
5593 	objcg = get_migration_objcg(old, new);
5594 
5595 	rcu_read_lock();
5596 	memcg = obj_cgroup_memcg(objcg);
5597 
5598 	/*
5599 	 * Force-charge the new page. The old one will be freed soon.
5600 	 *
5601 	 * The rootness of the committed objcg decides whether the final
5602 	 * uncharge of @new goes through the page counters (see
5603 	 * uncharge_folio()); charge them only if the uncharge will.
5604 	 */
5605 	if (!obj_cgroup_is_root(objcg)) {
5606 		page_counter_charge(&memcg->memory, nr_pages);
5607 		if (do_memsw_account())
5608 			page_counter_charge(&memcg->memsw, nr_pages);
5609 	}
5610 
5611 	commit_charge(new, objcg);
5612 	memcg1_commit_charge(new, memcg);
5613 	rcu_read_unlock();
5614 }
5615 
5616 /**
5617  * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
5618  * @old: Currently circulating folio.
5619  * @new: Replacement folio.
5620  *
5621  * Transfer the memcg data from the old folio to the new folio for migration.
5622  * The old folio's data info will be cleared. The memory counters remain
5623  * unchanged, unless the charge moves out of a fully reparented ancestry
5624  * and has to be settled (see below).
5625  *
5626  * Both folios must be locked, @new->mapping must be set up.
5627  */
5628 void mem_cgroup_migrate(struct folio *old, struct folio *new)
5629 {
5630 	struct obj_cgroup *objcg, *new_objcg;
5631 
5632 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
5633 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5634 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5635 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
5636 	VM_BUG_ON_FOLIO(folio_test_lru(old), old);
5637 
5638 	if (mem_cgroup_disabled())
5639 		return;
5640 
5641 	objcg = folio_objcg(old);
5642 	/*
5643 	 * Note that it is normal to see !objcg for a hugetlb folio.
5644 	 * For e.g, it could have been allocated when memory_hugetlb_accounting
5645 	 * was not selected.
5646 	 */
5647 	VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !objcg, old);
5648 	if (!objcg)
5649 		return;
5650 
5651 	new_objcg = get_migration_objcg(old, new);
5652 
5653 	/*
5654 	 * @old was charged through a non-root objcg, so its charge is in the
5655 	 * page counters. If the re-derivation walked up to the root objcg -
5656 	 * @old's entire ancestry is dying and already reparented - the final
5657 	 * uncharge of @new will skip the page counters (see uncharge_folio()).
5658 	 * Settle them now: this is @old's eventual uncharge, moved up to the
5659 	 * point where its charge record ends.
5660 	 */
5661 	if (obj_cgroup_is_root(new_objcg) && !obj_cgroup_is_root(objcg)) {
5662 		rcu_read_lock();
5663 		memcg_uncharge(obj_cgroup_memcg(objcg), folio_nr_pages(old));
5664 		rcu_read_unlock();
5665 	}
5666 
5667 	commit_charge(new, new_objcg);
5668 
5669 	/* Warning should never happen, so don't worry about refcount non-0 */
5670 	WARN_ON_ONCE(folio_unqueue_deferred_split(old));
5671 	old->memcg_data = 0;
5672 
5673 	/* @new holds its own reference now, drop @old's */
5674 	obj_cgroup_put(objcg);
5675 }
5676 
5677 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
5678 EXPORT_SYMBOL(memcg_sockets_enabled_key);
5679 
5680 void mem_cgroup_sk_alloc(struct sock *sk)
5681 {
5682 	struct mem_cgroup *memcg;
5683 
5684 	if (!mem_cgroup_sockets_enabled)
5685 		return;
5686 
5687 	/* Do not associate the sock with unrelated interrupted task's memcg. */
5688 	if (!in_task())
5689 		return;
5690 
5691 	rcu_read_lock();
5692 	memcg = mem_cgroup_from_task(current);
5693 	if (mem_cgroup_is_root(memcg))
5694 		goto out;
5695 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
5696 		goto out;
5697 	if (css_tryget(&memcg->css))
5698 		sk->sk_memcg = memcg;
5699 out:
5700 	rcu_read_unlock();
5701 }
5702 
5703 void mem_cgroup_sk_free(struct sock *sk)
5704 {
5705 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5706 
5707 	if (memcg)
5708 		css_put(&memcg->css);
5709 }
5710 
5711 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk)
5712 {
5713 	struct mem_cgroup *memcg;
5714 
5715 	if (sk->sk_memcg == newsk->sk_memcg)
5716 		return;
5717 
5718 	mem_cgroup_sk_free(newsk);
5719 
5720 	memcg = mem_cgroup_from_sk(sk);
5721 	if (memcg)
5722 		css_get(&memcg->css);
5723 
5724 	newsk->sk_memcg = sk->sk_memcg;
5725 }
5726 
5727 /**
5728  * mem_cgroup_sk_charge - charge socket memory
5729  * @sk: socket in memcg to charge
5730  * @nr_pages: number of pages to charge
5731  * @gfp_mask: reclaim mode
5732  *
5733  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
5734  * @memcg's configured limit, %false if it doesn't.
5735  */
5736 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages,
5737 			  gfp_t gfp_mask)
5738 {
5739 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5740 
5741 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5742 		return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
5743 
5744 	if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) {
5745 		mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
5746 		return true;
5747 	}
5748 
5749 	return false;
5750 }
5751 
5752 /**
5753  * mem_cgroup_sk_uncharge - uncharge socket memory
5754  * @sk: socket in memcg to uncharge
5755  * @nr_pages: number of pages to uncharge
5756  */
5757 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages)
5758 {
5759 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5760 
5761 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
5762 		memcg1_uncharge_skmem(memcg, nr_pages);
5763 		return;
5764 	}
5765 
5766 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
5767 
5768 	refill_stock(memcg, nr_pages);
5769 }
5770 
5771 void mem_cgroup_flush_workqueue(void)
5772 {
5773 	flush_workqueue(memcg_wq);
5774 }
5775 
5776 static int __init cgroup_memory(char *s)
5777 {
5778 	char *token;
5779 
5780 	while ((token = strsep(&s, ",")) != NULL) {
5781 		if (!*token)
5782 			continue;
5783 		if (!strcmp(token, "nosocket"))
5784 			cgroup_memory_nosocket = true;
5785 		if (!strcmp(token, "nokmem"))
5786 			cgroup_memory_nokmem = true;
5787 		if (!strcmp(token, "nobpf"))
5788 			cgroup_memory_nobpf = true;
5789 	}
5790 	return 1;
5791 }
5792 __setup("cgroup.memory=", cgroup_memory);
5793 
5794 /*
5795  * Memory controller init before cgroup_init() initialize root_mem_cgroup.
5796  *
5797  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
5798  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
5799  * basically everything that doesn't depend on a specific mem_cgroup structure
5800  * should be initialized from here.
5801  */
5802 /*
5803  * Fields are grouped by access pattern. Putting a field in the wrong group
5804  * breaks the build here.
5805  */
5806 static void __init memcg_struct_check(void)
5807 {
5808 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5809 				      socket_pressure);
5810 #if BITS_PER_LONG < 64
5811 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5812 				      socket_pressure_seqlock);
5813 #endif
5814 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5815 				      memory_events);
5816 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5817 				      memory_events_local);
5818 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5819 				      vmpressure);
5820 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5821 				      private_id_ref);
5822 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
5823 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5824 				      kmem_stat);
5825 #endif
5826 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5827 				      high_irq_work);
5828 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_write_hot,
5829 				      high_work);
5830 
5831 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5832 				      memory_peaks);
5833 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5834 				      swap_peaks);
5835 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5836 				      peaks_lock);
5837 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5838 				      events_file);
5839 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5840 				      events_local_file);
5841 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5842 				      swap_events_file);
5843 #ifdef CONFIG_CGROUP_WRITEBACK
5844 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5845 				      cgwb_list);
5846 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5847 				      cgwb_domain);
5848 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5849 				      cgwb_frn);
5850 #endif
5851 #ifdef CONFIG_LRU_GEN_WALKS_MMU
5852 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_cold,
5853 				      mm_list);
5854 #endif
5855 
5856 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5857 				      vmstats_percpu);
5858 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5859 				      vmstats);
5860 #ifdef CONFIG_ZSWAP
5861 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5862 				      zswap_max);
5863 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5864 				      zswap_writeback);
5865 #endif
5866 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5867 				      private_id);
5868 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5869 				      kmemcg_id);
5870 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup, memcg_read_mostly,
5871 				      oom_group);
5872 
5873 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5874 				      memcg_pn_read_mostly, memcg);
5875 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5876 				      memcg_pn_read_mostly, lruvec_stats_percpu);
5877 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5878 				      memcg_pn_read_mostly, lruvec_stats);
5879 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5880 				      memcg_pn_read_mostly, shrinker_info);
5881 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5882 				      memcg_pn_read_mostly, objcg);
5883 
5884 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5885 				      memcg_pn_lruvec, lruvec);
5886 
5887 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5888 				      memcg_pn_write_hot, lru_zone_size);
5889 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5890 				      memcg_pn_write_hot, iter);
5891 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
5892 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5893 				      memcg_pn_write_hot, slab_reclaimable);
5894 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5895 				      memcg_pn_write_hot, slab_unreclaimable);
5896 #endif
5897 
5898 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5899 				      memcg_pn_cold, orig_objcg);
5900 	CACHELINE_ASSERT_GROUP_MEMBER(struct mem_cgroup_per_node,
5901 				      memcg_pn_cold, objcg_list);
5902 }
5903 
5904 int __init mem_cgroup_init(void)
5905 {
5906 	unsigned int memcg_size;
5907 	int cpu;
5908 
5909 	/*
5910 	 * Currently s32 type (can refer to struct batched_lruvec_stat) is
5911 	 * used for per-memcg-per-cpu caching of per-node statistics. In order
5912 	 * to work fine, we should make sure that the overfill threshold can't
5913 	 * exceed S32_MAX / PAGE_SIZE.
5914 	 */
5915 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
5916 
5917 	memcg_struct_check();
5918 
5919 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
5920 				  memcg_hotplug_cpu_dead);
5921 
5922 	memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0);
5923 	WARN_ON(!memcg_wq);
5924 
5925 	for_each_possible_cpu(cpu) {
5926 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
5927 			  drain_local_memcg_stock);
5928 		INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work,
5929 			  drain_local_obj_stock);
5930 	}
5931 
5932 	memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
5933 	memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
5934 					 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
5935 
5936 	memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
5937 				     SLAB_PANIC | SLAB_HWCACHE_ALIGN);
5938 
5939 	return 0;
5940 }
5941 
5942 #ifdef CONFIG_SWAP
5943 /**
5944  * __mem_cgroup_try_charge_swap - try charging swap space for a folio
5945  * @folio: folio being added to swap
5946  *
5947  * Try to charge @folio's memcg for the swap space at folio->swap.
5948  *
5949  * Returns 0 on success, -ENOMEM on failure.
5950  */
5951 int __mem_cgroup_try_charge_swap(struct folio *folio)
5952 {
5953 	unsigned int nr_pages = folio_nr_pages(folio);
5954 	struct swap_cluster_info *ci;
5955 	struct page_counter *counter;
5956 	struct mem_cgroup *memcg;
5957 	struct obj_cgroup *objcg;
5958 
5959 	if (do_memsw_account())
5960 		return 0;
5961 
5962 	objcg = folio_objcg(folio);
5963 	VM_WARN_ON_ONCE_FOLIO(!objcg, folio);
5964 	if (!objcg)
5965 		return 0;
5966 
5967 	rcu_read_lock();
5968 	memcg = obj_cgroup_memcg(objcg);
5969 	if (!folio_test_swapcache(folio)) {
5970 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5971 		rcu_read_unlock();
5972 		return 0;
5973 	}
5974 
5975 	memcg = mem_cgroup_private_id_get_online(memcg, nr_pages);
5976 	/* memcg is pined by memcg ID. */
5977 	rcu_read_unlock();
5978 
5979 	if (!mem_cgroup_is_root(memcg) &&
5980 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
5981 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
5982 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5983 		mem_cgroup_private_id_put(memcg, nr_pages);
5984 		return -ENOMEM;
5985 	}
5986 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
5987 
5988 	ci = swap_cluster_get_and_lock(folio);
5989 	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_pages,
5990 			  mem_cgroup_private_id(memcg));
5991 	swap_cluster_unlock(ci);
5992 
5993 	return 0;
5994 }
5995 
5996 /**
5997  * __mem_cgroup_uncharge_swap - uncharge swap space
5998  * @id: cgroup id to uncharge
5999  * @nr_pages: the amount of swap space to uncharge
6000  */
6001 void __mem_cgroup_uncharge_swap(unsigned short id, unsigned int nr_pages)
6002 {
6003 	struct mem_cgroup *memcg;
6004 
6005 	rcu_read_lock();
6006 	memcg = mem_cgroup_from_private_id(id);
6007 	if (memcg) {
6008 		if (!mem_cgroup_is_root(memcg)) {
6009 			if (do_memsw_account())
6010 				page_counter_uncharge(&memcg->memsw, nr_pages);
6011 			else
6012 				page_counter_uncharge(&memcg->swap, nr_pages);
6013 		}
6014 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
6015 		mem_cgroup_private_id_put(memcg, nr_pages);
6016 	}
6017 	rcu_read_unlock();
6018 }
6019 
6020 long mem_cgroup_get_nr_swap_pages(const struct mem_cgroup *memcg)
6021 {
6022 	long nr_swap_pages = get_nr_swap_pages();
6023 
6024 	if (!mem_cgroup_disabled() && !do_memsw_account())
6025 		nr_swap_pages = min(nr_swap_pages, page_counter_margin(&memcg->swap));
6026 
6027 	return nr_swap_pages;
6028 }
6029 
6030 /**
6031  * mem_cgroup_get_folio_swap_margin - get a folio's memcg swap margin
6032  * @folio: folio whose memcg margin is queried
6033  *
6034  * Return: Remaining chargeable pages in the folio's memcg hierarchy.
6035  */
6036 long mem_cgroup_get_folio_swap_margin(const struct folio *folio)
6037 {
6038 	struct mem_cgroup *memcg;
6039 	long margin;
6040 
6041 	if (mem_cgroup_disabled() || do_memsw_account() ||
6042 	    !folio_memcg_charged(folio))
6043 		return PAGE_COUNTER_MAX;
6044 
6045 	rcu_read_lock();
6046 	memcg = folio_memcg(folio);
6047 	margin = page_counter_margin(&memcg->swap);
6048 	rcu_read_unlock();
6049 
6050 	return margin;
6051 }
6052 
6053 bool mem_cgroup_swap_full(const struct folio *folio)
6054 {
6055 	struct mem_cgroup *memcg;
6056 	bool ret = false;
6057 
6058 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
6059 
6060 	if (vm_swap_full())
6061 		return true;
6062 	if (do_memsw_account() || !folio_memcg_charged(folio))
6063 		return ret;
6064 
6065 	rcu_read_lock();
6066 	memcg = folio_memcg(folio);
6067 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
6068 		unsigned long usage = page_counter_read(&memcg->swap);
6069 
6070 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
6071 		    usage * 2 >= READ_ONCE(memcg->swap.max)) {
6072 			ret = true;
6073 			break;
6074 		}
6075 	}
6076 	rcu_read_unlock();
6077 
6078 	return ret;
6079 }
6080 
6081 static int __init setup_swap_account(char *s)
6082 {
6083 	bool res;
6084 
6085 	if (!kstrtobool(s, &res) && !res)
6086 		pr_warn_once("The swapaccount=0 commandline option is deprecated "
6087 			     "in favor of configuring swap control via cgroupfs. "
6088 			     "Please report your usecase to linux-mm@kvack.org if you "
6089 			     "depend on this functionality.\n");
6090 	return 1;
6091 }
6092 __setup("swapaccount=", setup_swap_account);
6093 
6094 static u64 swap_current_read(struct cgroup_subsys_state *css,
6095 			     struct cftype *cft)
6096 {
6097 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6098 
6099 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
6100 }
6101 
6102 static int swap_peak_show(struct seq_file *sf, void *v)
6103 {
6104 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
6105 
6106 	guard(spinlock)(&memcg->peaks_lock);
6107 	return peak_show(sf, v, &memcg->swap);
6108 }
6109 
6110 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
6111 			       size_t nbytes, loff_t off)
6112 {
6113 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6114 
6115 	return peak_write(of, buf, nbytes, off, &memcg->swap,
6116 			  &memcg->swap_peaks);
6117 }
6118 
6119 static int swap_high_show(struct seq_file *m, void *v)
6120 {
6121 	return seq_puts_memcg_tunable(m,
6122 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
6123 }
6124 
6125 static ssize_t swap_high_write(struct kernfs_open_file *of,
6126 			       char *buf, size_t nbytes, loff_t off)
6127 {
6128 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6129 	unsigned long high;
6130 	int err;
6131 
6132 	buf = strstrip(buf);
6133 	err = page_counter_memparse(buf, "max", &high);
6134 	if (err)
6135 		return err;
6136 
6137 	page_counter_set_high(&memcg->swap, high);
6138 
6139 	return nbytes;
6140 }
6141 
6142 static int swap_max_show(struct seq_file *m, void *v)
6143 {
6144 	return seq_puts_memcg_tunable(m,
6145 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
6146 }
6147 
6148 static ssize_t swap_max_write(struct kernfs_open_file *of,
6149 			      char *buf, size_t nbytes, loff_t off)
6150 {
6151 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6152 	unsigned long max;
6153 	int err;
6154 
6155 	buf = strstrip(buf);
6156 	err = page_counter_memparse(buf, "max", &max);
6157 	if (err)
6158 		return err;
6159 
6160 	xchg(&memcg->swap.max, max);
6161 
6162 	return nbytes;
6163 }
6164 
6165 static int swap_events_show(struct seq_file *m, void *v)
6166 {
6167 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6168 
6169 	seq_printf(m, "high %lu\n",
6170 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
6171 	seq_printf(m, "max %lu\n",
6172 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
6173 	seq_printf(m, "fail %lu\n",
6174 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
6175 
6176 	return 0;
6177 }
6178 
6179 static struct cftype swap_files[] = {
6180 	{
6181 		.name = "swap.current",
6182 		.flags = CFTYPE_NOT_ON_ROOT,
6183 		.read_u64 = swap_current_read,
6184 	},
6185 	{
6186 		.name = "swap.high",
6187 		.flags = CFTYPE_NOT_ON_ROOT,
6188 		.seq_show = swap_high_show,
6189 		.write = swap_high_write,
6190 	},
6191 	{
6192 		.name = "swap.max",
6193 		.flags = CFTYPE_NOT_ON_ROOT,
6194 		.seq_show = swap_max_show,
6195 		.write = swap_max_write,
6196 	},
6197 	{
6198 		.name = "swap.peak",
6199 		.flags = CFTYPE_NOT_ON_ROOT,
6200 		.open = peak_open,
6201 		.release = peak_release,
6202 		.seq_show = swap_peak_show,
6203 		.write = swap_peak_write,
6204 	},
6205 	{
6206 		.name = "swap.events",
6207 		.flags = CFTYPE_NOT_ON_ROOT,
6208 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
6209 		.seq_show = swap_events_show,
6210 	},
6211 	{ }	/* terminate */
6212 };
6213 
6214 #ifdef CONFIG_ZSWAP
6215 /**
6216  * obj_cgroup_may_zswap - check if this cgroup can zswap
6217  * @objcg: the object cgroup
6218  *
6219  * Check if the hierarchical zswap limit has been reached.
6220  *
6221  * This doesn't check for specific headroom, and it is not atomic
6222  * either. But with zswap, the size of the allocation is only known
6223  * once compression has occurred, and this optimistic pre-check avoids
6224  * spending cycles on compression when there is already no room left
6225  * or zswap is disabled altogether somewhere in the hierarchy.
6226  */
6227 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
6228 {
6229 	struct mem_cgroup *memcg, *original_memcg;
6230 	bool ret = true;
6231 
6232 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
6233 		return true;
6234 
6235 	original_memcg = get_mem_cgroup_from_objcg(objcg);
6236 	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
6237 	     memcg = parent_mem_cgroup(memcg)) {
6238 		unsigned long max = READ_ONCE(memcg->zswap_max);
6239 		unsigned long pages;
6240 
6241 		if (max == PAGE_COUNTER_MAX)
6242 			continue;
6243 		if (max == 0) {
6244 			ret = false;
6245 			break;
6246 		}
6247 
6248 		/* Force flush to get accurate stats for charging */
6249 		__mem_cgroup_flush_stats(memcg, true);
6250 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
6251 		if (pages < max)
6252 			continue;
6253 		ret = false;
6254 		break;
6255 	}
6256 	mem_cgroup_put(original_memcg);
6257 	return ret;
6258 }
6259 
6260 /**
6261  * obj_cgroup_charge_zswap - charge compression backend memory
6262  * @objcg: the object cgroup
6263  * @size: size of compressed object
6264  *
6265  * This forces the charge after obj_cgroup_may_zswap() allowed
6266  * compression and storage in zswap for this cgroup to go ahead.
6267  */
6268 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
6269 {
6270 	struct mem_cgroup *memcg;
6271 
6272 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
6273 		return;
6274 
6275 	if (obj_cgroup_is_root(objcg))
6276 		return;
6277 
6278 	VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
6279 
6280 	/* PF_MEMALLOC context, charging must succeed */
6281 	if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
6282 		VM_WARN_ON_ONCE(1);
6283 
6284 	rcu_read_lock();
6285 	memcg = obj_cgroup_memcg(objcg);
6286 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
6287 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
6288 	if (size == PAGE_SIZE)
6289 		mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, 1);
6290 	rcu_read_unlock();
6291 }
6292 
6293 /**
6294  * obj_cgroup_uncharge_zswap - uncharge compression backend memory
6295  * @objcg: the object cgroup
6296  * @size: size of compressed object
6297  *
6298  * Uncharges zswap memory on page in.
6299  */
6300 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
6301 {
6302 	struct mem_cgroup *memcg;
6303 
6304 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
6305 		return;
6306 
6307 	if (obj_cgroup_is_root(objcg))
6308 		return;
6309 
6310 	obj_cgroup_uncharge(objcg, size);
6311 
6312 	rcu_read_lock();
6313 	memcg = obj_cgroup_memcg(objcg);
6314 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
6315 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
6316 	if (size == PAGE_SIZE)
6317 		mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, -1);
6318 	rcu_read_unlock();
6319 }
6320 
6321 bool mem_cgroup_zswap_writeback_enabled(const struct mem_cgroup *memcg)
6322 {
6323 	/* if zswap is disabled, do not block pages going to the swapping device */
6324 	if (!zswap_is_enabled())
6325 		return true;
6326 
6327 	for (; memcg; memcg = parent_mem_cgroup(memcg))
6328 		if (!READ_ONCE(memcg->zswap_writeback))
6329 			return false;
6330 
6331 	return true;
6332 }
6333 
6334 static u64 zswap_current_read(struct cgroup_subsys_state *css,
6335 			      struct cftype *cft)
6336 {
6337 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6338 
6339 	mem_cgroup_flush_stats(memcg);
6340 	return memcg_page_state(memcg, MEMCG_ZSWAP_B);
6341 }
6342 
6343 static int zswap_max_show(struct seq_file *m, void *v)
6344 {
6345 	return seq_puts_memcg_tunable(m,
6346 		READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
6347 }
6348 
6349 static ssize_t zswap_max_write(struct kernfs_open_file *of,
6350 			       char *buf, size_t nbytes, loff_t off)
6351 {
6352 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6353 	unsigned long max;
6354 	int err;
6355 
6356 	buf = strstrip(buf);
6357 	err = page_counter_memparse(buf, "max", &max);
6358 	if (err)
6359 		return err;
6360 
6361 	xchg(&memcg->zswap_max, max);
6362 
6363 	return nbytes;
6364 }
6365 
6366 static int zswap_writeback_show(struct seq_file *m, void *v)
6367 {
6368 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6369 
6370 	seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
6371 	return 0;
6372 }
6373 
6374 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
6375 				char *buf, size_t nbytes, loff_t off)
6376 {
6377 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6378 	int zswap_writeback;
6379 	ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
6380 
6381 	if (parse_ret)
6382 		return parse_ret;
6383 
6384 	if (zswap_writeback != 0 && zswap_writeback != 1)
6385 		return -EINVAL;
6386 
6387 	WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
6388 	return nbytes;
6389 }
6390 
6391 static struct cftype zswap_files[] = {
6392 	{
6393 		.name = "zswap.current",
6394 		.flags = CFTYPE_NOT_ON_ROOT,
6395 		.read_u64 = zswap_current_read,
6396 	},
6397 	{
6398 		.name = "zswap.max",
6399 		.flags = CFTYPE_NOT_ON_ROOT,
6400 		.seq_show = zswap_max_show,
6401 		.write = zswap_max_write,
6402 	},
6403 	{
6404 		.name = "zswap.writeback",
6405 		.seq_show = zswap_writeback_show,
6406 		.write = zswap_writeback_write,
6407 	},
6408 	{ }	/* terminate */
6409 };
6410 #endif /* CONFIG_ZSWAP */
6411 
6412 static int __init mem_cgroup_swap_init(void)
6413 {
6414 	if (mem_cgroup_disabled())
6415 		return 0;
6416 
6417 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
6418 #ifdef CONFIG_MEMCG_V1
6419 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
6420 #endif
6421 #ifdef CONFIG_ZSWAP
6422 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
6423 #endif
6424 	return 0;
6425 }
6426 subsys_initcall(mem_cgroup_swap_init);
6427 
6428 #endif /* CONFIG_SWAP */
6429 
6430 void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask)
6431 {
6432 	nodemask_t allowed;
6433 
6434 	if (!memcg)
6435 		return;
6436 
6437 	/*
6438 	 * Since this interface is intended for use by migration paths, and
6439 	 * reclaim and migration are subject to race conditions such as changes
6440 	 * in effective_mems and hot-unpluging of nodes, inaccurate allowed
6441 	 * mask is acceptable.
6442 	 */
6443 	cpuset_nodes_allowed(memcg->css.cgroup, &allowed);
6444 	nodes_and(*mask, *mask, allowed);
6445 }
6446 
6447 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
6448 {
6449 	if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
6450 		return;
6451 
6452 	if (!memcg)
6453 		memcg = root_mem_cgroup;
6454 
6455 	pr_warn("Memory cgroup min protection %lukB -- low protection %lukB",
6456 		K(atomic_long_read(&memcg->memory.children_min_usage)),
6457 		K(atomic_long_read(&memcg->memory.children_low_usage)));
6458 }
6459