xref: /linux/mm/memcontrol.c (revision 458c95de5c55c05b7a149da1509f4f0f68d28625)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
3  *
4  * Copyright IBM Corporation, 2007
5  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6  *
7  * Copyright 2007 OpenVZ SWsoft Inc
8  * Author: Pavel Emelianov <xemul@openvz.org>
9  *
10  * Memory thresholds
11  * Copyright (C) 2009 Nokia Corporation
12  * Author: Kirill A. Shutemov
13  *
14  * Kernel Memory Controller
15  * Copyright (C) 2012 Parallels Inc. and Google Inc.
16  * Authors: Glauber Costa and Suleiman Souhlal
17  *
18  * Native page reclaim
19  * Charge lifetime sanitation
20  * Lockless page tracking & accounting
21  * Unified hierarchy configuration model
22  * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
23  *
24  * Per memcg lru locking
25  * Copyright (C) 2020 Alibaba, Inc, Alex Shi
26  */
27 
28 #include <linux/cgroup-defs.h>
29 #include <linux/page_counter.h>
30 #include <linux/memcontrol.h>
31 #include <linux/cgroup.h>
32 #include <linux/cpuset.h>
33 #include <linux/sched/mm.h>
34 #include <linux/shmem_fs.h>
35 #include <linux/hugetlb.h>
36 #include <linux/pagemap.h>
37 #include <linux/pagevec.h>
38 #include <linux/vm_event_item.h>
39 #include <linux/smp.h>
40 #include <linux/page-flags.h>
41 #include <linux/backing-dev.h>
42 #include <linux/bit_spinlock.h>
43 #include <linux/rcupdate.h>
44 #include <linux/limits.h>
45 #include <linux/export.h>
46 #include <linux/list.h>
47 #include <linux/mutex.h>
48 #include <linux/rbtree.h>
49 #include <linux/slab.h>
50 #include <linux/swapops.h>
51 #include <linux/spinlock.h>
52 #include <linux/fs.h>
53 #include <linux/seq_file.h>
54 #include <linux/vmpressure.h>
55 #include <linux/memremap.h>
56 #include <linux/mm_inline.h>
57 #include <linux/swap_cgroup.h>
58 #include <linux/cpu.h>
59 #include <linux/oom.h>
60 #include <linux/lockdep.h>
61 #include <linux/resume_user_mode.h>
62 #include <linux/psi.h>
63 #include <linux/seq_buf.h>
64 #include <linux/sched/isolation.h>
65 #include <linux/kmemleak.h>
66 #include "internal.h"
67 #include <net/sock.h>
68 #include <net/ip.h>
69 #include "slab.h"
70 #include "memcontrol-v1.h"
71 
72 #include <linux/uaccess.h>
73 
74 #define CREATE_TRACE_POINTS
75 #include <trace/events/memcg.h>
76 #undef CREATE_TRACE_POINTS
77 
78 #include <trace/events/vmscan.h>
79 
80 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
81 EXPORT_SYMBOL(memory_cgrp_subsys);
82 
83 struct mem_cgroup *root_mem_cgroup __read_mostly;
84 EXPORT_SYMBOL(root_mem_cgroup);
85 
86 /* Active memory cgroup to use from an interrupt context */
87 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
88 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
89 
90 /* Socket memory accounting disabled? */
91 static bool cgroup_memory_nosocket __ro_after_init;
92 
93 /* Kernel memory accounting disabled? */
94 static bool cgroup_memory_nokmem __ro_after_init;
95 
96 /* BPF memory accounting disabled? */
97 static bool cgroup_memory_nobpf __ro_after_init;
98 
99 static struct workqueue_struct *memcg_wq __ro_after_init;
100 
101 static struct kmem_cache *memcg_cachep;
102 static struct kmem_cache *memcg_pn_cachep;
103 
104 #ifdef CONFIG_CGROUP_WRITEBACK
105 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
106 #endif
107 
108 static inline bool task_is_dying(void)
109 {
110 	return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
111 		(current->flags & PF_EXITING);
112 }
113 
114 /* Some nice accessors for the vmpressure. */
115 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
116 {
117 	if (!memcg)
118 		memcg = root_mem_cgroup;
119 	return &memcg->vmpressure;
120 }
121 
122 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
123 {
124 	return container_of(vmpr, struct mem_cgroup, vmpressure);
125 }
126 
127 #define SEQ_BUF_SIZE SZ_4K
128 #define CURRENT_OBJCG_UPDATE_BIT 0
129 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
130 
131 static DEFINE_SPINLOCK(objcg_lock);
132 
133 bool mem_cgroup_kmem_disabled(void)
134 {
135 	return cgroup_memory_nokmem;
136 }
137 
138 static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages);
139 
140 static void obj_cgroup_release(struct percpu_ref *ref)
141 {
142 	struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
143 	unsigned int nr_bytes;
144 	unsigned int nr_pages;
145 	unsigned long flags;
146 
147 	/*
148 	 * At this point all allocated objects are freed, and
149 	 * objcg->nr_charged_bytes can't have an arbitrary byte value.
150 	 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
151 	 *
152 	 * The following sequence can lead to it:
153 	 * 1) CPU0: objcg == stock->cached_objcg
154 	 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
155 	 *          PAGE_SIZE bytes are charged
156 	 * 3) CPU1: a process from another memcg is allocating something,
157 	 *          the stock if flushed,
158 	 *          objcg->nr_charged_bytes = PAGE_SIZE - 92
159 	 * 5) CPU0: we do release this object,
160 	 *          92 bytes are added to stock->nr_bytes
161 	 * 6) CPU0: stock is flushed,
162 	 *          92 bytes are added to objcg->nr_charged_bytes
163 	 *
164 	 * In the result, nr_charged_bytes == PAGE_SIZE.
165 	 * This page will be uncharged in obj_cgroup_release().
166 	 */
167 	nr_bytes = atomic_read(&objcg->nr_charged_bytes);
168 	WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
169 	nr_pages = nr_bytes >> PAGE_SHIFT;
170 
171 	if (nr_pages) {
172 		struct mem_cgroup *memcg;
173 
174 		memcg = get_mem_cgroup_from_objcg(objcg);
175 		mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
176 		memcg1_account_kmem(memcg, -nr_pages);
177 		if (!mem_cgroup_is_root(memcg))
178 			memcg_uncharge(memcg, nr_pages);
179 		mem_cgroup_put(memcg);
180 	}
181 
182 	spin_lock_irqsave(&objcg_lock, flags);
183 	list_del(&objcg->list);
184 	spin_unlock_irqrestore(&objcg_lock, flags);
185 
186 	percpu_ref_exit(ref);
187 	kfree_rcu(objcg, rcu);
188 }
189 
190 static struct obj_cgroup *obj_cgroup_alloc(void)
191 {
192 	struct obj_cgroup *objcg;
193 	int ret;
194 
195 	objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
196 	if (!objcg)
197 		return NULL;
198 
199 	ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
200 			      GFP_KERNEL);
201 	if (ret) {
202 		kfree(objcg);
203 		return NULL;
204 	}
205 	INIT_LIST_HEAD(&objcg->list);
206 	return objcg;
207 }
208 
209 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
210 				  struct mem_cgroup *parent)
211 {
212 	struct obj_cgroup *objcg, *iter;
213 
214 	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
215 
216 	spin_lock_irq(&objcg_lock);
217 
218 	/* 1) Ready to reparent active objcg. */
219 	list_add(&objcg->list, &memcg->objcg_list);
220 	/* 2) Reparent active objcg and already reparented objcgs to parent. */
221 	list_for_each_entry(iter, &memcg->objcg_list, list)
222 		WRITE_ONCE(iter->memcg, parent);
223 	/* 3) Move already reparented objcgs to the parent's list */
224 	list_splice(&memcg->objcg_list, &parent->objcg_list);
225 
226 	spin_unlock_irq(&objcg_lock);
227 
228 	percpu_ref_kill(&objcg->refcnt);
229 }
230 
231 /*
232  * A lot of the calls to the cache allocation functions are expected to be
233  * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
234  * conditional to this static branch, we'll have to allow modules that does
235  * kmem_cache_alloc and the such to see this symbol as well
236  */
237 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
238 EXPORT_SYMBOL(memcg_kmem_online_key);
239 
240 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
241 EXPORT_SYMBOL(memcg_bpf_enabled_key);
242 
243 /**
244  * mem_cgroup_css_from_folio - css of the memcg associated with a folio
245  * @folio: folio of interest
246  *
247  * If memcg is bound to the default hierarchy, css of the memcg associated
248  * with @folio is returned.  The returned css remains associated with @folio
249  * until it is released.
250  *
251  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
252  * is returned.
253  */
254 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
255 {
256 	struct mem_cgroup *memcg = folio_memcg(folio);
257 
258 	if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
259 		memcg = root_mem_cgroup;
260 
261 	return &memcg->css;
262 }
263 
264 /**
265  * page_cgroup_ino - return inode number of the memcg a page is charged to
266  * @page: the page
267  *
268  * Look up the closest online ancestor of the memory cgroup @page is charged to
269  * and return its inode number or 0 if @page is not charged to any cgroup. It
270  * is safe to call this function without holding a reference to @page.
271  *
272  * Note, this function is inherently racy, because there is nothing to prevent
273  * the cgroup inode from getting torn down and potentially reallocated a moment
274  * after page_cgroup_ino() returns, so it only should be used by callers that
275  * do not care (such as procfs interfaces).
276  */
277 ino_t page_cgroup_ino(struct page *page)
278 {
279 	struct mem_cgroup *memcg;
280 	unsigned long ino = 0;
281 
282 	rcu_read_lock();
283 	/* page_folio() is racy here, but the entire function is racy anyway */
284 	memcg = folio_memcg_check(page_folio(page));
285 
286 	while (memcg && !css_is_online(&memcg->css))
287 		memcg = parent_mem_cgroup(memcg);
288 	if (memcg)
289 		ino = cgroup_ino(memcg->css.cgroup);
290 	rcu_read_unlock();
291 	return ino;
292 }
293 EXPORT_SYMBOL_GPL(page_cgroup_ino);
294 
295 /* Subset of node_stat_item for memcg stats */
296 static const unsigned int memcg_node_stat_items[] = {
297 	NR_INACTIVE_ANON,
298 	NR_ACTIVE_ANON,
299 	NR_INACTIVE_FILE,
300 	NR_ACTIVE_FILE,
301 	NR_UNEVICTABLE,
302 	NR_SLAB_RECLAIMABLE_B,
303 	NR_SLAB_UNRECLAIMABLE_B,
304 	WORKINGSET_REFAULT_ANON,
305 	WORKINGSET_REFAULT_FILE,
306 	WORKINGSET_ACTIVATE_ANON,
307 	WORKINGSET_ACTIVATE_FILE,
308 	WORKINGSET_RESTORE_ANON,
309 	WORKINGSET_RESTORE_FILE,
310 	WORKINGSET_NODERECLAIM,
311 	NR_ANON_MAPPED,
312 	NR_FILE_MAPPED,
313 	NR_FILE_PAGES,
314 	NR_FILE_DIRTY,
315 	NR_WRITEBACK,
316 	NR_SHMEM,
317 	NR_SHMEM_THPS,
318 	NR_FILE_THPS,
319 	NR_ANON_THPS,
320 	NR_KERNEL_STACK_KB,
321 	NR_PAGETABLE,
322 	NR_SECONDARY_PAGETABLE,
323 #ifdef CONFIG_SWAP
324 	NR_SWAPCACHE,
325 #endif
326 #ifdef CONFIG_NUMA_BALANCING
327 	PGPROMOTE_SUCCESS,
328 #endif
329 	PGDEMOTE_KSWAPD,
330 	PGDEMOTE_DIRECT,
331 	PGDEMOTE_KHUGEPAGED,
332 	PGDEMOTE_PROACTIVE,
333 #ifdef CONFIG_HUGETLB_PAGE
334 	NR_HUGETLB,
335 #endif
336 };
337 
338 static const unsigned int memcg_stat_items[] = {
339 	MEMCG_SWAP,
340 	MEMCG_SOCK,
341 	MEMCG_PERCPU_B,
342 	MEMCG_VMALLOC,
343 	MEMCG_KMEM,
344 	MEMCG_ZSWAP_B,
345 	MEMCG_ZSWAPPED,
346 };
347 
348 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
349 #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
350 			   ARRAY_SIZE(memcg_stat_items))
351 #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
352 static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
353 
354 static void init_memcg_stats(void)
355 {
356 	u8 i, j = 0;
357 
358 	BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
359 
360 	memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
361 
362 	for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
363 		mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
364 
365 	for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
366 		mem_cgroup_stats_index[memcg_stat_items[i]] = j;
367 }
368 
369 static inline int memcg_stats_index(int idx)
370 {
371 	return mem_cgroup_stats_index[idx];
372 }
373 
374 struct lruvec_stats_percpu {
375 	/* Local (CPU and cgroup) state */
376 	long state[NR_MEMCG_NODE_STAT_ITEMS];
377 
378 	/* Delta calculation for lockless upward propagation */
379 	long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
380 };
381 
382 struct lruvec_stats {
383 	/* Aggregated (CPU and subtree) state */
384 	long state[NR_MEMCG_NODE_STAT_ITEMS];
385 
386 	/* Non-hierarchical (CPU aggregated) state */
387 	long state_local[NR_MEMCG_NODE_STAT_ITEMS];
388 
389 	/* Pending child counts during tree propagation */
390 	long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
391 };
392 
393 unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
394 {
395 	struct mem_cgroup_per_node *pn;
396 	long x;
397 	int i;
398 
399 	if (mem_cgroup_disabled())
400 		return node_page_state(lruvec_pgdat(lruvec), idx);
401 
402 	i = memcg_stats_index(idx);
403 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
404 		return 0;
405 
406 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
407 	x = READ_ONCE(pn->lruvec_stats->state[i]);
408 #ifdef CONFIG_SMP
409 	if (x < 0)
410 		x = 0;
411 #endif
412 	return x;
413 }
414 
415 unsigned long lruvec_page_state_local(struct lruvec *lruvec,
416 				      enum node_stat_item idx)
417 {
418 	struct mem_cgroup_per_node *pn;
419 	long x;
420 	int i;
421 
422 	if (mem_cgroup_disabled())
423 		return node_page_state(lruvec_pgdat(lruvec), idx);
424 
425 	i = memcg_stats_index(idx);
426 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
427 		return 0;
428 
429 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
430 	x = READ_ONCE(pn->lruvec_stats->state_local[i]);
431 #ifdef CONFIG_SMP
432 	if (x < 0)
433 		x = 0;
434 #endif
435 	return x;
436 }
437 
438 /* Subset of vm_event_item to report for memcg event stats */
439 static const unsigned int memcg_vm_event_stat[] = {
440 #ifdef CONFIG_MEMCG_V1
441 	PGPGIN,
442 	PGPGOUT,
443 #endif
444 	PSWPIN,
445 	PSWPOUT,
446 	PGSCAN_KSWAPD,
447 	PGSCAN_DIRECT,
448 	PGSCAN_KHUGEPAGED,
449 	PGSCAN_PROACTIVE,
450 	PGSTEAL_KSWAPD,
451 	PGSTEAL_DIRECT,
452 	PGSTEAL_KHUGEPAGED,
453 	PGSTEAL_PROACTIVE,
454 	PGFAULT,
455 	PGMAJFAULT,
456 	PGREFILL,
457 	PGACTIVATE,
458 	PGDEACTIVATE,
459 	PGLAZYFREE,
460 	PGLAZYFREED,
461 #ifdef CONFIG_SWAP
462 	SWPIN_ZERO,
463 	SWPOUT_ZERO,
464 #endif
465 #ifdef CONFIG_ZSWAP
466 	ZSWPIN,
467 	ZSWPOUT,
468 	ZSWPWB,
469 #endif
470 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
471 	THP_FAULT_ALLOC,
472 	THP_COLLAPSE_ALLOC,
473 	THP_SWPOUT,
474 	THP_SWPOUT_FALLBACK,
475 #endif
476 #ifdef CONFIG_NUMA_BALANCING
477 	NUMA_PAGE_MIGRATE,
478 	NUMA_PTE_UPDATES,
479 	NUMA_HINT_FAULTS,
480 #endif
481 };
482 
483 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
484 static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
485 
486 static void init_memcg_events(void)
487 {
488 	u8 i;
489 
490 	BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
491 
492 	memset(mem_cgroup_events_index, U8_MAX,
493 	       sizeof(mem_cgroup_events_index));
494 
495 	for (i = 0; i < NR_MEMCG_EVENTS; ++i)
496 		mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
497 }
498 
499 static inline int memcg_events_index(enum vm_event_item idx)
500 {
501 	return mem_cgroup_events_index[idx];
502 }
503 
504 struct memcg_vmstats_percpu {
505 	/* Stats updates since the last flush */
506 	unsigned int			stats_updates;
507 
508 	/* Cached pointers for fast iteration in memcg_rstat_updated() */
509 	struct memcg_vmstats_percpu __percpu	*parent_pcpu;
510 	struct memcg_vmstats			*vmstats;
511 
512 	/* The above should fit a single cacheline for memcg_rstat_updated() */
513 
514 	/* Local (CPU and cgroup) page state & events */
515 	long			state[MEMCG_VMSTAT_SIZE];
516 	unsigned long		events[NR_MEMCG_EVENTS];
517 
518 	/* Delta calculation for lockless upward propagation */
519 	long			state_prev[MEMCG_VMSTAT_SIZE];
520 	unsigned long		events_prev[NR_MEMCG_EVENTS];
521 } ____cacheline_aligned;
522 
523 struct memcg_vmstats {
524 	/* Aggregated (CPU and subtree) page state & events */
525 	long			state[MEMCG_VMSTAT_SIZE];
526 	unsigned long		events[NR_MEMCG_EVENTS];
527 
528 	/* Non-hierarchical (CPU aggregated) page state & events */
529 	long			state_local[MEMCG_VMSTAT_SIZE];
530 	unsigned long		events_local[NR_MEMCG_EVENTS];
531 
532 	/* Pending child counts during tree propagation */
533 	long			state_pending[MEMCG_VMSTAT_SIZE];
534 	unsigned long		events_pending[NR_MEMCG_EVENTS];
535 
536 	/* Stats updates since the last flush */
537 	atomic_t		stats_updates;
538 };
539 
540 /*
541  * memcg and lruvec stats flushing
542  *
543  * Many codepaths leading to stats update or read are performance sensitive and
544  * adding stats flushing in such codepaths is not desirable. So, to optimize the
545  * flushing the kernel does:
546  *
547  * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
548  *    rstat update tree grow unbounded.
549  *
550  * 2) Flush the stats synchronously on reader side only when there are more than
551  *    (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
552  *    will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
553  *    only for 2 seconds due to (1).
554  */
555 static void flush_memcg_stats_dwork(struct work_struct *w);
556 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
557 static u64 flush_last_time;
558 
559 #define FLUSH_TIME (2UL*HZ)
560 
561 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
562 {
563 	return atomic_read(&vmstats->stats_updates) >
564 		MEMCG_CHARGE_BATCH * num_online_cpus();
565 }
566 
567 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val,
568 				       int cpu)
569 {
570 	struct memcg_vmstats_percpu __percpu *statc_pcpu;
571 	struct memcg_vmstats_percpu *statc;
572 	unsigned int stats_updates;
573 
574 	if (!val)
575 		return;
576 
577 	css_rstat_updated(&memcg->css, cpu);
578 	statc_pcpu = memcg->vmstats_percpu;
579 	for (; statc_pcpu; statc_pcpu = statc->parent_pcpu) {
580 		statc = this_cpu_ptr(statc_pcpu);
581 		/*
582 		 * If @memcg is already flushable then all its ancestors are
583 		 * flushable as well and also there is no need to increase
584 		 * stats_updates.
585 		 */
586 		if (memcg_vmstats_needs_flush(statc->vmstats))
587 			break;
588 
589 		stats_updates = this_cpu_add_return(statc_pcpu->stats_updates,
590 						    abs(val));
591 		if (stats_updates < MEMCG_CHARGE_BATCH)
592 			continue;
593 
594 		stats_updates = this_cpu_xchg(statc_pcpu->stats_updates, 0);
595 		atomic_add(stats_updates, &statc->vmstats->stats_updates);
596 	}
597 }
598 
599 static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force)
600 {
601 	bool needs_flush = memcg_vmstats_needs_flush(memcg->vmstats);
602 
603 	trace_memcg_flush_stats(memcg, atomic_read(&memcg->vmstats->stats_updates),
604 		force, needs_flush);
605 
606 	if (!force && !needs_flush)
607 		return;
608 
609 	if (mem_cgroup_is_root(memcg))
610 		WRITE_ONCE(flush_last_time, jiffies_64);
611 
612 	css_rstat_flush(&memcg->css);
613 }
614 
615 /*
616  * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
617  * @memcg: root of the subtree to flush
618  *
619  * Flushing is serialized by the underlying global rstat lock. There is also a
620  * minimum amount of work to be done even if there are no stat updates to flush.
621  * Hence, we only flush the stats if the updates delta exceeds a threshold. This
622  * avoids unnecessary work and contention on the underlying lock.
623  */
624 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
625 {
626 	if (mem_cgroup_disabled())
627 		return;
628 
629 	if (!memcg)
630 		memcg = root_mem_cgroup;
631 
632 	__mem_cgroup_flush_stats(memcg, false);
633 }
634 
635 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
636 {
637 	/* Only flush if the periodic flusher is one full cycle late */
638 	if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
639 		mem_cgroup_flush_stats(memcg);
640 }
641 
642 static void flush_memcg_stats_dwork(struct work_struct *w)
643 {
644 	/*
645 	 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
646 	 * in latency-sensitive paths is as cheap as possible.
647 	 */
648 	__mem_cgroup_flush_stats(root_mem_cgroup, true);
649 	queue_delayed_work(system_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 	unsigned long obj_exts;
2631 	struct slabobj_ext *obj_ext;
2632 	unsigned int off;
2633 
2634 	obj_exts = slab_obj_exts(slab);
2635 	if (!obj_exts)
2636 		return NULL;
2637 
2638 	get_slab_obj_exts(obj_exts);
2639 	off = obj_to_index(slab->slab_cache, slab, p);
2640 	obj_ext = slab_obj_ext(slab, obj_exts, off);
2641 	if (obj_ext->objcg) {
2642 		struct obj_cgroup *objcg = obj_ext->objcg;
2643 
2644 		put_slab_obj_exts(obj_exts);
2645 		return obj_cgroup_memcg(objcg);
2646 	}
2647 	put_slab_obj_exts(obj_exts);
2648 
2649 	return NULL;
2650 }
2651 
2652 /*
2653  * Returns a pointer to the memory cgroup to which the kernel object is charged.
2654  * It is not suitable for objects allocated using vmalloc().
2655  *
2656  * A passed kernel object must be a slab object or a generic kernel page.
2657  *
2658  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2659  * cgroup_mutex, etc.
2660  */
2661 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2662 {
2663 	struct slab *slab;
2664 
2665 	if (mem_cgroup_disabled())
2666 		return NULL;
2667 
2668 	slab = virt_to_slab(p);
2669 	if (slab)
2670 		return mem_cgroup_from_obj_slab(slab, p);
2671 	return folio_memcg_check(virt_to_folio(p));
2672 }
2673 
2674 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2675 {
2676 	struct obj_cgroup *objcg = NULL;
2677 
2678 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
2679 		objcg = rcu_dereference(memcg->objcg);
2680 		if (likely(objcg && obj_cgroup_tryget(objcg)))
2681 			break;
2682 		objcg = NULL;
2683 	}
2684 	return objcg;
2685 }
2686 
2687 static struct obj_cgroup *current_objcg_update(void)
2688 {
2689 	struct mem_cgroup *memcg;
2690 	struct obj_cgroup *old, *objcg = NULL;
2691 
2692 	do {
2693 		/* Atomically drop the update bit. */
2694 		old = xchg(&current->objcg, NULL);
2695 		if (old) {
2696 			old = (struct obj_cgroup *)
2697 				((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
2698 			obj_cgroup_put(old);
2699 
2700 			old = NULL;
2701 		}
2702 
2703 		/* If new objcg is NULL, no reason for the second atomic update. */
2704 		if (!current->mm || (current->flags & PF_KTHREAD))
2705 			return NULL;
2706 
2707 		/*
2708 		 * Release the objcg pointer from the previous iteration,
2709 		 * if try_cmpxcg() below fails.
2710 		 */
2711 		if (unlikely(objcg)) {
2712 			obj_cgroup_put(objcg);
2713 			objcg = NULL;
2714 		}
2715 
2716 		/*
2717 		 * Obtain the new objcg pointer. The current task can be
2718 		 * asynchronously moved to another memcg and the previous
2719 		 * memcg can be offlined. So let's get the memcg pointer
2720 		 * and try get a reference to objcg under a rcu read lock.
2721 		 */
2722 
2723 		rcu_read_lock();
2724 		memcg = mem_cgroup_from_task(current);
2725 		objcg = __get_obj_cgroup_from_memcg(memcg);
2726 		rcu_read_unlock();
2727 
2728 		/*
2729 		 * Try set up a new objcg pointer atomically. If it
2730 		 * fails, it means the update flag was set concurrently, so
2731 		 * the whole procedure should be repeated.
2732 		 */
2733 	} while (!try_cmpxchg(&current->objcg, &old, objcg));
2734 
2735 	return objcg;
2736 }
2737 
2738 __always_inline struct obj_cgroup *current_obj_cgroup(void)
2739 {
2740 	struct mem_cgroup *memcg;
2741 	struct obj_cgroup *objcg;
2742 
2743 	if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi())
2744 		return NULL;
2745 
2746 	if (in_task()) {
2747 		memcg = current->active_memcg;
2748 		if (unlikely(memcg))
2749 			goto from_memcg;
2750 
2751 		objcg = READ_ONCE(current->objcg);
2752 		if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
2753 			objcg = current_objcg_update();
2754 		/*
2755 		 * Objcg reference is kept by the task, so it's safe
2756 		 * to use the objcg by the current task.
2757 		 */
2758 		return objcg;
2759 	}
2760 
2761 	memcg = this_cpu_read(int_active_memcg);
2762 	if (unlikely(memcg))
2763 		goto from_memcg;
2764 
2765 	return NULL;
2766 
2767 from_memcg:
2768 	objcg = NULL;
2769 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
2770 		/*
2771 		 * Memcg pointer is protected by scope (see set_active_memcg())
2772 		 * and is pinning the corresponding objcg, so objcg can't go
2773 		 * away and can be used within the scope without any additional
2774 		 * protection.
2775 		 */
2776 		objcg = rcu_dereference_check(memcg->objcg, 1);
2777 		if (likely(objcg))
2778 			break;
2779 	}
2780 
2781 	return objcg;
2782 }
2783 
2784 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
2785 {
2786 	struct obj_cgroup *objcg;
2787 
2788 	if (!memcg_kmem_online())
2789 		return NULL;
2790 
2791 	if (folio_memcg_kmem(folio)) {
2792 		objcg = __folio_objcg(folio);
2793 		obj_cgroup_get(objcg);
2794 	} else {
2795 		struct mem_cgroup *memcg;
2796 
2797 		rcu_read_lock();
2798 		memcg = __folio_memcg(folio);
2799 		if (memcg)
2800 			objcg = __get_obj_cgroup_from_memcg(memcg);
2801 		else
2802 			objcg = NULL;
2803 		rcu_read_unlock();
2804 	}
2805 	return objcg;
2806 }
2807 
2808 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
2809 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
2810 {
2811 	if (likely(!in_nmi())) {
2812 		mod_memcg_state(memcg, MEMCG_KMEM, val);
2813 	} else {
2814 		/* preemption is disabled in_nmi(). */
2815 		css_rstat_updated(&memcg->css, smp_processor_id());
2816 		atomic_add(val, &memcg->kmem_stat);
2817 	}
2818 }
2819 #else
2820 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
2821 {
2822 	mod_memcg_state(memcg, MEMCG_KMEM, val);
2823 }
2824 #endif
2825 
2826 /*
2827  * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2828  * @objcg: object cgroup to uncharge
2829  * @nr_pages: number of pages to uncharge
2830  */
2831 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2832 				      unsigned int nr_pages)
2833 {
2834 	struct mem_cgroup *memcg;
2835 
2836 	memcg = get_mem_cgroup_from_objcg(objcg);
2837 
2838 	account_kmem_nmi_safe(memcg, -nr_pages);
2839 	memcg1_account_kmem(memcg, -nr_pages);
2840 	if (!mem_cgroup_is_root(memcg))
2841 		refill_stock(memcg, nr_pages);
2842 
2843 	css_put(&memcg->css);
2844 }
2845 
2846 /*
2847  * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2848  * @objcg: object cgroup to charge
2849  * @gfp: reclaim mode
2850  * @nr_pages: number of pages to charge
2851  *
2852  * Returns 0 on success, an error code on failure.
2853  */
2854 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2855 				   unsigned int nr_pages)
2856 {
2857 	struct mem_cgroup *memcg;
2858 	int ret;
2859 
2860 	memcg = get_mem_cgroup_from_objcg(objcg);
2861 
2862 	ret = try_charge_memcg(memcg, gfp, nr_pages);
2863 	if (ret)
2864 		goto out;
2865 
2866 	account_kmem_nmi_safe(memcg, nr_pages);
2867 	memcg1_account_kmem(memcg, nr_pages);
2868 out:
2869 	css_put(&memcg->css);
2870 
2871 	return ret;
2872 }
2873 
2874 static struct obj_cgroup *page_objcg(const struct page *page)
2875 {
2876 	unsigned long memcg_data = page->memcg_data;
2877 
2878 	if (mem_cgroup_disabled() || !memcg_data)
2879 		return NULL;
2880 
2881 	VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM,
2882 			page);
2883 	return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM);
2884 }
2885 
2886 static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg)
2887 {
2888 	page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM;
2889 }
2890 
2891 /**
2892  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2893  * @page: page to charge
2894  * @gfp: reclaim mode
2895  * @order: allocation order
2896  *
2897  * Returns 0 on success, an error code on failure.
2898  */
2899 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2900 {
2901 	struct obj_cgroup *objcg;
2902 	int ret = 0;
2903 
2904 	objcg = current_obj_cgroup();
2905 	if (objcg) {
2906 		ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
2907 		if (!ret) {
2908 			obj_cgroup_get(objcg);
2909 			page_set_objcg(page, objcg);
2910 			return 0;
2911 		}
2912 	}
2913 	return ret;
2914 }
2915 
2916 /**
2917  * __memcg_kmem_uncharge_page: uncharge a kmem page
2918  * @page: page to uncharge
2919  * @order: allocation order
2920  */
2921 void __memcg_kmem_uncharge_page(struct page *page, int order)
2922 {
2923 	struct obj_cgroup *objcg = page_objcg(page);
2924 	unsigned int nr_pages = 1 << order;
2925 
2926 	if (!objcg)
2927 		return;
2928 
2929 	obj_cgroup_uncharge_pages(objcg, nr_pages);
2930 	page->memcg_data = 0;
2931 	obj_cgroup_put(objcg);
2932 }
2933 
2934 static void __account_obj_stock(struct obj_cgroup *objcg,
2935 				struct obj_stock_pcp *stock, int nr,
2936 				struct pglist_data *pgdat, enum node_stat_item idx)
2937 {
2938 	int *bytes;
2939 
2940 	/*
2941 	 * Save vmstat data in stock and skip vmstat array update unless
2942 	 * accumulating over a page of vmstat data or when pgdat changes.
2943 	 */
2944 	if (stock->cached_pgdat != pgdat) {
2945 		/* Flush the existing cached vmstat data */
2946 		struct pglist_data *oldpg = stock->cached_pgdat;
2947 
2948 		if (stock->nr_slab_reclaimable_b) {
2949 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
2950 					  stock->nr_slab_reclaimable_b);
2951 			stock->nr_slab_reclaimable_b = 0;
2952 		}
2953 		if (stock->nr_slab_unreclaimable_b) {
2954 			mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
2955 					  stock->nr_slab_unreclaimable_b);
2956 			stock->nr_slab_unreclaimable_b = 0;
2957 		}
2958 		stock->cached_pgdat = pgdat;
2959 	}
2960 
2961 	bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
2962 					       : &stock->nr_slab_unreclaimable_b;
2963 	/*
2964 	 * Even for large object >= PAGE_SIZE, the vmstat data will still be
2965 	 * cached locally at least once before pushing it out.
2966 	 */
2967 	if (!*bytes) {
2968 		*bytes = nr;
2969 		nr = 0;
2970 	} else {
2971 		*bytes += nr;
2972 		if (abs(*bytes) > PAGE_SIZE) {
2973 			nr = *bytes;
2974 			*bytes = 0;
2975 		} else {
2976 			nr = 0;
2977 		}
2978 	}
2979 	if (nr)
2980 		mod_objcg_mlstate(objcg, pgdat, idx, nr);
2981 }
2982 
2983 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
2984 			      struct pglist_data *pgdat, enum node_stat_item idx)
2985 {
2986 	struct obj_stock_pcp *stock;
2987 	bool ret = false;
2988 
2989 	if (!local_trylock(&obj_stock.lock))
2990 		return ret;
2991 
2992 	stock = this_cpu_ptr(&obj_stock);
2993 	if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
2994 		stock->nr_bytes -= nr_bytes;
2995 		ret = true;
2996 
2997 		if (pgdat)
2998 			__account_obj_stock(objcg, stock, nr_bytes, pgdat, idx);
2999 	}
3000 
3001 	local_unlock(&obj_stock.lock);
3002 
3003 	return ret;
3004 }
3005 
3006 static void drain_obj_stock(struct obj_stock_pcp *stock)
3007 {
3008 	struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
3009 
3010 	if (!old)
3011 		return;
3012 
3013 	if (stock->nr_bytes) {
3014 		unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3015 		unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3016 
3017 		if (nr_pages) {
3018 			struct mem_cgroup *memcg;
3019 
3020 			memcg = get_mem_cgroup_from_objcg(old);
3021 
3022 			mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
3023 			memcg1_account_kmem(memcg, -nr_pages);
3024 			if (!mem_cgroup_is_root(memcg))
3025 				memcg_uncharge(memcg, nr_pages);
3026 
3027 			css_put(&memcg->css);
3028 		}
3029 
3030 		/*
3031 		 * The leftover is flushed to the centralized per-memcg value.
3032 		 * On the next attempt to refill obj stock it will be moved
3033 		 * to a per-cpu stock (probably, on an other CPU), see
3034 		 * refill_obj_stock().
3035 		 *
3036 		 * How often it's flushed is a trade-off between the memory
3037 		 * limit enforcement accuracy and potential CPU contention,
3038 		 * so it might be changed in the future.
3039 		 */
3040 		atomic_add(nr_bytes, &old->nr_charged_bytes);
3041 		stock->nr_bytes = 0;
3042 	}
3043 
3044 	/*
3045 	 * Flush the vmstat data in current stock
3046 	 */
3047 	if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
3048 		if (stock->nr_slab_reclaimable_b) {
3049 			mod_objcg_mlstate(old, stock->cached_pgdat,
3050 					  NR_SLAB_RECLAIMABLE_B,
3051 					  stock->nr_slab_reclaimable_b);
3052 			stock->nr_slab_reclaimable_b = 0;
3053 		}
3054 		if (stock->nr_slab_unreclaimable_b) {
3055 			mod_objcg_mlstate(old, stock->cached_pgdat,
3056 					  NR_SLAB_UNRECLAIMABLE_B,
3057 					  stock->nr_slab_unreclaimable_b);
3058 			stock->nr_slab_unreclaimable_b = 0;
3059 		}
3060 		stock->cached_pgdat = NULL;
3061 	}
3062 
3063 	WRITE_ONCE(stock->cached_objcg, NULL);
3064 	obj_cgroup_put(old);
3065 }
3066 
3067 static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
3068 				     struct mem_cgroup *root_memcg)
3069 {
3070 	struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
3071 	struct mem_cgroup *memcg;
3072 	bool flush = false;
3073 
3074 	rcu_read_lock();
3075 	if (objcg) {
3076 		memcg = obj_cgroup_memcg(objcg);
3077 		if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3078 			flush = true;
3079 	}
3080 	rcu_read_unlock();
3081 
3082 	return flush;
3083 }
3084 
3085 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
3086 		bool allow_uncharge, int nr_acct, struct pglist_data *pgdat,
3087 		enum node_stat_item idx)
3088 {
3089 	struct obj_stock_pcp *stock;
3090 	unsigned int nr_pages = 0;
3091 
3092 	if (!local_trylock(&obj_stock.lock)) {
3093 		if (pgdat)
3094 			mod_objcg_mlstate(objcg, pgdat, idx, nr_bytes);
3095 		nr_pages = nr_bytes >> PAGE_SHIFT;
3096 		nr_bytes = nr_bytes & (PAGE_SIZE - 1);
3097 		atomic_add(nr_bytes, &objcg->nr_charged_bytes);
3098 		goto out;
3099 	}
3100 
3101 	stock = this_cpu_ptr(&obj_stock);
3102 	if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
3103 		drain_obj_stock(stock);
3104 		obj_cgroup_get(objcg);
3105 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
3106 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
3107 		WRITE_ONCE(stock->cached_objcg, objcg);
3108 
3109 		allow_uncharge = true;	/* Allow uncharge when objcg changes */
3110 	}
3111 	stock->nr_bytes += nr_bytes;
3112 
3113 	if (pgdat)
3114 		__account_obj_stock(objcg, stock, nr_acct, pgdat, idx);
3115 
3116 	if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
3117 		nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3118 		stock->nr_bytes &= (PAGE_SIZE - 1);
3119 	}
3120 
3121 	local_unlock(&obj_stock.lock);
3122 out:
3123 	if (nr_pages)
3124 		obj_cgroup_uncharge_pages(objcg, nr_pages);
3125 }
3126 
3127 static int obj_cgroup_charge_account(struct obj_cgroup *objcg, gfp_t gfp, size_t size,
3128 				     struct pglist_data *pgdat, enum node_stat_item idx)
3129 {
3130 	unsigned int nr_pages, nr_bytes;
3131 	int ret;
3132 
3133 	if (likely(consume_obj_stock(objcg, size, pgdat, idx)))
3134 		return 0;
3135 
3136 	/*
3137 	 * In theory, objcg->nr_charged_bytes can have enough
3138 	 * pre-charged bytes to satisfy the allocation. However,
3139 	 * flushing objcg->nr_charged_bytes requires two atomic
3140 	 * operations, and objcg->nr_charged_bytes can't be big.
3141 	 * The shared objcg->nr_charged_bytes can also become a
3142 	 * performance bottleneck if all tasks of the same memcg are
3143 	 * trying to update it. So it's better to ignore it and try
3144 	 * grab some new pages. The stock's nr_bytes will be flushed to
3145 	 * objcg->nr_charged_bytes later on when objcg changes.
3146 	 *
3147 	 * The stock's nr_bytes may contain enough pre-charged bytes
3148 	 * to allow one less page from being charged, but we can't rely
3149 	 * on the pre-charged bytes not being changed outside of
3150 	 * consume_obj_stock() or refill_obj_stock(). So ignore those
3151 	 * pre-charged bytes as well when charging pages. To avoid a
3152 	 * page uncharge right after a page charge, we set the
3153 	 * allow_uncharge flag to false when calling refill_obj_stock()
3154 	 * to temporarily allow the pre-charged bytes to exceed the page
3155 	 * size limit. The maximum reachable value of the pre-charged
3156 	 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
3157 	 * race.
3158 	 */
3159 	nr_pages = size >> PAGE_SHIFT;
3160 	nr_bytes = size & (PAGE_SIZE - 1);
3161 
3162 	if (nr_bytes)
3163 		nr_pages += 1;
3164 
3165 	ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
3166 	if (!ret && (nr_bytes || pgdat))
3167 		refill_obj_stock(objcg, nr_bytes ? PAGE_SIZE - nr_bytes : 0,
3168 					 false, size, pgdat, idx);
3169 
3170 	return ret;
3171 }
3172 
3173 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3174 {
3175 	return obj_cgroup_charge_account(objcg, gfp, size, NULL, 0);
3176 }
3177 
3178 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3179 {
3180 	refill_obj_stock(objcg, size, true, 0, NULL, 0);
3181 }
3182 
3183 static inline size_t obj_full_size(struct kmem_cache *s)
3184 {
3185 	/*
3186 	 * For each accounted object there is an extra space which is used
3187 	 * to store obj_cgroup membership. Charge it too.
3188 	 */
3189 	return s->size + sizeof(struct obj_cgroup *);
3190 }
3191 
3192 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3193 				  gfp_t flags, size_t size, void **p)
3194 {
3195 	struct obj_cgroup *objcg;
3196 	struct slab *slab;
3197 	unsigned long off;
3198 	size_t i;
3199 
3200 	/*
3201 	 * The obtained objcg pointer is safe to use within the current scope,
3202 	 * defined by current task or set_active_memcg() pair.
3203 	 * obj_cgroup_get() is used to get a permanent reference.
3204 	 */
3205 	objcg = current_obj_cgroup();
3206 	if (!objcg)
3207 		return true;
3208 
3209 	/*
3210 	 * slab_alloc_node() avoids the NULL check, so we might be called with a
3211 	 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3212 	 * the whole requested size.
3213 	 * return success as there's nothing to free back
3214 	 */
3215 	if (unlikely(*p == NULL))
3216 		return true;
3217 
3218 	flags &= gfp_allowed_mask;
3219 
3220 	if (lru) {
3221 		int ret;
3222 		struct mem_cgroup *memcg;
3223 
3224 		memcg = get_mem_cgroup_from_objcg(objcg);
3225 		ret = memcg_list_lru_alloc(memcg, lru, flags);
3226 		css_put(&memcg->css);
3227 
3228 		if (ret)
3229 			return false;
3230 	}
3231 
3232 	for (i = 0; i < size; i++) {
3233 		unsigned long obj_exts;
3234 		struct slabobj_ext *obj_ext;
3235 
3236 		slab = virt_to_slab(p[i]);
3237 
3238 		if (!slab_obj_exts(slab) &&
3239 		    alloc_slab_obj_exts(slab, s, flags, false)) {
3240 			continue;
3241 		}
3242 
3243 		/*
3244 		 * if we fail and size is 1, memcg_alloc_abort_single() will
3245 		 * just free the object, which is ok as we have not assigned
3246 		 * objcg to its obj_ext yet
3247 		 *
3248 		 * for larger sizes, kmem_cache_free_bulk() will uncharge
3249 		 * any objects that were already charged and obj_ext assigned
3250 		 *
3251 		 * TODO: we could batch this until slab_pgdat(slab) changes
3252 		 * between iterations, with a more complicated undo
3253 		 */
3254 		if (obj_cgroup_charge_account(objcg, flags, obj_full_size(s),
3255 					slab_pgdat(slab), cache_vmstat_idx(s)))
3256 			return false;
3257 
3258 		obj_exts = slab_obj_exts(slab);
3259 		get_slab_obj_exts(obj_exts);
3260 		off = obj_to_index(s, slab, p[i]);
3261 		obj_ext = slab_obj_ext(slab, obj_exts, off);
3262 		obj_cgroup_get(objcg);
3263 		obj_ext->objcg = objcg;
3264 		put_slab_obj_exts(obj_exts);
3265 	}
3266 
3267 	return true;
3268 }
3269 
3270 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3271 			    void **p, int objects, unsigned long obj_exts)
3272 {
3273 	size_t obj_size = obj_full_size(s);
3274 
3275 	for (int i = 0; i < objects; i++) {
3276 		struct obj_cgroup *objcg;
3277 		struct slabobj_ext *obj_ext;
3278 		unsigned int off;
3279 
3280 		off = obj_to_index(s, slab, p[i]);
3281 		obj_ext = slab_obj_ext(slab, obj_exts, off);
3282 		objcg = obj_ext->objcg;
3283 		if (!objcg)
3284 			continue;
3285 
3286 		obj_ext->objcg = NULL;
3287 		refill_obj_stock(objcg, obj_size, true, -obj_size,
3288 				 slab_pgdat(slab), cache_vmstat_idx(s));
3289 		obj_cgroup_put(objcg);
3290 	}
3291 }
3292 
3293 /*
3294  * The objcg is only set on the first page, so transfer it to all the
3295  * other pages.
3296  */
3297 void split_page_memcg(struct page *page, unsigned order)
3298 {
3299 	struct obj_cgroup *objcg = page_objcg(page);
3300 	unsigned int i, nr = 1 << order;
3301 
3302 	if (!objcg)
3303 		return;
3304 
3305 	for (i = 1; i < nr; i++)
3306 		page_set_objcg(&page[i], objcg);
3307 
3308 	obj_cgroup_get_many(objcg, nr - 1);
3309 }
3310 
3311 void folio_split_memcg_refs(struct folio *folio, unsigned old_order,
3312 		unsigned new_order)
3313 {
3314 	unsigned new_refs;
3315 
3316 	if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
3317 		return;
3318 
3319 	new_refs = (1 << (old_order - new_order)) - 1;
3320 	css_get_many(&__folio_memcg(folio)->css, new_refs);
3321 }
3322 
3323 unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3324 {
3325 	unsigned long val;
3326 
3327 	if (mem_cgroup_is_root(memcg)) {
3328 		/*
3329 		 * Approximate root's usage from global state. This isn't
3330 		 * perfect, but the root usage was always an approximation.
3331 		 */
3332 		val = global_node_page_state(NR_FILE_PAGES) +
3333 			global_node_page_state(NR_ANON_MAPPED);
3334 		if (swap)
3335 			val += total_swap_pages - get_nr_swap_pages();
3336 	} else {
3337 		if (!swap)
3338 			val = page_counter_read(&memcg->memory);
3339 		else
3340 			val = page_counter_read(&memcg->memsw);
3341 	}
3342 	return val;
3343 }
3344 
3345 static int memcg_online_kmem(struct mem_cgroup *memcg)
3346 {
3347 	struct obj_cgroup *objcg;
3348 
3349 	if (mem_cgroup_kmem_disabled())
3350 		return 0;
3351 
3352 	if (unlikely(mem_cgroup_is_root(memcg)))
3353 		return 0;
3354 
3355 	objcg = obj_cgroup_alloc();
3356 	if (!objcg)
3357 		return -ENOMEM;
3358 
3359 	objcg->memcg = memcg;
3360 	rcu_assign_pointer(memcg->objcg, objcg);
3361 	obj_cgroup_get(objcg);
3362 	memcg->orig_objcg = objcg;
3363 
3364 	static_branch_enable(&memcg_kmem_online_key);
3365 
3366 	memcg->kmemcg_id = memcg->id.id;
3367 
3368 	return 0;
3369 }
3370 
3371 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3372 {
3373 	struct mem_cgroup *parent;
3374 
3375 	if (mem_cgroup_kmem_disabled())
3376 		return;
3377 
3378 	if (unlikely(mem_cgroup_is_root(memcg)))
3379 		return;
3380 
3381 	parent = parent_mem_cgroup(memcg);
3382 	if (!parent)
3383 		parent = root_mem_cgroup;
3384 
3385 	memcg_reparent_list_lrus(memcg, parent);
3386 
3387 	/*
3388 	 * Objcg's reparenting must be after list_lru's, make sure list_lru
3389 	 * helpers won't use parent's list_lru until child is drained.
3390 	 */
3391 	memcg_reparent_objcgs(memcg, parent);
3392 }
3393 
3394 #ifdef CONFIG_CGROUP_WRITEBACK
3395 
3396 #include <trace/events/writeback.h>
3397 
3398 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3399 {
3400 	return wb_domain_init(&memcg->cgwb_domain, gfp);
3401 }
3402 
3403 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3404 {
3405 	wb_domain_exit(&memcg->cgwb_domain);
3406 }
3407 
3408 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3409 {
3410 	wb_domain_size_changed(&memcg->cgwb_domain);
3411 }
3412 
3413 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3414 {
3415 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3416 
3417 	if (!memcg->css.parent)
3418 		return NULL;
3419 
3420 	return &memcg->cgwb_domain;
3421 }
3422 
3423 /**
3424  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3425  * @wb: bdi_writeback in question
3426  * @pfilepages: out parameter for number of file pages
3427  * @pheadroom: out parameter for number of allocatable pages according to memcg
3428  * @pdirty: out parameter for number of dirty pages
3429  * @pwriteback: out parameter for number of pages under writeback
3430  *
3431  * Determine the numbers of file, headroom, dirty, and writeback pages in
3432  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
3433  * is a bit more involved.
3434  *
3435  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
3436  * headroom is calculated as the lowest headroom of itself and the
3437  * ancestors.  Note that this doesn't consider the actual amount of
3438  * available memory in the system.  The caller should further cap
3439  * *@pheadroom accordingly.
3440  */
3441 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3442 			 unsigned long *pheadroom, unsigned long *pdirty,
3443 			 unsigned long *pwriteback)
3444 {
3445 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3446 	struct mem_cgroup *parent;
3447 
3448 	mem_cgroup_flush_stats_ratelimited(memcg);
3449 
3450 	*pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
3451 	*pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
3452 	*pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
3453 			memcg_page_state(memcg, NR_ACTIVE_FILE);
3454 
3455 	*pheadroom = PAGE_COUNTER_MAX;
3456 	while ((parent = parent_mem_cgroup(memcg))) {
3457 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
3458 					    READ_ONCE(memcg->memory.high));
3459 		unsigned long used = page_counter_read(&memcg->memory);
3460 
3461 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
3462 		memcg = parent;
3463 	}
3464 }
3465 
3466 /*
3467  * Foreign dirty flushing
3468  *
3469  * There's an inherent mismatch between memcg and writeback.  The former
3470  * tracks ownership per-page while the latter per-inode.  This was a
3471  * deliberate design decision because honoring per-page ownership in the
3472  * writeback path is complicated, may lead to higher CPU and IO overheads
3473  * and deemed unnecessary given that write-sharing an inode across
3474  * different cgroups isn't a common use-case.
3475  *
3476  * Combined with inode majority-writer ownership switching, this works well
3477  * enough in most cases but there are some pathological cases.  For
3478  * example, let's say there are two cgroups A and B which keep writing to
3479  * different but confined parts of the same inode.  B owns the inode and
3480  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
3481  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
3482  * triggering background writeback.  A will be slowed down without a way to
3483  * make writeback of the dirty pages happen.
3484  *
3485  * Conditions like the above can lead to a cgroup getting repeatedly and
3486  * severely throttled after making some progress after each
3487  * dirty_expire_interval while the underlying IO device is almost
3488  * completely idle.
3489  *
3490  * Solving this problem completely requires matching the ownership tracking
3491  * granularities between memcg and writeback in either direction.  However,
3492  * the more egregious behaviors can be avoided by simply remembering the
3493  * most recent foreign dirtying events and initiating remote flushes on
3494  * them when local writeback isn't enough to keep the memory clean enough.
3495  *
3496  * The following two functions implement such mechanism.  When a foreign
3497  * page - a page whose memcg and writeback ownerships don't match - is
3498  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
3499  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
3500  * decides that the memcg needs to sleep due to high dirty ratio, it calls
3501  * mem_cgroup_flush_foreign() which queues writeback on the recorded
3502  * foreign bdi_writebacks which haven't expired.  Both the numbers of
3503  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
3504  * limited to MEMCG_CGWB_FRN_CNT.
3505  *
3506  * The mechanism only remembers IDs and doesn't hold any object references.
3507  * As being wrong occasionally doesn't matter, updates and accesses to the
3508  * records are lockless and racy.
3509  */
3510 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
3511 					     struct bdi_writeback *wb)
3512 {
3513 	struct mem_cgroup *memcg = folio_memcg(folio);
3514 	struct memcg_cgwb_frn *frn;
3515 	u64 now = get_jiffies_64();
3516 	u64 oldest_at = now;
3517 	int oldest = -1;
3518 	int i;
3519 
3520 	trace_track_foreign_dirty(folio, wb);
3521 
3522 	/*
3523 	 * Pick the slot to use.  If there is already a slot for @wb, keep
3524 	 * using it.  If not replace the oldest one which isn't being
3525 	 * written out.
3526 	 */
3527 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3528 		frn = &memcg->cgwb_frn[i];
3529 		if (frn->bdi_id == wb->bdi->id &&
3530 		    frn->memcg_id == wb->memcg_css->id)
3531 			break;
3532 		if (time_before64(frn->at, oldest_at) &&
3533 		    atomic_read(&frn->done.cnt) == 1) {
3534 			oldest = i;
3535 			oldest_at = frn->at;
3536 		}
3537 	}
3538 
3539 	if (i < MEMCG_CGWB_FRN_CNT) {
3540 		/*
3541 		 * Re-using an existing one.  Update timestamp lazily to
3542 		 * avoid making the cacheline hot.  We want them to be
3543 		 * reasonably up-to-date and significantly shorter than
3544 		 * dirty_expire_interval as that's what expires the record.
3545 		 * Use the shorter of 1s and dirty_expire_interval / 8.
3546 		 */
3547 		unsigned long update_intv =
3548 			min_t(unsigned long, HZ,
3549 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
3550 
3551 		if (time_before64(frn->at, now - update_intv))
3552 			frn->at = now;
3553 	} else if (oldest >= 0) {
3554 		/* replace the oldest free one */
3555 		frn = &memcg->cgwb_frn[oldest];
3556 		frn->bdi_id = wb->bdi->id;
3557 		frn->memcg_id = wb->memcg_css->id;
3558 		frn->at = now;
3559 	}
3560 }
3561 
3562 /* issue foreign writeback flushes for recorded foreign dirtying events */
3563 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
3564 {
3565 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3566 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
3567 	u64 now = jiffies_64;
3568 	int i;
3569 
3570 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3571 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
3572 
3573 		/*
3574 		 * If the record is older than dirty_expire_interval,
3575 		 * writeback on it has already started.  No need to kick it
3576 		 * off again.  Also, don't start a new one if there's
3577 		 * already one in flight.
3578 		 */
3579 		if (time_after64(frn->at, now - intv) &&
3580 		    atomic_read(&frn->done.cnt) == 1) {
3581 			frn->at = 0;
3582 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
3583 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
3584 					       WB_REASON_FOREIGN_FLUSH,
3585 					       &frn->done);
3586 		}
3587 	}
3588 }
3589 
3590 #else	/* CONFIG_CGROUP_WRITEBACK */
3591 
3592 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3593 {
3594 	return 0;
3595 }
3596 
3597 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3598 {
3599 }
3600 
3601 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3602 {
3603 }
3604 
3605 #endif	/* CONFIG_CGROUP_WRITEBACK */
3606 
3607 /*
3608  * Private memory cgroup IDR
3609  *
3610  * Swap-out records and page cache shadow entries need to store memcg
3611  * references in constrained space, so we maintain an ID space that is
3612  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
3613  * memory-controlled cgroups to 64k.
3614  *
3615  * However, there usually are many references to the offline CSS after
3616  * the cgroup has been destroyed, such as page cache or reclaimable
3617  * slab objects, that don't need to hang on to the ID. We want to keep
3618  * those dead CSS from occupying IDs, or we might quickly exhaust the
3619  * relatively small ID space and prevent the creation of new cgroups
3620  * even when there are much fewer than 64k cgroups - possibly none.
3621  *
3622  * Maintain a private 16-bit ID space for memcg, and allow the ID to
3623  * be freed and recycled when it's no longer needed, which is usually
3624  * when the CSS is offlined.
3625  *
3626  * The only exception to that are records of swapped out tmpfs/shmem
3627  * pages that need to be attributed to live ancestors on swapin. But
3628  * those references are manageable from userspace.
3629  */
3630 
3631 #define MEM_CGROUP_ID_MAX	((1UL << MEM_CGROUP_ID_SHIFT) - 1)
3632 static DEFINE_XARRAY_ALLOC1(mem_cgroup_ids);
3633 
3634 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
3635 {
3636 	if (memcg->id.id > 0) {
3637 		xa_erase(&mem_cgroup_ids, memcg->id.id);
3638 		memcg->id.id = 0;
3639 	}
3640 }
3641 
3642 void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
3643 					   unsigned int n)
3644 {
3645 	refcount_add(n, &memcg->id.ref);
3646 }
3647 
3648 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
3649 {
3650 	if (refcount_sub_and_test(n, &memcg->id.ref)) {
3651 		mem_cgroup_id_remove(memcg);
3652 
3653 		/* Memcg ID pins CSS */
3654 		css_put(&memcg->css);
3655 	}
3656 }
3657 
3658 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
3659 {
3660 	mem_cgroup_id_put_many(memcg, 1);
3661 }
3662 
3663 struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
3664 {
3665 	while (!refcount_inc_not_zero(&memcg->id.ref)) {
3666 		/*
3667 		 * The root cgroup cannot be destroyed, so it's refcount must
3668 		 * always be >= 1.
3669 		 */
3670 		if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
3671 			VM_BUG_ON(1);
3672 			break;
3673 		}
3674 		memcg = parent_mem_cgroup(memcg);
3675 		if (!memcg)
3676 			memcg = root_mem_cgroup;
3677 	}
3678 	return memcg;
3679 }
3680 
3681 /**
3682  * mem_cgroup_from_id - look up a memcg from a memcg id
3683  * @id: the memcg id to look up
3684  *
3685  * Caller must hold rcu_read_lock().
3686  */
3687 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
3688 {
3689 	WARN_ON_ONCE(!rcu_read_lock_held());
3690 	return xa_load(&mem_cgroup_ids, id);
3691 }
3692 
3693 #ifdef CONFIG_SHRINKER_DEBUG
3694 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
3695 {
3696 	struct cgroup *cgrp;
3697 	struct cgroup_subsys_state *css;
3698 	struct mem_cgroup *memcg;
3699 
3700 	cgrp = cgroup_get_from_id(ino);
3701 	if (IS_ERR(cgrp))
3702 		return ERR_CAST(cgrp);
3703 
3704 	css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
3705 	if (css)
3706 		memcg = container_of(css, struct mem_cgroup, css);
3707 	else
3708 		memcg = ERR_PTR(-ENOENT);
3709 
3710 	cgroup_put(cgrp);
3711 
3712 	return memcg;
3713 }
3714 #endif
3715 
3716 static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn)
3717 {
3718 	if (!pn)
3719 		return;
3720 
3721 	free_percpu(pn->lruvec_stats_percpu);
3722 	kfree(pn->lruvec_stats);
3723 	kfree(pn);
3724 }
3725 
3726 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
3727 {
3728 	struct mem_cgroup_per_node *pn;
3729 
3730 	pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
3731 				   node);
3732 	if (!pn)
3733 		return false;
3734 
3735 	pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
3736 					GFP_KERNEL_ACCOUNT, node);
3737 	if (!pn->lruvec_stats)
3738 		goto fail;
3739 
3740 	pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
3741 						   GFP_KERNEL_ACCOUNT);
3742 	if (!pn->lruvec_stats_percpu)
3743 		goto fail;
3744 
3745 	lruvec_init(&pn->lruvec);
3746 	pn->memcg = memcg;
3747 
3748 	memcg->nodeinfo[node] = pn;
3749 	return true;
3750 fail:
3751 	free_mem_cgroup_per_node_info(pn);
3752 	return false;
3753 }
3754 
3755 static void __mem_cgroup_free(struct mem_cgroup *memcg)
3756 {
3757 	int node;
3758 
3759 	obj_cgroup_put(memcg->orig_objcg);
3760 
3761 	for_each_node(node)
3762 		free_mem_cgroup_per_node_info(memcg->nodeinfo[node]);
3763 	memcg1_free_events(memcg);
3764 	kfree(memcg->vmstats);
3765 	free_percpu(memcg->vmstats_percpu);
3766 	kfree(memcg);
3767 }
3768 
3769 static void mem_cgroup_free(struct mem_cgroup *memcg)
3770 {
3771 	lru_gen_exit_memcg(memcg);
3772 	memcg_wb_domain_exit(memcg);
3773 	__mem_cgroup_free(memcg);
3774 }
3775 
3776 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
3777 {
3778 	struct memcg_vmstats_percpu *statc;
3779 	struct memcg_vmstats_percpu __percpu *pstatc_pcpu;
3780 	struct mem_cgroup *memcg;
3781 	int node, cpu;
3782 	int __maybe_unused i;
3783 	long error;
3784 
3785 	memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
3786 	if (!memcg)
3787 		return ERR_PTR(-ENOMEM);
3788 
3789 	error = xa_alloc(&mem_cgroup_ids, &memcg->id.id, NULL,
3790 			 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
3791 	if (error)
3792 		goto fail;
3793 	error = -ENOMEM;
3794 
3795 	memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
3796 				 GFP_KERNEL_ACCOUNT);
3797 	if (!memcg->vmstats)
3798 		goto fail;
3799 
3800 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
3801 						 GFP_KERNEL_ACCOUNT);
3802 	if (!memcg->vmstats_percpu)
3803 		goto fail;
3804 
3805 	if (!memcg1_alloc_events(memcg))
3806 		goto fail;
3807 
3808 	for_each_possible_cpu(cpu) {
3809 		if (parent)
3810 			pstatc_pcpu = parent->vmstats_percpu;
3811 		statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
3812 		statc->parent_pcpu = parent ? pstatc_pcpu : NULL;
3813 		statc->vmstats = memcg->vmstats;
3814 	}
3815 
3816 	for_each_node(node)
3817 		if (!alloc_mem_cgroup_per_node_info(memcg, node))
3818 			goto fail;
3819 
3820 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
3821 		goto fail;
3822 
3823 	INIT_WORK(&memcg->high_work, high_work_func);
3824 	vmpressure_init(&memcg->vmpressure);
3825 	INIT_LIST_HEAD(&memcg->memory_peaks);
3826 	INIT_LIST_HEAD(&memcg->swap_peaks);
3827 	spin_lock_init(&memcg->peaks_lock);
3828 	memcg->socket_pressure = get_jiffies_64();
3829 #if BITS_PER_LONG < 64
3830 	seqlock_init(&memcg->socket_pressure_seqlock);
3831 #endif
3832 	memcg1_memcg_init(memcg);
3833 	memcg->kmemcg_id = -1;
3834 	INIT_LIST_HEAD(&memcg->objcg_list);
3835 #ifdef CONFIG_CGROUP_WRITEBACK
3836 	INIT_LIST_HEAD(&memcg->cgwb_list);
3837 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3838 		memcg->cgwb_frn[i].done =
3839 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
3840 #endif
3841 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3842 	spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
3843 	INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
3844 	memcg->deferred_split_queue.split_queue_len = 0;
3845 #endif
3846 	lru_gen_init_memcg(memcg);
3847 	return memcg;
3848 fail:
3849 	mem_cgroup_id_remove(memcg);
3850 	__mem_cgroup_free(memcg);
3851 	return ERR_PTR(error);
3852 }
3853 
3854 static struct cgroup_subsys_state * __ref
3855 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
3856 {
3857 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
3858 	struct mem_cgroup *memcg, *old_memcg;
3859 	bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys);
3860 
3861 	old_memcg = set_active_memcg(parent);
3862 	memcg = mem_cgroup_alloc(parent);
3863 	set_active_memcg(old_memcg);
3864 	if (IS_ERR(memcg))
3865 		return ERR_CAST(memcg);
3866 
3867 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
3868 	memcg1_soft_limit_reset(memcg);
3869 #ifdef CONFIG_ZSWAP
3870 	memcg->zswap_max = PAGE_COUNTER_MAX;
3871 	WRITE_ONCE(memcg->zswap_writeback, true);
3872 #endif
3873 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
3874 	if (parent) {
3875 		WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
3876 
3877 		page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl);
3878 		page_counter_init(&memcg->swap, &parent->swap, false);
3879 #ifdef CONFIG_MEMCG_V1
3880 		memcg->memory.track_failcnt = !memcg_on_dfl;
3881 		WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
3882 		page_counter_init(&memcg->kmem, &parent->kmem, false);
3883 		page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
3884 #endif
3885 	} else {
3886 		init_memcg_stats();
3887 		init_memcg_events();
3888 		page_counter_init(&memcg->memory, NULL, true);
3889 		page_counter_init(&memcg->swap, NULL, false);
3890 #ifdef CONFIG_MEMCG_V1
3891 		page_counter_init(&memcg->kmem, NULL, false);
3892 		page_counter_init(&memcg->tcpmem, NULL, false);
3893 #endif
3894 		root_mem_cgroup = memcg;
3895 		return &memcg->css;
3896 	}
3897 
3898 	if (memcg_on_dfl && !cgroup_memory_nosocket)
3899 		static_branch_inc(&memcg_sockets_enabled_key);
3900 
3901 	if (!cgroup_memory_nobpf)
3902 		static_branch_inc(&memcg_bpf_enabled_key);
3903 
3904 	return &memcg->css;
3905 }
3906 
3907 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
3908 {
3909 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3910 
3911 	if (memcg_online_kmem(memcg))
3912 		goto remove_id;
3913 
3914 	/*
3915 	 * A memcg must be visible for expand_shrinker_info()
3916 	 * by the time the maps are allocated. So, we allocate maps
3917 	 * here, when for_each_mem_cgroup() can't skip it.
3918 	 */
3919 	if (alloc_shrinker_info(memcg))
3920 		goto offline_kmem;
3921 
3922 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
3923 		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
3924 				   FLUSH_TIME);
3925 	lru_gen_online_memcg(memcg);
3926 
3927 	/* Online state pins memcg ID, memcg ID pins CSS */
3928 	refcount_set(&memcg->id.ref, 1);
3929 	css_get(css);
3930 
3931 	/*
3932 	 * Ensure mem_cgroup_from_id() works once we're fully online.
3933 	 *
3934 	 * We could do this earlier and require callers to filter with
3935 	 * css_tryget_online(). But right now there are no users that
3936 	 * need earlier access, and the workingset code relies on the
3937 	 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
3938 	 * publish it here at the end of onlining. This matches the
3939 	 * regular ID destruction during offlining.
3940 	 */
3941 	xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
3942 
3943 	return 0;
3944 offline_kmem:
3945 	memcg_offline_kmem(memcg);
3946 remove_id:
3947 	mem_cgroup_id_remove(memcg);
3948 	return -ENOMEM;
3949 }
3950 
3951 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
3952 {
3953 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3954 
3955 	memcg1_css_offline(memcg);
3956 
3957 	page_counter_set_min(&memcg->memory, 0);
3958 	page_counter_set_low(&memcg->memory, 0);
3959 
3960 	zswap_memcg_offline_cleanup(memcg);
3961 
3962 	memcg_offline_kmem(memcg);
3963 	reparent_deferred_split_queue(memcg);
3964 	reparent_shrinker_deferred(memcg);
3965 	wb_memcg_offline(memcg);
3966 	lru_gen_offline_memcg(memcg);
3967 
3968 	drain_all_stock(memcg);
3969 
3970 	mem_cgroup_id_put(memcg);
3971 }
3972 
3973 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
3974 {
3975 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3976 
3977 	invalidate_reclaim_iterators(memcg);
3978 	lru_gen_release_memcg(memcg);
3979 }
3980 
3981 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
3982 {
3983 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3984 	int __maybe_unused i;
3985 
3986 #ifdef CONFIG_CGROUP_WRITEBACK
3987 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3988 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
3989 #endif
3990 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
3991 		static_branch_dec(&memcg_sockets_enabled_key);
3992 
3993 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
3994 		static_branch_dec(&memcg_sockets_enabled_key);
3995 
3996 	if (!cgroup_memory_nobpf)
3997 		static_branch_dec(&memcg_bpf_enabled_key);
3998 
3999 	vmpressure_cleanup(&memcg->vmpressure);
4000 	cancel_work_sync(&memcg->high_work);
4001 	memcg1_remove_from_trees(memcg);
4002 	free_shrinker_info(memcg);
4003 	mem_cgroup_free(memcg);
4004 }
4005 
4006 /**
4007  * mem_cgroup_css_reset - reset the states of a mem_cgroup
4008  * @css: the target css
4009  *
4010  * Reset the states of the mem_cgroup associated with @css.  This is
4011  * invoked when the userland requests disabling on the default hierarchy
4012  * but the memcg is pinned through dependency.  The memcg should stop
4013  * applying policies and should revert to the vanilla state as it may be
4014  * made visible again.
4015  *
4016  * The current implementation only resets the essential configurations.
4017  * This needs to be expanded to cover all the visible parts.
4018  */
4019 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
4020 {
4021 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4022 
4023 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
4024 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
4025 #ifdef CONFIG_MEMCG_V1
4026 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
4027 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
4028 #endif
4029 	page_counter_set_min(&memcg->memory, 0);
4030 	page_counter_set_low(&memcg->memory, 0);
4031 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
4032 	memcg1_soft_limit_reset(memcg);
4033 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
4034 	memcg_wb_domain_size_changed(memcg);
4035 }
4036 
4037 struct aggregate_control {
4038 	/* pointer to the aggregated (CPU and subtree aggregated) counters */
4039 	long *aggregate;
4040 	/* pointer to the non-hierarchichal (CPU aggregated) counters */
4041 	long *local;
4042 	/* pointer to the pending child counters during tree propagation */
4043 	long *pending;
4044 	/* pointer to the parent's pending counters, could be NULL */
4045 	long *ppending;
4046 	/* pointer to the percpu counters to be aggregated */
4047 	long *cstat;
4048 	/* pointer to the percpu counters of the last aggregation*/
4049 	long *cstat_prev;
4050 	/* size of the above counters */
4051 	int size;
4052 };
4053 
4054 static void mem_cgroup_stat_aggregate(struct aggregate_control *ac)
4055 {
4056 	int i;
4057 	long delta, delta_cpu, v;
4058 
4059 	for (i = 0; i < ac->size; i++) {
4060 		/*
4061 		 * Collect the aggregated propagation counts of groups
4062 		 * below us. We're in a per-cpu loop here and this is
4063 		 * a global counter, so the first cycle will get them.
4064 		 */
4065 		delta = ac->pending[i];
4066 		if (delta)
4067 			ac->pending[i] = 0;
4068 
4069 		/* Add CPU changes on this level since the last flush */
4070 		delta_cpu = 0;
4071 		v = READ_ONCE(ac->cstat[i]);
4072 		if (v != ac->cstat_prev[i]) {
4073 			delta_cpu = v - ac->cstat_prev[i];
4074 			delta += delta_cpu;
4075 			ac->cstat_prev[i] = v;
4076 		}
4077 
4078 		/* Aggregate counts on this level and propagate upwards */
4079 		if (delta_cpu)
4080 			ac->local[i] += delta_cpu;
4081 
4082 		if (delta) {
4083 			ac->aggregate[i] += delta;
4084 			if (ac->ppending)
4085 				ac->ppending[i] += delta;
4086 		}
4087 	}
4088 }
4089 
4090 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
4091 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4092 			    int cpu)
4093 {
4094 	int nid;
4095 
4096 	if (atomic_read(&memcg->kmem_stat)) {
4097 		int kmem = atomic_xchg(&memcg->kmem_stat, 0);
4098 		int index = memcg_stats_index(MEMCG_KMEM);
4099 
4100 		memcg->vmstats->state[index] += kmem;
4101 		if (parent)
4102 			parent->vmstats->state_pending[index] += kmem;
4103 	}
4104 
4105 	for_each_node_state(nid, N_MEMORY) {
4106 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4107 		struct lruvec_stats *lstats = pn->lruvec_stats;
4108 		struct lruvec_stats *plstats = NULL;
4109 
4110 		if (parent)
4111 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4112 
4113 		if (atomic_read(&pn->slab_reclaimable)) {
4114 			int slab = atomic_xchg(&pn->slab_reclaimable, 0);
4115 			int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B);
4116 
4117 			lstats->state[index] += slab;
4118 			if (plstats)
4119 				plstats->state_pending[index] += slab;
4120 		}
4121 		if (atomic_read(&pn->slab_unreclaimable)) {
4122 			int slab = atomic_xchg(&pn->slab_unreclaimable, 0);
4123 			int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B);
4124 
4125 			lstats->state[index] += slab;
4126 			if (plstats)
4127 				plstats->state_pending[index] += slab;
4128 		}
4129 	}
4130 }
4131 #else
4132 static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
4133 			    int cpu)
4134 {}
4135 #endif
4136 
4137 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
4138 {
4139 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4140 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4141 	struct memcg_vmstats_percpu *statc;
4142 	struct aggregate_control ac;
4143 	int nid;
4144 
4145 	flush_nmi_stats(memcg, parent, cpu);
4146 
4147 	statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
4148 
4149 	ac = (struct aggregate_control) {
4150 		.aggregate = memcg->vmstats->state,
4151 		.local = memcg->vmstats->state_local,
4152 		.pending = memcg->vmstats->state_pending,
4153 		.ppending = parent ? parent->vmstats->state_pending : NULL,
4154 		.cstat = statc->state,
4155 		.cstat_prev = statc->state_prev,
4156 		.size = MEMCG_VMSTAT_SIZE,
4157 	};
4158 	mem_cgroup_stat_aggregate(&ac);
4159 
4160 	ac = (struct aggregate_control) {
4161 		.aggregate = memcg->vmstats->events,
4162 		.local = memcg->vmstats->events_local,
4163 		.pending = memcg->vmstats->events_pending,
4164 		.ppending = parent ? parent->vmstats->events_pending : NULL,
4165 		.cstat = statc->events,
4166 		.cstat_prev = statc->events_prev,
4167 		.size = NR_MEMCG_EVENTS,
4168 	};
4169 	mem_cgroup_stat_aggregate(&ac);
4170 
4171 	for_each_node_state(nid, N_MEMORY) {
4172 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
4173 		struct lruvec_stats *lstats = pn->lruvec_stats;
4174 		struct lruvec_stats *plstats = NULL;
4175 		struct lruvec_stats_percpu *lstatc;
4176 
4177 		if (parent)
4178 			plstats = parent->nodeinfo[nid]->lruvec_stats;
4179 
4180 		lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
4181 
4182 		ac = (struct aggregate_control) {
4183 			.aggregate = lstats->state,
4184 			.local = lstats->state_local,
4185 			.pending = lstats->state_pending,
4186 			.ppending = plstats ? plstats->state_pending : NULL,
4187 			.cstat = lstatc->state,
4188 			.cstat_prev = lstatc->state_prev,
4189 			.size = NR_MEMCG_NODE_STAT_ITEMS,
4190 		};
4191 		mem_cgroup_stat_aggregate(&ac);
4192 
4193 	}
4194 	WRITE_ONCE(statc->stats_updates, 0);
4195 	/* We are in a per-cpu loop here, only do the atomic write once */
4196 	if (atomic_read(&memcg->vmstats->stats_updates))
4197 		atomic_set(&memcg->vmstats->stats_updates, 0);
4198 }
4199 
4200 static void mem_cgroup_fork(struct task_struct *task)
4201 {
4202 	/*
4203 	 * Set the update flag to cause task->objcg to be initialized lazily
4204 	 * on the first allocation. 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 = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
4209 }
4210 
4211 static void mem_cgroup_exit(struct task_struct *task)
4212 {
4213 	struct obj_cgroup *objcg = task->objcg;
4214 
4215 	objcg = (struct obj_cgroup *)
4216 		((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
4217 	obj_cgroup_put(objcg);
4218 
4219 	/*
4220 	 * Some kernel allocations can happen after this point,
4221 	 * but let's ignore them. It can be done without any synchronization
4222 	 * because it's always performed on the current task, so does
4223 	 * current_objcg_update().
4224 	 */
4225 	task->objcg = NULL;
4226 }
4227 
4228 #ifdef CONFIG_LRU_GEN
4229 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
4230 {
4231 	struct task_struct *task;
4232 	struct cgroup_subsys_state *css;
4233 
4234 	/* find the first leader if there is any */
4235 	cgroup_taskset_for_each_leader(task, css, tset)
4236 		break;
4237 
4238 	if (!task)
4239 		return;
4240 
4241 	task_lock(task);
4242 	if (task->mm && READ_ONCE(task->mm->owner) == task)
4243 		lru_gen_migrate_mm(task->mm);
4244 	task_unlock(task);
4245 }
4246 #else
4247 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
4248 #endif /* CONFIG_LRU_GEN */
4249 
4250 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
4251 {
4252 	struct task_struct *task;
4253 	struct cgroup_subsys_state *css;
4254 
4255 	cgroup_taskset_for_each(task, css, tset) {
4256 		/* atomically set the update bit */
4257 		set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
4258 	}
4259 }
4260 
4261 static void mem_cgroup_attach(struct cgroup_taskset *tset)
4262 {
4263 	mem_cgroup_lru_gen_attach(tset);
4264 	mem_cgroup_kmem_attach(tset);
4265 }
4266 
4267 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
4268 {
4269 	if (value == PAGE_COUNTER_MAX)
4270 		seq_puts(m, "max\n");
4271 	else
4272 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
4273 
4274 	return 0;
4275 }
4276 
4277 static u64 memory_current_read(struct cgroup_subsys_state *css,
4278 			       struct cftype *cft)
4279 {
4280 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4281 
4282 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
4283 }
4284 
4285 #define OFP_PEAK_UNSET (((-1UL)))
4286 
4287 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
4288 {
4289 	struct cgroup_of_peak *ofp = of_peak(sf->private);
4290 	u64 fd_peak = READ_ONCE(ofp->value), peak;
4291 
4292 	/* User wants global or local peak? */
4293 	if (fd_peak == OFP_PEAK_UNSET)
4294 		peak = pc->watermark;
4295 	else
4296 		peak = max(fd_peak, READ_ONCE(pc->local_watermark));
4297 
4298 	seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
4299 	return 0;
4300 }
4301 
4302 static int memory_peak_show(struct seq_file *sf, void *v)
4303 {
4304 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
4305 
4306 	return peak_show(sf, v, &memcg->memory);
4307 }
4308 
4309 static int peak_open(struct kernfs_open_file *of)
4310 {
4311 	struct cgroup_of_peak *ofp = of_peak(of);
4312 
4313 	ofp->value = OFP_PEAK_UNSET;
4314 	return 0;
4315 }
4316 
4317 static void peak_release(struct kernfs_open_file *of)
4318 {
4319 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4320 	struct cgroup_of_peak *ofp = of_peak(of);
4321 
4322 	if (ofp->value == OFP_PEAK_UNSET) {
4323 		/* fast path (no writes on this fd) */
4324 		return;
4325 	}
4326 	spin_lock(&memcg->peaks_lock);
4327 	list_del(&ofp->list);
4328 	spin_unlock(&memcg->peaks_lock);
4329 }
4330 
4331 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
4332 			  loff_t off, struct page_counter *pc,
4333 			  struct list_head *watchers)
4334 {
4335 	unsigned long usage;
4336 	struct cgroup_of_peak *peer_ctx;
4337 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4338 	struct cgroup_of_peak *ofp = of_peak(of);
4339 
4340 	spin_lock(&memcg->peaks_lock);
4341 
4342 	usage = page_counter_read(pc);
4343 	WRITE_ONCE(pc->local_watermark, usage);
4344 
4345 	list_for_each_entry(peer_ctx, watchers, list)
4346 		if (usage > peer_ctx->value)
4347 			WRITE_ONCE(peer_ctx->value, usage);
4348 
4349 	/* initial write, register watcher */
4350 	if (ofp->value == OFP_PEAK_UNSET)
4351 		list_add(&ofp->list, watchers);
4352 
4353 	WRITE_ONCE(ofp->value, usage);
4354 	spin_unlock(&memcg->peaks_lock);
4355 
4356 	return nbytes;
4357 }
4358 
4359 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
4360 				 size_t nbytes, loff_t off)
4361 {
4362 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4363 
4364 	return peak_write(of, buf, nbytes, off, &memcg->memory,
4365 			  &memcg->memory_peaks);
4366 }
4367 
4368 #undef OFP_PEAK_UNSET
4369 
4370 static int memory_min_show(struct seq_file *m, void *v)
4371 {
4372 	return seq_puts_memcg_tunable(m,
4373 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
4374 }
4375 
4376 static ssize_t memory_min_write(struct kernfs_open_file *of,
4377 				char *buf, size_t nbytes, loff_t off)
4378 {
4379 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4380 	unsigned long min;
4381 	int err;
4382 
4383 	buf = strstrip(buf);
4384 	err = page_counter_memparse(buf, "max", &min);
4385 	if (err)
4386 		return err;
4387 
4388 	page_counter_set_min(&memcg->memory, min);
4389 
4390 	return nbytes;
4391 }
4392 
4393 static int memory_low_show(struct seq_file *m, void *v)
4394 {
4395 	return seq_puts_memcg_tunable(m,
4396 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
4397 }
4398 
4399 static ssize_t memory_low_write(struct kernfs_open_file *of,
4400 				char *buf, size_t nbytes, loff_t off)
4401 {
4402 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4403 	unsigned long low;
4404 	int err;
4405 
4406 	buf = strstrip(buf);
4407 	err = page_counter_memparse(buf, "max", &low);
4408 	if (err)
4409 		return err;
4410 
4411 	page_counter_set_low(&memcg->memory, low);
4412 
4413 	return nbytes;
4414 }
4415 
4416 static int memory_high_show(struct seq_file *m, void *v)
4417 {
4418 	return seq_puts_memcg_tunable(m,
4419 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
4420 }
4421 
4422 static ssize_t memory_high_write(struct kernfs_open_file *of,
4423 				 char *buf, size_t nbytes, loff_t off)
4424 {
4425 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4426 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
4427 	bool drained = false;
4428 	unsigned long high;
4429 	int err;
4430 
4431 	buf = strstrip(buf);
4432 	err = page_counter_memparse(buf, "max", &high);
4433 	if (err)
4434 		return err;
4435 
4436 	page_counter_set_high(&memcg->memory, high);
4437 
4438 	if (of->file->f_flags & O_NONBLOCK)
4439 		goto out;
4440 
4441 	for (;;) {
4442 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4443 		unsigned long reclaimed;
4444 
4445 		if (nr_pages <= high)
4446 			break;
4447 
4448 		if (signal_pending(current))
4449 			break;
4450 
4451 		if (!drained) {
4452 			drain_all_stock(memcg);
4453 			drained = true;
4454 			continue;
4455 		}
4456 
4457 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
4458 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
4459 
4460 		if (!reclaimed && !nr_retries--)
4461 			break;
4462 	}
4463 out:
4464 	memcg_wb_domain_size_changed(memcg);
4465 	return nbytes;
4466 }
4467 
4468 static int memory_max_show(struct seq_file *m, void *v)
4469 {
4470 	return seq_puts_memcg_tunable(m,
4471 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
4472 }
4473 
4474 static ssize_t memory_max_write(struct kernfs_open_file *of,
4475 				char *buf, size_t nbytes, loff_t off)
4476 {
4477 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4478 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
4479 	bool drained = false;
4480 	unsigned long max;
4481 	int err;
4482 
4483 	buf = strstrip(buf);
4484 	err = page_counter_memparse(buf, "max", &max);
4485 	if (err)
4486 		return err;
4487 
4488 	xchg(&memcg->memory.max, max);
4489 
4490 	if (of->file->f_flags & O_NONBLOCK)
4491 		goto out;
4492 
4493 	for (;;) {
4494 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4495 
4496 		if (nr_pages <= max)
4497 			break;
4498 
4499 		if (signal_pending(current))
4500 			break;
4501 
4502 		if (!drained) {
4503 			drain_all_stock(memcg);
4504 			drained = true;
4505 			continue;
4506 		}
4507 
4508 		if (nr_reclaims) {
4509 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
4510 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
4511 				nr_reclaims--;
4512 			continue;
4513 		}
4514 
4515 		memcg_memory_event(memcg, MEMCG_OOM);
4516 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
4517 			break;
4518 		cond_resched();
4519 	}
4520 out:
4521 	memcg_wb_domain_size_changed(memcg);
4522 	return nbytes;
4523 }
4524 
4525 /*
4526  * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
4527  * if any new events become available.
4528  */
4529 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
4530 {
4531 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
4532 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
4533 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
4534 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
4535 	seq_printf(m, "oom_kill %lu\n",
4536 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
4537 	seq_printf(m, "oom_group_kill %lu\n",
4538 		   atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
4539 	seq_printf(m, "sock_throttled %lu\n",
4540 		   atomic_long_read(&events[MEMCG_SOCK_THROTTLED]));
4541 }
4542 
4543 static int memory_events_show(struct seq_file *m, void *v)
4544 {
4545 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4546 
4547 	__memory_events_show(m, memcg->memory_events);
4548 	return 0;
4549 }
4550 
4551 static int memory_events_local_show(struct seq_file *m, void *v)
4552 {
4553 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4554 
4555 	__memory_events_show(m, memcg->memory_events_local);
4556 	return 0;
4557 }
4558 
4559 int memory_stat_show(struct seq_file *m, void *v)
4560 {
4561 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4562 	char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
4563 	struct seq_buf s;
4564 
4565 	if (!buf)
4566 		return -ENOMEM;
4567 	seq_buf_init(&s, buf, SEQ_BUF_SIZE);
4568 	memory_stat_format(memcg, &s);
4569 	seq_puts(m, buf);
4570 	kfree(buf);
4571 	return 0;
4572 }
4573 
4574 #ifdef CONFIG_NUMA
4575 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
4576 						     int item)
4577 {
4578 	return lruvec_page_state(lruvec, item) *
4579 		memcg_page_state_output_unit(item);
4580 }
4581 
4582 static int memory_numa_stat_show(struct seq_file *m, void *v)
4583 {
4584 	int i;
4585 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4586 
4587 	mem_cgroup_flush_stats(memcg);
4588 
4589 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
4590 		int nid;
4591 
4592 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
4593 			continue;
4594 
4595 		seq_printf(m, "%s", memory_stats[i].name);
4596 		for_each_node_state(nid, N_MEMORY) {
4597 			u64 size;
4598 			struct lruvec *lruvec;
4599 
4600 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4601 			size = lruvec_page_state_output(lruvec,
4602 							memory_stats[i].idx);
4603 			seq_printf(m, " N%d=%llu", nid, size);
4604 		}
4605 		seq_putc(m, '\n');
4606 	}
4607 
4608 	return 0;
4609 }
4610 #endif
4611 
4612 static int memory_oom_group_show(struct seq_file *m, void *v)
4613 {
4614 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4615 
4616 	seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
4617 
4618 	return 0;
4619 }
4620 
4621 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
4622 				      char *buf, size_t nbytes, loff_t off)
4623 {
4624 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4625 	int ret, oom_group;
4626 
4627 	buf = strstrip(buf);
4628 	if (!buf)
4629 		return -EINVAL;
4630 
4631 	ret = kstrtoint(buf, 0, &oom_group);
4632 	if (ret)
4633 		return ret;
4634 
4635 	if (oom_group != 0 && oom_group != 1)
4636 		return -EINVAL;
4637 
4638 	WRITE_ONCE(memcg->oom_group, oom_group);
4639 
4640 	return nbytes;
4641 }
4642 
4643 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
4644 			      size_t nbytes, loff_t off)
4645 {
4646 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4647 	int ret;
4648 
4649 	ret = user_proactive_reclaim(buf, memcg, NULL);
4650 	if (ret)
4651 		return ret;
4652 
4653 	return nbytes;
4654 }
4655 
4656 static struct cftype memory_files[] = {
4657 	{
4658 		.name = "current",
4659 		.flags = CFTYPE_NOT_ON_ROOT,
4660 		.read_u64 = memory_current_read,
4661 	},
4662 	{
4663 		.name = "peak",
4664 		.flags = CFTYPE_NOT_ON_ROOT,
4665 		.open = peak_open,
4666 		.release = peak_release,
4667 		.seq_show = memory_peak_show,
4668 		.write = memory_peak_write,
4669 	},
4670 	{
4671 		.name = "min",
4672 		.flags = CFTYPE_NOT_ON_ROOT,
4673 		.seq_show = memory_min_show,
4674 		.write = memory_min_write,
4675 	},
4676 	{
4677 		.name = "low",
4678 		.flags = CFTYPE_NOT_ON_ROOT,
4679 		.seq_show = memory_low_show,
4680 		.write = memory_low_write,
4681 	},
4682 	{
4683 		.name = "high",
4684 		.flags = CFTYPE_NOT_ON_ROOT,
4685 		.seq_show = memory_high_show,
4686 		.write = memory_high_write,
4687 	},
4688 	{
4689 		.name = "max",
4690 		.flags = CFTYPE_NOT_ON_ROOT,
4691 		.seq_show = memory_max_show,
4692 		.write = memory_max_write,
4693 	},
4694 	{
4695 		.name = "events",
4696 		.flags = CFTYPE_NOT_ON_ROOT,
4697 		.file_offset = offsetof(struct mem_cgroup, events_file),
4698 		.seq_show = memory_events_show,
4699 	},
4700 	{
4701 		.name = "events.local",
4702 		.flags = CFTYPE_NOT_ON_ROOT,
4703 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
4704 		.seq_show = memory_events_local_show,
4705 	},
4706 	{
4707 		.name = "stat",
4708 		.seq_show = memory_stat_show,
4709 	},
4710 #ifdef CONFIG_NUMA
4711 	{
4712 		.name = "numa_stat",
4713 		.seq_show = memory_numa_stat_show,
4714 	},
4715 #endif
4716 	{
4717 		.name = "oom.group",
4718 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
4719 		.seq_show = memory_oom_group_show,
4720 		.write = memory_oom_group_write,
4721 	},
4722 	{
4723 		.name = "reclaim",
4724 		.flags = CFTYPE_NS_DELEGATABLE,
4725 		.write = memory_reclaim,
4726 	},
4727 	{ }	/* terminate */
4728 };
4729 
4730 struct cgroup_subsys memory_cgrp_subsys = {
4731 	.css_alloc = mem_cgroup_css_alloc,
4732 	.css_online = mem_cgroup_css_online,
4733 	.css_offline = mem_cgroup_css_offline,
4734 	.css_released = mem_cgroup_css_released,
4735 	.css_free = mem_cgroup_css_free,
4736 	.css_reset = mem_cgroup_css_reset,
4737 	.css_rstat_flush = mem_cgroup_css_rstat_flush,
4738 	.attach = mem_cgroup_attach,
4739 	.fork = mem_cgroup_fork,
4740 	.exit = mem_cgroup_exit,
4741 	.dfl_cftypes = memory_files,
4742 #ifdef CONFIG_MEMCG_V1
4743 	.legacy_cftypes = mem_cgroup_legacy_files,
4744 #endif
4745 	.early_init = 0,
4746 };
4747 
4748 /**
4749  * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
4750  * @root: the top ancestor of the sub-tree being checked
4751  * @memcg: the memory cgroup to check
4752  *
4753  * WARNING: This function is not stateless! It can only be used as part
4754  *          of a top-down tree iteration, not for isolated queries.
4755  */
4756 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
4757 				     struct mem_cgroup *memcg)
4758 {
4759 	bool recursive_protection =
4760 		cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
4761 
4762 	if (mem_cgroup_disabled())
4763 		return;
4764 
4765 	if (!root)
4766 		root = root_mem_cgroup;
4767 
4768 	page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
4769 }
4770 
4771 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
4772 			gfp_t gfp)
4773 {
4774 	int ret;
4775 
4776 	ret = try_charge(memcg, gfp, folio_nr_pages(folio));
4777 	if (ret)
4778 		goto out;
4779 
4780 	css_get(&memcg->css);
4781 	commit_charge(folio, memcg);
4782 	memcg1_commit_charge(folio, memcg);
4783 out:
4784 	return ret;
4785 }
4786 
4787 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
4788 {
4789 	struct mem_cgroup *memcg;
4790 	int ret;
4791 
4792 	memcg = get_mem_cgroup_from_mm(mm);
4793 	ret = charge_memcg(folio, memcg, gfp);
4794 	css_put(&memcg->css);
4795 
4796 	return ret;
4797 }
4798 
4799 /**
4800  * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
4801  * @folio: folio being charged
4802  * @gfp: reclaim mode
4803  *
4804  * This function is called when allocating a huge page folio, after the page has
4805  * already been obtained and charged to the appropriate hugetlb cgroup
4806  * controller (if it is enabled).
4807  *
4808  * Returns ENOMEM if the memcg is already full.
4809  * Returns 0 if either the charge was successful, or if we skip the charging.
4810  */
4811 int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
4812 {
4813 	struct mem_cgroup *memcg = get_mem_cgroup_from_current();
4814 	int ret = 0;
4815 
4816 	/*
4817 	 * Even memcg does not account for hugetlb, we still want to update
4818 	 * system-level stats via lruvec_stat_mod_folio. Return 0, and skip
4819 	 * charging the memcg.
4820 	 */
4821 	if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() ||
4822 		!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
4823 		goto out;
4824 
4825 	if (charge_memcg(folio, memcg, gfp))
4826 		ret = -ENOMEM;
4827 
4828 out:
4829 	mem_cgroup_put(memcg);
4830 	return ret;
4831 }
4832 
4833 /**
4834  * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
4835  * @folio: folio to charge.
4836  * @mm: mm context of the victim
4837  * @gfp: reclaim mode
4838  * @entry: swap entry for which the folio is allocated
4839  *
4840  * This function charges a folio allocated for swapin. Please call this before
4841  * adding the folio to the swapcache.
4842  *
4843  * Returns 0 on success. Otherwise, an error code is returned.
4844  */
4845 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
4846 				  gfp_t gfp, swp_entry_t entry)
4847 {
4848 	struct mem_cgroup *memcg;
4849 	unsigned short id;
4850 	int ret;
4851 
4852 	if (mem_cgroup_disabled())
4853 		return 0;
4854 
4855 	id = lookup_swap_cgroup_id(entry);
4856 	rcu_read_lock();
4857 	memcg = mem_cgroup_from_id(id);
4858 	if (!memcg || !css_tryget_online(&memcg->css))
4859 		memcg = get_mem_cgroup_from_mm(mm);
4860 	rcu_read_unlock();
4861 
4862 	ret = charge_memcg(folio, memcg, gfp);
4863 
4864 	css_put(&memcg->css);
4865 	return ret;
4866 }
4867 
4868 struct uncharge_gather {
4869 	struct mem_cgroup *memcg;
4870 	unsigned long nr_memory;
4871 	unsigned long pgpgout;
4872 	unsigned long nr_kmem;
4873 	int nid;
4874 };
4875 
4876 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
4877 {
4878 	memset(ug, 0, sizeof(*ug));
4879 }
4880 
4881 static void uncharge_batch(const struct uncharge_gather *ug)
4882 {
4883 	if (ug->nr_memory) {
4884 		memcg_uncharge(ug->memcg, ug->nr_memory);
4885 		if (ug->nr_kmem) {
4886 			mod_memcg_state(ug->memcg, MEMCG_KMEM, -ug->nr_kmem);
4887 			memcg1_account_kmem(ug->memcg, -ug->nr_kmem);
4888 		}
4889 		memcg1_oom_recover(ug->memcg);
4890 	}
4891 
4892 	memcg1_uncharge_batch(ug->memcg, ug->pgpgout, ug->nr_memory, ug->nid);
4893 
4894 	/* drop reference from uncharge_folio */
4895 	css_put(&ug->memcg->css);
4896 }
4897 
4898 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
4899 {
4900 	long nr_pages;
4901 	struct mem_cgroup *memcg;
4902 	struct obj_cgroup *objcg;
4903 
4904 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
4905 
4906 	/*
4907 	 * Nobody should be changing or seriously looking at
4908 	 * folio memcg or objcg at this point, we have fully
4909 	 * exclusive access to the folio.
4910 	 */
4911 	if (folio_memcg_kmem(folio)) {
4912 		objcg = __folio_objcg(folio);
4913 		/*
4914 		 * This get matches the put at the end of the function and
4915 		 * kmem pages do not hold memcg references anymore.
4916 		 */
4917 		memcg = get_mem_cgroup_from_objcg(objcg);
4918 	} else {
4919 		memcg = __folio_memcg(folio);
4920 	}
4921 
4922 	if (!memcg)
4923 		return;
4924 
4925 	if (ug->memcg != memcg) {
4926 		if (ug->memcg) {
4927 			uncharge_batch(ug);
4928 			uncharge_gather_clear(ug);
4929 		}
4930 		ug->memcg = memcg;
4931 		ug->nid = folio_nid(folio);
4932 
4933 		/* pairs with css_put in uncharge_batch */
4934 		css_get(&memcg->css);
4935 	}
4936 
4937 	nr_pages = folio_nr_pages(folio);
4938 
4939 	if (folio_memcg_kmem(folio)) {
4940 		ug->nr_memory += nr_pages;
4941 		ug->nr_kmem += nr_pages;
4942 
4943 		folio->memcg_data = 0;
4944 		obj_cgroup_put(objcg);
4945 	} else {
4946 		/* LRU pages aren't accounted at the root level */
4947 		if (!mem_cgroup_is_root(memcg))
4948 			ug->nr_memory += nr_pages;
4949 		ug->pgpgout++;
4950 
4951 		WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
4952 		folio->memcg_data = 0;
4953 	}
4954 
4955 	css_put(&memcg->css);
4956 }
4957 
4958 void __mem_cgroup_uncharge(struct folio *folio)
4959 {
4960 	struct uncharge_gather ug;
4961 
4962 	/* Don't touch folio->lru of any random page, pre-check: */
4963 	if (!folio_memcg_charged(folio))
4964 		return;
4965 
4966 	uncharge_gather_clear(&ug);
4967 	uncharge_folio(folio, &ug);
4968 	uncharge_batch(&ug);
4969 }
4970 
4971 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
4972 {
4973 	struct uncharge_gather ug;
4974 	unsigned int i;
4975 
4976 	uncharge_gather_clear(&ug);
4977 	for (i = 0; i < folios->nr; i++)
4978 		uncharge_folio(folios->folios[i], &ug);
4979 	if (ug.memcg)
4980 		uncharge_batch(&ug);
4981 }
4982 
4983 /**
4984  * mem_cgroup_replace_folio - Charge a folio's replacement.
4985  * @old: Currently circulating folio.
4986  * @new: Replacement folio.
4987  *
4988  * Charge @new as a replacement folio for @old. @old will
4989  * be uncharged upon free.
4990  *
4991  * Both folios must be locked, @new->mapping must be set up.
4992  */
4993 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
4994 {
4995 	struct mem_cgroup *memcg;
4996 	long nr_pages = folio_nr_pages(new);
4997 
4998 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
4999 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5000 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5001 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
5002 
5003 	if (mem_cgroup_disabled())
5004 		return;
5005 
5006 	/* Page cache replacement: new folio already charged? */
5007 	if (folio_memcg_charged(new))
5008 		return;
5009 
5010 	memcg = folio_memcg(old);
5011 	VM_WARN_ON_ONCE_FOLIO(!memcg, old);
5012 	if (!memcg)
5013 		return;
5014 
5015 	/* Force-charge the new page. The old one will be freed soon */
5016 	if (!mem_cgroup_is_root(memcg)) {
5017 		page_counter_charge(&memcg->memory, nr_pages);
5018 		if (do_memsw_account())
5019 			page_counter_charge(&memcg->memsw, nr_pages);
5020 	}
5021 
5022 	css_get(&memcg->css);
5023 	commit_charge(new, memcg);
5024 	memcg1_commit_charge(new, memcg);
5025 }
5026 
5027 /**
5028  * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
5029  * @old: Currently circulating folio.
5030  * @new: Replacement folio.
5031  *
5032  * Transfer the memcg data from the old folio to the new folio for migration.
5033  * The old folio's data info will be cleared. Note that the memory counters
5034  * will remain unchanged throughout the process.
5035  *
5036  * Both folios must be locked, @new->mapping must be set up.
5037  */
5038 void mem_cgroup_migrate(struct folio *old, struct folio *new)
5039 {
5040 	struct mem_cgroup *memcg;
5041 
5042 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
5043 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
5044 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
5045 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
5046 	VM_BUG_ON_FOLIO(folio_test_lru(old), old);
5047 
5048 	if (mem_cgroup_disabled())
5049 		return;
5050 
5051 	memcg = folio_memcg(old);
5052 	/*
5053 	 * Note that it is normal to see !memcg for a hugetlb folio.
5054 	 * For e.g, itt could have been allocated when memory_hugetlb_accounting
5055 	 * was not selected.
5056 	 */
5057 	VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
5058 	if (!memcg)
5059 		return;
5060 
5061 	/* Transfer the charge and the css ref */
5062 	commit_charge(new, memcg);
5063 
5064 	/* Warning should never happen, so don't worry about refcount non-0 */
5065 	WARN_ON_ONCE(folio_unqueue_deferred_split(old));
5066 	old->memcg_data = 0;
5067 }
5068 
5069 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
5070 EXPORT_SYMBOL(memcg_sockets_enabled_key);
5071 
5072 void mem_cgroup_sk_alloc(struct sock *sk)
5073 {
5074 	struct mem_cgroup *memcg;
5075 
5076 	if (!mem_cgroup_sockets_enabled)
5077 		return;
5078 
5079 	/* Do not associate the sock with unrelated interrupted task's memcg. */
5080 	if (!in_task())
5081 		return;
5082 
5083 	rcu_read_lock();
5084 	memcg = mem_cgroup_from_task(current);
5085 	if (mem_cgroup_is_root(memcg))
5086 		goto out;
5087 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
5088 		goto out;
5089 	if (css_tryget(&memcg->css))
5090 		sk->sk_memcg = memcg;
5091 out:
5092 	rcu_read_unlock();
5093 }
5094 
5095 void mem_cgroup_sk_free(struct sock *sk)
5096 {
5097 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5098 
5099 	if (memcg)
5100 		css_put(&memcg->css);
5101 }
5102 
5103 void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk)
5104 {
5105 	struct mem_cgroup *memcg;
5106 
5107 	if (sk->sk_memcg == newsk->sk_memcg)
5108 		return;
5109 
5110 	mem_cgroup_sk_free(newsk);
5111 
5112 	memcg = mem_cgroup_from_sk(sk);
5113 	if (memcg)
5114 		css_get(&memcg->css);
5115 
5116 	newsk->sk_memcg = sk->sk_memcg;
5117 }
5118 
5119 /**
5120  * mem_cgroup_sk_charge - charge socket memory
5121  * @sk: socket in memcg to charge
5122  * @nr_pages: number of pages to charge
5123  * @gfp_mask: reclaim mode
5124  *
5125  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
5126  * @memcg's configured limit, %false if it doesn't.
5127  */
5128 bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages,
5129 			  gfp_t gfp_mask)
5130 {
5131 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5132 
5133 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5134 		return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
5135 
5136 	if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) {
5137 		mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
5138 		return true;
5139 	}
5140 
5141 	return false;
5142 }
5143 
5144 /**
5145  * mem_cgroup_sk_uncharge - uncharge socket memory
5146  * @sk: socket in memcg to uncharge
5147  * @nr_pages: number of pages to uncharge
5148  */
5149 void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages)
5150 {
5151 	struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
5152 
5153 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
5154 		memcg1_uncharge_skmem(memcg, nr_pages);
5155 		return;
5156 	}
5157 
5158 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
5159 
5160 	refill_stock(memcg, nr_pages);
5161 }
5162 
5163 void mem_cgroup_flush_workqueue(void)
5164 {
5165 	flush_workqueue(memcg_wq);
5166 }
5167 
5168 static int __init cgroup_memory(char *s)
5169 {
5170 	char *token;
5171 
5172 	while ((token = strsep(&s, ",")) != NULL) {
5173 		if (!*token)
5174 			continue;
5175 		if (!strcmp(token, "nosocket"))
5176 			cgroup_memory_nosocket = true;
5177 		if (!strcmp(token, "nokmem"))
5178 			cgroup_memory_nokmem = true;
5179 		if (!strcmp(token, "nobpf"))
5180 			cgroup_memory_nobpf = true;
5181 	}
5182 	return 1;
5183 }
5184 __setup("cgroup.memory=", cgroup_memory);
5185 
5186 /*
5187  * Memory controller init before cgroup_init() initialize root_mem_cgroup.
5188  *
5189  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
5190  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
5191  * basically everything that doesn't depend on a specific mem_cgroup structure
5192  * should be initialized from here.
5193  */
5194 int __init mem_cgroup_init(void)
5195 {
5196 	unsigned int memcg_size;
5197 	int cpu;
5198 
5199 	/*
5200 	 * Currently s32 type (can refer to struct batched_lruvec_stat) is
5201 	 * used for per-memcg-per-cpu caching of per-node statistics. In order
5202 	 * to work fine, we should make sure that the overfill threshold can't
5203 	 * exceed S32_MAX / PAGE_SIZE.
5204 	 */
5205 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
5206 
5207 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
5208 				  memcg_hotplug_cpu_dead);
5209 
5210 	memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0);
5211 	WARN_ON(!memcg_wq);
5212 
5213 	for_each_possible_cpu(cpu) {
5214 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
5215 			  drain_local_memcg_stock);
5216 		INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work,
5217 			  drain_local_obj_stock);
5218 	}
5219 
5220 	memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
5221 	memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
5222 					 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
5223 
5224 	memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
5225 				     SLAB_PANIC | SLAB_HWCACHE_ALIGN);
5226 
5227 	return 0;
5228 }
5229 
5230 #ifdef CONFIG_SWAP
5231 /**
5232  * __mem_cgroup_try_charge_swap - try charging swap space for a folio
5233  * @folio: folio being added to swap
5234  * @entry: swap entry to charge
5235  *
5236  * Try to charge @folio's memcg for the swap space at @entry.
5237  *
5238  * Returns 0 on success, -ENOMEM on failure.
5239  */
5240 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
5241 {
5242 	unsigned int nr_pages = folio_nr_pages(folio);
5243 	struct page_counter *counter;
5244 	struct mem_cgroup *memcg;
5245 
5246 	if (do_memsw_account())
5247 		return 0;
5248 
5249 	memcg = folio_memcg(folio);
5250 
5251 	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
5252 	if (!memcg)
5253 		return 0;
5254 
5255 	if (!entry.val) {
5256 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5257 		return 0;
5258 	}
5259 
5260 	memcg = mem_cgroup_id_get_online(memcg);
5261 
5262 	if (!mem_cgroup_is_root(memcg) &&
5263 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
5264 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
5265 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5266 		mem_cgroup_id_put(memcg);
5267 		return -ENOMEM;
5268 	}
5269 
5270 	/* Get references for the tail pages, too */
5271 	if (nr_pages > 1)
5272 		mem_cgroup_id_get_many(memcg, nr_pages - 1);
5273 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
5274 
5275 	swap_cgroup_record(folio, mem_cgroup_id(memcg), entry);
5276 
5277 	return 0;
5278 }
5279 
5280 /**
5281  * __mem_cgroup_uncharge_swap - uncharge swap space
5282  * @entry: swap entry to uncharge
5283  * @nr_pages: the amount of swap space to uncharge
5284  */
5285 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
5286 {
5287 	struct mem_cgroup *memcg;
5288 	unsigned short id;
5289 
5290 	id = swap_cgroup_clear(entry, nr_pages);
5291 	rcu_read_lock();
5292 	memcg = mem_cgroup_from_id(id);
5293 	if (memcg) {
5294 		if (!mem_cgroup_is_root(memcg)) {
5295 			if (do_memsw_account())
5296 				page_counter_uncharge(&memcg->memsw, nr_pages);
5297 			else
5298 				page_counter_uncharge(&memcg->swap, nr_pages);
5299 		}
5300 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
5301 		mem_cgroup_id_put_many(memcg, nr_pages);
5302 	}
5303 	rcu_read_unlock();
5304 }
5305 
5306 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
5307 {
5308 	long nr_swap_pages = get_nr_swap_pages();
5309 
5310 	if (mem_cgroup_disabled() || do_memsw_account())
5311 		return nr_swap_pages;
5312 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
5313 		nr_swap_pages = min_t(long, nr_swap_pages,
5314 				      READ_ONCE(memcg->swap.max) -
5315 				      page_counter_read(&memcg->swap));
5316 	return nr_swap_pages;
5317 }
5318 
5319 bool mem_cgroup_swap_full(struct folio *folio)
5320 {
5321 	struct mem_cgroup *memcg;
5322 
5323 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5324 
5325 	if (vm_swap_full())
5326 		return true;
5327 	if (do_memsw_account())
5328 		return false;
5329 
5330 	memcg = folio_memcg(folio);
5331 	if (!memcg)
5332 		return false;
5333 
5334 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
5335 		unsigned long usage = page_counter_read(&memcg->swap);
5336 
5337 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
5338 		    usage * 2 >= READ_ONCE(memcg->swap.max))
5339 			return true;
5340 	}
5341 
5342 	return false;
5343 }
5344 
5345 static int __init setup_swap_account(char *s)
5346 {
5347 	bool res;
5348 
5349 	if (!kstrtobool(s, &res) && !res)
5350 		pr_warn_once("The swapaccount=0 commandline option is deprecated "
5351 			     "in favor of configuring swap control via cgroupfs. "
5352 			     "Please report your usecase to linux-mm@kvack.org if you "
5353 			     "depend on this functionality.\n");
5354 	return 1;
5355 }
5356 __setup("swapaccount=", setup_swap_account);
5357 
5358 static u64 swap_current_read(struct cgroup_subsys_state *css,
5359 			     struct cftype *cft)
5360 {
5361 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5362 
5363 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
5364 }
5365 
5366 static int swap_peak_show(struct seq_file *sf, void *v)
5367 {
5368 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
5369 
5370 	return peak_show(sf, v, &memcg->swap);
5371 }
5372 
5373 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
5374 			       size_t nbytes, loff_t off)
5375 {
5376 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5377 
5378 	return peak_write(of, buf, nbytes, off, &memcg->swap,
5379 			  &memcg->swap_peaks);
5380 }
5381 
5382 static int swap_high_show(struct seq_file *m, void *v)
5383 {
5384 	return seq_puts_memcg_tunable(m,
5385 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
5386 }
5387 
5388 static ssize_t swap_high_write(struct kernfs_open_file *of,
5389 			       char *buf, size_t nbytes, loff_t off)
5390 {
5391 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5392 	unsigned long high;
5393 	int err;
5394 
5395 	buf = strstrip(buf);
5396 	err = page_counter_memparse(buf, "max", &high);
5397 	if (err)
5398 		return err;
5399 
5400 	page_counter_set_high(&memcg->swap, high);
5401 
5402 	return nbytes;
5403 }
5404 
5405 static int swap_max_show(struct seq_file *m, void *v)
5406 {
5407 	return seq_puts_memcg_tunable(m,
5408 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
5409 }
5410 
5411 static ssize_t swap_max_write(struct kernfs_open_file *of,
5412 			      char *buf, size_t nbytes, loff_t off)
5413 {
5414 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5415 	unsigned long max;
5416 	int err;
5417 
5418 	buf = strstrip(buf);
5419 	err = page_counter_memparse(buf, "max", &max);
5420 	if (err)
5421 		return err;
5422 
5423 	xchg(&memcg->swap.max, max);
5424 
5425 	return nbytes;
5426 }
5427 
5428 static int swap_events_show(struct seq_file *m, void *v)
5429 {
5430 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5431 
5432 	seq_printf(m, "high %lu\n",
5433 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
5434 	seq_printf(m, "max %lu\n",
5435 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
5436 	seq_printf(m, "fail %lu\n",
5437 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
5438 
5439 	return 0;
5440 }
5441 
5442 static struct cftype swap_files[] = {
5443 	{
5444 		.name = "swap.current",
5445 		.flags = CFTYPE_NOT_ON_ROOT,
5446 		.read_u64 = swap_current_read,
5447 	},
5448 	{
5449 		.name = "swap.high",
5450 		.flags = CFTYPE_NOT_ON_ROOT,
5451 		.seq_show = swap_high_show,
5452 		.write = swap_high_write,
5453 	},
5454 	{
5455 		.name = "swap.max",
5456 		.flags = CFTYPE_NOT_ON_ROOT,
5457 		.seq_show = swap_max_show,
5458 		.write = swap_max_write,
5459 	},
5460 	{
5461 		.name = "swap.peak",
5462 		.flags = CFTYPE_NOT_ON_ROOT,
5463 		.open = peak_open,
5464 		.release = peak_release,
5465 		.seq_show = swap_peak_show,
5466 		.write = swap_peak_write,
5467 	},
5468 	{
5469 		.name = "swap.events",
5470 		.flags = CFTYPE_NOT_ON_ROOT,
5471 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
5472 		.seq_show = swap_events_show,
5473 	},
5474 	{ }	/* terminate */
5475 };
5476 
5477 #ifdef CONFIG_ZSWAP
5478 /**
5479  * obj_cgroup_may_zswap - check if this cgroup can zswap
5480  * @objcg: the object cgroup
5481  *
5482  * Check if the hierarchical zswap limit has been reached.
5483  *
5484  * This doesn't check for specific headroom, and it is not atomic
5485  * either. But with zswap, the size of the allocation is only known
5486  * once compression has occurred, and this optimistic pre-check avoids
5487  * spending cycles on compression when there is already no room left
5488  * or zswap is disabled altogether somewhere in the hierarchy.
5489  */
5490 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
5491 {
5492 	struct mem_cgroup *memcg, *original_memcg;
5493 	bool ret = true;
5494 
5495 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5496 		return true;
5497 
5498 	original_memcg = get_mem_cgroup_from_objcg(objcg);
5499 	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
5500 	     memcg = parent_mem_cgroup(memcg)) {
5501 		unsigned long max = READ_ONCE(memcg->zswap_max);
5502 		unsigned long pages;
5503 
5504 		if (max == PAGE_COUNTER_MAX)
5505 			continue;
5506 		if (max == 0) {
5507 			ret = false;
5508 			break;
5509 		}
5510 
5511 		/* Force flush to get accurate stats for charging */
5512 		__mem_cgroup_flush_stats(memcg, true);
5513 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
5514 		if (pages < max)
5515 			continue;
5516 		ret = false;
5517 		break;
5518 	}
5519 	mem_cgroup_put(original_memcg);
5520 	return ret;
5521 }
5522 
5523 /**
5524  * obj_cgroup_charge_zswap - charge compression backend memory
5525  * @objcg: the object cgroup
5526  * @size: size of compressed object
5527  *
5528  * This forces the charge after obj_cgroup_may_zswap() allowed
5529  * compression and storage in zswap for this cgroup to go ahead.
5530  */
5531 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
5532 {
5533 	struct mem_cgroup *memcg;
5534 
5535 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5536 		return;
5537 
5538 	VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
5539 
5540 	/* PF_MEMALLOC context, charging must succeed */
5541 	if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
5542 		VM_WARN_ON_ONCE(1);
5543 
5544 	rcu_read_lock();
5545 	memcg = obj_cgroup_memcg(objcg);
5546 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
5547 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
5548 	rcu_read_unlock();
5549 }
5550 
5551 /**
5552  * obj_cgroup_uncharge_zswap - uncharge compression backend memory
5553  * @objcg: the object cgroup
5554  * @size: size of compressed object
5555  *
5556  * Uncharges zswap memory on page in.
5557  */
5558 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
5559 {
5560 	struct mem_cgroup *memcg;
5561 
5562 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5563 		return;
5564 
5565 	obj_cgroup_uncharge(objcg, size);
5566 
5567 	rcu_read_lock();
5568 	memcg = obj_cgroup_memcg(objcg);
5569 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
5570 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
5571 	rcu_read_unlock();
5572 }
5573 
5574 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
5575 {
5576 	/* if zswap is disabled, do not block pages going to the swapping device */
5577 	if (!zswap_is_enabled())
5578 		return true;
5579 
5580 	for (; memcg; memcg = parent_mem_cgroup(memcg))
5581 		if (!READ_ONCE(memcg->zswap_writeback))
5582 			return false;
5583 
5584 	return true;
5585 }
5586 
5587 static u64 zswap_current_read(struct cgroup_subsys_state *css,
5588 			      struct cftype *cft)
5589 {
5590 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5591 
5592 	mem_cgroup_flush_stats(memcg);
5593 	return memcg_page_state(memcg, MEMCG_ZSWAP_B);
5594 }
5595 
5596 static int zswap_max_show(struct seq_file *m, void *v)
5597 {
5598 	return seq_puts_memcg_tunable(m,
5599 		READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
5600 }
5601 
5602 static ssize_t zswap_max_write(struct kernfs_open_file *of,
5603 			       char *buf, size_t nbytes, loff_t off)
5604 {
5605 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5606 	unsigned long max;
5607 	int err;
5608 
5609 	buf = strstrip(buf);
5610 	err = page_counter_memparse(buf, "max", &max);
5611 	if (err)
5612 		return err;
5613 
5614 	xchg(&memcg->zswap_max, max);
5615 
5616 	return nbytes;
5617 }
5618 
5619 static int zswap_writeback_show(struct seq_file *m, void *v)
5620 {
5621 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5622 
5623 	seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
5624 	return 0;
5625 }
5626 
5627 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
5628 				char *buf, size_t nbytes, loff_t off)
5629 {
5630 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5631 	int zswap_writeback;
5632 	ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
5633 
5634 	if (parse_ret)
5635 		return parse_ret;
5636 
5637 	if (zswap_writeback != 0 && zswap_writeback != 1)
5638 		return -EINVAL;
5639 
5640 	WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
5641 	return nbytes;
5642 }
5643 
5644 static struct cftype zswap_files[] = {
5645 	{
5646 		.name = "zswap.current",
5647 		.flags = CFTYPE_NOT_ON_ROOT,
5648 		.read_u64 = zswap_current_read,
5649 	},
5650 	{
5651 		.name = "zswap.max",
5652 		.flags = CFTYPE_NOT_ON_ROOT,
5653 		.seq_show = zswap_max_show,
5654 		.write = zswap_max_write,
5655 	},
5656 	{
5657 		.name = "zswap.writeback",
5658 		.seq_show = zswap_writeback_show,
5659 		.write = zswap_writeback_write,
5660 	},
5661 	{ }	/* terminate */
5662 };
5663 #endif /* CONFIG_ZSWAP */
5664 
5665 static int __init mem_cgroup_swap_init(void)
5666 {
5667 	if (mem_cgroup_disabled())
5668 		return 0;
5669 
5670 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
5671 #ifdef CONFIG_MEMCG_V1
5672 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
5673 #endif
5674 #ifdef CONFIG_ZSWAP
5675 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
5676 #endif
5677 	return 0;
5678 }
5679 subsys_initcall(mem_cgroup_swap_init);
5680 
5681 #endif /* CONFIG_SWAP */
5682 
5683 bool mem_cgroup_node_allowed(struct mem_cgroup *memcg, int nid)
5684 {
5685 	return memcg ? cpuset_node_allowed(memcg->css.cgroup, nid) : true;
5686 }
5687 
5688 void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
5689 {
5690 	if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
5691 		return;
5692 
5693 	if (!memcg)
5694 		memcg = root_mem_cgroup;
5695 
5696 	pr_warn("Memory cgroup min protection %lukB -- low protection %lukB",
5697 		K(atomic_long_read(&memcg->memory.children_min_usage)),
5698 		K(atomic_long_read(&memcg->memory.children_low_usage)));
5699 }
5700