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