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