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