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