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