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