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