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