xref: /linux/mm/memcontrol.c (revision c0cafe24d3f6534294c4b2bc2d47734ff7cbd313)
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/swap_cgroup.h>
58 #include <linux/cpu.h>
59 #include <linux/oom.h>
60 #include <linux/lockdep.h>
61 #include <linux/resume_user_mode.h>
62 #include <linux/psi.h>
63 #include <linux/seq_buf.h>
64 #include <linux/sched/isolation.h>
65 #include <linux/kmemleak.h>
66 #include "internal.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 == stock->cached_objcg
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 	 * 5) CPU0: we do release this object,
160 	 *          92 bytes are added to stock->nr_bytes
161 	 * 6) 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 struct obj_stock_pcp {
2022 	local_trylock_t lock;
2023 	unsigned int nr_bytes;
2024 	struct obj_cgroup *cached_objcg;
2025 	struct pglist_data *cached_pgdat;
2026 	int nr_slab_reclaimable_b;
2027 	int nr_slab_unreclaimable_b;
2028 
2029 	struct work_struct work;
2030 	unsigned long flags;
2031 };
2032 
2033 static DEFINE_PER_CPU_ALIGNED(struct obj_stock_pcp, obj_stock) = {
2034 	.lock = INIT_LOCAL_TRYLOCK(lock),
2035 };
2036 
2037 static DEFINE_MUTEX(percpu_charge_mutex);
2038 
2039 static void drain_obj_stock(struct obj_stock_pcp *stock);
2040 static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
2041 				     struct mem_cgroup *root_memcg);
2042 
2043 /**
2044  * consume_stock: Try to consume stocked charge on this cpu.
2045  * @memcg: memcg to consume from.
2046  * @nr_pages: how many pages to charge.
2047  *
2048  * Consume the cached charge if enough nr_pages are present otherwise return
2049  * failure. Also return failure for charge request larger than
2050  * MEMCG_CHARGE_BATCH or if the local lock is already taken.
2051  *
2052  * returns true if successful, false otherwise.
2053  */
2054 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2055 {
2056 	struct memcg_stock_pcp *stock;
2057 	uint8_t stock_pages;
2058 	bool ret = false;
2059 	int i;
2060 
2061 	if (nr_pages > MEMCG_CHARGE_BATCH ||
2062 	    !local_trylock(&memcg_stock.lock))
2063 		return ret;
2064 
2065 	stock = this_cpu_ptr(&memcg_stock);
2066 
2067 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2068 		if (memcg != READ_ONCE(stock->cached[i]))
2069 			continue;
2070 
2071 		stock_pages = READ_ONCE(stock->nr_pages[i]);
2072 		if (stock_pages >= nr_pages) {
2073 			WRITE_ONCE(stock->nr_pages[i], stock_pages - nr_pages);
2074 			ret = true;
2075 		}
2076 		break;
2077 	}
2078 
2079 	local_unlock(&memcg_stock.lock);
2080 
2081 	return ret;
2082 }
2083 
2084 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
2085 {
2086 	page_counter_uncharge(&memcg->memory, nr_pages);
2087 	if (do_memsw_account())
2088 		page_counter_uncharge(&memcg->memsw, nr_pages);
2089 }
2090 
2091 /*
2092  * Returns stocks cached in percpu and reset cached information.
2093  */
2094 static void drain_stock(struct memcg_stock_pcp *stock, int i)
2095 {
2096 	struct mem_cgroup *old = READ_ONCE(stock->cached[i]);
2097 	uint8_t stock_pages;
2098 
2099 	if (!old)
2100 		return;
2101 
2102 	stock_pages = READ_ONCE(stock->nr_pages[i]);
2103 	if (stock_pages) {
2104 		memcg_uncharge(old, stock_pages);
2105 		WRITE_ONCE(stock->nr_pages[i], 0);
2106 	}
2107 
2108 	css_put(&old->css);
2109 	WRITE_ONCE(stock->cached[i], NULL);
2110 }
2111 
2112 static void drain_stock_fully(struct memcg_stock_pcp *stock)
2113 {
2114 	int i;
2115 
2116 	for (i = 0; i < NR_MEMCG_STOCK; ++i)
2117 		drain_stock(stock, i);
2118 }
2119 
2120 static void drain_local_memcg_stock(struct work_struct *dummy)
2121 {
2122 	struct memcg_stock_pcp *stock;
2123 
2124 	if (WARN_ONCE(!in_task(), "drain in non-task context"))
2125 		return;
2126 
2127 	local_lock(&memcg_stock.lock);
2128 
2129 	stock = this_cpu_ptr(&memcg_stock);
2130 	drain_stock_fully(stock);
2131 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2132 
2133 	local_unlock(&memcg_stock.lock);
2134 }
2135 
2136 static void drain_local_obj_stock(struct work_struct *dummy)
2137 {
2138 	struct obj_stock_pcp *stock;
2139 
2140 	if (WARN_ONCE(!in_task(), "drain in non-task context"))
2141 		return;
2142 
2143 	local_lock(&obj_stock.lock);
2144 
2145 	stock = this_cpu_ptr(&obj_stock);
2146 	drain_obj_stock(stock);
2147 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2148 
2149 	local_unlock(&obj_stock.lock);
2150 }
2151 
2152 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2153 {
2154 	struct memcg_stock_pcp *stock;
2155 	struct mem_cgroup *cached;
2156 	uint8_t stock_pages;
2157 	bool success = false;
2158 	int empty_slot = -1;
2159 	int i;
2160 
2161 	/*
2162 	 * For now limit MEMCG_CHARGE_BATCH to 127 and less. In future if we
2163 	 * decide to increase it more than 127 then we will need more careful
2164 	 * handling of nr_pages[] in struct memcg_stock_pcp.
2165 	 */
2166 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S8_MAX);
2167 
2168 	VM_WARN_ON_ONCE(mem_cgroup_is_root(memcg));
2169 
2170 	if (nr_pages > MEMCG_CHARGE_BATCH ||
2171 	    !local_trylock(&memcg_stock.lock)) {
2172 		/*
2173 		 * In case of larger than batch refill or unlikely failure to
2174 		 * lock the percpu memcg_stock.lock, uncharge memcg directly.
2175 		 */
2176 		memcg_uncharge(memcg, nr_pages);
2177 		return;
2178 	}
2179 
2180 	stock = this_cpu_ptr(&memcg_stock);
2181 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2182 		cached = READ_ONCE(stock->cached[i]);
2183 		if (!cached && empty_slot == -1)
2184 			empty_slot = i;
2185 		if (memcg == READ_ONCE(stock->cached[i])) {
2186 			stock_pages = READ_ONCE(stock->nr_pages[i]) + nr_pages;
2187 			WRITE_ONCE(stock->nr_pages[i], stock_pages);
2188 			if (stock_pages > MEMCG_CHARGE_BATCH)
2189 				drain_stock(stock, i);
2190 			success = true;
2191 			break;
2192 		}
2193 	}
2194 
2195 	if (!success) {
2196 		i = empty_slot;
2197 		if (i == -1) {
2198 			i = stock->drain_idx++;
2199 			if (stock->drain_idx == NR_MEMCG_STOCK)
2200 				stock->drain_idx = 0;
2201 			drain_stock(stock, i);
2202 		}
2203 		css_get(&memcg->css);
2204 		WRITE_ONCE(stock->cached[i], memcg);
2205 		WRITE_ONCE(stock->nr_pages[i], nr_pages);
2206 	}
2207 
2208 	local_unlock(&memcg_stock.lock);
2209 }
2210 
2211 static bool is_memcg_drain_needed(struct memcg_stock_pcp *stock,
2212 				  struct mem_cgroup *root_memcg)
2213 {
2214 	struct mem_cgroup *memcg;
2215 	bool flush = false;
2216 	int i;
2217 
2218 	rcu_read_lock();
2219 	for (i = 0; i < NR_MEMCG_STOCK; ++i) {
2220 		memcg = READ_ONCE(stock->cached[i]);
2221 		if (!memcg)
2222 			continue;
2223 
2224 		if (READ_ONCE(stock->nr_pages[i]) &&
2225 		    mem_cgroup_is_descendant(memcg, root_memcg)) {
2226 			flush = true;
2227 			break;
2228 		}
2229 	}
2230 	rcu_read_unlock();
2231 	return flush;
2232 }
2233 
2234 static void schedule_drain_work(int cpu, struct work_struct *work)
2235 {
2236 	/*
2237 	 * Protect housekeeping cpumask read and work enqueue together
2238 	 * in the same RCU critical section so that later cpuset isolated
2239 	 * partition update only need to wait for an RCU GP and flush the
2240 	 * pending work on newly isolated CPUs.
2241 	 */
2242 	guard(rcu)();
2243 	if (!cpu_is_isolated(cpu))
2244 		queue_work_on(cpu, memcg_wq, work);
2245 }
2246 
2247 /*
2248  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2249  * of the hierarchy under it.
2250  */
2251 void drain_all_stock(struct mem_cgroup *root_memcg)
2252 {
2253 	int cpu, curcpu;
2254 
2255 	/* If someone's already draining, avoid adding running more workers. */
2256 	if (!mutex_trylock(&percpu_charge_mutex))
2257 		return;
2258 	/*
2259 	 * Notify other cpus that system-wide "drain" is running
2260 	 * We do not care about races with the cpu hotplug because cpu down
2261 	 * as well as workers from this path always operate on the local
2262 	 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2263 	 */
2264 	migrate_disable();
2265 	curcpu = smp_processor_id();
2266 	for_each_online_cpu(cpu) {
2267 		struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu);
2268 		struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu);
2269 
2270 		if (!test_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags) &&
2271 		    is_memcg_drain_needed(memcg_st, root_memcg) &&
2272 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE,
2273 				      &memcg_st->flags)) {
2274 			if (cpu == curcpu)
2275 				drain_local_memcg_stock(&memcg_st->work);
2276 			else
2277 				schedule_drain_work(cpu, &memcg_st->work);
2278 		}
2279 
2280 		if (!test_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags) &&
2281 		    obj_stock_flush_required(obj_st, root_memcg) &&
2282 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE,
2283 				      &obj_st->flags)) {
2284 			if (cpu == curcpu)
2285 				drain_local_obj_stock(&obj_st->work);
2286 			else
2287 				schedule_drain_work(cpu, &obj_st->work);
2288 		}
2289 	}
2290 	migrate_enable();
2291 	mutex_unlock(&percpu_charge_mutex);
2292 }
2293 
2294 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2295 {
2296 	/* no need for the local lock */
2297 	drain_obj_stock(&per_cpu(obj_stock, cpu));
2298 	drain_stock_fully(&per_cpu(memcg_stock, cpu));
2299 
2300 	return 0;
2301 }
2302 
2303 static unsigned long reclaim_high(struct mem_cgroup *memcg,
2304 				  unsigned int nr_pages,
2305 				  gfp_t gfp_mask)
2306 {
2307 	unsigned long nr_reclaimed = 0;
2308 
2309 	do {
2310 		unsigned long pflags;
2311 
2312 		if (page_counter_read(&memcg->memory) <=
2313 		    READ_ONCE(memcg->memory.high))
2314 			continue;
2315 
2316 		memcg_memory_event(memcg, MEMCG_HIGH);
2317 
2318 		psi_memstall_enter(&pflags);
2319 		nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
2320 							gfp_mask,
2321 							MEMCG_RECLAIM_MAY_SWAP,
2322 							NULL);
2323 		psi_memstall_leave(&pflags);
2324 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2325 		 !mem_cgroup_is_root(memcg));
2326 
2327 	return nr_reclaimed;
2328 }
2329 
2330 static void high_work_func(struct work_struct *work)
2331 {
2332 	struct mem_cgroup *memcg;
2333 
2334 	memcg = container_of(work, struct mem_cgroup, high_work);
2335 	reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2336 }
2337 
2338 /*
2339  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2340  * enough to still cause a significant slowdown in most cases, while still
2341  * allowing diagnostics and tracing to proceed without becoming stuck.
2342  */
2343 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2344 
2345 /*
2346  * When calculating the delay, we use these either side of the exponentiation to
2347  * maintain precision and scale to a reasonable number of jiffies (see the table
2348  * below.
2349  *
2350  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2351  *   overage ratio to a delay.
2352  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2353  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2354  *   to produce a reasonable delay curve.
2355  *
2356  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2357  * reasonable delay curve compared to precision-adjusted overage, not
2358  * penalising heavily at first, but still making sure that growth beyond the
2359  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2360  * example, with a high of 100 megabytes:
2361  *
2362  *  +-------+------------------------+
2363  *  | usage | time to allocate in ms |
2364  *  +-------+------------------------+
2365  *  | 100M  |                      0 |
2366  *  | 101M  |                      6 |
2367  *  | 102M  |                     25 |
2368  *  | 103M  |                     57 |
2369  *  | 104M  |                    102 |
2370  *  | 105M  |                    159 |
2371  *  | 106M  |                    230 |
2372  *  | 107M  |                    313 |
2373  *  | 108M  |                    409 |
2374  *  | 109M  |                    518 |
2375  *  | 110M  |                    639 |
2376  *  | 111M  |                    774 |
2377  *  | 112M  |                    921 |
2378  *  | 113M  |                   1081 |
2379  *  | 114M  |                   1254 |
2380  *  | 115M  |                   1439 |
2381  *  | 116M  |                   1638 |
2382  *  | 117M  |                   1849 |
2383  *  | 118M  |                   2000 |
2384  *  | 119M  |                   2000 |
2385  *  | 120M  |                   2000 |
2386  *  +-------+------------------------+
2387  */
2388  #define MEMCG_DELAY_PRECISION_SHIFT 20
2389  #define MEMCG_DELAY_SCALING_SHIFT 14
2390 
2391 static u64 calculate_overage(unsigned long usage, unsigned long high)
2392 {
2393 	u64 overage;
2394 
2395 	if (usage <= high)
2396 		return 0;
2397 
2398 	/*
2399 	 * Prevent division by 0 in overage calculation by acting as if
2400 	 * it was a threshold of 1 page
2401 	 */
2402 	high = max(high, 1UL);
2403 
2404 	overage = usage - high;
2405 	overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2406 	return div64_u64(overage, high);
2407 }
2408 
2409 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2410 {
2411 	u64 overage, max_overage = 0;
2412 
2413 	do {
2414 		overage = calculate_overage(page_counter_read(&memcg->memory),
2415 					    READ_ONCE(memcg->memory.high));
2416 		max_overage = max(overage, max_overage);
2417 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2418 		 !mem_cgroup_is_root(memcg));
2419 
2420 	return max_overage;
2421 }
2422 
2423 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2424 {
2425 	u64 overage, max_overage = 0;
2426 
2427 	do {
2428 		overage = calculate_overage(page_counter_read(&memcg->swap),
2429 					    READ_ONCE(memcg->swap.high));
2430 		if (overage)
2431 			memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2432 		max_overage = max(overage, max_overage);
2433 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2434 		 !mem_cgroup_is_root(memcg));
2435 
2436 	return max_overage;
2437 }
2438 
2439 /*
2440  * Get the number of jiffies that we should penalise a mischievous cgroup which
2441  * is exceeding its memory.high by checking both it and its ancestors.
2442  */
2443 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2444 					  unsigned int nr_pages,
2445 					  u64 max_overage)
2446 {
2447 	unsigned long penalty_jiffies;
2448 
2449 	if (!max_overage)
2450 		return 0;
2451 
2452 	/*
2453 	 * We use overage compared to memory.high to calculate the number of
2454 	 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2455 	 * fairly lenient on small overages, and increasingly harsh when the
2456 	 * memcg in question makes it clear that it has no intention of stopping
2457 	 * its crazy behaviour, so we exponentially increase the delay based on
2458 	 * overage amount.
2459 	 */
2460 	penalty_jiffies = max_overage * max_overage * HZ;
2461 	penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2462 	penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2463 
2464 	/*
2465 	 * Factor in the task's own contribution to the overage, such that four
2466 	 * N-sized allocations are throttled approximately the same as one
2467 	 * 4N-sized allocation.
2468 	 *
2469 	 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2470 	 * larger the current charge patch is than that.
2471 	 */
2472 	return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2473 }
2474 
2475 /*
2476  * Reclaims memory over the high limit. Called directly from
2477  * try_charge() (context permitting), as well as from the userland
2478  * return path where reclaim is always able to block.
2479  */
2480 void __mem_cgroup_handle_over_high(gfp_t gfp_mask)
2481 {
2482 	unsigned long penalty_jiffies;
2483 	unsigned long pflags;
2484 	unsigned long nr_reclaimed;
2485 	unsigned int nr_pages = current->memcg_nr_pages_over_high;
2486 	int nr_retries = MAX_RECLAIM_RETRIES;
2487 	struct mem_cgroup *memcg;
2488 	bool in_retry = false;
2489 
2490 	memcg = get_mem_cgroup_from_mm(current->mm);
2491 	current->memcg_nr_pages_over_high = 0;
2492 
2493 retry_reclaim:
2494 	/*
2495 	 * Bail if the task is already exiting. Unlike memory.max,
2496 	 * memory.high enforcement isn't as strict, and there is no
2497 	 * OOM killer involved, which means the excess could already
2498 	 * be much bigger (and still growing) than it could for
2499 	 * memory.max; the dying task could get stuck in fruitless
2500 	 * reclaim for a long time, which isn't desirable.
2501 	 */
2502 	if (task_is_dying())
2503 		goto out;
2504 
2505 	/*
2506 	 * The allocating task should reclaim at least the batch size, but for
2507 	 * subsequent retries we only want to do what's necessary to prevent oom
2508 	 * or breaching resource isolation.
2509 	 *
2510 	 * This is distinct from memory.max or page allocator behaviour because
2511 	 * memory.high is currently batched, whereas memory.max and the page
2512 	 * allocator run every time an allocation is made.
2513 	 */
2514 	nr_reclaimed = reclaim_high(memcg,
2515 				    in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2516 				    gfp_mask);
2517 
2518 	/*
2519 	 * memory.high is breached and reclaim is unable to keep up. Throttle
2520 	 * allocators proactively to slow down excessive growth.
2521 	 */
2522 	penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2523 					       mem_find_max_overage(memcg));
2524 
2525 	penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2526 						swap_find_max_overage(memcg));
2527 
2528 	/*
2529 	 * Clamp the max delay per usermode return so as to still keep the
2530 	 * application moving forwards and also permit diagnostics, albeit
2531 	 * extremely slowly.
2532 	 */
2533 	penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2534 
2535 	/*
2536 	 * Don't sleep if the amount of jiffies this memcg owes us is so low
2537 	 * that it's not even worth doing, in an attempt to be nice to those who
2538 	 * go only a small amount over their memory.high value and maybe haven't
2539 	 * been aggressively reclaimed enough yet.
2540 	 */
2541 	if (penalty_jiffies <= HZ / 100)
2542 		goto out;
2543 
2544 	/*
2545 	 * If reclaim is making forward progress but we're still over
2546 	 * memory.high, we want to encourage that rather than doing allocator
2547 	 * throttling.
2548 	 */
2549 	if (nr_reclaimed || nr_retries--) {
2550 		in_retry = true;
2551 		goto retry_reclaim;
2552 	}
2553 
2554 	/*
2555 	 * Reclaim didn't manage to push usage below the limit, slow
2556 	 * this allocating task down.
2557 	 *
2558 	 * If we exit early, we're guaranteed to die (since
2559 	 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2560 	 * need to account for any ill-begotten jiffies to pay them off later.
2561 	 */
2562 	psi_memstall_enter(&pflags);
2563 	schedule_timeout_killable(penalty_jiffies);
2564 	psi_memstall_leave(&pflags);
2565 
2566 out:
2567 	css_put(&memcg->css);
2568 }
2569 
2570 static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2571 			    unsigned int nr_pages)
2572 {
2573 	unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2574 	int nr_retries = MAX_RECLAIM_RETRIES;
2575 	struct mem_cgroup *mem_over_limit;
2576 	struct page_counter *counter;
2577 	unsigned long nr_reclaimed;
2578 	bool passed_oom = false;
2579 	unsigned int reclaim_options;
2580 	bool drained = false;
2581 	bool raised_max_event = false;
2582 	unsigned long pflags;
2583 	bool allow_spinning = gfpflags_allow_spinning(gfp_mask);
2584 
2585 retry:
2586 	if (consume_stock(memcg, nr_pages))
2587 		return 0;
2588 
2589 	if (!allow_spinning)
2590 		/* Avoid the refill and flush of the older stock */
2591 		batch = nr_pages;
2592 
2593 	reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2594 	if (!do_memsw_account() ||
2595 	    page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2596 		if (page_counter_try_charge(&memcg->memory, batch, &counter))
2597 			goto done_restock;
2598 		if (do_memsw_account())
2599 			page_counter_uncharge(&memcg->memsw, batch);
2600 		mem_over_limit = mem_cgroup_from_counter(counter, memory);
2601 	} else {
2602 		mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2603 		reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2604 	}
2605 
2606 	if (batch > nr_pages) {
2607 		batch = nr_pages;
2608 		goto retry;
2609 	}
2610 
2611 	/*
2612 	 * Prevent unbounded recursion when reclaim operations need to
2613 	 * allocate memory. This might exceed the limits temporarily,
2614 	 * but we prefer facilitating memory reclaim and getting back
2615 	 * under the limit over triggering OOM kills in these cases.
2616 	 */
2617 	if (unlikely(current->flags & PF_MEMALLOC))
2618 		goto force;
2619 
2620 	if (unlikely(task_in_memcg_oom(current)))
2621 		goto nomem;
2622 
2623 	if (!gfpflags_allow_blocking(gfp_mask))
2624 		goto nomem;
2625 
2626 	__memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
2627 	raised_max_event = true;
2628 
2629 	psi_memstall_enter(&pflags);
2630 	nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2631 						    gfp_mask, reclaim_options, NULL);
2632 	psi_memstall_leave(&pflags);
2633 
2634 	if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2635 		goto retry;
2636 
2637 	if (!drained) {
2638 		drain_all_stock(mem_over_limit);
2639 		drained = true;
2640 		goto retry;
2641 	}
2642 
2643 	if (gfp_mask & __GFP_NORETRY)
2644 		goto nomem;
2645 	/*
2646 	 * Even though the limit is exceeded at this point, reclaim
2647 	 * may have been able to free some pages.  Retry the charge
2648 	 * before killing the task.
2649 	 *
2650 	 * Only for regular pages, though: huge pages are rather
2651 	 * unlikely to succeed so close to the limit, and we fall back
2652 	 * to regular pages anyway in case of failure.
2653 	 */
2654 	if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2655 		goto retry;
2656 
2657 	if (nr_retries--)
2658 		goto retry;
2659 
2660 	if (gfp_mask & __GFP_RETRY_MAYFAIL)
2661 		goto nomem;
2662 
2663 	/* Avoid endless loop for tasks bypassed by the oom killer */
2664 	if (passed_oom && task_is_dying())
2665 		goto nomem;
2666 
2667 	/*
2668 	 * keep retrying as long as the memcg oom killer is able to make
2669 	 * a forward progress or bypass the charge if the oom killer
2670 	 * couldn't make any progress.
2671 	 */
2672 	if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2673 			   get_order(nr_pages * PAGE_SIZE))) {
2674 		passed_oom = true;
2675 		nr_retries = MAX_RECLAIM_RETRIES;
2676 		goto retry;
2677 	}
2678 nomem:
2679 	/*
2680 	 * Memcg doesn't have a dedicated reserve for atomic
2681 	 * allocations. But like the global atomic pool, we need to
2682 	 * put the burden of reclaim on regular allocation requests
2683 	 * and let these go through as privileged allocations.
2684 	 */
2685 	if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2686 		return -ENOMEM;
2687 force:
2688 	/*
2689 	 * If the allocation has to be enforced, don't forget to raise
2690 	 * a MEMCG_MAX event.
2691 	 */
2692 	if (!raised_max_event)
2693 		__memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
2694 
2695 	/*
2696 	 * The allocation either can't fail or will lead to more memory
2697 	 * being freed very soon.  Allow memory usage go over the limit
2698 	 * temporarily by force charging it.
2699 	 */
2700 	page_counter_charge(&memcg->memory, nr_pages);
2701 	if (do_memsw_account())
2702 		page_counter_charge(&memcg->memsw, nr_pages);
2703 
2704 	return 0;
2705 
2706 done_restock:
2707 	if (batch > nr_pages)
2708 		refill_stock(memcg, batch - nr_pages);
2709 
2710 	/*
2711 	 * If the hierarchy is above the normal consumption range, schedule
2712 	 * reclaim on returning to userland.  We can perform reclaim here
2713 	 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2714 	 * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2715 	 * not recorded as it most likely matches current's and won't
2716 	 * change in the meantime.  As high limit is checked again before
2717 	 * reclaim, the cost of mismatch is negligible.
2718 	 */
2719 	do {
2720 		bool mem_high, swap_high;
2721 
2722 		mem_high = page_counter_read(&memcg->memory) >
2723 			READ_ONCE(memcg->memory.high);
2724 		swap_high = page_counter_read(&memcg->swap) >
2725 			READ_ONCE(memcg->swap.high);
2726 
2727 		/* Don't bother a random interrupted task */
2728 		if (!in_task()) {
2729 			if (mem_high) {
2730 				schedule_work(&memcg->high_work);
2731 				break;
2732 			}
2733 			continue;
2734 		}
2735 
2736 		if (mem_high || swap_high) {
2737 			/*
2738 			 * The allocating tasks in this cgroup will need to do
2739 			 * reclaim or be throttled to prevent further growth
2740 			 * of the memory or swap footprints.
2741 			 *
2742 			 * Target some best-effort fairness between the tasks,
2743 			 * and distribute reclaim work and delay penalties
2744 			 * based on how much each task is actually allocating.
2745 			 */
2746 			current->memcg_nr_pages_over_high += batch;
2747 			set_notify_resume(current);
2748 			break;
2749 		}
2750 	} while ((memcg = parent_mem_cgroup(memcg)));
2751 
2752 	/*
2753 	 * Reclaim is set up above to be called from the userland
2754 	 * return path. But also attempt synchronous reclaim to avoid
2755 	 * excessive overrun while the task is still inside the
2756 	 * kernel. If this is successful, the return path will see it
2757 	 * when it rechecks the overage and simply bail out.
2758 	 */
2759 	if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2760 	    !(current->flags & PF_MEMALLOC) &&
2761 	    gfpflags_allow_blocking(gfp_mask))
2762 		__mem_cgroup_handle_over_high(gfp_mask);
2763 	return 0;
2764 }
2765 
2766 static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2767 			     unsigned int nr_pages)
2768 {
2769 	if (mem_cgroup_is_root(memcg))
2770 		return 0;
2771 
2772 	return try_charge_memcg(memcg, gfp_mask, nr_pages);
2773 }
2774 
2775 static void commit_charge(struct folio *folio, struct obj_cgroup *objcg)
2776 {
2777 	VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
2778 	/*
2779 	 * Any of the following ensures folio's objcg stability:
2780 	 *
2781 	 * - the page lock
2782 	 * - LRU isolation
2783 	 * - exclusive reference
2784 	 */
2785 	folio->memcg_data = (unsigned long)objcg;
2786 }
2787 
2788 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
2789 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2790 					 struct pglist_data *pgdat,
2791 					 enum node_stat_item idx, int nr)
2792 {
2793 	struct lruvec *lruvec;
2794 
2795 	if (likely(!in_nmi())) {
2796 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
2797 		mod_memcg_lruvec_state(lruvec, idx, nr);
2798 	} else {
2799 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id];
2800 
2801 		/* preemption is disabled in_nmi(). */
2802 		__css_rstat_updated(&memcg->css, smp_processor_id());
2803 		if (idx == NR_SLAB_RECLAIMABLE_B)
2804 			atomic_add(nr, &pn->slab_reclaimable);
2805 		else
2806 			atomic_add(nr, &pn->slab_unreclaimable);
2807 	}
2808 }
2809 #else
2810 static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
2811 					 struct pglist_data *pgdat,
2812 					 enum node_stat_item idx, int nr)
2813 {
2814 	struct lruvec *lruvec;
2815 
2816 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
2817 	mod_memcg_lruvec_state(lruvec, idx, nr);
2818 }
2819 #endif
2820 
2821 static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
2822 				       struct pglist_data *pgdat,
2823 				       enum node_stat_item idx, int nr)
2824 {
2825 	struct mem_cgroup *memcg;
2826 
2827 	rcu_read_lock();
2828 	memcg = obj_cgroup_memcg(objcg);
2829 	account_slab_nmi_safe(memcg, pgdat, idx, nr);
2830 	rcu_read_unlock();
2831 }
2832 
2833 static __always_inline
2834 struct mem_cgroup *mem_cgroup_from_obj_slab(struct slab *slab, void *p)
2835 {
2836 	/*
2837 	 * Slab objects are accounted individually, not per-page.
2838 	 * Memcg membership data for each individual object is saved in
2839 	 * slab->obj_exts.
2840 	 */
2841 	unsigned long obj_exts;
2842 	struct slabobj_ext *obj_ext;
2843 	unsigned int off;
2844 
2845 	obj_exts = slab_obj_exts(slab);
2846 	if (!obj_exts)
2847 		return NULL;
2848 
2849 	get_slab_obj_exts(obj_exts);
2850 	off = obj_to_index(slab->slab_cache, slab, p);
2851 	obj_ext = slab_obj_ext(slab, obj_exts, off);
2852 	if (obj_ext->objcg) {
2853 		struct obj_cgroup *objcg = obj_ext->objcg;
2854 
2855 		put_slab_obj_exts(obj_exts);
2856 		return obj_cgroup_memcg(objcg);
2857 	}
2858 	put_slab_obj_exts(obj_exts);
2859 
2860 	return NULL;
2861 }
2862 
2863 /*
2864  * Returns a pointer to the memory cgroup to which the kernel object is charged.
2865  * It is not suitable for objects allocated using vmalloc().
2866  *
2867  * A passed kernel object must be a slab object or a generic kernel page.
2868  *
2869  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2870  * cgroup_mutex, etc.
2871  */
2872 struct mem_cgroup *mem_cgroup_from_virt(void *p)
2873 {
2874 	struct slab *slab;
2875 
2876 	if (mem_cgroup_disabled())
2877 		return NULL;
2878 
2879 	slab = virt_to_slab(p);
2880 	if (slab)
2881 		return mem_cgroup_from_obj_slab(slab, p);
2882 	return folio_memcg_check(virt_to_folio(p));
2883 }
2884 
2885 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2886 {
2887 	int nid = numa_node_id();
2888 
2889 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2890 		struct obj_cgroup *objcg = rcu_dereference(memcg->nodeinfo[nid]->objcg);
2891 
2892 		if (likely(objcg && obj_cgroup_tryget(objcg)))
2893 			return objcg;
2894 	}
2895 
2896 	return NULL;
2897 }
2898 
2899 static inline struct obj_cgroup *get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2900 {
2901 	struct obj_cgroup *objcg;
2902 
2903 	rcu_read_lock();
2904 	objcg = __get_obj_cgroup_from_memcg(memcg);
2905 	rcu_read_unlock();
2906 
2907 	return objcg;
2908 }
2909 
2910 static struct obj_cgroup *current_objcg_update(void)
2911 {
2912 	struct mem_cgroup *memcg;
2913 	struct obj_cgroup *old, *objcg = NULL;
2914 
2915 	do {
2916 		/* Atomically drop the update bit. */
2917 		old = xchg(&current->objcg, NULL);
2918 		if (old) {
2919 			old = (struct obj_cgroup *)
2920 				((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
2921 			obj_cgroup_put(old);
2922 
2923 			old = NULL;
2924 		}
2925 
2926 		/* If new objcg is NULL, no reason for the second atomic update. */
2927 		if (!current->mm || (current->flags & PF_KTHREAD))
2928 			return NULL;
2929 
2930 		/*
2931 		 * Release the objcg pointer from the previous iteration,
2932 		 * if try_cmpxcg() below fails.
2933 		 */
2934 		if (unlikely(objcg)) {
2935 			obj_cgroup_put(objcg);
2936 			objcg = NULL;
2937 		}
2938 
2939 		/*
2940 		 * Obtain the new objcg pointer. The current task can be
2941 		 * asynchronously moved to another memcg and the previous
2942 		 * memcg can be offlined. So let's get the memcg pointer
2943 		 * and try get a reference to objcg under a rcu read lock.
2944 		 */
2945 
2946 		rcu_read_lock();
2947 		memcg = mem_cgroup_from_task(current);
2948 		objcg = __get_obj_cgroup_from_memcg(memcg);
2949 		rcu_read_unlock();
2950 
2951 		/*
2952 		 * Try set up a new objcg pointer atomically. If it
2953 		 * fails, it means the update flag was set concurrently, so
2954 		 * the whole procedure should be repeated.
2955 		 */
2956 	} while (!try_cmpxchg(&current->objcg, &old, objcg));
2957 
2958 	return objcg;
2959 }
2960 
2961 __always_inline struct obj_cgroup *current_obj_cgroup(void)
2962 {
2963 	struct mem_cgroup *memcg;
2964 	struct obj_cgroup *objcg;
2965 	int nid = numa_node_id();
2966 
2967 	if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi())
2968 		return NULL;
2969 
2970 	if (in_task()) {
2971 		memcg = current->active_memcg;
2972 		if (unlikely(memcg))
2973 			goto from_memcg;
2974 
2975 		objcg = READ_ONCE(current->objcg);
2976 		if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
2977 			objcg = current_objcg_update();
2978 		/*
2979 		 * Objcg reference is kept by the task, so it's safe
2980 		 * to use the objcg by the current task.
2981 		 */
2982 		return objcg ? : rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
2983 	}
2984 
2985 	memcg = this_cpu_read(int_active_memcg);
2986 	if (unlikely(memcg))
2987 		goto from_memcg;
2988 
2989 	return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
2990 
2991 from_memcg:
2992 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2993 		/*
2994 		 * Memcg pointer is protected by scope (see set_active_memcg())
2995 		 * and is pinning the corresponding objcg, so objcg can't go
2996 		 * away and can be used within the scope without any additional
2997 		 * protection.
2998 		 */
2999 		objcg = rcu_dereference_check(memcg->nodeinfo[nid]->objcg, 1);
3000 		if (likely(objcg))
3001 			return objcg;
3002 	}
3003 
3004 	return rcu_dereference_check(root_mem_cgroup->nodeinfo[nid]->objcg, 1);
3005 }
3006 
3007 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
3008 {
3009 	struct obj_cgroup *objcg;
3010 
3011 	objcg = folio_objcg(folio);
3012 	if (objcg)
3013 		obj_cgroup_get(objcg);
3014 
3015 	return objcg;
3016 }
3017 
3018 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
3019 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
3020 {
3021 	if (likely(!in_nmi())) {
3022 		mod_memcg_state(memcg, MEMCG_KMEM, val);
3023 	} else {
3024 		/* preemption is disabled in_nmi(). */
3025 		__css_rstat_updated(&memcg->css, smp_processor_id());
3026 		atomic_add(val, &memcg->kmem_stat);
3027 	}
3028 }
3029 #else
3030 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
3031 {
3032 	mod_memcg_state(memcg, MEMCG_KMEM, val);
3033 }
3034 #endif
3035 
3036 /*
3037  * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
3038  * @objcg: object cgroup to uncharge
3039  * @nr_pages: number of pages to uncharge
3040  */
3041 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
3042 				      unsigned int nr_pages)
3043 {
3044 	struct mem_cgroup *memcg;
3045 
3046 	memcg = get_mem_cgroup_from_objcg(objcg);
3047 
3048 	account_kmem_nmi_safe(memcg, -nr_pages);
3049 	memcg1_account_kmem(memcg, -nr_pages);
3050 	if (!mem_cgroup_is_root(memcg))
3051 		refill_stock(memcg, nr_pages);
3052 
3053 	css_put(&memcg->css);
3054 }
3055 
3056 /*
3057  * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
3058  * @objcg: object cgroup to charge
3059  * @gfp: reclaim mode
3060  * @nr_pages: number of pages to charge
3061  *
3062  * Returns 0 on success, an error code on failure.
3063  */
3064 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
3065 				   unsigned int nr_pages)
3066 {
3067 	struct mem_cgroup *memcg;
3068 	int ret;
3069 
3070 	memcg = get_mem_cgroup_from_objcg(objcg);
3071 
3072 	ret = try_charge_memcg(memcg, gfp, nr_pages);
3073 	if (ret)
3074 		goto out;
3075 
3076 	account_kmem_nmi_safe(memcg, nr_pages);
3077 	memcg1_account_kmem(memcg, nr_pages);
3078 out:
3079 	css_put(&memcg->css);
3080 
3081 	return ret;
3082 }
3083 
3084 static struct obj_cgroup *page_objcg(const struct page *page)
3085 {
3086 	unsigned long memcg_data = page->memcg_data;
3087 
3088 	if (mem_cgroup_disabled() || !memcg_data)
3089 		return NULL;
3090 
3091 	VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM,
3092 			page);
3093 	return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM);
3094 }
3095 
3096 static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg)
3097 {
3098 	page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM;
3099 }
3100 
3101 /**
3102  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
3103  * @page: page to charge
3104  * @gfp: reclaim mode
3105  * @order: allocation order
3106  *
3107  * Returns 0 on success, an error code on failure.
3108  */
3109 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
3110 {
3111 	struct obj_cgroup *objcg;
3112 	int ret = 0;
3113 
3114 	objcg = current_obj_cgroup();
3115 	if (objcg && !obj_cgroup_is_root(objcg)) {
3116 		ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
3117 		if (!ret) {
3118 			obj_cgroup_get(objcg);
3119 			page_set_objcg(page, objcg);
3120 			return 0;
3121 		}
3122 	}
3123 	return ret;
3124 }
3125 
3126 /**
3127  * __memcg_kmem_uncharge_page: uncharge a kmem page
3128  * @page: page to uncharge
3129  * @order: allocation order
3130  */
3131 void __memcg_kmem_uncharge_page(struct page *page, int order)
3132 {
3133 	struct obj_cgroup *objcg = page_objcg(page);
3134 	unsigned int nr_pages = 1 << order;
3135 
3136 	if (!objcg)
3137 		return;
3138 
3139 	obj_cgroup_uncharge_pages(objcg, nr_pages);
3140 	page->memcg_data = 0;
3141 	obj_cgroup_put(objcg);
3142 }
3143 
3144 static struct obj_stock_pcp *trylock_stock(void)
3145 {
3146 	if (local_trylock(&obj_stock.lock))
3147 		return this_cpu_ptr(&obj_stock);
3148 
3149 	return NULL;
3150 }
3151 
3152 static void unlock_stock(struct obj_stock_pcp *stock)
3153 {
3154 	if (stock)
3155 		local_unlock(&obj_stock.lock);
3156 }
3157 
3158 /* Call after __refill_obj_stock() to ensure stock->cached_objg == objcg */
3159 static void __account_obj_stock(struct obj_cgroup *objcg,
3160 				struct obj_stock_pcp *stock, int nr,
3161 				struct pglist_data *pgdat, enum node_stat_item idx)
3162 {
3163 	int *bytes;
3164 
3165 	if (!stock || READ_ONCE(stock->cached_objcg) != objcg)
3166 		goto direct;
3167 
3168 	/*
3169 	 * Save vmstat data in stock and skip vmstat array update unless
3170 	 * accumulating over a page of vmstat data or when pgdat changes.
3171 	 */
3172 	if (stock->cached_pgdat != pgdat) {
3173 		/* Flush the existing cached vmstat data */
3174 		struct pglist_data *oldpg = stock->cached_pgdat;
3175 
3176 		if (stock->nr_slab_reclaimable_b) {
3177 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
3178 					  stock->nr_slab_reclaimable_b);
3179 			stock->nr_slab_reclaimable_b = 0;
3180 		}
3181 		if (stock->nr_slab_unreclaimable_b) {
3182 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
3183 					  stock->nr_slab_unreclaimable_b);
3184 			stock->nr_slab_unreclaimable_b = 0;
3185 		}
3186 		stock->cached_pgdat = pgdat;
3187 	}
3188 
3189 	bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
3190 					       : &stock->nr_slab_unreclaimable_b;
3191 	/*
3192 	 * Even for large object >= PAGE_SIZE, the vmstat data will still be
3193 	 * cached locally at least once before pushing it out.
3194 	 */
3195 	if (!*bytes) {
3196 		*bytes = nr;
3197 		nr = 0;
3198 	} else {
3199 		*bytes += nr;
3200 		if (abs(*bytes) > PAGE_SIZE) {
3201 			nr = *bytes;
3202 			*bytes = 0;
3203 		} else {
3204 			nr = 0;
3205 		}
3206 	}
3207 direct:
3208 	if (nr)
3209 		mod_objcg_mlstate(objcg, pgdat, idx, nr);
3210 }
3211 
3212 static bool __consume_obj_stock(struct obj_cgroup *objcg,
3213 				struct obj_stock_pcp *stock,
3214 				unsigned int nr_bytes)
3215 {
3216 	if (objcg == READ_ONCE(stock->cached_objcg) &&
3217 	    stock->nr_bytes >= nr_bytes) {
3218 		stock->nr_bytes -= nr_bytes;
3219 		return true;
3220 	}
3221 
3222 	return false;
3223 }
3224 
3225 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3226 {
3227 	struct obj_stock_pcp *stock;
3228 	bool ret = false;
3229 
3230 	stock = trylock_stock();
3231 	if (!stock)
3232 		return ret;
3233 
3234 	ret = __consume_obj_stock(objcg, stock, nr_bytes);
3235 	unlock_stock(stock);
3236 
3237 	return ret;
3238 }
3239 
3240 static void drain_obj_stock(struct obj_stock_pcp *stock)
3241 {
3242 	struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3243 
3244 	if (!old)
3245 		return;
3246 
3247 	if (stock->nr_bytes) {
3248 		unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3249 		unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3250 
3251 		if (nr_pages) {
3252 			struct mem_cgroup *memcg;
3253 
3254 			memcg = get_mem_cgroup_from_objcg(old);
3255 
3256 			mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
3257 			memcg1_account_kmem(memcg, -nr_pages);
3258 			if (!mem_cgroup_is_root(memcg))
3259 				memcg_uncharge(memcg, nr_pages);
3260 
3261 			css_put(&memcg->css);
3262 		}
3263 
3264 		/*
3265 		 * The leftover is flushed to the centralized per-memcg value.
3266 		 * On the next attempt to refill obj stock it will be moved
3267 		 * to a per-cpu stock (probably, on an other CPU), see
3268 		 * refill_obj_stock().
3269 		 *
3270 		 * How often it's flushed is a trade-off between the memory
3271 		 * limit enforcement accuracy and potential CPU contention,
3272 		 * so it might be changed in the future.
3273 		 */
3274 		atomic_add(nr_bytes, &old->nr_charged_bytes);
3275 		stock->nr_bytes = 0;
3276 	}
3277 
3278 	/*
3279 	 * Flush the vmstat data in current stock
3280 	 */
3281 	if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3282 		if (stock->nr_slab_reclaimable_b) {
3283 			mod_objcg_mlstate(old, stock->cached_pgdat,
3284 					  NR_SLAB_RECLAIMABLE_B,
3285 					  stock->nr_slab_reclaimable_b);
3286 			stock->nr_slab_reclaimable_b = 0;
3287 		}
3288 		if (stock->nr_slab_unreclaimable_b) {
3289 			mod_objcg_mlstate(old, stock->cached_pgdat,
3290 					  NR_SLAB_UNRECLAIMABLE_B,
3291 					  stock->nr_slab_unreclaimable_b);
3292 			stock->nr_slab_unreclaimable_b = 0;
3293 		}
3294 		stock->cached_pgdat = NULL;
3295 	}
3296 
3297 	WRITE_ONCE(stock->cached_objcg, NULL);
3298 	obj_cgroup_put(old);
3299 }
3300 
3301 static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
3302 				     struct mem_cgroup *root_memcg)
3303 {
3304 	struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3305 	struct mem_cgroup *memcg;
3306 	bool flush = false;
3307 
3308 	rcu_read_lock();
3309 	if (objcg) {
3310 		memcg = obj_cgroup_memcg(objcg);
3311 		if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3312 			flush = true;
3313 	}
3314 	rcu_read_unlock();
3315 
3316 	return flush;
3317 }
3318 
3319 static void __refill_obj_stock(struct obj_cgroup *objcg,
3320 			       struct obj_stock_pcp *stock,
3321 			       unsigned int nr_bytes,
3322 			       bool allow_uncharge)
3323 {
3324 	unsigned int nr_pages = 0;
3325 
3326 	if (!stock) {
3327 		nr_pages = nr_bytes >> PAGE_SHIFT;
3328 		nr_bytes = nr_bytes & (PAGE_SIZE - 1);
3329 		atomic_add(nr_bytes, &objcg->nr_charged_bytes);
3330 		goto out;
3331 	}
3332 
3333 	if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3334 		drain_obj_stock(stock);
3335 		obj_cgroup_get(objcg);
3336 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3337 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3338 		WRITE_ONCE(stock->cached_objcg, objcg);
3339 
3340 		allow_uncharge = true;	/* Allow uncharge when objcg changes */
3341 	}
3342 	stock->nr_bytes += nr_bytes;
3343 
3344 	if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3345 		nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3346 		stock->nr_bytes &= (PAGE_SIZE - 1);
3347 	}
3348 
3349 out:
3350 	if (nr_pages)
3351 		obj_cgroup_uncharge_pages(objcg, nr_pages);
3352 }
3353 
3354 static void refill_obj_stock(struct obj_cgroup *objcg,
3355 			     unsigned int nr_bytes,
3356 			     bool allow_uncharge)
3357 {
3358 	struct obj_stock_pcp *stock = trylock_stock();
3359 	__refill_obj_stock(objcg, stock, nr_bytes, allow_uncharge);
3360 	unlock_stock(stock);
3361 }
3362 
3363 static int __obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp,
3364 			       size_t size, size_t *remainder)
3365 {
3366 	size_t charge_size;
3367 	int ret;
3368 
3369 	charge_size = PAGE_ALIGN(size);
3370 	ret = obj_cgroup_charge_pages(objcg, gfp, charge_size >> PAGE_SHIFT);
3371 	if (!ret)
3372 		*remainder = charge_size - size;
3373 
3374 	return ret;
3375 }
3376 
3377 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3378 {
3379 	size_t remainder;
3380 	int ret;
3381 
3382 	if (likely(consume_obj_stock(objcg, size)))
3383 		return 0;
3384 
3385 	/*
3386 	 * In theory, objcg->nr_charged_bytes can have enough
3387 	 * pre-charged bytes to satisfy the allocation. However,
3388 	 * flushing objcg->nr_charged_bytes requires two atomic
3389 	 * operations, and objcg->nr_charged_bytes can't be big.
3390 	 * The shared objcg->nr_charged_bytes can also become a
3391 	 * performance bottleneck if all tasks of the same memcg are
3392 	 * trying to update it. So it's better to ignore it and try
3393 	 * grab some new pages. The stock's nr_bytes will be flushed to
3394 	 * objcg->nr_charged_bytes later on when objcg changes.
3395 	 *
3396 	 * The stock's nr_bytes may contain enough pre-charged bytes
3397 	 * to allow one less page from being charged, but we can't rely
3398 	 * on the pre-charged bytes not being changed outside of
3399 	 * consume_obj_stock() or refill_obj_stock(). So ignore those
3400 	 * pre-charged bytes as well when charging pages. To avoid a
3401 	 * page uncharge right after a page charge, we set the
3402 	 * allow_uncharge flag to false when calling refill_obj_stock()
3403 	 * to temporarily allow the pre-charged bytes to exceed the page
3404 	 * size limit. The maximum reachable value of the pre-charged
3405 	 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3406 	 * race.
3407 	 */
3408 	ret = __obj_cgroup_charge(objcg, gfp, size, &remainder);
3409 	if (!ret && remainder)
3410 		refill_obj_stock(objcg, remainder, false);
3411 
3412 	return ret;
3413 }
3414 
3415 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3416 {
3417 	refill_obj_stock(objcg, size, true);
3418 }
3419 
3420 static inline size_t obj_full_size(struct kmem_cache *s)
3421 {
3422 	/*
3423 	 * For each accounted object there is an extra space which is used
3424 	 * to store obj_cgroup membership. Charge it too.
3425 	 */
3426 	return s->size + sizeof(struct obj_cgroup *);
3427 }
3428 
3429 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3430 				  gfp_t flags, size_t size, void **p)
3431 {
3432 	size_t obj_size = obj_full_size(s);
3433 	struct obj_cgroup *objcg;
3434 	struct slab *slab;
3435 	unsigned long off;
3436 	size_t i;
3437 
3438 	/*
3439 	 * The obtained objcg pointer is safe to use within the current scope,
3440 	 * defined by current task or set_active_memcg() pair.
3441 	 * obj_cgroup_get() is used to get a permanent reference.
3442 	 */
3443 	objcg = current_obj_cgroup();
3444 	if (!objcg || obj_cgroup_is_root(objcg))
3445 		return true;
3446 
3447 	/*
3448 	 * slab_alloc_node() avoids the NULL check, so we might be called with a
3449 	 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3450 	 * the whole requested size.
3451 	 * return success as there's nothing to free back
3452 	 */
3453 	if (unlikely(*p == NULL))
3454 		return true;
3455 
3456 	flags &= gfp_allowed_mask;
3457 
3458 	if (lru) {
3459 		int ret;
3460 		struct mem_cgroup *memcg;
3461 
3462 		memcg = get_mem_cgroup_from_objcg(objcg);
3463 		ret = memcg_list_lru_alloc(memcg, lru, flags);
3464 		css_put(&memcg->css);
3465 
3466 		if (ret)
3467 			return false;
3468 	}
3469 
3470 	for (i = 0; i < size; i++) {
3471 		unsigned long obj_exts;
3472 		struct slabobj_ext *obj_ext;
3473 		struct obj_stock_pcp *stock;
3474 
3475 		slab = virt_to_slab(p[i]);
3476 
3477 		if (!slab_obj_exts(slab) &&
3478 		    alloc_slab_obj_exts(slab, s, flags, false)) {
3479 			continue;
3480 		}
3481 
3482 		/*
3483 		 * if we fail and size is 1, memcg_alloc_abort_single() will
3484 		 * just free the object, which is ok as we have not assigned
3485 		 * objcg to its obj_ext yet
3486 		 *
3487 		 * for larger sizes, kmem_cache_free_bulk() will uncharge
3488 		 * any objects that were already charged and obj_ext assigned
3489 		 *
3490 		 * TODO: we could batch this until slab_pgdat(slab) changes
3491 		 * between iterations, with a more complicated undo
3492 		 */
3493 		stock = trylock_stock();
3494 		if (!stock || !__consume_obj_stock(objcg, stock, obj_size)) {
3495 			size_t remainder;
3496 
3497 			unlock_stock(stock);
3498 			if (__obj_cgroup_charge(objcg, flags, obj_size, &remainder))
3499 				return false;
3500 			stock = trylock_stock();
3501 			if (remainder)
3502 				__refill_obj_stock(objcg, stock, remainder, false);
3503 		}
3504 		__account_obj_stock(objcg, stock, obj_size,
3505 				    slab_pgdat(slab), cache_vmstat_idx(s));
3506 		unlock_stock(stock);
3507 
3508 		obj_exts = slab_obj_exts(slab);
3509 		get_slab_obj_exts(obj_exts);
3510 		off = obj_to_index(s, slab, p[i]);
3511 		obj_ext = slab_obj_ext(slab, obj_exts, off);
3512 		obj_cgroup_get(objcg);
3513 		obj_ext->objcg = objcg;
3514 		put_slab_obj_exts(obj_exts);
3515 	}
3516 
3517 	return true;
3518 }
3519 
3520 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3521 			    void **p, int objects, unsigned long obj_exts)
3522 {
3523 	size_t obj_size = obj_full_size(s);
3524 
3525 	for (int i = 0; i < objects; i++) {
3526 		struct obj_cgroup *objcg;
3527 		struct slabobj_ext *obj_ext;
3528 		struct obj_stock_pcp *stock;
3529 		unsigned int off;
3530 
3531 		off = obj_to_index(s, slab, p[i]);
3532 		obj_ext = slab_obj_ext(slab, obj_exts, off);
3533 		objcg = obj_ext->objcg;
3534 		if (!objcg)
3535 			continue;
3536 
3537 		obj_ext->objcg = NULL;
3538 
3539 		stock = trylock_stock();
3540 		__refill_obj_stock(objcg, stock, obj_size, true);
3541 		__account_obj_stock(objcg, stock, -obj_size,
3542 				    slab_pgdat(slab), cache_vmstat_idx(s));
3543 		unlock_stock(stock);
3544 
3545 		obj_cgroup_put(objcg);
3546 	}
3547 }
3548 
3549 /*
3550  * The objcg is only set on the first page, so transfer it to all the
3551  * other pages.
3552  */
3553 void split_page_memcg(struct page *page, unsigned order)
3554 {
3555 	struct obj_cgroup *objcg = page_objcg(page);
3556 	unsigned int i, nr = 1 << order;
3557 
3558 	if (!objcg)
3559 		return;
3560 
3561 	for (i = 1; i < nr; i++)
3562 		page_set_objcg(&page[i], objcg);
3563 
3564 	obj_cgroup_get_many(objcg, nr - 1);
3565 }
3566 
3567 void folio_split_memcg_refs(struct folio *folio, unsigned old_order,
3568 		unsigned new_order)
3569 {
3570 	unsigned new_refs;
3571 
3572 	if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
3573 		return;
3574 
3575 	new_refs = (1 << (old_order - new_order)) - 1;
3576 	obj_cgroup_get_many(folio_objcg(folio), new_refs);
3577 }
3578 
3579 static void memcg_online_kmem(struct mem_cgroup *memcg)
3580 {
3581 	if (mem_cgroup_kmem_disabled())
3582 		return;
3583 
3584 	if (unlikely(mem_cgroup_is_root(memcg)))
3585 		return;
3586 
3587 	static_branch_enable(&memcg_kmem_online_key);
3588 
3589 	memcg->kmemcg_id = memcg->id.id;
3590 }
3591 
3592 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3593 {
3594 	struct mem_cgroup *parent;
3595 
3596 	if (mem_cgroup_kmem_disabled())
3597 		return;
3598 
3599 	if (unlikely(mem_cgroup_is_root(memcg)))
3600 		return;
3601 
3602 	parent = parent_mem_cgroup(memcg);
3603 	memcg_reparent_list_lrus(memcg, parent);
3604 }
3605 
3606 #ifdef CONFIG_CGROUP_WRITEBACK
3607 
3608 #include <trace/events/writeback.h>
3609 
3610 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3611 {
3612 	return wb_domain_init(&memcg->cgwb_domain, gfp);
3613 }
3614 
3615 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3616 {
3617 	wb_domain_exit(&memcg->cgwb_domain);
3618 }
3619 
3620 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3621 {
3622 	wb_domain_size_changed(&memcg->cgwb_domain);
3623 }
3624 
3625 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3626 {
3627 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3628 
3629 	if (!memcg->css.parent)
3630 		return NULL;
3631 
3632 	return &memcg->cgwb_domain;
3633 }
3634 
3635 /**
3636  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3637  * @wb: bdi_writeback in question
3638  * @pfilepages: out parameter for number of file pages
3639  * @pheadroom: out parameter for number of allocatable pages according to memcg
3640  * @pdirty: out parameter for number of dirty pages
3641  * @pwriteback: out parameter for number of pages under writeback
3642  *
3643  * Determine the numbers of file, headroom, dirty, and writeback pages in
3644  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
3645  * is a bit more involved.
3646  *
3647  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
3648  * headroom is calculated as the lowest headroom of itself and the
3649  * ancestors.  Note that this doesn't consider the actual amount of
3650  * available memory in the system.  The caller should further cap
3651  * *@pheadroom accordingly.
3652  */
3653 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3654 			 unsigned long *pheadroom, unsigned long *pdirty,
3655 			 unsigned long *pwriteback)
3656 {
3657 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3658 	struct mem_cgroup *parent;
3659 
3660 	mem_cgroup_flush_stats_ratelimited(memcg);
3661 
3662 	*pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
3663 	*pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
3664 	*pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
3665 			memcg_page_state(memcg, NR_ACTIVE_FILE);
3666 
3667 	*pheadroom = PAGE_COUNTER_MAX;
3668 	while ((parent = parent_mem_cgroup(memcg))) {
3669 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
3670 					    READ_ONCE(memcg->memory.high));
3671 		unsigned long used = page_counter_read(&memcg->memory);
3672 
3673 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
3674 		memcg = parent;
3675 	}
3676 }
3677 
3678 /*
3679  * Foreign dirty flushing
3680  *
3681  * There's an inherent mismatch between memcg and writeback.  The former
3682  * tracks ownership per-page while the latter per-inode.  This was a
3683  * deliberate design decision because honoring per-page ownership in the
3684  * writeback path is complicated, may lead to higher CPU and IO overheads
3685  * and deemed unnecessary given that write-sharing an inode across
3686  * different cgroups isn't a common use-case.
3687  *
3688  * Combined with inode majority-writer ownership switching, this works well
3689  * enough in most cases but there are some pathological cases.  For
3690  * example, let's say there are two cgroups A and B which keep writing to
3691  * different but confined parts of the same inode.  B owns the inode and
3692  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
3693  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
3694  * triggering background writeback.  A will be slowed down without a way to
3695  * make writeback of the dirty pages happen.
3696  *
3697  * Conditions like the above can lead to a cgroup getting repeatedly and
3698  * severely throttled after making some progress after each
3699  * dirty_expire_interval while the underlying IO device is almost
3700  * completely idle.
3701  *
3702  * Solving this problem completely requires matching the ownership tracking
3703  * granularities between memcg and writeback in either direction.  However,
3704  * the more egregious behaviors can be avoided by simply remembering the
3705  * most recent foreign dirtying events and initiating remote flushes on
3706  * them when local writeback isn't enough to keep the memory clean enough.
3707  *
3708  * The following two functions implement such mechanism.  When a foreign
3709  * page - a page whose memcg and writeback ownerships don't match - is
3710  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
3711  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
3712  * decides that the memcg needs to sleep due to high dirty ratio, it calls
3713  * mem_cgroup_flush_foreign() which queues writeback on the recorded
3714  * foreign bdi_writebacks which haven't expired.  Both the numbers of
3715  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
3716  * limited to MEMCG_CGWB_FRN_CNT.
3717  *
3718  * The mechanism only remembers IDs and doesn't hold any object references.
3719  * As being wrong occasionally doesn't matter, updates and accesses to the
3720  * records are lockless and racy.
3721  */
3722 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
3723 					     struct bdi_writeback *wb)
3724 {
3725 	struct mem_cgroup *memcg = folio_memcg(folio);
3726 	struct memcg_cgwb_frn *frn;
3727 	u64 now = get_jiffies_64();
3728 	u64 oldest_at = now;
3729 	int oldest = -1;
3730 	int i;
3731 
3732 	trace_track_foreign_dirty(folio, wb);
3733 
3734 	/*
3735 	 * Pick the slot to use.  If there is already a slot for @wb, keep
3736 	 * using it.  If not replace the oldest one which isn't being
3737 	 * written out.
3738 	 */
3739 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3740 		frn = &memcg->cgwb_frn[i];
3741 		if (frn->bdi_id == wb->bdi->id &&
3742 		    frn->memcg_id == wb->memcg_css->id)
3743 			break;
3744 		if (time_before64(frn->at, oldest_at) &&
3745 		    atomic_read(&frn->done.cnt) == 1) {
3746 			oldest = i;
3747 			oldest_at = frn->at;
3748 		}
3749 	}
3750 
3751 	if (i < MEMCG_CGWB_FRN_CNT) {
3752 		/*
3753 		 * Re-using an existing one.  Update timestamp lazily to
3754 		 * avoid making the cacheline hot.  We want them to be
3755 		 * reasonably up-to-date and significantly shorter than
3756 		 * dirty_expire_interval as that's what expires the record.
3757 		 * Use the shorter of 1s and dirty_expire_interval / 8.
3758 		 */
3759 		unsigned long update_intv =
3760 			min_t(unsigned long, HZ,
3761 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
3762 
3763 		if (time_before64(frn->at, now - update_intv))
3764 			frn->at = now;
3765 	} else if (oldest >= 0) {
3766 		/* replace the oldest free one */
3767 		frn = &memcg->cgwb_frn[oldest];
3768 		frn->bdi_id = wb->bdi->id;
3769 		frn->memcg_id = wb->memcg_css->id;
3770 		frn->at = now;
3771 	}
3772 }
3773 
3774 /* issue foreign writeback flushes for recorded foreign dirtying events */
3775 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
3776 {
3777 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3778 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
3779 	u64 now = jiffies_64;
3780 	int i;
3781 
3782 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3783 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
3784 
3785 		/*
3786 		 * If the record is older than dirty_expire_interval,
3787 		 * writeback on it has already started.  No need to kick it
3788 		 * off again.  Also, don't start a new one if there's
3789 		 * already one in flight.
3790 		 */
3791 		if (time_after64(frn->at, now - intv) &&
3792 		    atomic_read(&frn->done.cnt) == 1) {
3793 			frn->at = 0;
3794 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
3795 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
3796 					       WB_REASON_FOREIGN_FLUSH,
3797 					       &frn->done);
3798 		}
3799 	}
3800 }
3801 
3802 #else	/* CONFIG_CGROUP_WRITEBACK */
3803 
3804 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3805 {
3806 	return 0;
3807 }
3808 
3809 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3810 {
3811 }
3812 
3813 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3814 {
3815 }
3816 
3817 #endif	/* CONFIG_CGROUP_WRITEBACK */
3818 
3819 /*
3820  * Private memory cgroup IDR
3821  *
3822  * Swap-out records and page cache shadow entries need to store memcg
3823  * references in constrained space, so we maintain an ID space that is
3824  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
3825  * memory-controlled cgroups to 64k.
3826  *
3827  * However, there usually are many references to the offline CSS after
3828  * the cgroup has been destroyed, such as page cache or reclaimable
3829  * slab objects, that don't need to hang on to the ID. We want to keep
3830  * those dead CSS from occupying IDs, or we might quickly exhaust the
3831  * relatively small ID space and prevent the creation of new cgroups
3832  * even when there are much fewer than 64k cgroups - possibly none.
3833  *
3834  * Maintain a private 16-bit ID space for memcg, and allow the ID to
3835  * be freed and recycled when it's no longer needed, which is usually
3836  * when the CSS is offlined.
3837  *
3838  * The only exception to that are records of swapped out tmpfs/shmem
3839  * pages that need to be attributed to live ancestors on swapin. But
3840  * those references are manageable from userspace.
3841  */
3842 
3843 #define MEM_CGROUP_ID_MAX	((1UL << MEM_CGROUP_ID_SHIFT) - 1)
3844 static DEFINE_XARRAY_ALLOC1(mem_cgroup_private_ids);
3845 
3846 static void mem_cgroup_private_id_remove(struct mem_cgroup *memcg)
3847 {
3848 	if (memcg->id.id > 0) {
3849 		xa_erase(&mem_cgroup_private_ids, memcg->id.id);
3850 		memcg->id.id = 0;
3851 	}
3852 }
3853 
3854 static inline void mem_cgroup_private_id_put(struct mem_cgroup *memcg, unsigned int n)
3855 {
3856 	if (refcount_sub_and_test(n, &memcg->id.ref)) {
3857 		mem_cgroup_private_id_remove(memcg);
3858 
3859 		/* Memcg ID pins CSS */
3860 		css_put(&memcg->css);
3861 	}
3862 }
3863 
3864 struct mem_cgroup *mem_cgroup_private_id_get_online(struct mem_cgroup *memcg, unsigned int n)
3865 {
3866 	while (!refcount_add_not_zero(n, &memcg->id.ref)) {
3867 		/*
3868 		 * The root cgroup cannot be destroyed, so it's refcount must
3869 		 * always be >= 1.
3870 		 */
3871 		if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
3872 			VM_BUG_ON(1);
3873 			break;
3874 		}
3875 		memcg = parent_mem_cgroup(memcg);
3876 	}
3877 	return memcg;
3878 }
3879 
3880 /**
3881  * mem_cgroup_from_private_id - look up a memcg from a memcg id
3882  * @id: the memcg id to look up
3883  *
3884  * Caller must hold rcu_read_lock().
3885  */
3886 struct mem_cgroup *mem_cgroup_from_private_id(unsigned short id)
3887 {
3888 	WARN_ON_ONCE(!rcu_read_lock_held());
3889 	return xa_load(&mem_cgroup_private_ids, id);
3890 }
3891 
3892 struct mem_cgroup *mem_cgroup_get_from_id(u64 id)
3893 {
3894 	struct cgroup *cgrp;
3895 	struct cgroup_subsys_state *css;
3896 	struct mem_cgroup *memcg = NULL;
3897 
3898 	cgrp = cgroup_get_from_id(id);
3899 	if (IS_ERR(cgrp))
3900 		return NULL;
3901 
3902 	css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
3903 	if (css)
3904 		memcg = container_of(css, struct mem_cgroup, css);
3905 
3906 	cgroup_put(cgrp);
3907 
3908 	return memcg;
3909 }
3910 
3911 static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn)
3912 {
3913 	if (!pn)
3914 		return;
3915 
3916 	free_percpu(pn->lruvec_stats_percpu);
3917 	kfree(pn->lruvec_stats);
3918 	kfree(pn);
3919 }
3920 
3921 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
3922 {
3923 	struct mem_cgroup_per_node *pn;
3924 
3925 	pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
3926 				   node);
3927 	if (!pn)
3928 		return false;
3929 
3930 	pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
3931 					GFP_KERNEL_ACCOUNT, node);
3932 	if (!pn->lruvec_stats)
3933 		goto fail;
3934 
3935 	pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
3936 						   GFP_KERNEL_ACCOUNT);
3937 	if (!pn->lruvec_stats_percpu)
3938 		goto fail;
3939 
3940 	INIT_LIST_HEAD(&pn->objcg_list);
3941 
3942 	lruvec_init(&pn->lruvec);
3943 	pn->memcg = memcg;
3944 
3945 	memcg->nodeinfo[node] = pn;
3946 	return true;
3947 fail:
3948 	free_mem_cgroup_per_node_info(pn);
3949 	return false;
3950 }
3951 
3952 static void __mem_cgroup_free(struct mem_cgroup *memcg)
3953 {
3954 	int node;
3955 
3956 	for_each_node(node) {
3957 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3958 		if (!pn)
3959 			continue;
3960 
3961 		obj_cgroup_put(pn->orig_objcg);
3962 		free_mem_cgroup_per_node_info(pn);
3963 	}
3964 	memcg1_free_events(memcg);
3965 	kfree(memcg->vmstats);
3966 	free_percpu(memcg->vmstats_percpu);
3967 	kfree(memcg);
3968 }
3969 
3970 static void mem_cgroup_free(struct mem_cgroup *memcg)
3971 {
3972 	lru_gen_exit_memcg(memcg);
3973 	memcg_wb_domain_exit(memcg);
3974 	__mem_cgroup_free(memcg);
3975 }
3976 
3977 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
3978 {
3979 	struct memcg_vmstats_percpu *statc;
3980 	struct memcg_vmstats_percpu __percpu *pstatc_pcpu;
3981 	struct mem_cgroup *memcg;
3982 	int node, cpu;
3983 	int __maybe_unused i;
3984 	long error;
3985 
3986 	memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
3987 	if (!memcg)
3988 		return ERR_PTR(-ENOMEM);
3989 
3990 	error = xa_alloc(&mem_cgroup_private_ids, &memcg->id.id, NULL,
3991 			 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
3992 	if (error)
3993 		goto fail;
3994 	error = -ENOMEM;
3995 
3996 	memcg->vmstats = kzalloc_obj(struct memcg_vmstats, GFP_KERNEL_ACCOUNT);
3997 	if (!memcg->vmstats)
3998 		goto fail;
3999 
4000 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
4001 						 GFP_KERNEL_ACCOUNT);
4002 	if (!memcg->vmstats_percpu)
4003 		goto fail;
4004 
4005 	if (!memcg1_alloc_events(memcg))
4006 		goto fail;
4007 
4008 	for_each_possible_cpu(cpu) {
4009 		if (parent)
4010 			pstatc_pcpu = parent->vmstats_percpu;
4011 		statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
4012 		statc->parent_pcpu = parent ? pstatc_pcpu : NULL;
4013 		statc->vmstats = memcg->vmstats;
4014 	}
4015 
4016 	for_each_node(node)
4017 		if (!alloc_mem_cgroup_per_node_info(memcg, node))
4018 			goto fail;
4019 
4020 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
4021 		goto fail;
4022 
4023 	INIT_WORK(&memcg->high_work, high_work_func);
4024 	vmpressure_init(&memcg->vmpressure);
4025 	INIT_LIST_HEAD(&memcg->memory_peaks);
4026 	INIT_LIST_HEAD(&memcg->swap_peaks);
4027 	spin_lock_init(&memcg->peaks_lock);
4028 	memcg->socket_pressure = get_jiffies_64();
4029 #if BITS_PER_LONG < 64
4030 	seqlock_init(&memcg->socket_pressure_seqlock);
4031 #endif
4032 	memcg1_memcg_init(memcg);
4033 	memcg->kmemcg_id = -1;
4034 #ifdef CONFIG_CGROUP_WRITEBACK
4035 	INIT_LIST_HEAD(&memcg->cgwb_list);
4036 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
4037 		memcg->cgwb_frn[i].done =
4038 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
4039 #endif
4040 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4041 	spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
4042 	INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
4043 	memcg->deferred_split_queue.split_queue_len = 0;
4044 #endif
4045 	lru_gen_init_memcg(memcg);
4046 	return memcg;
4047 fail:
4048 	mem_cgroup_private_id_remove(memcg);
4049 	__mem_cgroup_free(memcg);
4050 	return ERR_PTR(error);
4051 }
4052 
4053 static struct cgroup_subsys_state * __ref
4054 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
4055 {
4056 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
4057 	struct mem_cgroup *memcg, *old_memcg;
4058 	bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys);
4059 
4060 	old_memcg = set_active_memcg(parent);
4061 	memcg = mem_cgroup_alloc(parent);
4062 	set_active_memcg(old_memcg);
4063 	if (IS_ERR(memcg))
4064 		return ERR_CAST(memcg);
4065 
4066 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
4067 	memcg1_soft_limit_reset(memcg);
4068 #ifdef CONFIG_ZSWAP
4069 	memcg->zswap_max = PAGE_COUNTER_MAX;
4070 	WRITE_ONCE(memcg->zswap_writeback, true);
4071 #endif
4072 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
4073 	if (parent) {
4074 		WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
4075 
4076 		page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl);
4077 		page_counter_init(&memcg->swap, &parent->swap, false);
4078 #ifdef CONFIG_MEMCG_V1
4079 		memcg->memory.track_failcnt = !memcg_on_dfl;
4080 		WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
4081 		page_counter_init(&memcg->kmem, &parent->kmem, false);
4082 		page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
4083 #endif
4084 	} else {
4085 		init_memcg_stats();
4086 		init_memcg_events();
4087 		page_counter_init(&memcg->memory, NULL, true);
4088 		page_counter_init(&memcg->swap, NULL, false);
4089 #ifdef CONFIG_MEMCG_V1
4090 		page_counter_init(&memcg->kmem, NULL, false);
4091 		page_counter_init(&memcg->tcpmem, NULL, false);
4092 #endif
4093 		root_mem_cgroup = memcg;
4094 		return &memcg->css;
4095 	}
4096 
4097 	if (memcg_on_dfl && !cgroup_memory_nosocket)
4098 		static_branch_inc(&memcg_sockets_enabled_key);
4099 
4100 	if (!cgroup_memory_nobpf)
4101 		static_branch_inc(&memcg_bpf_enabled_key);
4102 
4103 	return &memcg->css;
4104 }
4105 
4106 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
4107 {
4108 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4109 	struct obj_cgroup *objcg;
4110 	int nid;
4111 
4112 	memcg_online_kmem(memcg);
4113 
4114 	/*
4115 	 * A memcg must be visible for expand_shrinker_info()
4116 	 * by the time the maps are allocated. So, we allocate maps
4117 	 * here, when for_each_mem_cgroup() can't skip it.
4118 	 */
4119 	if (alloc_shrinker_info(memcg))
4120 		goto offline_kmem;
4121 
4122 	for_each_node(nid) {
4123 		objcg = obj_cgroup_alloc();
4124 		if (!objcg)
4125 			goto free_objcg;
4126 
4127 		if (unlikely(mem_cgroup_is_root(memcg)))
4128 			objcg->is_root = true;
4129 
4130 		objcg->memcg = memcg;
4131 		rcu_assign_pointer(memcg->nodeinfo[nid]->objcg, objcg);
4132 		obj_cgroup_get(objcg);
4133 		memcg->nodeinfo[nid]->orig_objcg = objcg;
4134 	}
4135 
4136 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
4137 		queue_delayed_work(system_dfl_wq, &stats_flush_dwork,
4138 				   FLUSH_TIME);
4139 	lru_gen_online_memcg(memcg);
4140 
4141 	/* Online state pins memcg ID, memcg ID pins CSS */
4142 	refcount_set(&memcg->id.ref, 1);
4143 	css_get(css);
4144 
4145 	/*
4146 	 * Ensure mem_cgroup_from_private_id() works once we're fully online.
4147 	 *
4148 	 * We could do this earlier and require callers to filter with
4149 	 * css_tryget_online(). But right now there are no users that
4150 	 * need earlier access, and the workingset code relies on the
4151 	 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
4152 	 * publish it here at the end of onlining. This matches the
4153 	 * regular ID destruction during offlining.
4154 	 */
4155 	xa_store(&mem_cgroup_private_ids, memcg->id.id, memcg, GFP_KERNEL);
4156 
4157 	return 0;
4158 free_objcg:
4159 	for_each_node(nid) {
4160 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4161 
4162 		objcg = rcu_replace_pointer(pn->objcg, NULL, true);
4163 		if (objcg)
4164 			percpu_ref_kill(&objcg->refcnt);
4165 
4166 		if (pn->orig_objcg) {
4167 			obj_cgroup_put(pn->orig_objcg);
4168 			/*
4169 			 * Reset pn->orig_objcg to NULL to prevent
4170 			 * obj_cgroup_put() from being called again in
4171 			 * __mem_cgroup_free().
4172 			 */
4173 			pn->orig_objcg = NULL;
4174 		}
4175 	}
4176 	free_shrinker_info(memcg);
4177 offline_kmem:
4178 	memcg_offline_kmem(memcg);
4179 	mem_cgroup_private_id_remove(memcg);
4180 	return -ENOMEM;
4181 }
4182 
4183 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
4184 {
4185 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4186 
4187 	memcg1_css_offline(memcg);
4188 
4189 	page_counter_set_min(&memcg->memory, 0);
4190 	page_counter_set_low(&memcg->memory, 0);
4191 
4192 	zswap_memcg_offline_cleanup(memcg);
4193 
4194 	memcg_offline_kmem(memcg);
4195 	reparent_deferred_split_queue(memcg);
4196 	/*
4197 	 * The reparenting of objcg must be after the reparenting of the
4198 	 * list_lru and deferred_split_queue above, which ensures that they will
4199 	 * not mistakenly get the parent list_lru and deferred_split_queue.
4200 	 */
4201 	memcg_reparent_objcgs(memcg);
4202 	reparent_shrinker_deferred(memcg);
4203 	wb_memcg_offline(memcg);
4204 	lru_gen_offline_memcg(memcg);
4205 
4206 	drain_all_stock(memcg);
4207 
4208 	mem_cgroup_private_id_put(memcg, 1);
4209 }
4210 
4211 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
4212 {
4213 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4214 
4215 	invalidate_reclaim_iterators(memcg);
4216 	lru_gen_release_memcg(memcg);
4217 }
4218 
4219 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
4220 {
4221 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4222 	int __maybe_unused i;
4223 
4224 #ifdef CONFIG_CGROUP_WRITEBACK
4225 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
4226 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
4227 #endif
4228 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
4229 		static_branch_dec(&memcg_sockets_enabled_key);
4230 
4231 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
4232 		static_branch_dec(&memcg_sockets_enabled_key);
4233 
4234 	if (!cgroup_memory_nobpf)
4235 		static_branch_dec(&memcg_bpf_enabled_key);
4236 
4237 	vmpressure_cleanup(&memcg->vmpressure);
4238 	cancel_work_sync(&memcg->high_work);
4239 	memcg1_remove_from_trees(memcg);
4240 	free_shrinker_info(memcg);
4241 	mem_cgroup_free(memcg);
4242 }
4243 
4244 /**
4245  * mem_cgroup_css_reset - reset the states of a mem_cgroup
4246  * @css: the target css
4247  *
4248  * Reset the states of the mem_cgroup associated with @css.  This is
4249  * invoked when the userland requests disabling on the default hierarchy
4250  * but the memcg is pinned through dependency.  The memcg should stop
4251  * applying policies and should revert to the vanilla state as it may be
4252  * made visible again.
4253  *
4254  * The current implementation only resets the essential configurations.
4255  * This needs to be expanded to cover all the visible parts.
4256  */
4257 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4258 {
4259 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4260 
4261 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
4262 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
4263 #ifdef CONFIG_MEMCG_V1
4264 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
4265 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
4266 #endif
4267 	page_counter_set_min(&memcg->memory, 0);
4268 	page_counter_set_low(&memcg->memory, 0);
4269 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
4270 	memcg1_soft_limit_reset(memcg);
4271 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
4272 	memcg_wb_domain_size_changed(memcg);
4273 }
4274 
4275 struct aggregate_control {
4276 	/* pointer to the aggregated (CPU and subtree aggregated) counters */
4277 	long *aggregate;
4278 	/* pointer to the non-hierarchichal (CPU aggregated) counters */
4279 	long *local;
4280 	/* pointer to the pending child counters during tree propagation */
4281 	long *pending;
4282 	/* pointer to the parent's pending counters, could be NULL */
4283 	long *ppending;
4284 	/* pointer to the percpu counters to be aggregated */
4285 	long *cstat;
4286 	/* pointer to the percpu counters of the last aggregation*/
4287 	long *cstat_prev;
4288 	/* size of the above counters */
4289 	int size;
4290 };
4291 
4292 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac)
4293 {
4294 	int i;
4295 	long delta, delta_cpu, v;
4296 
4297 	for (i = 0; i < ac->size; i++) {
4298 		/*
4299 		 * Collect the aggregated propagation counts of groups
4300 		 * below us. We're in a per-cpu loop here and this is
4301 		 * a global counter, so the first cycle will get them.
4302 		 */
4303 		delta = ac->pending[i];
4304 		if (delta)
4305 			ac->pending[i] = 0;
4306 
4307 		/* Add CPU changes on this level since the last flush */
4308 		delta_cpu = 0;
4309 		v = READ_ONCE(ac->cstat[i]);
4310 		if (v != ac->cstat_prev[i]) {
4311 			delta_cpu = v - ac->cstat_prev[i];
4312 			delta += delta_cpu;
4313 			ac->cstat_prev[i] = v;
4314 		}
4315 
4316 		/* Aggregate counts on this level and propagate upwards */
4317 		if (delta_cpu)
4318 			ac->local[i] += delta_cpu;
4319 
4320 		if (delta) {
4321 			ac->aggregate[i] += delta;
4322 			if (ac->ppending)
4323 				ac->ppending[i] += delta;
4324 		}
4325 	}
4326 }
4327 
4328 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
4329 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4330 			    int cpu)
4331 {
4332 	int nid;
4333 
4334 	if (atomic_read(&memcg->kmem_stat)) {
4335 		int kmem = atomic_xchg(&memcg->kmem_stat, 0);
4336 		int index = memcg_stats_index(MEMCG_KMEM);
4337 
4338 		memcg->vmstats->state[index] += kmem;
4339 		if (parent)
4340 			parent->vmstats->state_pending[index] += kmem;
4341 	}
4342 
4343 	for_each_node_state(nid, N_MEMORY) {
4344 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4345 		struct lruvec_stats *lstats = pn->lruvec_stats;
4346 		struct lruvec_stats *plstats = NULL;
4347 
4348 		if (parent)
4349 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4350 
4351 		if (atomic_read(&pn->slab_reclaimable)) {
4352 			int slab = atomic_xchg(&pn->slab_reclaimable, 0);
4353 			int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B);
4354 
4355 			lstats->state[index] += slab;
4356 			if (plstats)
4357 				plstats->state_pending[index] += slab;
4358 			memcg->vmstats->state[index] += slab;
4359 			if (parent)
4360 				parent->vmstats->state_pending[index] += slab;
4361 		}
4362 		if (atomic_read(&pn->slab_unreclaimable)) {
4363 			int slab = atomic_xchg(&pn->slab_unreclaimable, 0);
4364 			int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B);
4365 
4366 			lstats->state[index] += slab;
4367 			if (plstats)
4368 				plstats->state_pending[index] += slab;
4369 			memcg->vmstats->state[index] += slab;
4370 			if (parent)
4371 				parent->vmstats->state_pending[index] += slab;
4372 		}
4373 	}
4374 }
4375 #else
4376 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4377 			    int cpu)
4378 {}
4379 #endif
4380 
4381 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
4382 {
4383 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4384 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4385 	struct memcg_vmstats_percpu *statc;
4386 	struct aggregate_control ac;
4387 	int nid;
4388 
4389 	flush_nmi_stats(memcg, parent, cpu);
4390 
4391 	statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
4392 
4393 	ac = (struct aggregate_control) {
4394 		.aggregate = memcg->vmstats->state,
4395 		.local = memcg->vmstats->state_local,
4396 		.pending = memcg->vmstats->state_pending,
4397 		.ppending = parent ? parent->vmstats->state_pending : NULL,
4398 		.cstat = statc->state,
4399 		.cstat_prev = statc->state_prev,
4400 		.size = MEMCG_VMSTAT_SIZE,
4401 	};
4402 	mem_cgroup_stat_aggregate(&ac);
4403 
4404 	ac = (struct aggregate_control) {
4405 		.aggregate = memcg->vmstats->events,
4406 		.local = memcg->vmstats->events_local,
4407 		.pending = memcg->vmstats->events_pending,
4408 		.ppending = parent ? parent->vmstats->events_pending : NULL,
4409 		.cstat = statc->events,
4410 		.cstat_prev = statc->events_prev,
4411 		.size = NR_MEMCG_EVENTS,
4412 	};
4413 	mem_cgroup_stat_aggregate(&ac);
4414 
4415 	for_each_node_state(nid, N_MEMORY) {
4416 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4417 		struct lruvec_stats *lstats = pn->lruvec_stats;
4418 		struct lruvec_stats *plstats = NULL;
4419 		struct lruvec_stats_percpu *lstatc;
4420 
4421 		if (parent)
4422 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4423 
4424 		lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
4425 
4426 		ac = (struct aggregate_control) {
4427 			.aggregate = lstats->state,
4428 			.local = lstats->state_local,
4429 			.pending = lstats->state_pending,
4430 			.ppending = plstats ? plstats->state_pending : NULL,
4431 			.cstat = lstatc->state,
4432 			.cstat_prev = lstatc->state_prev,
4433 			.size = NR_MEMCG_NODE_STAT_ITEMS,
4434 		};
4435 		mem_cgroup_stat_aggregate(&ac);
4436 
4437 	}
4438 	WRITE_ONCE(statc->stats_updates, 0);
4439 	/* We are in a per-cpu loop here, only do the atomic write once */
4440 	if (atomic_long_read(&memcg->vmstats->stats_updates))
4441 		atomic_long_set(&memcg->vmstats->stats_updates, 0);
4442 }
4443 
4444 static void mem_cgroup_fork(struct task_struct *task)
4445 {
4446 	/*
4447 	 * Set the update flag to cause task->objcg to be initialized lazily
4448 	 * on the first allocation. It can be done without any synchronization
4449 	 * because it's always performed on the current task, so does
4450 	 * current_objcg_update().
4451 	 */
4452 	task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
4453 }
4454 
4455 static void mem_cgroup_exit(struct task_struct *task)
4456 {
4457 	struct obj_cgroup *objcg = task->objcg;
4458 
4459 	objcg = (struct obj_cgroup *)
4460 		((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
4461 	obj_cgroup_put(objcg);
4462 
4463 	/*
4464 	 * Some kernel allocations can happen after this point,
4465 	 * but let's ignore them. It can be done without any synchronization
4466 	 * because it's always performed on the current task, so does
4467 	 * current_objcg_update().
4468 	 */
4469 	task->objcg = NULL;
4470 }
4471 
4472 #ifdef CONFIG_LRU_GEN
4473 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
4474 {
4475 	struct task_struct *task;
4476 	struct cgroup_subsys_state *css;
4477 
4478 	/* find the first leader if there is any */
4479 	cgroup_taskset_for_each_leader(task, css, tset)
4480 		break;
4481 
4482 	if (!task)
4483 		return;
4484 
4485 	task_lock(task);
4486 	if (task->mm && READ_ONCE(task->mm->owner) == task)
4487 		lru_gen_migrate_mm(task->mm);
4488 	task_unlock(task);
4489 }
4490 #else
4491 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
4492 #endif /* CONFIG_LRU_GEN */
4493 
4494 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
4495 {
4496 	struct task_struct *task;
4497 	struct cgroup_subsys_state *css;
4498 
4499 	cgroup_taskset_for_each(task, css, tset) {
4500 		/* atomically set the update bit */
4501 		set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
4502 	}
4503 }
4504 
4505 static void mem_cgroup_attach(struct cgroup_taskset *tset)
4506 {
4507 	mem_cgroup_lru_gen_attach(tset);
4508 	mem_cgroup_kmem_attach(tset);
4509 }
4510 
4511 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
4512 {
4513 	if (value == PAGE_COUNTER_MAX)
4514 		seq_puts(m, "max\n");
4515 	else
4516 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
4517 
4518 	return 0;
4519 }
4520 
4521 static u64 memory_current_read(struct cgroup_subsys_state *css,
4522 			       struct cftype *cft)
4523 {
4524 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4525 
4526 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
4527 }
4528 
4529 #define OFP_PEAK_UNSET (((-1UL)))
4530 
4531 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
4532 {
4533 	struct cgroup_of_peak *ofp = of_peak(sf->private);
4534 	u64 fd_peak = READ_ONCE(ofp->value), peak;
4535 
4536 	/* User wants global or local peak? */
4537 	if (fd_peak == OFP_PEAK_UNSET)
4538 		peak = pc->watermark;
4539 	else
4540 		peak = max(fd_peak, READ_ONCE(pc->local_watermark));
4541 
4542 	seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
4543 	return 0;
4544 }
4545 
4546 static int memory_peak_show(struct seq_file *sf, void *v)
4547 {
4548 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
4549 
4550 	return peak_show(sf, v, &memcg->memory);
4551 }
4552 
4553 static int peak_open(struct kernfs_open_file *of)
4554 {
4555 	struct cgroup_of_peak *ofp = of_peak(of);
4556 
4557 	ofp->value = OFP_PEAK_UNSET;
4558 	return 0;
4559 }
4560 
4561 static void peak_release(struct kernfs_open_file *of)
4562 {
4563 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4564 	struct cgroup_of_peak *ofp = of_peak(of);
4565 
4566 	if (ofp->value == OFP_PEAK_UNSET) {
4567 		/* fast path (no writes on this fd) */
4568 		return;
4569 	}
4570 	spin_lock(&memcg->peaks_lock);
4571 	list_del(&ofp->list);
4572 	spin_unlock(&memcg->peaks_lock);
4573 }
4574 
4575 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
4576 			  loff_t off, struct page_counter *pc,
4577 			  struct list_head *watchers)
4578 {
4579 	unsigned long usage;
4580 	struct cgroup_of_peak *peer_ctx;
4581 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4582 	struct cgroup_of_peak *ofp = of_peak(of);
4583 
4584 	spin_lock(&memcg->peaks_lock);
4585 
4586 	usage = page_counter_read(pc);
4587 	WRITE_ONCE(pc->local_watermark, usage);
4588 
4589 	list_for_each_entry(peer_ctx, watchers, list)
4590 		if (usage > peer_ctx->value)
4591 			WRITE_ONCE(peer_ctx->value, usage);
4592 
4593 	/* initial write, register watcher */
4594 	if (ofp->value == OFP_PEAK_UNSET)
4595 		list_add(&ofp->list, watchers);
4596 
4597 	WRITE_ONCE(ofp->value, usage);
4598 	spin_unlock(&memcg->peaks_lock);
4599 
4600 	return nbytes;
4601 }
4602 
4603 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
4604 				 size_t nbytes, loff_t off)
4605 {
4606 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4607 
4608 	return peak_write(of, buf, nbytes, off, &memcg->memory,
4609 			  &memcg->memory_peaks);
4610 }
4611 
4612 #undef OFP_PEAK_UNSET
4613 
4614 static int memory_min_show(struct seq_file *m, void *v)
4615 {
4616 	return seq_puts_memcg_tunable(m,
4617 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
4618 }
4619 
4620 static ssize_t memory_min_write(struct kernfs_open_file *of,
4621 				char *buf, size_t nbytes, loff_t off)
4622 {
4623 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4624 	unsigned long min;
4625 	int err;
4626 
4627 	buf = strstrip(buf);
4628 	err = page_counter_memparse(buf, "max", &min);
4629 	if (err)
4630 		return err;
4631 
4632 	page_counter_set_min(&memcg->memory, min);
4633 
4634 	return nbytes;
4635 }
4636 
4637 static int memory_low_show(struct seq_file *m, void *v)
4638 {
4639 	return seq_puts_memcg_tunable(m,
4640 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
4641 }
4642 
4643 static ssize_t memory_low_write(struct kernfs_open_file *of,
4644 				char *buf, size_t nbytes, loff_t off)
4645 {
4646 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4647 	unsigned long low;
4648 	int err;
4649 
4650 	buf = strstrip(buf);
4651 	err = page_counter_memparse(buf, "max", &low);
4652 	if (err)
4653 		return err;
4654 
4655 	page_counter_set_low(&memcg->memory, low);
4656 
4657 	return nbytes;
4658 }
4659 
4660 static int memory_high_show(struct seq_file *m, void *v)
4661 {
4662 	return seq_puts_memcg_tunable(m,
4663 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
4664 }
4665 
4666 static ssize_t memory_high_write(struct kernfs_open_file *of,
4667 				 char *buf, size_t nbytes, loff_t off)
4668 {
4669 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4670 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
4671 	bool drained = false;
4672 	unsigned long high;
4673 	int err;
4674 
4675 	buf = strstrip(buf);
4676 	err = page_counter_memparse(buf, "max", &high);
4677 	if (err)
4678 		return err;
4679 
4680 	page_counter_set_high(&memcg->memory, high);
4681 
4682 	if (of->file->f_flags & O_NONBLOCK)
4683 		goto out;
4684 
4685 	for (;;) {
4686 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4687 		unsigned long reclaimed;
4688 
4689 		if (nr_pages <= high)
4690 			break;
4691 
4692 		if (signal_pending(current))
4693 			break;
4694 
4695 		if (!drained) {
4696 			drain_all_stock(memcg);
4697 			drained = true;
4698 			continue;
4699 		}
4700 
4701 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
4702 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
4703 
4704 		if (!reclaimed && !nr_retries--)
4705 			break;
4706 	}
4707 out:
4708 	memcg_wb_domain_size_changed(memcg);
4709 	return nbytes;
4710 }
4711 
4712 static int memory_max_show(struct seq_file *m, void *v)
4713 {
4714 	return seq_puts_memcg_tunable(m,
4715 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
4716 }
4717 
4718 static ssize_t memory_max_write(struct kernfs_open_file *of,
4719 				char *buf, size_t nbytes, loff_t off)
4720 {
4721 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4722 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
4723 	bool drained = false;
4724 	unsigned long max;
4725 	int err;
4726 
4727 	buf = strstrip(buf);
4728 	err = page_counter_memparse(buf, "max", &max);
4729 	if (err)
4730 		return err;
4731 
4732 	xchg(&memcg->memory.max, max);
4733 
4734 	if (of->file->f_flags & O_NONBLOCK)
4735 		goto out;
4736 
4737 	for (;;) {
4738 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4739 
4740 		if (nr_pages <= max)
4741 			break;
4742 
4743 		if (signal_pending(current))
4744 			break;
4745 
4746 		if (!drained) {
4747 			drain_all_stock(memcg);
4748 			drained = true;
4749 			continue;
4750 		}
4751 
4752 		if (nr_reclaims) {
4753 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
4754 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
4755 				nr_reclaims--;
4756 			continue;
4757 		}
4758 
4759 		memcg_memory_event(memcg, MEMCG_OOM);
4760 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
4761 			break;
4762 		cond_resched();
4763 	}
4764 out:
4765 	memcg_wb_domain_size_changed(memcg);
4766 	return nbytes;
4767 }
4768 
4769 /*
4770  * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
4771  * if any new events become available.
4772  */
4773 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
4774 {
4775 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
4776 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
4777 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
4778 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
4779 	seq_printf(m, "oom_kill %lu\n",
4780 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
4781 	seq_printf(m, "oom_group_kill %lu\n",
4782 		   atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
4783 	seq_printf(m, "sock_throttled %lu\n",
4784 		   atomic_long_read(&events[MEMCG_SOCK_THROTTLED]));
4785 }
4786 
4787 static int memory_events_show(struct seq_file *m, void *v)
4788 {
4789 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4790 
4791 	__memory_events_show(m, memcg->memory_events);
4792 	return 0;
4793 }
4794 
4795 static int memory_events_local_show(struct seq_file *m, void *v)
4796 {
4797 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4798 
4799 	__memory_events_show(m, memcg->memory_events_local);
4800 	return 0;
4801 }
4802 
4803 int memory_stat_show(struct seq_file *m, void *v)
4804 {
4805 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4806 	char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
4807 	struct seq_buf s;
4808 
4809 	if (!buf)
4810 		return -ENOMEM;
4811 	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
4812 	memory_stat_format(memcg, &s);
4813 	seq_puts(m, buf);
4814 	kfree(buf);
4815 	return 0;
4816 }
4817 
4818 #ifdef CONFIG_NUMA
4819 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
4820 						     int item)
4821 {
4822 	return lruvec_page_state(lruvec, item) *
4823 		memcg_page_state_output_unit(item);
4824 }
4825 
4826 static int memory_numa_stat_show(struct seq_file *m, void *v)
4827 {
4828 	int i;
4829 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4830 
4831 	mem_cgroup_flush_stats(memcg);
4832 
4833 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
4834 		int nid;
4835 
4836 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
4837 			continue;
4838 
4839 		seq_printf(m, "%s", memory_stats[i].name);
4840 		for_each_node_state(nid, N_MEMORY) {
4841 			u64 size;
4842 			struct lruvec *lruvec;
4843 
4844 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4845 			size = lruvec_page_state_output(lruvec,
4846 							memory_stats[i].idx);
4847 			seq_printf(m, " N%d=%llu", nid, size);
4848 		}
4849 		seq_putc(m, '\n');
4850 	}
4851 
4852 	return 0;
4853 }
4854 #endif
4855 
4856 static int memory_oom_group_show(struct seq_file *m, void *v)
4857 {
4858 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4859 
4860 	seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
4861 
4862 	return 0;
4863 }
4864 
4865 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
4866 				      char *buf, size_t nbytes, loff_t off)
4867 {
4868 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4869 	int ret, oom_group;
4870 
4871 	buf = strstrip(buf);
4872 	if (!buf)
4873 		return -EINVAL;
4874 
4875 	ret = kstrtoint(buf, 0, &oom_group);
4876 	if (ret)
4877 		return ret;
4878 
4879 	if (oom_group != 0 && oom_group != 1)
4880 		return -EINVAL;
4881 
4882 	WRITE_ONCE(memcg->oom_group, oom_group);
4883 
4884 	return nbytes;
4885 }
4886 
4887 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
4888 			      size_t nbytes, loff_t off)
4889 {
4890 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4891 	int ret;
4892 
4893 	ret = user_proactive_reclaim(buf, memcg, NULL);
4894 	if (ret)
4895 		return ret;
4896 
4897 	return nbytes;
4898 }
4899 
4900 static struct cftype memory_files[] = {
4901 	{
4902 		.name = "current",
4903 		.flags = CFTYPE_NOT_ON_ROOT,
4904 		.read_u64 = memory_current_read,
4905 	},
4906 	{
4907 		.name = "peak",
4908 		.flags = CFTYPE_NOT_ON_ROOT,
4909 		.open = peak_open,
4910 		.release = peak_release,
4911 		.seq_show = memory_peak_show,
4912 		.write = memory_peak_write,
4913 	},
4914 	{
4915 		.name = "min",
4916 		.flags = CFTYPE_NOT_ON_ROOT,
4917 		.seq_show = memory_min_show,
4918 		.write = memory_min_write,
4919 	},
4920 	{
4921 		.name = "low",
4922 		.flags = CFTYPE_NOT_ON_ROOT,
4923 		.seq_show = memory_low_show,
4924 		.write = memory_low_write,
4925 	},
4926 	{
4927 		.name = "high",
4928 		.flags = CFTYPE_NOT_ON_ROOT,
4929 		.seq_show = memory_high_show,
4930 		.write = memory_high_write,
4931 	},
4932 	{
4933 		.name = "max",
4934 		.flags = CFTYPE_NOT_ON_ROOT,
4935 		.seq_show = memory_max_show,
4936 		.write = memory_max_write,
4937 	},
4938 	{
4939 		.name = "events",
4940 		.flags = CFTYPE_NOT_ON_ROOT,
4941 		.file_offset = offsetof(struct mem_cgroup, events_file),
4942 		.seq_show = memory_events_show,
4943 	},
4944 	{
4945 		.name = "events.local",
4946 		.flags = CFTYPE_NOT_ON_ROOT,
4947 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
4948 		.seq_show = memory_events_local_show,
4949 	},
4950 	{
4951 		.name = "stat",
4952 		.seq_show = memory_stat_show,
4953 	},
4954 #ifdef CONFIG_NUMA
4955 	{
4956 		.name = "numa_stat",
4957 		.seq_show = memory_numa_stat_show,
4958 	},
4959 #endif
4960 	{
4961 		.name = "oom.group",
4962 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
4963 		.seq_show = memory_oom_group_show,
4964 		.write = memory_oom_group_write,
4965 	},
4966 	{
4967 		.name = "reclaim",
4968 		.flags = CFTYPE_NS_DELEGATABLE,
4969 		.write = memory_reclaim,
4970 	},
4971 	{ }	/* terminate */
4972 };
4973 
4974 struct cgroup_subsys memory_cgrp_subsys = {
4975 	.css_alloc = mem_cgroup_css_alloc,
4976 	.css_online = mem_cgroup_css_online,
4977 	.css_offline = mem_cgroup_css_offline,
4978 	.css_released = mem_cgroup_css_released,
4979 	.css_free = mem_cgroup_css_free,
4980 	.css_reset = mem_cgroup_css_reset,
4981 	.css_rstat_flush = mem_cgroup_css_rstat_flush,
4982 	.attach = mem_cgroup_attach,
4983 	.fork = mem_cgroup_fork,
4984 	.exit = mem_cgroup_exit,
4985 	.dfl_cftypes = memory_files,
4986 #ifdef CONFIG_MEMCG_V1
4987 	.legacy_cftypes = mem_cgroup_legacy_files,
4988 #endif
4989 	.early_init = 0,
4990 };
4991 
4992 /**
4993  * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
4994  * @root: the top ancestor of the sub-tree being checked
4995  * @memcg: the memory cgroup to check
4996  *
4997  * WARNING: This function is not stateless! It can only be used as part
4998  *          of a top-down tree iteration, not for isolated queries.
4999  */
5000 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
5001 				     struct mem_cgroup *memcg)
5002 {
5003 	bool recursive_protection =
5004 		cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
5005 
5006 	if (mem_cgroup_disabled())
5007 		return;
5008 
5009 	if (!root)
5010 		root = root_mem_cgroup;
5011 
5012 	page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
5013 }
5014 
5015 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
5016 			gfp_t gfp)
5017 {
5018 	int ret = 0;
5019 	struct obj_cgroup *objcg;
5020 
5021 	objcg = get_obj_cgroup_from_memcg(memcg);
5022 	/* Do not account at the root objcg level. */
5023 	if (!obj_cgroup_is_root(objcg))
5024 		ret = try_charge_memcg(memcg, gfp, folio_nr_pages(folio));
5025 	if (ret) {
5026 		obj_cgroup_put(objcg);
5027 		return ret;
5028 	}
5029 	commit_charge(folio, objcg);
5030 	memcg1_commit_charge(folio, memcg);
5031 
5032 	return ret;
5033 }
5034 
5035 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
5036 {
5037 	struct mem_cgroup *memcg;
5038 	int ret;
5039 
5040 	memcg = get_mem_cgroup_from_mm(mm);
5041 	ret = charge_memcg(folio, memcg, gfp);
5042 	css_put(&memcg->css);
5043 
5044 	return ret;
5045 }
5046 
5047 /**
5048  * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
5049  * @folio: folio being charged
5050  * @gfp: reclaim mode
5051  *
5052  * This function is called when allocating a huge page folio, after the page has
5053  * already been obtained and charged to the appropriate hugetlb cgroup
5054  * controller (if it is enabled).
5055  *
5056  * Returns ENOMEM if the memcg is already full.
5057  * Returns 0 if either the charge was successful, or if we skip the charging.
5058  */
5059 int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
5060 {
5061 	struct mem_cgroup *memcg = get_mem_cgroup_from_current();
5062 	int ret = 0;
5063 
5064 	/*
5065 	 * Even memcg does not account for hugetlb, we still want to update
5066 	 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip
5067 	 * charging the memcg.
5068 	 */
5069 	if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() ||
5070 		!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5071 		goto out;
5072 
5073 	if (charge_memcg(folio, memcg, gfp))
5074 		ret = -ENOMEM;
5075 
5076 out:
5077 	mem_cgroup_put(memcg);
5078 	return ret;
5079 }
5080 
5081 /**
5082  * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
5083  * @folio: folio to charge.
5084  * @mm: mm context of the victim
5085  * @gfp: reclaim mode
5086  * @entry: swap entry for which the folio is allocated
5087  *
5088  * This function charges a folio allocated for swapin. Please call this before
5089  * adding the folio to the swapcache.
5090  *
5091  * Returns 0 on success. Otherwise, an error code is returned.
5092  */
5093 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
5094 				  gfp_t gfp, swp_entry_t entry)
5095 {
5096 	struct mem_cgroup *memcg;
5097 	unsigned short id;
5098 	int ret;
5099 
5100 	if (mem_cgroup_disabled())
5101 		return 0;
5102 
5103 	id = lookup_swap_cgroup_id(entry);
5104 	rcu_read_lock();
5105 	memcg = mem_cgroup_from_private_id(id);
5106 	if (!memcg || !css_tryget_online(&memcg->css))
5107 		memcg = get_mem_cgroup_from_mm(mm);
5108 	rcu_read_unlock();
5109 
5110 	ret = charge_memcg(folio, memcg, gfp);
5111 
5112 	css_put(&memcg->css);
5113 	return ret;
5114 }
5115 
5116 struct uncharge_gather {
5117 	struct obj_cgroup *objcg;
5118 	unsigned long nr_memory;
5119 	unsigned long pgpgout;
5120 	unsigned long nr_kmem;
5121 	int nid;
5122 };
5123 
5124 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
5125 {
5126 	memset(ug, 0, sizeof(*ug));
5127 }
5128 
5129 static void uncharge_batch(const struct uncharge_gather *ug)
5130 {
5131 	struct mem_cgroup *memcg;
5132 
5133 	rcu_read_lock();
5134 	memcg = obj_cgroup_memcg(ug->objcg);
5135 	if (ug->nr_memory) {
5136 		memcg_uncharge(memcg, ug->nr_memory);
5137 		if (ug->nr_kmem) {
5138 			mod_memcg_state(memcg, MEMCG_KMEM, -ug->nr_kmem);
5139 			memcg1_account_kmem(memcg, -ug->nr_kmem);
5140 		}
5141 		memcg1_oom_recover(memcg);
5142 	}
5143 
5144 	memcg1_uncharge_batch(memcg, ug->pgpgout, ug->nr_memory, ug->nid);
5145 	rcu_read_unlock();
5146 
5147 	/* drop reference from uncharge_folio */
5148 	obj_cgroup_put(ug->objcg);
5149 }
5150 
5151 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
5152 {
5153 	long nr_pages;
5154 	struct obj_cgroup *objcg;
5155 
5156 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5157 
5158 	/*
5159 	 * Nobody should be changing or seriously looking at
5160 	 * folio objcg at this point, we have fully exclusive
5161 	 * access to the folio.
5162 	 */
5163 	objcg = folio_objcg(folio);
5164 	if (!objcg)
5165 		return;
5166 
5167 	if (ug->objcg != objcg) {
5168 		if (ug->objcg) {
5169 			uncharge_batch(ug);
5170 			uncharge_gather_clear(ug);
5171 		}
5172 		ug->objcg = objcg;
5173 		ug->nid = folio_nid(folio);
5174 
5175 		/* pairs with obj_cgroup_put in uncharge_batch */
5176 		obj_cgroup_get(objcg);
5177 	}
5178 
5179 	nr_pages = folio_nr_pages(folio);
5180 
5181 	if (folio_memcg_kmem(folio)) {
5182 		ug->nr_memory += nr_pages;
5183 		ug->nr_kmem += nr_pages;
5184 	} else {
5185 		/* LRU pages aren't accounted at the root level */
5186 		if (!obj_cgroup_is_root(objcg))
5187 			ug->nr_memory += nr_pages;
5188 		ug->pgpgout++;
5189 
5190 		WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
5191 	}
5192 
5193 	folio->memcg_data = 0;
5194 	obj_cgroup_put(objcg);
5195 }
5196 
5197 void __mem_cgroup_uncharge(struct folio *folio)
5198 {
5199 	struct uncharge_gather ug;
5200 
5201 	/* Don't touch folio->lru of any random page, pre-check: */
5202 	if (!folio_memcg_charged(folio))
5203 		return;
5204 
5205 	uncharge_gather_clear(&ug);
5206 	uncharge_folio(folio, &ug);
5207 	uncharge_batch(&ug);
5208 }
5209 
5210 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
5211 {
5212 	struct uncharge_gather ug;
5213 	unsigned int i;
5214 
5215 	uncharge_gather_clear(&ug);
5216 	for (i = 0; i < folios->nr; i++)
5217 		uncharge_folio(folios->folios[i], &ug);
5218 	if (ug.objcg)
5219 		uncharge_batch(&ug);
5220 }
5221 
5222 /**
5223  * mem_cgroup_replace_folio - Charge a folio's replacement.
5224  * @old: Currently circulating folio.
5225  * @new: Replacement folio.
5226  *
5227  * Charge @new as a replacement folio for @old. @old will
5228  * be uncharged upon free.
5229  *
5230  * Both folios must be locked, @new->mapping must be set up.
5231  */
5232 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
5233 {
5234 	struct mem_cgroup *memcg;
5235 	struct obj_cgroup *objcg;
5236 	long nr_pages = folio_nr_pages(new);
5237 
5238 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
5239 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5240 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5241 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
5242 
5243 	if (mem_cgroup_disabled())
5244 		return;
5245 
5246 	/* Page cache replacement: new folio already charged? */
5247 	if (folio_memcg_charged(new))
5248 		return;
5249 
5250 	objcg = folio_objcg(old);
5251 	VM_WARN_ON_ONCE_FOLIO(!objcg, old);
5252 	if (!objcg)
5253 		return;
5254 
5255 	rcu_read_lock();
5256 	memcg = obj_cgroup_memcg(objcg);
5257 	/* Force-charge the new page. The old one will be freed soon */
5258 	if (!obj_cgroup_is_root(objcg)) {
5259 		page_counter_charge(&memcg->memory, nr_pages);
5260 		if (do_memsw_account())
5261 			page_counter_charge(&memcg->memsw, nr_pages);
5262 	}
5263 
5264 	obj_cgroup_get(objcg);
5265 	commit_charge(new, objcg);
5266 	memcg1_commit_charge(new, memcg);
5267 	rcu_read_unlock();
5268 }
5269 
5270 /**
5271  * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
5272  * @old: Currently circulating folio.
5273  * @new: Replacement folio.
5274  *
5275  * Transfer the memcg data from the old folio to the new folio for migration.
5276  * The old folio's data info will be cleared. Note that the memory counters
5277  * will remain unchanged throughout the process.
5278  *
5279  * Both folios must be locked, @new->mapping must be set up.
5280  */
5281 void mem_cgroup_migrate(struct folio *old, struct folio *new)
5282 {
5283 	struct obj_cgroup *objcg;
5284 
5285 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
5286 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5287 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5288 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
5289 	VM_BUG_ON_FOLIO(folio_test_lru(old), old);
5290 
5291 	if (mem_cgroup_disabled())
5292 		return;
5293 
5294 	objcg = folio_objcg(old);
5295 	/*
5296 	 * Note that it is normal to see !objcg for a hugetlb folio.
5297 	 * For e.g, it could have been allocated when memory_hugetlb_accounting
5298 	 * was not selected.
5299 	 */
5300 	VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !objcg, old);
5301 	if (!objcg)
5302 		return;
5303 
5304 	/* Transfer the charge and the objcg ref */
5305 	commit_charge(new, objcg);
5306 
5307 	/* Warning should never happen, so don't worry about refcount non-0 */
5308 	WARN_ON_ONCE(folio_unqueue_deferred_split(old));
5309 	old->memcg_data = 0;
5310 }
5311 
5312 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
5313 EXPORT_SYMBOL(memcg_sockets_enabled_key);
5314 
5315 void mem_cgroup_sk_alloc(struct sock *sk)
5316 {
5317 	struct mem_cgroup *memcg;
5318 
5319 	if (!mem_cgroup_sockets_enabled)
5320 		return;
5321 
5322 	/* Do not associate the sock with unrelated interrupted task's memcg. */
5323 	if (!in_task())
5324 		return;
5325 
5326 	rcu_read_lock();
5327 	memcg = mem_cgroup_from_task(current);
5328 	if (mem_cgroup_is_root(memcg))
5329 		goto out;
5330 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
5331 		goto out;
5332 	if (css_tryget(&memcg->css))
5333 		sk->sk_memcg = memcg;
5334 out:
5335 	rcu_read_unlock();
5336 }
5337 
5338 void mem_cgroup_sk_free(struct sock *sk)
5339 {
5340 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5341 
5342 	if (memcg)
5343 		css_put(&memcg->css);
5344 }
5345 
5346 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk)
5347 {
5348 	struct mem_cgroup *memcg;
5349 
5350 	if (sk->sk_memcg == newsk->sk_memcg)
5351 		return;
5352 
5353 	mem_cgroup_sk_free(newsk);
5354 
5355 	memcg = mem_cgroup_from_sk(sk);
5356 	if (memcg)
5357 		css_get(&memcg->css);
5358 
5359 	newsk->sk_memcg = sk->sk_memcg;
5360 }
5361 
5362 /**
5363  * mem_cgroup_sk_charge - charge socket memory
5364  * @sk: socket in memcg to charge
5365  * @nr_pages: number of pages to charge
5366  * @gfp_mask: reclaim mode
5367  *
5368  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
5369  * @memcg's configured limit, %false if it doesn't.
5370  */
5371 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages,
5372 			  gfp_t gfp_mask)
5373 {
5374 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5375 
5376 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5377 		return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
5378 
5379 	if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) {
5380 		mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
5381 		return true;
5382 	}
5383 
5384 	return false;
5385 }
5386 
5387 /**
5388  * mem_cgroup_sk_uncharge - uncharge socket memory
5389  * @sk: socket in memcg to uncharge
5390  * @nr_pages: number of pages to uncharge
5391  */
5392 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages)
5393 {
5394 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5395 
5396 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
5397 		memcg1_uncharge_skmem(memcg, nr_pages);
5398 		return;
5399 	}
5400 
5401 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
5402 
5403 	refill_stock(memcg, nr_pages);
5404 }
5405 
5406 void mem_cgroup_flush_workqueue(void)
5407 {
5408 	flush_workqueue(memcg_wq);
5409 }
5410 
5411 static int __init cgroup_memory(char *s)
5412 {
5413 	char *token;
5414 
5415 	while ((token = strsep(&s, ",")) != NULL) {
5416 		if (!*token)
5417 			continue;
5418 		if (!strcmp(token, "nosocket"))
5419 			cgroup_memory_nosocket = true;
5420 		if (!strcmp(token, "nokmem"))
5421 			cgroup_memory_nokmem = true;
5422 		if (!strcmp(token, "nobpf"))
5423 			cgroup_memory_nobpf = true;
5424 	}
5425 	return 1;
5426 }
5427 __setup("cgroup.memory=", cgroup_memory);
5428 
5429 /*
5430  * Memory controller init before cgroup_init() initialize root_mem_cgroup.
5431  *
5432  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
5433  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
5434  * basically everything that doesn't depend on a specific mem_cgroup structure
5435  * should be initialized from here.
5436  */
5437 int __init mem_cgroup_init(void)
5438 {
5439 	unsigned int memcg_size;
5440 	int cpu;
5441 
5442 	/*
5443 	 * Currently s32 type (can refer to struct batched_lruvec_stat) is
5444 	 * used for per-memcg-per-cpu caching of per-node statistics. In order
5445 	 * to work fine, we should make sure that the overfill threshold can't
5446 	 * exceed S32_MAX / PAGE_SIZE.
5447 	 */
5448 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
5449 
5450 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
5451 				  memcg_hotplug_cpu_dead);
5452 
5453 	memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0);
5454 	WARN_ON(!memcg_wq);
5455 
5456 	for_each_possible_cpu(cpu) {
5457 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
5458 			  drain_local_memcg_stock);
5459 		INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work,
5460 			  drain_local_obj_stock);
5461 	}
5462 
5463 	memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
5464 	memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
5465 					 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
5466 
5467 	memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
5468 				     SLAB_PANIC | SLAB_HWCACHE_ALIGN);
5469 
5470 	return 0;
5471 }
5472 
5473 #ifdef CONFIG_SWAP
5474 /**
5475  * __mem_cgroup_try_charge_swap - try charging swap space for a folio
5476  * @folio: folio being added to swap
5477  * @entry: swap entry to charge
5478  *
5479  * Try to charge @folio's memcg for the swap space at @entry.
5480  *
5481  * Returns 0 on success, -ENOMEM on failure.
5482  */
5483 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
5484 {
5485 	unsigned int nr_pages = folio_nr_pages(folio);
5486 	struct page_counter *counter;
5487 	struct mem_cgroup *memcg;
5488 	struct obj_cgroup *objcg;
5489 
5490 	if (do_memsw_account())
5491 		return 0;
5492 
5493 	objcg = folio_objcg(folio);
5494 	VM_WARN_ON_ONCE_FOLIO(!objcg, folio);
5495 	if (!objcg)
5496 		return 0;
5497 
5498 	rcu_read_lock();
5499 	memcg = obj_cgroup_memcg(objcg);
5500 	if (!entry.val) {
5501 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5502 		rcu_read_unlock();
5503 		return 0;
5504 	}
5505 
5506 	memcg = mem_cgroup_private_id_get_online(memcg, nr_pages);
5507 	/* memcg is pined by memcg ID. */
5508 	rcu_read_unlock();
5509 
5510 	if (!mem_cgroup_is_root(memcg) &&
5511 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
5512 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
5513 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5514 		mem_cgroup_private_id_put(memcg, nr_pages);
5515 		return -ENOMEM;
5516 	}
5517 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
5518 
5519 	swap_cgroup_record(folio, mem_cgroup_private_id(memcg), entry);
5520 
5521 	return 0;
5522 }
5523 
5524 /**
5525  * __mem_cgroup_uncharge_swap - uncharge swap space
5526  * @entry: swap entry to uncharge
5527  * @nr_pages: the amount of swap space to uncharge
5528  */
5529 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
5530 {
5531 	struct mem_cgroup *memcg;
5532 	unsigned short id;
5533 
5534 	id = swap_cgroup_clear(entry, nr_pages);
5535 	rcu_read_lock();
5536 	memcg = mem_cgroup_from_private_id(id);
5537 	if (memcg) {
5538 		if (!mem_cgroup_is_root(memcg)) {
5539 			if (do_memsw_account())
5540 				page_counter_uncharge(&memcg->memsw, nr_pages);
5541 			else
5542 				page_counter_uncharge(&memcg->swap, nr_pages);
5543 		}
5544 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
5545 		mem_cgroup_private_id_put(memcg, nr_pages);
5546 	}
5547 	rcu_read_unlock();
5548 }
5549 
5550 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
5551 {
5552 	long nr_swap_pages = get_nr_swap_pages();
5553 
5554 	if (mem_cgroup_disabled() || do_memsw_account())
5555 		return nr_swap_pages;
5556 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
5557 		nr_swap_pages = min_t(long, nr_swap_pages,
5558 				      READ_ONCE(memcg->swap.max) -
5559 				      page_counter_read(&memcg->swap));
5560 	return nr_swap_pages;
5561 }
5562 
5563 bool mem_cgroup_swap_full(struct folio *folio)
5564 {
5565 	struct mem_cgroup *memcg;
5566 	bool ret = false;
5567 
5568 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5569 
5570 	if (vm_swap_full())
5571 		return true;
5572 	if (do_memsw_account() || !folio_memcg_charged(folio))
5573 		return ret;
5574 
5575 	rcu_read_lock();
5576 	memcg = folio_memcg(folio);
5577 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
5578 		unsigned long usage = page_counter_read(&memcg->swap);
5579 
5580 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
5581 		    usage * 2 >= READ_ONCE(memcg->swap.max)) {
5582 			ret = true;
5583 			break;
5584 		}
5585 	}
5586 	rcu_read_unlock();
5587 
5588 	return ret;
5589 }
5590 
5591 static int __init setup_swap_account(char *s)
5592 {
5593 	bool res;
5594 
5595 	if (!kstrtobool(s, &res) && !res)
5596 		pr_warn_once("The swapaccount=0 commandline option is deprecated "
5597 			     "in favor of configuring swap control via cgroupfs. "
5598 			     "Please report your usecase to linux-mm@kvack.org if you "
5599 			     "depend on this functionality.\n");
5600 	return 1;
5601 }
5602 __setup("swapaccount=", setup_swap_account);
5603 
5604 static u64 swap_current_read(struct cgroup_subsys_state *css,
5605 			     struct cftype *cft)
5606 {
5607 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5608 
5609 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
5610 }
5611 
5612 static int swap_peak_show(struct seq_file *sf, void *v)
5613 {
5614 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
5615 
5616 	return peak_show(sf, v, &memcg->swap);
5617 }
5618 
5619 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
5620 			       size_t nbytes, loff_t off)
5621 {
5622 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5623 
5624 	return peak_write(of, buf, nbytes, off, &memcg->swap,
5625 			  &memcg->swap_peaks);
5626 }
5627 
5628 static int swap_high_show(struct seq_file *m, void *v)
5629 {
5630 	return seq_puts_memcg_tunable(m,
5631 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
5632 }
5633 
5634 static ssize_t swap_high_write(struct kernfs_open_file *of,
5635 			       char *buf, size_t nbytes, loff_t off)
5636 {
5637 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5638 	unsigned long high;
5639 	int err;
5640 
5641 	buf = strstrip(buf);
5642 	err = page_counter_memparse(buf, "max", &high);
5643 	if (err)
5644 		return err;
5645 
5646 	page_counter_set_high(&memcg->swap, high);
5647 
5648 	return nbytes;
5649 }
5650 
5651 static int swap_max_show(struct seq_file *m, void *v)
5652 {
5653 	return seq_puts_memcg_tunable(m,
5654 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
5655 }
5656 
5657 static ssize_t swap_max_write(struct kernfs_open_file *of,
5658 			      char *buf, size_t nbytes, loff_t off)
5659 {
5660 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5661 	unsigned long max;
5662 	int err;
5663 
5664 	buf = strstrip(buf);
5665 	err = page_counter_memparse(buf, "max", &max);
5666 	if (err)
5667 		return err;
5668 
5669 	xchg(&memcg->swap.max, max);
5670 
5671 	return nbytes;
5672 }
5673 
5674 static int swap_events_show(struct seq_file *m, void *v)
5675 {
5676 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5677 
5678 	seq_printf(m, "high %lu\n",
5679 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
5680 	seq_printf(m, "max %lu\n",
5681 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
5682 	seq_printf(m, "fail %lu\n",
5683 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
5684 
5685 	return 0;
5686 }
5687 
5688 static struct cftype swap_files[] = {
5689 	{
5690 		.name = "swap.current",
5691 		.flags = CFTYPE_NOT_ON_ROOT,
5692 		.read_u64 = swap_current_read,
5693 	},
5694 	{
5695 		.name = "swap.high",
5696 		.flags = CFTYPE_NOT_ON_ROOT,
5697 		.seq_show = swap_high_show,
5698 		.write = swap_high_write,
5699 	},
5700 	{
5701 		.name = "swap.max",
5702 		.flags = CFTYPE_NOT_ON_ROOT,
5703 		.seq_show = swap_max_show,
5704 		.write = swap_max_write,
5705 	},
5706 	{
5707 		.name = "swap.peak",
5708 		.flags = CFTYPE_NOT_ON_ROOT,
5709 		.open = peak_open,
5710 		.release = peak_release,
5711 		.seq_show = swap_peak_show,
5712 		.write = swap_peak_write,
5713 	},
5714 	{
5715 		.name = "swap.events",
5716 		.flags = CFTYPE_NOT_ON_ROOT,
5717 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
5718 		.seq_show = swap_events_show,
5719 	},
5720 	{ }	/* terminate */
5721 };
5722 
5723 #ifdef CONFIG_ZSWAP
5724 /**
5725  * obj_cgroup_may_zswap - check if this cgroup can zswap
5726  * @objcg: the object cgroup
5727  *
5728  * Check if the hierarchical zswap limit has been reached.
5729  *
5730  * This doesn't check for specific headroom, and it is not atomic
5731  * either. But with zswap, the size of the allocation is only known
5732  * once compression has occurred, and this optimistic pre-check avoids
5733  * spending cycles on compression when there is already no room left
5734  * or zswap is disabled altogether somewhere in the hierarchy.
5735  */
5736 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
5737 {
5738 	struct mem_cgroup *memcg, *original_memcg;
5739 	bool ret = true;
5740 
5741 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5742 		return true;
5743 
5744 	original_memcg = get_mem_cgroup_from_objcg(objcg);
5745 	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
5746 	     memcg = parent_mem_cgroup(memcg)) {
5747 		unsigned long max = READ_ONCE(memcg->zswap_max);
5748 		unsigned long pages;
5749 
5750 		if (max == PAGE_COUNTER_MAX)
5751 			continue;
5752 		if (max == 0) {
5753 			ret = false;
5754 			break;
5755 		}
5756 
5757 		/* Force flush to get accurate stats for charging */
5758 		__mem_cgroup_flush_stats(memcg, true);
5759 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
5760 		if (pages < max)
5761 			continue;
5762 		ret = false;
5763 		break;
5764 	}
5765 	mem_cgroup_put(original_memcg);
5766 	return ret;
5767 }
5768 
5769 /**
5770  * obj_cgroup_charge_zswap - charge compression backend memory
5771  * @objcg: the object cgroup
5772  * @size: size of compressed object
5773  *
5774  * This forces the charge after obj_cgroup_may_zswap() allowed
5775  * compression and storage in zswap for this cgroup to go ahead.
5776  */
5777 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
5778 {
5779 	struct mem_cgroup *memcg;
5780 
5781 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5782 		return;
5783 
5784 	if (obj_cgroup_is_root(objcg))
5785 		return;
5786 
5787 	VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
5788 
5789 	/* PF_MEMALLOC context, charging must succeed */
5790 	if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
5791 		VM_WARN_ON_ONCE(1);
5792 
5793 	rcu_read_lock();
5794 	memcg = obj_cgroup_memcg(objcg);
5795 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
5796 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
5797 	if (size == PAGE_SIZE)
5798 		mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, 1);
5799 	rcu_read_unlock();
5800 }
5801 
5802 /**
5803  * obj_cgroup_uncharge_zswap - uncharge compression backend memory
5804  * @objcg: the object cgroup
5805  * @size: size of compressed object
5806  *
5807  * Uncharges zswap memory on page in.
5808  */
5809 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
5810 {
5811 	struct mem_cgroup *memcg;
5812 
5813 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5814 		return;
5815 
5816 	if (obj_cgroup_is_root(objcg))
5817 		return;
5818 
5819 	obj_cgroup_uncharge(objcg, size);
5820 
5821 	rcu_read_lock();
5822 	memcg = obj_cgroup_memcg(objcg);
5823 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
5824 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
5825 	if (size == PAGE_SIZE)
5826 		mod_memcg_state(memcg, MEMCG_ZSWAP_INCOMP, -1);
5827 	rcu_read_unlock();
5828 }
5829 
5830 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
5831 {
5832 	/* if zswap is disabled, do not block pages going to the swapping device */
5833 	if (!zswap_is_enabled())
5834 		return true;
5835 
5836 	for (; memcg; memcg = parent_mem_cgroup(memcg))
5837 		if (!READ_ONCE(memcg->zswap_writeback))
5838 			return false;
5839 
5840 	return true;
5841 }
5842 
5843 static u64 zswap_current_read(struct cgroup_subsys_state *css,
5844 			      struct cftype *cft)
5845 {
5846 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5847 
5848 	mem_cgroup_flush_stats(memcg);
5849 	return memcg_page_state(memcg, MEMCG_ZSWAP_B);
5850 }
5851 
5852 static int zswap_max_show(struct seq_file *m, void *v)
5853 {
5854 	return seq_puts_memcg_tunable(m,
5855 		READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
5856 }
5857 
5858 static ssize_t zswap_max_write(struct kernfs_open_file *of,
5859 			       char *buf, size_t nbytes, loff_t off)
5860 {
5861 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5862 	unsigned long max;
5863 	int err;
5864 
5865 	buf = strstrip(buf);
5866 	err = page_counter_memparse(buf, "max", &max);
5867 	if (err)
5868 		return err;
5869 
5870 	xchg(&memcg->zswap_max, max);
5871 
5872 	return nbytes;
5873 }
5874 
5875 static int zswap_writeback_show(struct seq_file *m, void *v)
5876 {
5877 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5878 
5879 	seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
5880 	return 0;
5881 }
5882 
5883 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
5884 				char *buf, size_t nbytes, loff_t off)
5885 {
5886 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5887 	int zswap_writeback;
5888 	ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
5889 
5890 	if (parse_ret)
5891 		return parse_ret;
5892 
5893 	if (zswap_writeback != 0 && zswap_writeback != 1)
5894 		return -EINVAL;
5895 
5896 	WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
5897 	return nbytes;
5898 }
5899 
5900 static struct cftype zswap_files[] = {
5901 	{
5902 		.name = "zswap.current",
5903 		.flags = CFTYPE_NOT_ON_ROOT,
5904 		.read_u64 = zswap_current_read,
5905 	},
5906 	{
5907 		.name = "zswap.max",
5908 		.flags = CFTYPE_NOT_ON_ROOT,
5909 		.seq_show = zswap_max_show,
5910 		.write = zswap_max_write,
5911 	},
5912 	{
5913 		.name = "zswap.writeback",
5914 		.seq_show = zswap_writeback_show,
5915 		.write = zswap_writeback_write,
5916 	},
5917 	{ }	/* terminate */
5918 };
5919 #endif /* CONFIG_ZSWAP */
5920 
5921 static int __init mem_cgroup_swap_init(void)
5922 {
5923 	if (mem_cgroup_disabled())
5924 		return 0;
5925 
5926 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
5927 #ifdef CONFIG_MEMCG_V1
5928 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
5929 #endif
5930 #ifdef CONFIG_ZSWAP
5931 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
5932 #endif
5933 	return 0;
5934 }
5935 subsys_initcall(mem_cgroup_swap_init);
5936 
5937 #endif /* CONFIG_SWAP */
5938 
5939 void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask)
5940 {
5941 	nodemask_t allowed;
5942 
5943 	if (!memcg)
5944 		return;
5945 
5946 	/*
5947 	 * Since this interface is intended for use by migration paths, and
5948 	 * reclaim and migration are subject to race conditions such as changes
5949 	 * in effective_mems and hot-unpluging of nodes, inaccurate allowed
5950 	 * mask is acceptable.
5951 	 */
5952 	cpuset_nodes_allowed(memcg->css.cgroup, &allowed);
5953 	nodes_and(*mask, *mask, allowed);
5954 }
5955 
5956 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
5957 {
5958 	if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5959 		return;
5960 
5961 	if (!memcg)
5962 		memcg = root_mem_cgroup;
5963 
5964 	pr_warn("Memory cgroup min protection %lukB -- low protection %lukB",
5965 		K(atomic_long_read(&memcg->memory.children_min_usage)),
5966 		K(atomic_long_read(&memcg->memory.children_low_usage)));
5967 }
5968