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