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