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