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