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