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