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