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