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