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