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